blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10bd7da75baf5e9d7905d66f4c2f70dbe6188669 | [
"list(args).clear()\nresult = False\nif not isinstance(mapping[pattern], tuple):\n if flags[mapping[pattern].value]['count'] > 0:\n result = True\nelse:\n for flag in mapping[pattern]:\n if flags[flag.value]['count'] > 0:\n result = True\n break\nreturn result",
"list([in... | <|body_start_0|>
list(args).clear()
result = False
if not isinstance(mapping[pattern], tuple):
if flags[mapping[pattern].value]['count'] > 0:
result = True
else:
for flag in mapping[pattern]:
if flags[flag.value]['count'] > 0:
... | Rules for matching subpatterns | OpSubPatternRules | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpSubPatternRules:
"""Rules for matching subpatterns"""
def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool:
"""Simple pattern rule"""
<|body_0|>
def reduce_atomic_sub_pattern_rule(flags: dict, input_tensors: list, output_tensors: list, *args) -> bool:
... | stack_v2_sparse_classes_75kplus_train_005000 | 31,661 | no_license | [
{
"docstring": "Simple pattern rule",
"name": "simple_pattern_rule",
"signature": "def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool"
},
{
"docstring": "check reduce atomic pattern",
"name": "reduce_atomic_sub_pattern_rule",
"signature": "def reduce_atomic_sub_pattern... | 3 | stack_v2_sparse_classes_30k_train_033650 | Implement the Python class `OpSubPatternRules` described below.
Class description:
Rules for matching subpatterns
Method signatures and docstrings:
- def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool: Simple pattern rule
- def reduce_atomic_sub_pattern_rule(flags: dict, input_tensors: list, output... | Implement the Python class `OpSubPatternRules` described below.
Class description:
Rules for matching subpatterns
Method signatures and docstrings:
- def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool: Simple pattern rule
- def reduce_atomic_sub_pattern_rule(flags: dict, input_tensors: list, output... | 148511a31bfd195df889291946c43bb585acb546 | <|skeleton|>
class OpSubPatternRules:
"""Rules for matching subpatterns"""
def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool:
"""Simple pattern rule"""
<|body_0|>
def reduce_atomic_sub_pattern_rule(flags: dict, input_tensors: list, output_tensors: list, *args) -> bool:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpSubPatternRules:
"""Rules for matching subpatterns"""
def simple_pattern_rule(flags: dict, pattern, mapping, *args) -> bool:
"""Simple pattern rule"""
list(args).clear()
result = False
if not isinstance(mapping[pattern], tuple):
if flags[mapping[pattern].valu... | the_stack_v2_python_sparse | convertor/huawei/te/lang/cce/te_schedule/cce_schedule_distribution_rules.py | jizhuoran/caffe-huawei-atlas-convertor | train | 4 |
048ba717b834d22ca9e53dce00fe8eef3196aed0 | [
"super(BasicUnet, self).__init__()\nself.name = 'UNet'\nself.n_classes = n_classes\nself.n_channels = n_channels\nself.input_layer = DoubleConvolutionLayer(n_channels, 64)\nself.downscaling_layer1 = Downscaling_layer(64, 128)\nself.downscaling_layer2 = Downscaling_layer(128, 256)\nself.downscaling_layer3 = Downscal... | <|body_start_0|>
super(BasicUnet, self).__init__()
self.name = 'UNet'
self.n_classes = n_classes
self.n_channels = n_channels
self.input_layer = DoubleConvolutionLayer(n_channels, 64)
self.downscaling_layer1 = Downscaling_layer(64, 128)
self.downscaling_layer2 = D... | The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture. | BasicUnet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicUnet:
"""The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture."""
def __init__(self, n_channels, n_classes):
"""Initialises a BasicUn... | stack_v2_sparse_classes_75kplus_train_005001 | 10,764 | permissive | [
{
"docstring": "Initialises a BasicUnet object by definint all the layers it contains. The weight are randomly initialised. The BasicUnet object will take n_channels as input channels and return n_classes feature maps. n_channels : number of input channels (number of 2D matrixes) n_classes : number of classes t... | 3 | null | Implement the Python class `BasicUnet` described below.
Class description:
The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture.
Method signatures and docstrings:
- def __i... | Implement the Python class `BasicUnet` described below.
Class description:
The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture.
Method signatures and docstrings:
- def __i... | 4ad97b04f98b10554c3c0de85645578df336df98 | <|skeleton|>
class BasicUnet:
"""The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture."""
def __init__(self, n_channels, n_classes):
"""Initialises a BasicUn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicUnet:
"""The class BasicUnet extends the class Module of pytorch which is used to define Neural Networks. We redefine two functions which define the architecture and the flow of data through the architecture."""
def __init__(self, n_channels, n_classes):
"""Initialises a BasicUnet object by ... | the_stack_v2_python_sparse | Models/basicUnet.py | MinZHANG-WHU/LamboiseNet | train | 1 |
88f75ed11a9d89b16a53f9560e12f5c143088dc8 | [
"super(Candlestick, self).__init__()\nself.time = kwargs.get('time')\nself.bid = kwargs.get('bid')\nself.ask = kwargs.get('ask')\nself.mid = kwargs.get('mid')\nself.volume = kwargs.get('volume')\nself.complete = kwargs.get('complete')",
"data = data.copy()\nif data.get('bid') is not None:\n data['bid'] = ctx.i... | <|body_start_0|>
super(Candlestick, self).__init__()
self.time = kwargs.get('time')
self.bid = kwargs.get('bid')
self.ask = kwargs.get('ask')
self.mid = kwargs.get('mid')
self.volume = kwargs.get('volume')
self.complete = kwargs.get('complete')
<|end_body_0|>
<|b... | The Candlestick representation | Candlestick | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Candlestick:
"""The Candlestick representation"""
def __init__(self, **kwargs):
"""Create a new Candlestick instance"""
<|body_0|>
def from_dict(data, ctx):
"""Instantiate a new Candlestick from a dict (generally from loading a JSON response). The data used to in... | stack_v2_sparse_classes_75kplus_train_005002 | 11,143 | permissive | [
{
"docstring": "Create a new Candlestick instance",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Instantiate a new Candlestick from a dict (generally from loading a JSON response). The data used to instantiate the Candlestick is a shallow copy of the dict pa... | 2 | stack_v2_sparse_classes_30k_test_002621 | Implement the Python class `Candlestick` described below.
Class description:
The Candlestick representation
Method signatures and docstrings:
- def __init__(self, **kwargs): Create a new Candlestick instance
- def from_dict(data, ctx): Instantiate a new Candlestick from a dict (generally from loading a JSON response)... | Implement the Python class `Candlestick` described below.
Class description:
The Candlestick representation
Method signatures and docstrings:
- def __init__(self, **kwargs): Create a new Candlestick instance
- def from_dict(data, ctx): Instantiate a new Candlestick from a dict (generally from loading a JSON response)... | 055f51e55c52d6dd5cfd38550a48892a0fb09b0d | <|skeleton|>
class Candlestick:
"""The Candlestick representation"""
def __init__(self, **kwargs):
"""Create a new Candlestick instance"""
<|body_0|>
def from_dict(data, ctx):
"""Instantiate a new Candlestick from a dict (generally from loading a JSON response). The data used to in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Candlestick:
"""The Candlestick representation"""
def __init__(self, **kwargs):
"""Create a new Candlestick instance"""
super(Candlestick, self).__init__()
self.time = kwargs.get('time')
self.bid = kwargs.get('bid')
self.ask = kwargs.get('ask')
self.mid = k... | the_stack_v2_python_sparse | forex/env-python2/lib/python2.7/site-packages/v20/instrument.py | phroiland/forex_algos | train | 1 |
d86598f35ad32293c5dde7e4a1f678ca5e8a7bb9 | [
"super().__init__()\nself.n_atom_basis = n_atom_basis\nself.size = (self.n_atom_basis,)\nself.n_filters = n_filters or self.n_atom_basis\nself.radial_basis = radial_basis\nself.cutoff_fn = cutoff_fn\nif response_properties is not None:\n external_fields = required_fields_from_properties(response_properties)\nsel... | <|body_start_0|>
super().__init__()
self.n_atom_basis = n_atom_basis
self.size = (self.n_atom_basis,)
self.n_filters = n_filters or self.n_atom_basis
self.radial_basis = radial_basis
self.cutoff_fn = cutoff_fn
if response_properties is not None:
extern... | FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and reactions. Chemical Science, 12(34), 11473-11483. 2021. | FieldSchNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldSchNet:
"""FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and reactions. Chemical Science, 12(34), 11473-1... | stack_v2_sparse_classes_75kplus_train_005003 | 15,766 | permissive | [
{
"docstring": "Args: n_atom_basis: number of features to describe atomic environments. This determines the size of each embedding vector; i.e. embeddings_dim. n_interactions: number of interaction blocks. radial_basis: layer for expanding interatomic distances in a basis set external_fields (list(str)): List o... | 2 | null | Implement the Python class `FieldSchNet` described below.
Class description:
FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and react... | Implement the Python class `FieldSchNet` described below.
Class description:
FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and react... | 2ed8d1a3b773f4ed2dbd50623d43d578ff0146f6 | <|skeleton|>
class FieldSchNet:
"""FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and reactions. Chemical Science, 12(34), 11473-1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FieldSchNet:
"""FieldSchNet architecture for modeling interactions with external fields and response properties as described in [#field4]_. References: .. [#field4] Gastegger, Schütt, Müller: Machine learning of solvent effects on molecular spectra and reactions. Chemical Science, 12(34), 11473-11483. 2021.""... | the_stack_v2_python_sparse | src/schnetpack/representation/field_schnet.py | atomistic-machine-learning/schnetpack | train | 653 |
0790c50c5d42ccad1e9cb82832e8e4fcf88c88d7 | [
"try:\n return config_parser.get(section_name, value_name)\nexcept configparser.NoOptionError:\n return None",
"config_parser = configparser.ConfigParser(interpolation=None)\nconfig_parser.read_file(file_object)\nprojects_per_organization = {}\nfor option_name in config_parser.options('organizations'):\n ... | <|body_start_0|>
try:
return config_parser.get(section_name, value_name)
except configparser.NoOptionError:
return None
<|end_body_0|>
<|body_start_1|>
config_parser = configparser.ConfigParser(interpolation=None)
config_parser.read_file(file_object)
proj... | Class that implements a stats definition reader. | StatsDefinitionReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsDefinitionReader:
"""Class that implements a stats definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the sec... | stack_v2_sparse_classes_75kplus_train_005004 | 15,780 | permissive | [
{
"docstring": "Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: object: value or None if the value does not exists.",
"name": "_GetConfigValue",
... | 4 | stack_v2_sparse_classes_30k_train_039776 | Implement the Python class `StatsDefinitionReader` described below.
Class description:
Class that implements a stats definition reader.
Method signatures and docstrings:
- def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): ... | Implement the Python class `StatsDefinitionReader` described below.
Class description:
Class that implements a stats definition reader.
Method signatures and docstrings:
- def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): ... | 34709706cc3bee84db45883043b9dfc1811ba65b | <|skeleton|>
class StatsDefinitionReader:
"""Class that implements a stats definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the sec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatsDefinitionReader:
"""Class that implements a stats definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that con... | the_stack_v2_python_sparse | tools/stats.py | log2timeline/l2tdevtools | train | 7 |
d147be66a46875d93ef743b65b1917f1fec7292a | [
"try:\n music = {}\n music['music'] = self.manager.search(q=data['search'], limit=20, type='track')\n return music\nexcept (TypeError, KeyError, SpotifyException):\n raise exceptions.ValidationError(code=status.HTTP_400_BAD_REQUEST, detail=\"It's required `search` field.\")",
"try:\n music = {}\n ... | <|body_start_0|>
try:
music = {}
music['music'] = self.manager.search(q=data['search'], limit=20, type='track')
return music
except (TypeError, KeyError, SpotifyException):
raise exceptions.ValidationError(code=status.HTTP_400_BAD_REQUEST, detail="It's req... | Utilities for the service of music. | UtilsMusic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_75kplus_train_005005 | 11,622 | no_license | [
{
"docstring": "Search by all items.",
"name": "search_all",
"signature": "def search_all(self, data)"
},
{
"docstring": "Search by date.",
"name": "search_date",
"signature": "def search_date(self, data)"
},
{
"docstring": "Search by uuid.",
"name": "search_uuid",
"signa... | 4 | stack_v2_sparse_classes_30k_train_040344 | Implement the Python class `UtilsMusic` described below.
Class description:
Utilities for the service of music.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | Implement the Python class `UtilsMusic` described below.
Class description:
Utilities for the service of music.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
try:
music = {}
music['music'] = self.manager.search(q=data['search'], limit=20, type='track')
return music
except (TypeError, KeyError,... | the_stack_v2_python_sparse | api/services/utils.py | ignite7/backproject | train | 0 |
e5b17334cd00e85b7952d8c935c73c1fe90a1214 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('sbrz_nedg', 'sbrz_nedg')\ndb = client.repo\ncollection = db['sbrz_nedg.college_university']\nx = []\ncolleges = collection.find({}, {'properties.Name': 1, 'properties.Address': 1, 'properties.Zipcode': 1... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db = client.repo
collection = db['sbrz_nedg.college_university']
x = []
colleges = collection.find({}, {'... | selectAddressesColleges | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class selectAddressesColleges:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_75kplus_train_005006 | 3,278 | no_license | [
{
"docstring": "Select all of the addresses from the College/Universities data set",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document de... | 2 | null | Implement the Python class `selectAddressesColleges` described below.
Class description:
Implement the selectAddressesColleges class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the College/Universities data set
- def provenance(doc=prov.model.ProvDocument(), startTi... | Implement the Python class `selectAddressesColleges` described below.
Class description:
Implement the selectAddressesColleges class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the College/Universities data set
- def provenance(doc=prov.model.ProvDocument(), startTi... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class selectAddressesColleges:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class selectAddressesColleges:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db =... | the_stack_v2_python_sparse | sbrz_nedg/selectAddressesColleges.py | ROODAY/course-2017-fal-proj | train | 3 | |
447545e3f9e37acf0e1d78bdbad042056ae6a2e4 | [
"if media_url is not None:\n warnings.warn('%s ``media_url`` is deprecated. Use ``destination_url`` instead.' % self.__class__.__name__, DeprecationWarning)\n if destination_url is None:\n destination_url = media_url\n else:\n destination_url = destination_url\nelse:\n destination_url = de... | <|body_start_0|>
if media_url is not None:
warnings.warn('%s ``media_url`` is deprecated. Use ``destination_url`` instead.' % self.__class__.__name__, DeprecationWarning)
if destination_url is None:
destination_url = media_url
else:
destination... | Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use this class as the factory in :py:class:`django_downloadview.decorators.DownloadDecorator`. | XAccelRedirectMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XAccelRedirectMiddleware:
"""Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use this class as the factory in :py:class:`dj... | stack_v2_sparse_classes_75kplus_train_005007 | 5,172 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, source_dir=None, source_url=None, destination_url=None, expires=None, with_buffering=None, limit_rate=None, media_root=None, media_url=None)"
},
{
"docstring": "Replace DownloadResponse instances by NginxDownload... | 2 | stack_v2_sparse_classes_30k_train_035903 | Implement the Python class `XAccelRedirectMiddleware` described below.
Class description:
Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use thi... | Implement the Python class `XAccelRedirectMiddleware` described below.
Class description:
Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use thi... | ba1d3a7b6f4213b0db057b49956d1393c6c2c54b | <|skeleton|>
class XAccelRedirectMiddleware:
"""Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use this class as the factory in :py:class:`dj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XAccelRedirectMiddleware:
"""Configurable middleware, for use in decorators or in global middlewares. Standard Django middlewares are configured globally via settings. Instances of this class are to be configured individually. It makes it possible to use this class as the factory in :py:class:`django_download... | the_stack_v2_python_sparse | lib/python3.6/site-packages/django_downloadview/nginx/middlewares.py | shastrakalyan/origin2 | train | 0 |
9483b633b891a22f75f72194b6eaf591e5bd6787 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for scanning Docker images. | ScannerServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScannerServiceServicer:
"""A set of methods for scanning Docker images."""
def Scan(self, request, context):
"""Executes scanning of specified image."""
<|body_0|>
def Get(self, request, context):
"""Returns the specified ScanResult resource. To get the list of S... | stack_v2_sparse_classes_75kplus_train_005008 | 10,850 | permissive | [
{
"docstring": "Executes scanning of specified image.",
"name": "Scan",
"signature": "def Scan(self, request, context)"
},
{
"docstring": "Returns the specified ScanResult resource. To get the list of ScanResults for specified Image, make a [List] request.",
"name": "Get",
"signature": "... | 5 | stack_v2_sparse_classes_30k_test_000680 | Implement the Python class `ScannerServiceServicer` described below.
Class description:
A set of methods for scanning Docker images.
Method signatures and docstrings:
- def Scan(self, request, context): Executes scanning of specified image.
- def Get(self, request, context): Returns the specified ScanResult resource.... | Implement the Python class `ScannerServiceServicer` described below.
Class description:
A set of methods for scanning Docker images.
Method signatures and docstrings:
- def Scan(self, request, context): Executes scanning of specified image.
- def Get(self, request, context): Returns the specified ScanResult resource.... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ScannerServiceServicer:
"""A set of methods for scanning Docker images."""
def Scan(self, request, context):
"""Executes scanning of specified image."""
<|body_0|>
def Get(self, request, context):
"""Returns the specified ScanResult resource. To get the list of S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScannerServiceServicer:
"""A set of methods for scanning Docker images."""
def Scan(self, request, context):
"""Executes scanning of specified image."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError... | the_stack_v2_python_sparse | yandex/cloud/containerregistry/v1/scanner_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
8123c2990e6fbfbfc81c9ece296c412ace1c595e | [
"chats = getAllSalas()\nserializer = self.serializer_class(chats, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"try:\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n sala = crearSala(request.data)\n if not sala is None:\n ... | <|body_start_0|>
chats = getAllSalas()
serializer = self.serializer_class(chats, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
try:
serializer = self.serializer_class(data=request.data)
if serializer.is_val... | Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia | chatListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class chatListView:
"""Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia"""
def get(self, request, format=None):
"""Metodo GET que retorna la lista de chats Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None.... | stack_v2_sparse_classes_75kplus_train_005009 | 8,545 | no_license | [
{
"docstring": "Metodo GET que retorna la lista de chats Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: HTTP200 si el chat existe HTTP400 si hay algun error con algun dato",
"name": "get",
"signature": "def get(self, request, format=None)"
},... | 2 | null | Implement the Python class `chatListView` described below.
Class description:
Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia
Method signatures and docstrings:
- def get(self, request, format=None): Metodo GET que retorna la lista de chats Args: request ([type]): [description] fo... | Implement the Python class `chatListView` described below.
Class description:
Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia
Method signatures and docstrings:
- def get(self, request, format=None): Metodo GET que retorna la lista de chats Args: request ([type]): [description] fo... | 5edfc0fb9316c899dbd5cd5607989300c75ab4e8 | <|skeleton|>
class chatListView:
"""Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia"""
def get(self, request, format=None):
"""Metodo GET que retorna la lista de chats Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class chatListView:
"""Clase que contiene los metodos GET y POST para la sala de chat Args: APIView Herencia"""
def get(self, request, format=None):
"""Metodo GET que retorna la lista de chats Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: HTT... | the_stack_v2_python_sparse | chat_API/views.py | MartinGalvanCastro/ApoyaFem-API | train | 0 |
95ae0327106d45de3b9388d28fcca30ec14c8b24 | [
"self.file_name = file_name\nself.key_name = key_name\nself.plate = plate\nself.author = author\nself.md5sum = md5sum\nself.create_datetime = datetime.datetime.now()",
"self.down_link = down_link\nself.status = 1\nself.file_name = os.path.basename(self.file_name)\nself.upload_datetime = datetime.datetime.now()\nr... | <|body_start_0|>
self.file_name = file_name
self.key_name = key_name
self.plate = plate
self.author = author
self.md5sum = md5sum
self.create_datetime = datetime.datetime.now()
<|end_body_0|>
<|body_start_1|>
self.down_link = down_link
self.status = 1
... | CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` VARCHAR(80) DEFAULT '' COMMENT '文件信息摘要Hash', `plate` INT DEFAULT 0 COMMENT '版块... | Attachment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attachment:
"""CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` VARCHAR(80) DEFAULT '' COMMENT '文件信息摘要Ha... | stack_v2_sparse_classes_75kplus_train_005010 | 6,648 | no_license | [
{
"docstring": "扫描文件目录记录入库.",
"name": "__init__",
"signature": "def __init__(self, file_name, key_name, plate=0, author='', md5sum='')"
},
{
"docstring": "上传后更新.",
"name": "after_upload_action",
"signature": "def after_upload_action(self, down_link)"
}
] | 2 | null | Implement the Python class `Attachment` described below.
Class description:
CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` V... | Implement the Python class `Attachment` described below.
Class description:
CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` V... | 40faf78b2365137b9da0cc67f511248b390b4c13 | <|skeleton|>
class Attachment:
"""CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` VARCHAR(80) DEFAULT '' COMMENT '文件信息摘要Ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attachment:
"""CREATE TABLE `bbs_attachment` ( `id` INT NOT NULL AUTO_INCREMENT COMMENT '自动编号', `file_name` VARCHAR(255) NOT NULL COMMENT '文件名', `key_name` VARCHAR(80) DEFAULT '' COMMENT '七牛文件名', `down_link` VARCHAR(150) DEFAULT '' COMMENT '下载地址', `md5sum` VARCHAR(80) DEFAULT '' COMMENT '文件信息摘要Hash', `plate` ... | the_stack_v2_python_sparse | discuzx_tools/libs/models/record.py | BabyMelvin/discuzx-tools | train | 0 |
890e6a6c3221d60c87669ec9717a8205dc14348a | [
"super(GreedySolver, self).__init__(cascades)\nself.remaining_cascades = np.ndarray(len(cascades), dtype=np.bool)\nself.remaining_cascades.fill(True)",
"parents = []\nself.remaining_cascades.fill(True)\npotential_parents = Counter()\nwhile any(self.remaining_cascades):\n accounted_cascades = []\n for i, ali... | <|body_start_0|>
super(GreedySolver, self).__init__(cascades)
self.remaining_cascades = np.ndarray(len(cascades), dtype=np.bool)
self.remaining_cascades.fill(True)
<|end_body_0|>
<|body_start_1|>
parents = []
self.remaining_cascades.fill(True)
potential_parents = Counter... | A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper. | GreedySolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedySolver:
"""A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper."""
def __init__(self, cascades):
"""Sets up an instance of the greedy solver with a list of cascades. :param cascades: numpy array of cascades :return: None... | stack_v2_sparse_classes_75kplus_train_005011 | 3,788 | permissive | [
{
"docstring": "Sets up an instance of the greedy solver with a list of cascades. :param cascades: numpy array of cascades :return: None",
"name": "__init__",
"signature": "def __init__(self, cascades)"
},
{
"docstring": "Computes the parental neighborhood for a particular node. :param node: int... | 3 | stack_v2_sparse_classes_30k_train_020241 | Implement the Python class `GreedySolver` described below.
Class description:
A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper.
Method signatures and docstrings:
- def __init__(self, cascades): Sets up an instance of the greedy solver with a list of cascade... | Implement the Python class `GreedySolver` described below.
Class description:
A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper.
Method signatures and docstrings:
- def __init__(self, cascades): Sets up an instance of the greedy solver with a list of cascade... | 4b9f4cf76dd427bbc182e0f6d8fad8ce127172c0 | <|skeleton|>
class GreedySolver:
"""A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper."""
def __init__(self, cascades):
"""Sets up an instance of the greedy solver with a list of cascades. :param cascades: numpy array of cascades :return: None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GreedySolver:
"""A simple greedy algorithm for determining parental neighborhoods. The algorithm comes from Netrapalli's paper."""
def __init__(self, cascades):
"""Sets up an instance of the greedy solver with a list of cascades. :param cascades: numpy array of cascades :return: None"""
s... | the_stack_v2_python_sparse | graph_inference/solver/greedysolver.py | codyhan94/epidemic-graph-inference | train | 0 |
564e97ea94317420c54bbeeee9a9f0543e4171ed | [
"super().__init__()\ninitializer = tf.random_normal_initializer(0.0, 0.02)\nself.f_conv = tf.keras.layers.Conv2D(filters // 8, 1, strides=1, padding='same', kernel_initializer=initializer)\nself.g_conv = tf.keras.layers.Conv2D(filters // 8, 1, strides=1, padding='same', kernel_initializer=initializer)\nself.h_conv ... | <|body_start_0|>
super().__init__()
initializer = tf.random_normal_initializer(0.0, 0.02)
self.f_conv = tf.keras.layers.Conv2D(filters // 8, 1, strides=1, padding='same', kernel_initializer=initializer)
self.g_conv = tf.keras.layers.Conv2D(filters // 8, 1, strides=1, padding='same', kern... | Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp(s_{i,j})}{\\sum_{i=1}^{N}\\exp(s_{ij})} :math:`\\beta_{j,i}` indicates the ... | Attention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp(s_{i,j})}{\\sum_{i=1}^{N}\\exp(s_{ij})... | stack_v2_sparse_classes_75kplus_train_005012 | 4,038 | permissive | [
{
"docstring": "Build the Attention Layer. Args: filters (int): Number of filters of the input tensor. It should be preferably a multiple of 8.",
"name": "__init__",
"signature": "def __init__(self, filters: int) -> None"
},
{
"docstring": "Perform the computation. Args: inputs (:py:class:`tf.Te... | 2 | null | Implement the Python class `Attention` described below.
Class description:
Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp... | Implement the Python class `Attention` described below.
Class description:
Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp... | 92ac86fb0c962854e0d80c44165e0e7ff126b3c1 | <|skeleton|>
class Attention:
"""Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp(s_{i,j})}{\\sum_{i=1}^{N}\\exp(s_{ij})... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attention:
"""Attention Layer from Self-Attention GAN [1]_. First we extract features from the previous layer: .. math:: f(x) = W_f x .. math:: g(x) = W_g x .. math:: h(x) = W_h x Then we calculate the importance matrix: .. math:: \\beta_{j,i} = \\frac{\\exp(s_{i,j})}{\\sum_{i=1}^{N}\\exp(s_{ij})} :math:`\\be... | the_stack_v2_python_sparse | src/ashpy/layers/attention.py | zurutech/ashpy | train | 89 |
cb167349580fc6c5d043ad8195afc31d2603209d | [
"self.omega = omega\nself.w = wavefunction\nself.s = system\nself.analytical = analytical",
"step = 0.001\nposition_forward = np.array(positions)\nposition_backward = np.array(positions)\npsi_current = 0.0\npsi_moved = 0.0\nfor i in range(self.w.num_p):\n psi_current += 2 * self.w.num_d * self.w.wavefunction(p... | <|body_start_0|>
self.omega = omega
self.w = wavefunction
self.s = system
self.analytical = analytical
<|end_body_0|>
<|body_start_1|>
step = 0.001
position_forward = np.array(positions)
position_backward = np.array(positions)
psi_current = 0.0
ps... | Calculate variables regarding the Hamiltonian of given wavefunction. | Non_Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Non_Interaction:
"""Calculate variables regarding the Hamiltonian of given wavefunction."""
def __init__(self, omega, wavefunction, system, analytical):
"""Instance of class."""
<|body_0|>
def laplacian_numerical(self, positions):
"""Numerical differentiation for... | stack_v2_sparse_classes_75kplus_train_005013 | 3,023 | no_license | [
{
"docstring": "Instance of class.",
"name": "__init__",
"signature": "def __init__(self, omega, wavefunction, system, analytical)"
},
{
"docstring": "Numerical differentiation for solving laplacian.",
"name": "laplacian_numerical",
"signature": "def laplacian_numerical(self, positions)"... | 5 | null | Implement the Python class `Non_Interaction` described below.
Class description:
Calculate variables regarding the Hamiltonian of given wavefunction.
Method signatures and docstrings:
- def __init__(self, omega, wavefunction, system, analytical): Instance of class.
- def laplacian_numerical(self, positions): Numerica... | Implement the Python class `Non_Interaction` described below.
Class description:
Calculate variables regarding the Hamiltonian of given wavefunction.
Method signatures and docstrings:
- def __init__(self, omega, wavefunction, system, analytical): Instance of class.
- def laplacian_numerical(self, positions): Numerica... | bed19421ceef6203d089b67a657ca3290740300a | <|skeleton|>
class Non_Interaction:
"""Calculate variables regarding the Hamiltonian of given wavefunction."""
def __init__(self, omega, wavefunction, system, analytical):
"""Instance of class."""
<|body_0|>
def laplacian_numerical(self, positions):
"""Numerical differentiation for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Non_Interaction:
"""Calculate variables regarding the Hamiltonian of given wavefunction."""
def __init__(self, omega, wavefunction, system, analytical):
"""Instance of class."""
self.omega = omega
self.w = wavefunction
self.s = system
self.analytical = analytical
... | the_stack_v2_python_sparse | src/Hamiltonian/non_interaction.py | KariEriksen/VMC | train | 6 |
dd8ff6b113ba73124fabb702071ca88b414023ce | [
"for cabin in self._preprocessedData:\n self._initializeCabinMapping()\n self._mapCabin(cabin)\n self._processedData.append(self._currentCabinMapping)",
"self._currentCabinMapping = []\nfor i in range(9):\n self._currentCabinMapping.append(0.0)",
"if not type(cabin) == str:\n self._currentCabinMa... | <|body_start_0|>
for cabin in self._preprocessedData:
self._initializeCabinMapping()
self._mapCabin(cabin)
self._processedData.append(self._currentCabinMapping)
<|end_body_0|>
<|body_start_1|>
self._currentCabinMapping = []
for i in range(9):
self... | This processed data builder looks through the cabins for each passenger and maps them into different cabin bins. | CabinClassifierBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CabinClassifierBuilder:
"""This processed data builder looks through the cabins for each passenger and maps them into different cabin bins."""
def _buildProcessedData(self) -> None:
"""Goes through all of the cabins for each passenger and categorizes them into seperate bins"""
... | stack_v2_sparse_classes_75kplus_train_005014 | 1,690 | no_license | [
{
"docstring": "Goes through all of the cabins for each passenger and categorizes them into seperate bins",
"name": "_buildProcessedData",
"signature": "def _buildProcessedData(self) -> None"
},
{
"docstring": "Initializes a passengers mapping with 9 bins.",
"name": "_initializeCabinMapping"... | 3 | stack_v2_sparse_classes_30k_train_006687 | Implement the Python class `CabinClassifierBuilder` described below.
Class description:
This processed data builder looks through the cabins for each passenger and maps them into different cabin bins.
Method signatures and docstrings:
- def _buildProcessedData(self) -> None: Goes through all of the cabins for each pa... | Implement the Python class `CabinClassifierBuilder` described below.
Class description:
This processed data builder looks through the cabins for each passenger and maps them into different cabin bins.
Method signatures and docstrings:
- def _buildProcessedData(self) -> None: Goes through all of the cabins for each pa... | fa6ea47d161d3217f7dee001ec77f57e372afde7 | <|skeleton|>
class CabinClassifierBuilder:
"""This processed data builder looks through the cabins for each passenger and maps them into different cabin bins."""
def _buildProcessedData(self) -> None:
"""Goes through all of the cabins for each passenger and categorizes them into seperate bins"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CabinClassifierBuilder:
"""This processed data builder looks through the cabins for each passenger and maps them into different cabin bins."""
def _buildProcessedData(self) -> None:
"""Goes through all of the cabins for each passenger and categorizes them into seperate bins"""
for cabin i... | the_stack_v2_python_sparse | datacategoryvisitors/processeddatabuilders/CabinClassifierBuilder.py | SPD3/TitanicML | train | 0 |
49df31bc59022886b597c8540e39da0cfa5a7eb5 | [
"inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])\nfor pretrained_model_name in GPT2Encoder.available_checkpoints():\n encoder = GPT2Encoder(pretrained_model_name=pretrained_model_name)\n _ = encoder(inputs)",
"inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])\nhparams = {'pretrained_mo... | <|body_start_0|>
inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
for pretrained_model_name in GPT2Encoder.available_checkpoints():
encoder = GPT2Encoder(pretrained_model_name=pretrained_model_name)
_ = encoder(inputs)
<|end_body_0|>
<|body_start_1|>
inputs = ... | Tests :class:`~texar.torch.modules.GPT2Encoder` class. | GPT2EncoderTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPT2EncoderTest:
"""Tests :class:`~texar.torch.modules.GPT2Encoder` class."""
def test_model_loading(self):
"""Tests model loading functionality."""
<|body_0|>
def test_hparams(self):
"""Tests the priority of the encoder arch parameter."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_005015 | 4,235 | permissive | [
{
"docstring": "Tests model loading functionality.",
"name": "test_model_loading",
"signature": "def test_model_loading(self)"
},
{
"docstring": "Tests the priority of the encoder arch parameter.",
"name": "test_hparams",
"signature": "def test_hparams(self)"
},
{
"docstring": "T... | 4 | null | Implement the Python class `GPT2EncoderTest` described below.
Class description:
Tests :class:`~texar.torch.modules.GPT2Encoder` class.
Method signatures and docstrings:
- def test_model_loading(self): Tests model loading functionality.
- def test_hparams(self): Tests the priority of the encoder arch parameter.
- def... | Implement the Python class `GPT2EncoderTest` described below.
Class description:
Tests :class:`~texar.torch.modules.GPT2Encoder` class.
Method signatures and docstrings:
- def test_model_loading(self): Tests model loading functionality.
- def test_hparams(self): Tests the priority of the encoder arch parameter.
- def... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class GPT2EncoderTest:
"""Tests :class:`~texar.torch.modules.GPT2Encoder` class."""
def test_model_loading(self):
"""Tests model loading functionality."""
<|body_0|>
def test_hparams(self):
"""Tests the priority of the encoder arch parameter."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPT2EncoderTest:
"""Tests :class:`~texar.torch.modules.GPT2Encoder` class."""
def test_model_loading(self):
"""Tests model loading functionality."""
inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
for pretrained_model_name in GPT2Encoder.available_checkpoints():
... | the_stack_v2_python_sparse | texar/tf/modules/encoders/gpt2_encoder_test.py | arita37/texar | train | 2 |
75b58288cdf1656448282d23ab7466480cd104a9 | [
"super().__init__()\nself.x = x\nself.y = y\nself.width = width\nself.height = height\nassert self.x >= 0\nassert self.y >= 0\nassert self.width > 0\nassert self.height > 0",
"if len(inputs.shape) >= 4:\n return inputs[:, self.y:self.y + self.height, self.x:self.x + self.width]\nelse:\n return inputs[self.y... | <|body_start_0|>
super().__init__()
self.x = x
self.y = y
self.width = width
self.height = height
assert self.x >= 0
assert self.y >= 0
assert self.width > 0
assert self.height > 0
<|end_body_0|>
<|body_start_1|>
if len(inputs.shape) >= 4:... | Crops one or more images to a new size without touching the color channel. | ImageCrop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCrop:
"""Crops one or more images to a new size without touching the color channel."""
def __init__(self, x=0, y=0, width=0, height=0):
"""Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width of resulting image. height (int): Height of resulting ima... | stack_v2_sparse_classes_75kplus_train_005016 | 1,949 | permissive | [
{
"docstring": "Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width of resulting image. height (int): Height of resulting image.",
"name": "__init__",
"signature": "def __init__(self, x=0, y=0, width=0, height=0)"
},
{
"docstring": "Images come in with either a bat... | 2 | stack_v2_sparse_classes_30k_train_029345 | Implement the Python class `ImageCrop` described below.
Class description:
Crops one or more images to a new size without touching the color channel.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, width=0, height=0): Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width ... | Implement the Python class `ImageCrop` described below.
Class description:
Crops one or more images to a new size without touching the color channel.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, width=0, height=0): Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width ... | 8abfb18538340d50146c9c44f5ecb8a1e7d89ac3 | <|skeleton|>
class ImageCrop:
"""Crops one or more images to a new size without touching the color channel."""
def __init__(self, x=0, y=0, width=0, height=0):
"""Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width of resulting image. height (int): Height of resulting ima... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageCrop:
"""Crops one or more images to a new size without touching the color channel."""
def __init__(self, x=0, y=0, width=0, height=0):
"""Args: x (int): Start x coordinate. y (int): Start y coordinate. width (int): Width of resulting image. height (int): Height of resulting image."""
... | the_stack_v2_python_sparse | surreal/components/preprocessors/image_crop.py | ducandu/surreal | train | 6 |
f4e473994e46fb10d7249745bb3d6571b3bec214 | [
"ans = []\nnums = [1] + nums + [1]\nfor i in range(1, len(nums) - 1):\n ans.append(reduce(lambda x, y: x * y, nums[:i]) * reduce(lambda x, y: x * y, nums[i + 1:]))\nreturn ans",
"tmp_val = 1\ntmp = [0] * len(nums)\nfor i in range(len(nums)):\n tmp[i] = tmp_val\n tmp_val *= nums[i]\ntmp_val = 1\nfor i in ... | <|body_start_0|>
ans = []
nums = [1] + nums + [1]
for i in range(1, len(nums) - 1):
ans.append(reduce(lambda x, y: x * y, nums[:i]) * reduce(lambda x, y: x * y, nums[i + 1:]))
return ans
<|end_body_0|>
<|body_start_1|>
tmp_val = 1
tmp = [0] * len(nums)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
num... | stack_v2_sparse_classes_75kplus_train_005017 | 1,054 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf1",
"signature": "def productExceptSelf1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008197 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solut... | 2c47abbf020f44c97e7e439735e4b0d49f3b843f | <|skeleton|>
class Solution:
def productExceptSelf1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def productExceptSelf1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
ans = []
nums = [1] + nums + [1]
for i in range(1, len(nums) - 1):
ans.append(reduce(lambda x, y: x * y, nums[:i]) * reduce(lambda x, y: x * y, nums[i + 1:]))
return ... | the_stack_v2_python_sparse | LeetCode/LeetCode238product-of-array-except-self.py | weiguangjiayou/LeetCode | train | 0 | |
5b5677823e8beac3918efe5391a5bab11c40f765 | [
"result = []\nfor n in nums:\n i = 0\n j = len(result) - 1\n while i <= j:\n m = i + (j - i) / 2\n if result[m] >= n:\n j = m - 1\n else:\n i = m + 1\n if i <= len(result) - 1:\n result[i] = n\n else:\n result.append(n)\nreturn len(result)",
... | <|body_start_0|>
result = []
for n in nums:
i = 0
j = len(result) - 1
while i <= j:
m = i + (j - i) / 2
if result[m] >= n:
j = m - 1
else:
i = m + 1
if i <= len(result)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rewrite(self, nums):
""":type nums: List[int] :rtype: int 概念很簡單... e.g: [9, 2, 5, 7, 4, 8, 1] [2] [2,5] [2,5,7] binary search for 4's location in array [2,4,7] [2,4,7,8] 最後l... | stack_v2_sparse_classes_75kplus_train_005018 | 2,289 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 概念很簡單... e.g: [9, 2, 5, 7, 4, 8, 1] [2] [2,5] [2,5,7] binary search for 4's location in array [2,4,7] [2,4,7,8] 最後len == 4, 內... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def rewrite(self, nums): :type nums: List[int] :rtype: int 概念很簡單... e.g: [9, 2, 5, 7, 4, 8, 1] [2] [2,5] [2,5,7] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def rewrite(self, nums): :type nums: List[int] :rtype: int 概念很簡單... e.g: [9, 2, 5, 7, 4, 8, 1] [2] [2,5] [2,5,7] ... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rewrite(self, nums):
""":type nums: List[int] :rtype: int 概念很簡單... e.g: [9, 2, 5, 7, 4, 8, 1] [2] [2,5] [2,5,7] binary search for 4's location in array [2,4,7] [2,4,7,8] 最後l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
result = []
for n in nums:
i = 0
j = len(result) - 1
while i <= j:
m = i + (j - i) / 2
if result[m] >= n:
j = m - 1
... | the_stack_v2_python_sparse | co_fb/300_Longest_Increasing_Subsequence.py | vsdrun/lc_public | train | 6 | |
f30002293ee00204ae238b21a688fe15c48ed755 | [
"try:\n num = float(data[0])\nexcept ValueError as verr:\n print(verr)\n num = -1.0\nif len(data) > 1:\n unit = data[1]\n metric += '_' + str(unit)\nreturn (metric, num)",
"line = line.split(':')\nmetric = line[0].strip()\ndata = line[1].strip()\nurl_pattern = re.compile(ALPHANUMERIC_URL_REGEX)\nif... | <|body_start_0|>
try:
num = float(data[0])
except ValueError as verr:
print(verr)
num = -1.0
if len(data) > 1:
unit = data[1]
metric += '_' + str(unit)
return (metric, num)
<|end_body_0|>
<|body_start_1|>
line = line.sp... | Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DONE WARNING: Got 39 HTTP codes differ... | DjangoWorkloadParser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_75kplus_train_005019 | 4,783 | permissive | [
{
"docstring": "Helper method to handle errors when extracting metrics and values",
"name": "parse_dw_data",
"signature": "def parse_dw_data(self, data, metric)"
},
{
"docstring": "Helper method to parse django-workload output into key-value data structure",
"name": "parse_dw_key_val",
"... | 3 | stack_v2_sparse_classes_30k_train_053797 | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | 70bc9fcb8dcc02c4ee70675c965c746fad7e4165 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DON... | the_stack_v2_python_sparse | benchpress/benchpress/plugins/parsers/django_workload.py | meteorfox/fbkutils | train | 1 |
931b3f07e292e7cc6f5c65dda8fdde15b2cbecd9 | [
"dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]\ndp[-1][-1] = True\nfor i in range(len(text), -1, -1):\n for j in range(len(pattern) - 1, -1, -1):\n first_match = i < len(text) and pattern[j] in {text[i], '.'}\n if j + 1 < len(pattern) and pattern[j + 1] == '*':\n dp[i... | <|body_start_0|>
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(text), -1, -1):
for j in range(len(pattern) - 1, -1, -1):
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j + 1 < le... | PatternMatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatternMatcher:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
<|body_0|>
def is_match_(self, text: str, pattern: str) -> bool:
"""Approach: Recursion Time C... | stack_v2_sparse_classes_75kplus_train_005020 | 2,030 | no_license | [
{
"docstring": "Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:",
"name": "is_match",
"signature": "def is_match(self, text: str, pattern: str) -> bool"
},
{
"docstring": "Approach: Recursion Time Complexity: O ((T + P) * 2 ^ (T + P / 2)) Space C... | 2 | null | Implement the Python class `PatternMatcher` described below.
Class description:
Implement the PatternMatcher class.
Method signatures and docstrings:
- def is_match(self, text: str, pattern: str) -> bool: Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:
- def is_match_... | Implement the Python class `PatternMatcher` described below.
Class description:
Implement the PatternMatcher class.
Method signatures and docstrings:
- def is_match(self, text: str, pattern: str) -> bool: Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:
- def is_match_... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class PatternMatcher:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
<|body_0|>
def is_match_(self, text: str, pattern: str) -> bool:
"""Approach: Recursion Time C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PatternMatcher:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: DP Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(te... | the_stack_v2_python_sparse | revisited/math_and_strings/recursion_memoization_dp/pattern_matcher.py | Shiv2157k/leet_code | train | 1 | |
c3089435f7e96487e70e2c8dad863d92354ad51a | [
"project_id = request.GET.get('project_id')\nif not project_id:\n return response_success(data=[])\nservices = Service.objects.filter(project_id=project_id)\nret = []\nfor item in services:\n ret.append(model_to_dict(item))\nreturn response_success(data=ret)",
"body = request.body\ndata = json.loads(body, e... | <|body_start_0|>
project_id = request.GET.get('project_id')
if not project_id:
return response_success(data=[])
services = Service.objects.filter(project_id=project_id)
ret = []
for item in services:
ret.append(model_to_dict(item))
return response_... | ServicesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesView:
def get(self, request, *args, **kwargs):
"""请求列表数据 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建数据 :param request: :param project_id: :param args: :param kwargs: :return:"""
<|... | stack_v2_sparse_classes_75kplus_train_005021 | 3,597 | no_license | [
{
"docstring": "请求列表数据 :param request: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "创建数据 :param request: :param project_id: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(sel... | 2 | null | Implement the Python class `ServicesView` described below.
Class description:
Implement the ServicesView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 请求列表数据 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建数据 :param request: :par... | Implement the Python class `ServicesView` described below.
Class description:
Implement the ServicesView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 请求列表数据 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建数据 :param request: :par... | a6692f26d4bba09386f25be1912ccff0efa0bcbf | <|skeleton|>
class ServicesView:
def get(self, request, *args, **kwargs):
"""请求列表数据 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建数据 :param request: :param project_id: :param args: :param kwargs: :return:"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServicesView:
def get(self, request, *args, **kwargs):
"""请求列表数据 :param request: :param args: :param kwargs: :return:"""
project_id = request.GET.get('project_id')
if not project_id:
return response_success(data=[])
services = Service.objects.filter(project_id=proje... | the_stack_v2_python_sparse | itest_project/itest_backend/interface_app/views/service_views.py | harter123/test-dev4 | train | 2 | |
1c76306cbac0863ca58f76cdcc76a9c657d3fa4a | [
"super(Embedding, self).__init__()\nif len(counts) == 0:\n raise RuntimeError('Embedding must take input' + 'from at least 1 group')\nself.layer1 = nn.ModuleDict()\nfor k, v in counts.items():\n self.layer1[k] = stack_layers(v, layers=1, dropout=0.0, norm=norm)\nnum = sum(counts.values())\nself.layer2 = stack... | <|body_start_0|>
super(Embedding, self).__init__()
if len(counts) == 0:
raise RuntimeError('Embedding must take input' + 'from at least 1 group')
self.layer1 = nn.ModuleDict()
for k, v in counts.items():
self.layer1[k] = stack_layers(v, layers=1, dropout=0.0, norm... | Embedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict() with a superset... | stack_v2_sparse_classes_75kplus_train_005022 | 5,028 | permissive | [
{
"docstring": ":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization.",
"name": "__init__",
"signature": "def __init__(self, counts, dropout=None, norm=None)"
},
{
"docstring": "x: OrderedDict() with a superset of the key... | 2 | stack_v2_sparse_classes_30k_train_050907 | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, counts, dropout=None, norm=None): :param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normaliza... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, counts, dropout=None, norm=None): :param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normaliza... | b40e9b147186ca04efd384d05b0f5e27ff8bd71a | <|skeleton|>
class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict() with a superset... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
super(Embedding, self).__init__()
if len(counts) == 0:
raise RuntimeError('... | the_stack_v2_python_sparse | nets/util.py | yuwei-cheng/eBay | train | 0 | |
405fc27566d56c6e592f71ad67922c9a689c624f | [
"\"\"\"\n s.reverse()\n \"\"\"\n'\\n s[:] = s[::-1]\\n '\nmid = int(len(s) / 2)\nj = len(s) - 1\nfor i in xrange(mid):\n s[i], s[j - i] = (s[j - i], s[i])",
"left = 0\nright = len(s) - 1\nwhile left < right:\n s[left], s[right] = (s[right], s[left])\n left += 1\n right -= 1... | <|body_start_0|>
"""
s.reverse()
"""
'\n s[:] = s[::-1]\n '
mid = int(len(s) / 2)
j = len(s) - 1
for i in xrange(mid):
s[i], s[j - i] = (s[j - i], s[i])
<|end_body_0|>
<|body_start_1|>
left = 0
right = len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseString(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|bo... | stack_v2_sparse_classes_75kplus_train_005023 | 753 | no_license | [
{
"docstring": ":type s: List[str] :rtype: None Do not return anything, modify s in-place instead.",
"name": "reverseString",
"signature": "def reverseString(self, s)"
},
{
"docstring": ":type s: List[str] :rtype: None Do not return anything, modify s in-place instead.",
"name": "reverseStri... | 2 | stack_v2_sparse_classes_30k_train_002308 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString(self, s): :type s: List[str] :rtype: None Do no... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString(self, s): :type s: List[str] :rtype: None Do no... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def reverseString(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseString(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
"""
s.reverse()
"""
'\n s[:] = s[::-1]\n '
mid = int(len(s) / 2)
j = len(s) - 1
for i in ... | the_stack_v2_python_sparse | 0344_Reverse_String.py | bingli8802/leetcode | train | 0 | |
af698f43b85cd87f2f13c10f3871ef86b32154de | [
"if model_format not in [XGBoostModelHandler.ModelFormats.PKL, XGBoostModelHandler.ModelFormats.JSON]:\n raise mlrun.errors.MLRunInvalidArgumentError(f\"Unrecognized model format: '{model_format}'. Please use one of the class members of 'TFKerasModelHandler.ModelFormats'\")\nif model_format == XGBoostModelHandle... | <|body_start_0|>
if model_format not in [XGBoostModelHandler.ModelFormats.PKL, XGBoostModelHandler.ModelFormats.JSON]:
raise mlrun.errors.MLRunInvalidArgumentError(f"Unrecognized model format: '{model_format}'. Please use one of the class members of 'TFKerasModelHandler.ModelFormats'")
if mo... | Class for handling a XGBoost model, enabling loading and saving it during runs. | XGBoostModelHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoostModelHandler:
"""Class for handling a XGBoost model, enabling loading and saving it during runs."""
def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_m... | stack_v2_sparse_classes_75kplus_train_005024 | 11,617 | permissive | [
{
"docstring": "Initialize the handler. The model can be set here so it won't require loading. Note you must provide at least one of 'model' and 'model_path'. If a model is not given, the files in the model path will be collected automatically to be ready for loading. :param model: Model to handle or None in ca... | 5 | stack_v2_sparse_classes_30k_test_002809 | Implement the Python class `XGBoostModelHandler` described below.
Class description:
Class for handling a XGBoost model, enabling loading and saving it during runs.
Method signatures and docstrings:
- def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union... | Implement the Python class `XGBoostModelHandler` described below.
Class description:
Class for handling a XGBoost model, enabling loading and saving it during runs.
Method signatures and docstrings:
- def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class XGBoostModelHandler:
"""Class for handling a XGBoost model, enabling loading and saving it during runs."""
def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XGBoostModelHandler:
"""Class for handling a XGBoost model, enabling loading and saving it during runs."""
def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_map: Union[Dic... | the_stack_v2_python_sparse | mlrun/frameworks/xgboost/model_handler.py | mlrun/mlrun | train | 1,093 |
db2c5312beb5bbae00b5c9b4ad44ef4c3c80e458 | [
"try:\n return User.objects.get(pk=pk)\nexcept Exception as e:\n print(e)\n raise Http404",
"response = self.serializer(data=request.data)\nif response.is_valid():\n user = self.get_object(response.data['user_id'])\n if user.is_superuser is True:\n return Response('editing of superuser passw... | <|body_start_0|>
try:
return User.objects.get(pk=pk)
except Exception as e:
print(e)
raise Http404
<|end_body_0|>
<|body_start_1|>
response = self.serializer(data=request.data)
if response.is_valid():
user = self.get_object(response.data['... | Modify User Password | UserModifyPasswordView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModifyPasswordView:
"""Modify User Password"""
def get_object(pk):
"""..."""
<|body_0|>
def post(self, request, format=None):
"""..."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return User.objects.get(pk=pk)
exce... | stack_v2_sparse_classes_75kplus_train_005025 | 4,540 | permissive | [
{
"docstring": "...",
"name": "get_object",
"signature": "def get_object(pk)"
},
{
"docstring": "...",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043797 | Implement the Python class `UserModifyPasswordView` described below.
Class description:
Modify User Password
Method signatures and docstrings:
- def get_object(pk): ...
- def post(self, request, format=None): ... | Implement the Python class `UserModifyPasswordView` described below.
Class description:
Modify User Password
Method signatures and docstrings:
- def get_object(pk): ...
- def post(self, request, format=None): ...
<|skeleton|>
class UserModifyPasswordView:
"""Modify User Password"""
def get_object(pk):
... | 9c7f82a3fdaa7a8f2f34062d8803b4f33f8c07b7 | <|skeleton|>
class UserModifyPasswordView:
"""Modify User Password"""
def get_object(pk):
"""..."""
<|body_0|>
def post(self, request, format=None):
"""..."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserModifyPasswordView:
"""Modify User Password"""
def get_object(pk):
"""..."""
try:
return User.objects.get(pk=pk)
except Exception as e:
print(e)
raise Http404
def post(self, request, format=None):
"""..."""
response = se... | the_stack_v2_python_sparse | apps/user/views/vuser.py | magocod/dj_chat | train | 2 |
c5c5c9e51526029c580e1690e6c14ca4d7f0583f | [
"Parameter.checkFloat(tau, 0.0, 1.0)\nParameter.checkClass(kernelX, AbstractKernel)\nParameter.checkClass(kernelY, AbstractKernel)\nself.kernelX = kernelX\nself.kernelY = kernelY\nself.tau = tau",
"self.trainX = X\nself.trainY = Y\nKx = self.kernelX.evaluate(X, X)\nKy = self.kernelX.evaluate(Y, Y)\nKxx = numpy.do... | <|body_start_0|>
Parameter.checkFloat(tau, 0.0, 1.0)
Parameter.checkClass(kernelX, AbstractKernel)
Parameter.checkClass(kernelY, AbstractKernel)
self.kernelX = kernelX
self.kernelY = kernelY
self.tau = tau
<|end_body_0|>
<|body_start_1|>
self.trainX = X
s... | KernelCCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelCCA:
def __init__(self, kernelX, kernelY, tau):
"""Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kern... | stack_v2_sparse_classes_75kplus_train_005026 | 3,998 | no_license | [
{
"docstring": "Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kernel object on the X examples. :type kernelX: :class:`apgl.kernel.A... | 3 | stack_v2_sparse_classes_30k_train_004488 | Implement the Python class `KernelCCA` described below.
Class description:
Implement the KernelCCA class.
Method signatures and docstrings:
- def __init__(self, kernelX, kernelY, tau): Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation... | Implement the Python class `KernelCCA` described below.
Class description:
Implement the KernelCCA class.
Method signatures and docstrings:
- def __init__(self, kernelX, kernelY, tau): Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation... | 1703510cbb51ec6df0efe1de850cd48ef7004b00 | <|skeleton|>
class KernelCCA:
def __init__(self, kernelX, kernelY, tau):
"""Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kern... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KernelCCA:
def __init__(self, kernelX, kernelY, tau):
"""Intialise the object with kernels (i.e an object instantiating a subclass of AbstractKernel) on the X and Y spaces and regularisation parameter tau between 0 (no regularisation) and 1 (full regularisation). :param kernelX: The kernel object on t... | the_stack_v2_python_sparse | apgl/features/KernelCCA.py | malcolmreynolds/APGL | train | 0 | |
2409e849af27cb337230bfc385f2e6aa0f365a4b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service to manage customer-manager links. | CustomerManagerLinkServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
<|body_0|>
def MutateCustomerManagerLink(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_005027 | 3,589 | permissive | [
{
"docstring": "Returns the requested CustomerManagerLink in full detail.",
"name": "GetCustomerManagerLink",
"signature": "def GetCustomerManagerLink(self, request, context)"
},
{
"docstring": "Creates or updates customer manager links. Operation statuses are returned.",
"name": "MutateCust... | 2 | stack_v2_sparse_classes_30k_train_008791 | Implement the Python class `CustomerManagerLinkServiceServicer` described below.
Class description:
Service to manage customer-manager links.
Method signatures and docstrings:
- def GetCustomerManagerLink(self, request, context): Returns the requested CustomerManagerLink in full detail.
- def MutateCustomerManagerLin... | Implement the Python class `CustomerManagerLinkServiceServicer` described below.
Class description:
Service to manage customer-manager links.
Method signatures and docstrings:
- def GetCustomerManagerLink(self, request, context): Returns the requested CustomerManagerLink in full detail.
- def MutateCustomerManagerLin... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
<|body_0|>
def MutateCustomerManagerLink(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not i... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/customer_manager_link_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
a971639ee4c72c0847f435f74049cb2b0709a276 | [
"ImageList.__init__(self, images=images)\nif volume_start_times is None:\n volume_start_times = 1.0\nv = np.asarray(volume_start_times)\nlength = len(self.list)\nif v.shape == (length,):\n self.volume_start_times = volume_start_times\nelse:\n v = float(volume_start_times)\n self.volume_start_times = np.... | <|body_start_0|>
ImageList.__init__(self, images=images)
if volume_start_times is None:
volume_start_times = 1.0
v = np.asarray(volume_start_times)
length = len(self.list)
if v.shape == (length,):
self.volume_start_times = volume_start_times
else:
... | Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times | FmriImageList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FmriImageList:
"""Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times"""
def __init__(self, images=None, volume_start_times=None, slice_times=None):
"""An implementation of an fMRI image as in ImageList Parameters ---------- ima... | stack_v2_sparse_classes_75kplus_train_005028 | 5,036 | permissive | [
{
"docstring": "An implementation of an fMRI image as in ImageList Parameters ---------- images : iterable an iterable object whose items are meant to be images; this is checked by asserting that each has a `coordmap` attribute and a ``get_data`` method. Note that Image objects are not iterable by default; use ... | 3 | stack_v2_sparse_classes_30k_train_050210 | Implement the Python class `FmriImageList` described below.
Class description:
Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times
Method signatures and docstrings:
- def __init__(self, images=None, volume_start_times=None, slice_times=None): An implementation o... | Implement the Python class `FmriImageList` described below.
Class description:
Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times
Method signatures and docstrings:
- def __init__(self, images=None, volume_start_times=None, slice_times=None): An implementation o... | 7eede02471567487e454016c1e7cf637d3afac9e | <|skeleton|>
class FmriImageList:
"""Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times"""
def __init__(self, images=None, volume_start_times=None, slice_times=None):
"""An implementation of an fMRI image as in ImageList Parameters ---------- ima... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FmriImageList:
"""Class to implement image list interface for FMRI time series Allows metadata such as volume and slice times"""
def __init__(self, images=None, volume_start_times=None, slice_times=None):
"""An implementation of an fMRI image as in ImageList Parameters ---------- images : iterabl... | the_stack_v2_python_sparse | nipy/modalities/fmri/fmri.py | nipy/nipy | train | 275 |
a99e01082e7363486613e11769d7c6e8355b79c7 | [
"self.idx_map = {}\nfor idx, num in enumerate(nums):\n if num:\n self.idx_map[idx] = num",
"res = 0\nfor idx, v1 in self.idx_map.items():\n v2 = vec.idx_map.get(idx)\n if v2:\n res += v1 * v2\nreturn res"
] | <|body_start_0|>
self.idx_map = {}
for idx, num in enumerate(nums):
if num:
self.idx_map[idx] = num
<|end_body_0|>
<|body_start_1|>
res = 0
for idx, v1 in self.idx_map.items():
v2 = vec.idx_map.get(idx)
if v2:
res += v1... | SparseVector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.idx_map = {}
for idx, num in enumerate(nu... | stack_v2_sparse_classes_75kplus_train_005029 | 855 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type vec: 'SparseVector' :rtype: int",
"name": "dotProduct",
"signature": "def dotProduct(self, vec)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045573 | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int
<|skeleton|>
class SparseVector:
def __init__(sel... | 546cbce06fcd4bc34e16d42b5d5eb68fb25e16a9 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
self.idx_map = {}
for idx, num in enumerate(nums):
if num:
self.idx_map[idx] = num
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
res = 0
... | the_stack_v2_python_sparse | leetcode/solution_1570.py | eselyavka/python | train | 0 | |
57826a9cc561ed5faa2e2148c12393c31903e184 | [
"real_k = k % len(nums)\ntarget = nums[-real_k:] + nums[:-real_k]\nnums[:] = target",
"real_k = k % len(nums)\ni = 0\nwhile i != real_k:\n nums.insert(0, nums.pop())\n i += 1"
] | <|body_start_0|>
real_k = k % len(nums)
target = nums[-real_k:] + nums[:-real_k]
nums[:] = target
<|end_body_0|>
<|body_start_1|>
real_k = k % len(nums)
i = 0
while i != real_k:
nums.insert(0, nums.pop())
i += 1
<|end_body_1|>
| Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate_pop(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modif... | stack_v2_sparse_classes_75kplus_train_005030 | 1,443 | permissive | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 2 | stack_v2_sparse_classes_30k_train_001023 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate_pop(self, nums, k): :type nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate_pop(self, nums, k): :type nums: List... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate_pop(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
real_k = k % len(nums)
target = nums[-real_k:] + nums[:-real_k]
nums[:] = target
def rotate_pop(self, nums, k):
""":type... | the_stack_v2_python_sparse | LeetCode/LC189_rotate_array.py | jxie0755/Learning_Python | train | 0 | |
c67213ddfa85e3440729abd428f1349451e6cb87 | [
"fake_users = []\nfor fake_email_and_name in base_test.FAKE_EMAILS_AND_NAMES:\n fake_user = models.User(email=fake_email_and_name['email'], name=fake_email_and_name['name'], is_key_revoked=False)\n fake_user.save()\n fake_users.append(fake_user)\nkey_string = key_distributor.KeyDistributor().make_key_strin... | <|body_start_0|>
fake_users = []
for fake_email_and_name in base_test.FAKE_EMAILS_AND_NAMES:
fake_user = models.User(email=fake_email_and_name['email'], name=fake_email_and_name['name'], is_key_revoked=False)
fake_user.save()
fake_users.append(fake_user)
key_s... | Test key distributor class functionality. | KeyDistributorTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyDistributorTest:
"""Test key distributor class functionality."""
def testUnrevokedUsersAreInKeyString(self):
"""Test unrevoked users are in key string.."""
<|body_0|>
def testRevokedUsersAreNotInKeyString(self):
"""Test revoked users are not in key string.."""... | stack_v2_sparse_classes_75kplus_train_005031 | 1,644 | permissive | [
{
"docstring": "Test unrevoked users are in key string..",
"name": "testUnrevokedUsersAreInKeyString",
"signature": "def testUnrevokedUsersAreInKeyString(self)"
},
{
"docstring": "Test revoked users are not in key string..",
"name": "testRevokedUsersAreNotInKeyString",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_015551 | Implement the Python class `KeyDistributorTest` described below.
Class description:
Test key distributor class functionality.
Method signatures and docstrings:
- def testUnrevokedUsersAreInKeyString(self): Test unrevoked users are in key string..
- def testRevokedUsersAreNotInKeyString(self): Test revoked users are n... | Implement the Python class `KeyDistributorTest` described below.
Class description:
Test key distributor class functionality.
Method signatures and docstrings:
- def testUnrevokedUsersAreInKeyString(self): Test unrevoked users are in key string..
- def testRevokedUsersAreNotInKeyString(self): Test revoked users are n... | a9efb83cfa3a5aa26bf3c4012ca0ef99b6e67829 | <|skeleton|>
class KeyDistributorTest:
"""Test key distributor class functionality."""
def testUnrevokedUsersAreInKeyString(self):
"""Test unrevoked users are in key string.."""
<|body_0|>
def testRevokedUsersAreNotInKeyString(self):
"""Test revoked users are not in key string.."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyDistributorTest:
"""Test key distributor class functionality."""
def testUnrevokedUsersAreInKeyString(self):
"""Test unrevoked users are in key string.."""
fake_users = []
for fake_email_and_name in base_test.FAKE_EMAILS_AND_NAMES:
fake_user = models.User(email=fake... | the_stack_v2_python_sparse | ufo/services/key_distributor_test.py | UWNetworksLab/ufo-management-server-flask | train | 0 |
4288fa7532d098a3554ed69b536c8d502f0b6f9b | [
"flags.AddNodePoolNameArg(parser, 'The name of the node pool to delete.')\nparser.add_argument('--timeout', type=int, default=1800, hidden=True, help='THIS ARGUMENT NEEDS HELP TEXT.')\nflags.AddAsyncFlag(parser)\nflags.AddNodePoolClusterFlag(parser, 'The cluster from which to delete the node pool.')",
"adapter = ... | <|body_start_0|>
flags.AddNodePoolNameArg(parser, 'The name of the node pool to delete.')
parser.add_argument('--timeout', type=int, default=1800, hidden=True, help='THIS ARGUMENT NEEDS HELP TEXT.')
flags.AddAsyncFlag(parser)
flags.AddNodePoolClusterFlag(parser, 'The cluster from which t... | Delete an existing node pool in a running cluster. | Delete | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Delete:
"""Delete an existing node pool in a running cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_005032 | 3,844 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the... | 2 | stack_v2_sparse_classes_30k_train_023756 | Implement the Python class `Delete` described below.
Class description:
Delete an existing node pool in a running cluster.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information,... | Implement the Python class `Delete` described below.
Class description:
Delete an existing node pool in a running cluster.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information,... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Delete:
"""Delete an existing node pool in a running cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Delete:
"""Delete an existing node pool in a running cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
flags.AddNodePoolNameA... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/container/node_pools/delete.py | bopopescu/socialliteapp | train | 0 |
e0d84e9658e27354e27e9d5ebb95c1189e96565d | [
"names = super().valid_names()\nnames = names + [('sender_id', str, 0), ('receiver_id', str, 0), ('chat_id', str, 0)]\nreturn names",
"chats = Chat.find_all(sender_id=user_id)\nchats.extend(Chat.find_all(receiver_id=user_id))\nchats = sorted(chats, key=lambda chat: chat.updated_time, reverse=True)\nchat_ids = []\... | <|body_start_0|>
names = super().valid_names()
names = names + [('sender_id', str, 0), ('receiver_id', str, 0), ('chat_id', str, 0)]
return names
<|end_body_0|>
<|body_start_1|>
chats = Chat.find_all(sender_id=user_id)
chats.extend(Chat.find_all(receiver_id=user_id))
cha... | 保存对话数据的 model | Chat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chat:
"""保存对话数据的 model"""
def valid_names(cls):
"""代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中"""
<|body_0|>
def find_chat_ids(cls, user_id):
"""查找用户的所有 chat_id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
names = super().valid_names(... | stack_v2_sparse_classes_75kplus_train_005033 | 860 | no_license | [
{
"docstring": "代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中",
"name": "valid_names",
"signature": "def valid_names(cls)"
},
{
"docstring": "查找用户的所有 chat_id",
"name": "find_chat_ids",
"signature": "def find_chat_ids(cls, user_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026420 | Implement the Python class `Chat` described below.
Class description:
保存对话数据的 model
Method signatures and docstrings:
- def valid_names(cls): 代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中
- def find_chat_ids(cls, user_id): 查找用户的所有 chat_id | Implement the Python class `Chat` described below.
Class description:
保存对话数据的 model
Method signatures and docstrings:
- def valid_names(cls): 代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中
- def find_chat_ids(cls, user_id): 查找用户的所有 chat_id
<|skeleton|>
class Chat:
"""保存对话数据的 model"""
def valid_names(cl... | 9c54b0774038dde74de9e77e5b5152bec93f1614 | <|skeleton|>
class Chat:
"""保存对话数据的 model"""
def valid_names(cls):
"""代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中"""
<|body_0|>
def find_chat_ids(cls, user_id):
"""查找用户的所有 chat_id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chat:
"""保存对话数据的 model"""
def valid_names(cls):
"""代替 __init__ 函数,可以使 update 函数放到 models.__init__.py 中"""
names = super().valid_names()
names = names + [('sender_id', str, 0), ('receiver_id', str, 0), ('chat_id', str, 0)]
return names
def find_chat_ids(cls, user_id):
... | the_stack_v2_python_sparse | models/chat.py | snzhaoch/bbs | train | 5 |
0b7d751cda5ad44087fb4ea81df4e5ae16e54e4d | [
"super().__init__()\nself.args = args\nself.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits * 3))\nself.qai = quant_arc_interface",
"q_in = input_features\nq_in = q_in.to(self.args.device)\nq_out = torch.Tensor(0, self.args.target_class)\nq_out = q_out.to(self.args.d... | <|body_start_0|>
super().__init__()
self.args = args
self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits * 3))
self.qai = quant_arc_interface
<|end_body_0|>
<|body_start_1|>
q_in = input_features
q_in = q_in.to(self.args.de... | Torch module implementing the *dressed* quantum net. | apc_net | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class apc_net:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, args, quant_arc_interface):
"""Definition of the *dressed* layout."""
<|body_0|>
def forward(self, input_features):
"""Defining how tensors are supposed to move through the *dr... | stack_v2_sparse_classes_75kplus_train_005034 | 1,348 | permissive | [
{
"docstring": "Definition of the *dressed* layout.",
"name": "__init__",
"signature": "def __init__(self, args, quant_arc_interface)"
},
{
"docstring": "Defining how tensors are supposed to move through the *dressed* quantum net.",
"name": "forward",
"signature": "def forward(self, inpu... | 2 | null | Implement the Python class `apc_net` described below.
Class description:
Torch module implementing the *dressed* quantum net.
Method signatures and docstrings:
- def __init__(self, args, quant_arc_interface): Definition of the *dressed* layout.
- def forward(self, input_features): Defining how tensors are supposed to... | Implement the Python class `apc_net` described below.
Class description:
Torch module implementing the *dressed* quantum net.
Method signatures and docstrings:
- def __init__(self, args, quant_arc_interface): Definition of the *dressed* layout.
- def forward(self, input_features): Defining how tensors are supposed to... | 8126691b43bddc2b1a96f73ab35d04d1af200d7a | <|skeleton|>
class apc_net:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, args, quant_arc_interface):
"""Definition of the *dressed* layout."""
<|body_0|>
def forward(self, input_features):
"""Defining how tensors are supposed to move through the *dr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class apc_net:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, args, quant_arc_interface):
"""Definition of the *dressed* layout."""
super().__init__()
self.args = args
self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth *... | the_stack_v2_python_sparse | model/apc_layers.py | zzh237/quanthmc | train | 0 |
aa78ee743f438b9fdb7b1885c31c676cd25555ee | [
"self.accout = account\nself.passwod = password\nself.url = 'https://106.ihuyi.com/webservice/sms.php?method=Submit'",
"headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}\ndata = {'account': self.accout, 'password': self.passwod, 'mobile': mobile, 'content': content}\nresponse... | <|body_start_0|>
self.accout = account
self.passwod = password
self.url = 'https://106.ihuyi.com/webservice/sms.php?method=Submit'
<|end_body_0|>
<|body_start_1|>
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}
data = {'account': self.acco... | 短信发送功能 | SMS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMS:
"""短信发送功能"""
def __init__(self, account, password):
"""account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址"""
<|body_0|>
def send_sms(self, mobile, content):
"""发短信 :param mobile: 手机号 :param content: 短信内容 :return:Non... | stack_v2_sparse_classes_75kplus_train_005035 | 1,269 | no_license | [
{
"docstring": "account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址",
"name": "__init__",
"signature": "def __init__(self, account, password)"
},
{
"docstring": "发短信 :param mobile: 手机号 :param content: 短信内容 :return:None",
"name": "send_sms",
"sign... | 2 | null | Implement the Python class `SMS` described below.
Class description:
短信发送功能
Method signatures and docstrings:
- def __init__(self, account, password): account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址
- def send_sms(self, mobile, content): 发短信 :param mobile: 手机号 :param cont... | Implement the Python class `SMS` described below.
Class description:
短信发送功能
Method signatures and docstrings:
- def __init__(self, account, password): account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址
- def send_sms(self, mobile, content): 发短信 :param mobile: 手机号 :param cont... | 7dbd1bf705854c377da1a99243d8edd74751452b | <|skeleton|>
class SMS:
"""短信发送功能"""
def __init__(self, account, password):
"""account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址"""
<|body_0|>
def send_sms(self, mobile, content):
"""发短信 :param mobile: 手机号 :param content: 短信内容 :return:Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SMS:
"""短信发送功能"""
def __init__(self, account, password):
"""account:APIID(用户中心【验证码通知短信】-【产品纵览】查看) password:APIKEY(用户中心【验证码通知短信】-【产品纵览】查看) self.url:接口请求地址"""
self.accout = account
self.passwod = password
self.url = 'https://106.ihuyi.com/webservice/sms.php?method=Submit'
... | the_stack_v2_python_sparse | 发送邮箱/发送短信4.py | cooper-1/untitled1 | train | 0 |
440fa2c0cfcf6e5b4875dc700c31c61af8210bf7 | [
"context = super(LogInFormView, self).get_context_data(**kwargs)\ncontext['title'] = 'Login'\nreturn context",
"username = form.cleaned_data['username']\npassword = form.cleaned_data['password']\ncontext = self.get_context_data()\nuser = authenticate(self.request, username=username, password=password)\nif user is... | <|body_start_0|>
context = super(LogInFormView, self).get_context_data(**kwargs)
context['title'] = 'Login'
return context
<|end_body_0|>
<|body_start_1|>
username = form.cleaned_data['username']
password = form.cleaned_data['password']
context = self.get_context_data()
... | A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Logged in the user | LogInFormView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(... | stack_v2_sparse_classes_75kplus_train_005036 | 9,386 | no_license | [
{
"docstring": "Call the original method of the view and add the title on the context Parameters ---------- kwargs : str Some argument that Django are passing, need when call the original method of the view Returns ------- dict a dict of the context of the page",
"name": "get_context_data",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_050854 | Implement the Python class `LogInFormView` described below.
Class description:
A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): ... | Implement the Python class `LogInFormView` described below.
Class description:
A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): ... | 939245d046974fabf33fa540b4c3b6d077100ff5 | <|skeleton|>
class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Logged... | the_stack_v2_python_sparse | purebeurre/views/user.py | M0l42/P08_PureBeurre | train | 1 |
2ac8b8724f1cb05cd36103bdcee864b24f69ba14 | [
"download_path = user_download_dir(app_name='fake_download_dir_for_tests')\nself.assertIsNotNone(download_path)\nself.assertFalse(download_path.is_dir())\ndownload_path = user_download_dir(app_name='fake_download_dir_for_tests', ensure_exists=True)\nself.assertIsNotNone(download_path)\nself.assertTrue(download_path... | <|body_start_0|>
download_path = user_download_dir(app_name='fake_download_dir_for_tests')
self.assertIsNotNone(download_path)
self.assertFalse(download_path.is_dir())
download_path = user_download_dir(app_name='fake_download_dir_for_tests', ensure_exists=True)
self.assertIsNotNo... | Unit Tests of the user_dir() function and its derivatives on the Windows platform | UTestUserDirCommon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UTestUserDirCommon:
"""Unit Tests of the user_dir() function and its derivatives on the Windows platform"""
def test_n_user_download_dir(self) -> None:
"""Unit test of user_download_dir() in nominal cases"""
<|body_0|>
def test_d_user_dir(self) -> None:
"""Unit t... | stack_v2_sparse_classes_75kplus_train_005037 | 6,057 | permissive | [
{
"docstring": "Unit test of user_download_dir() in nominal cases",
"name": "test_n_user_download_dir",
"signature": "def test_n_user_download_dir(self) -> None"
},
{
"docstring": "Unit test of user_dir() in degraded cases",
"name": "test_d_user_dir",
"signature": "def test_d_user_dir(se... | 2 | null | Implement the Python class `UTestUserDirCommon` described below.
Class description:
Unit Tests of the user_dir() function and its derivatives on the Windows platform
Method signatures and docstrings:
- def test_n_user_download_dir(self) -> None: Unit test of user_download_dir() in nominal cases
- def test_d_user_dir(... | Implement the Python class `UTestUserDirCommon` described below.
Class description:
Unit Tests of the user_dir() function and its derivatives on the Windows platform
Method signatures and docstrings:
- def test_n_user_download_dir(self) -> None: Unit test of user_download_dir() in nominal cases
- def test_d_user_dir(... | 73266a1cb7ff49f0cb0da3615821c85ce974d733 | <|skeleton|>
class UTestUserDirCommon:
"""Unit Tests of the user_dir() function and its derivatives on the Windows platform"""
def test_n_user_download_dir(self) -> None:
"""Unit test of user_download_dir() in nominal cases"""
<|body_0|>
def test_d_user_dir(self) -> None:
"""Unit t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UTestUserDirCommon:
"""Unit Tests of the user_dir() function and its derivatives on the Windows platform"""
def test_n_user_download_dir(self) -> None:
"""Unit test of user_download_dir() in nominal cases"""
download_path = user_download_dir(app_name='fake_download_dir_for_tests')
... | the_stack_v2_python_sparse | resto_client_tests/tu/generic/utest_user_dirs.py | CNES/resto_client | train | 10 |
52c5e2c4087f40244dd3beac172b3d00beee0244 | [
"self.queue = deque([])\ncount = Counter(nums)\nself.judge = {}\nfor num in nums:\n self.queue.append(num)\n if count[num] == 1:\n self.judge[num] = True\n else:\n self.judge[num] = False",
"while self.queue and (not self.judge[self.queue[0]]):\n self.queue.popleft()\nif self.queue:\n ... | <|body_start_0|>
self.queue = deque([])
count = Counter(nums)
self.judge = {}
for num in nums:
self.queue.append(num)
if count[num] == 1:
self.judge[num] = True
else:
self.judge[num] = False
<|end_body_0|>
<|body_start_... | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
def __init__(self, nums: List[int]):
"""count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not in self.other: self.other[item] = True"""
<|body_0|>
def showFirstUnique(self) -> int:
... | stack_v2_sparse_classes_75kplus_train_005038 | 1,725 | no_license | [
{
"docstring": "count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not in self.other: self.other[item] = True",
"name": "__init__",
"signature": "def __init__(self, nums: List[int])"
},
{
"docstring": "if not self.un... | 3 | stack_v2_sparse_classes_30k_train_007709 | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums: List[int]): count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not ... | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums: List[int]): count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not ... | 90fd00246707b23d60a5d13b5a89d5b5f64ad008 | <|skeleton|>
class FirstUnique:
def __init__(self, nums: List[int]):
"""count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not in self.other: self.other[item] = True"""
<|body_0|>
def showFirstUnique(self) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirstUnique:
def __init__(self, nums: List[int]):
"""count = Counter(nums) self.unique = {} self.other = {} for item in nums: if count[item]==1: self.unique[item] = True else: if item not in self.other: self.other[item] = True"""
self.queue = deque([])
count = Counter(nums)
sel... | the_stack_v2_python_sparse | python_solution/1429.py | Dongzi-dq394/leetcode | train | 0 | |
c4fa359dc02ee1e76dae4bbb64b3451fa33ceb97 | [
"self.post_reqparser = reqparse.RequestParser()\nself.post_reqparser.add_argument('email', required=True, help='email is required', location=['form', 'json'])\nself.post_reqparser.add_argument('fullname', required=True, help='fullname is required', location=['form', 'json'])",
"args = self.post_reqparser.parse_ar... | <|body_start_0|>
self.post_reqparser = reqparse.RequestParser()
self.post_reqparser.add_argument('email', required=True, help='email is required', location=['form', 'json'])
self.post_reqparser.add_argument('fullname', required=True, help='fullname is required', location=['form', 'json'])
<|end_... | API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true or false :param email: users email address :param fullname: users fullname :type ... | ChangeUserName | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeUserName:
"""API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true or false :param email: users email addr... | stack_v2_sparse_classes_75kplus_train_005039 | 2,307 | permissive | [
{
"docstring": "Instanciates the Change users endpoint to change the users full name Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true or false :param email: users email address :param fullname: user... | 2 | stack_v2_sparse_classes_30k_train_018968 | Implement the Python class `ChangeUserName` described below.
Class description:
API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true ... | Implement the Python class `ChangeUserName` described below.
Class description:
API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true ... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class ChangeUserName:
"""API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true or false :param email: users email addr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeUserName:
"""API resource class which changes username and saves changes to the database Parameters can be passed using a POST request that contains a JSON with the following fields: :required: valid access JWT where the admin claim may be either true or false :param email: users email address :param fu... | the_stack_v2_python_sparse | Analytics/resources/admin/change_user_name.py | thanosbnt/SharingCitiesDashboard | train | 0 |
30040e46f6612422c1fc0ef6f18b770859b94e18 | [
"super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components)\nself.extract_hog_flag = extract_hog_flag\nself.type_cnn = type_cnn",
"if len(x.shape) != 3:\n raise DimensionalityError('DimensionalityError: Invalid shape for the \"x\" image data matrix! A shape {0} was provided, but admissible ... | <|body_start_0|>
super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components)
self.extract_hog_flag = extract_hog_flag
self.type_cnn = type_cnn
<|end_body_0|>
<|body_start_1|>
if len(x.shape) != 3:
raise DimensionalityError('DimensionalityError: Invalid sha... | Children Class of PreProcessor. Used to transform image data before training. | ImagePreProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the nump... | stack_v2_sparse_classes_75kplus_train_005040 | 17,079 | no_license | [
{
"docstring": "Constructor of the class. :param flatten_flag: (bool) whether to express the numpy array of data with shape [n_samples, n_features] :param n_pca_components: (int) number of principal components that will be computed from the data \"x\". Must be an integer between 2 and 3. :param type_cnn: (str) ... | 4 | stack_v2_sparse_classes_30k_train_000004 | Implement the Python class `ImagePreProcessor` described below.
Class description:
Children Class of PreProcessor. Used to transform image data before training.
Method signatures and docstrings:
- def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''): Constructor of the class... | Implement the Python class `ImagePreProcessor` described below.
Class description:
Children Class of PreProcessor. Used to transform image data before training.
Method signatures and docstrings:
- def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''): Constructor of the class... | c46f4b2ba7762420186cb710d2932adf00829d6f | <|skeleton|>
class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the nump... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the numpy array of da... | the_stack_v2_python_sparse | pre_processors.py | jonathand94/ML-Classifiers-Library | train | 0 |
93f01aee25788f991317e7da2fc6f56e36a504b7 | [
"UserModel = get_user_model()\nemail = self.cleaned_data['email']\ntry:\n user = UserModel.objects.get(email__iexact=email)\nexcept UserModel.DoesNotExist:\n raise forms.ValidationError(self.error_messages['unknown'])\nif not user.is_active:\n raise forms.ValidationError(self.error_messages['unknown'])\nif... | <|body_start_0|>
UserModel = get_user_model()
email = self.cleaned_data['email']
try:
user = UserModel.objects.get(email__iexact=email)
except UserModel.DoesNotExist:
raise forms.ValidationError(self.error_messages['unknown'])
if not user.is_active:
... | CircusPasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircusPasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, request=None, use_https=False, token_generator=default_token_generator, from_email=None, subject_template_... | stack_v2_sparse_classes_75kplus_train_005041 | 13,874 | no_license | [
{
"docstring": "Validates that an active user exists with the given email address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, d... | 2 | stack_v2_sparse_classes_30k_train_033143 | Implement the Python class `CircusPasswordResetForm` described below.
Class description:
Implement the CircusPasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, request=None, use_h... | Implement the Python class `CircusPasswordResetForm` described below.
Class description:
Implement the CircusPasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, request=None, use_h... | c47a6d36991e79b45437741034e147d6227e1f25 | <|skeleton|>
class CircusPasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, request=None, use_https=False, token_generator=default_token_generator, from_email=None, subject_template_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CircusPasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
UserModel = get_user_model()
email = self.cleaned_data['email']
try:
user = UserModel.objects.get(email__iexact=email)
except UserModel.D... | the_stack_v2_python_sparse | ViaDelivers/VTP/src/circus/accounts/forms.py | Kiranoneandonly/MyProjects | train | 0 | |
2a5bc61358de0197e95d4e0399229bb55b34b0af | [
"json_activity = json_data['activityType']\ntry:\n return Sport(json_activity['parentTypeId'])\nexcept ValueError:\n logger.info('Unknown sport type: %r', json_activity)\n raise",
"json_activity = json_data['activityTypeDTO']\ntry:\n return Sport(json_activity['parentTypeId'])\nexcept ValueError:\n ... | <|body_start_0|>
json_activity = json_data['activityType']
try:
return Sport(json_activity['parentTypeId'])
except ValueError:
logger.info('Unknown sport type: %r', json_activity)
raise
<|end_body_0|>
<|body_start_1|>
json_activity = json_data['activi... | Garmin Connect sport types enum. | Sport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sport:
"""Garmin Connect sport types enum."""
def from_json(cls, json_data):
"""Create a Sport enum instance from Garmin Connect JSON data."""
<|body_0|>
def from_details_json(cls, json_data):
"""Create a Sport enum instance from Garmin Connect JSON details data.... | stack_v2_sparse_classes_75kplus_train_005042 | 4,895 | no_license | [
{
"docstring": "Create a Sport enum instance from Garmin Connect JSON data.",
"name": "from_json",
"signature": "def from_json(cls, json_data)"
},
{
"docstring": "Create a Sport enum instance from Garmin Connect JSON details data.",
"name": "from_details_json",
"signature": "def from_det... | 4 | stack_v2_sparse_classes_30k_train_022088 | Implement the Python class `Sport` described below.
Class description:
Garmin Connect sport types enum.
Method signatures and docstrings:
- def from_json(cls, json_data): Create a Sport enum instance from Garmin Connect JSON data.
- def from_details_json(cls, json_data): Create a Sport enum instance from Garmin Conne... | Implement the Python class `Sport` described below.
Class description:
Garmin Connect sport types enum.
Method signatures and docstrings:
- def from_json(cls, json_data): Create a Sport enum instance from Garmin Connect JSON data.
- def from_details_json(cls, json_data): Create a Sport enum instance from Garmin Conne... | 754847ac819ed4597876673a4d10f423641f94cd | <|skeleton|>
class Sport:
"""Garmin Connect sport types enum."""
def from_json(cls, json_data):
"""Create a Sport enum instance from Garmin Connect JSON data."""
<|body_0|>
def from_details_json(cls, json_data):
"""Create a Sport enum instance from Garmin Connect JSON details data.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sport:
"""Garmin Connect sport types enum."""
def from_json(cls, json_data):
"""Create a Sport enum instance from Garmin Connect JSON data."""
json_activity = json_data['activityType']
try:
return Sport(json_activity['parentTypeId'])
except ValueError:
... | the_stack_v2_python_sparse | garmin_connect_enums.py | 8cH9azbsFifZ/GarminDB | train | 0 |
f95e2a4823853279716b486a957ff37e403fe942 | [
"for key, value in values.items():\n if 'addr' in key or 'rtt' in key:\n parts = key.split('_')\n if parts[2] == 'addr':\n if not self.hops.has_key(parts[1]):\n self.hops[int(parts[1])] = dict()\n self.hops[int(parts[1])][parts[3]] = value\n elif not self... | <|body_start_0|>
for key, value in values.items():
if 'addr' in key or 'rtt' in key:
parts = key.split('_')
if parts[2] == 'addr':
if not self.hops.has_key(parts[1]):
self.hops[int(parts[1])] = dict()
sel... | Encapsulates traceroute data and provides methods for analyzing it. | Traceroute | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Traceroute:
"""Encapsulates traceroute data and provides methods for analyzing it."""
def __init__(self, params, values):
"""Initializes the traceroute object with hops and latencies."""
<|body_0|>
def GetHTML(self):
"""Returns an HTML representation of this meas... | stack_v2_sparse_classes_75kplus_train_005043 | 3,113 | permissive | [
{
"docstring": "Initializes the traceroute object with hops and latencies.",
"name": "__init__",
"signature": "def __init__(self, params, values)"
},
{
"docstring": "Returns an HTML representation of this measurement.",
"name": "GetHTML",
"signature": "def GetHTML(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_028684 | Implement the Python class `Traceroute` described below.
Class description:
Encapsulates traceroute data and provides methods for analyzing it.
Method signatures and docstrings:
- def __init__(self, params, values): Initializes the traceroute object with hops and latencies.
- def GetHTML(self): Returns an HTML repres... | Implement the Python class `Traceroute` described below.
Class description:
Encapsulates traceroute data and provides methods for analyzing it.
Method signatures and docstrings:
- def __init__(self, params, values): Initializes the traceroute object with hops and latencies.
- def GetHTML(self): Returns an HTML repres... | 9277f9e0623eafe9a2f2cd387f3a2f0dfa9b94ba | <|skeleton|>
class Traceroute:
"""Encapsulates traceroute data and provides methods for analyzing it."""
def __init__(self, params, values):
"""Initializes the traceroute object with hops and latencies."""
<|body_0|>
def GetHTML(self):
"""Returns an HTML representation of this meas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Traceroute:
"""Encapsulates traceroute data and provides methods for analyzing it."""
def __init__(self, params, values):
"""Initializes the traceroute object with hops and latencies."""
for key, value in values.items():
if 'addr' in key or 'rtt' in key:
parts ... | the_stack_v2_python_sparse | server/gspeedometer/measurement/traceroute.py | Bugbustrs/bugb-mobiperf | train | 0 |
1723221b81208e85110d10a956dbfd8bceb694ba | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Query events by contract id or key. | EventQueryServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventQueryServiceServicer:
"""Query events by contract id or key."""
def GetEventsByContractId(self, request, context):
"""Get the create and the consuming exercise event for the contract with the provided ID. No events will be returned for contracts that have been pruned because the... | stack_v2_sparse_classes_75kplus_train_005044 | 5,706 | permissive | [
{
"docstring": "Get the create and the consuming exercise event for the contract with the provided ID. No events will be returned for contracts that have been pruned because they have already been archived before the latest pruning offset.",
"name": "GetEventsByContractId",
"signature": "def GetEventsBy... | 2 | stack_v2_sparse_classes_30k_train_040742 | Implement the Python class `EventQueryServiceServicer` described below.
Class description:
Query events by contract id or key.
Method signatures and docstrings:
- def GetEventsByContractId(self, request, context): Get the create and the consuming exercise event for the contract with the provided ID. No events will be... | Implement the Python class `EventQueryServiceServicer` described below.
Class description:
Query events by contract id or key.
Method signatures and docstrings:
- def GetEventsByContractId(self, request, context): Get the create and the consuming exercise event for the contract with the provided ID. No events will be... | efdbb00e54614c0af650d7440faaffbde92ad1f4 | <|skeleton|>
class EventQueryServiceServicer:
"""Query events by contract id or key."""
def GetEventsByContractId(self, request, context):
"""Get the create and the consuming exercise event for the contract with the provided ID. No events will be returned for contracts that have been pruned because the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventQueryServiceServicer:
"""Query events by contract id or key."""
def GetEventsByContractId(self, request, context):
"""Get the create and the consuming exercise event for the contract with the provided ID. No events will be returned for contracts that have been pruned because they have alread... | the_stack_v2_python_sparse | python/dazl/_gen/com/daml/ledger/api/v1/event_query_service_pb2_grpc.py | digital-asset/dazl-client | train | 12 |
70cc9038da7a77c90a7603d7adc5b9bf0f2d2a93 | [
"super().__init__(isonline=isonline)\nif self.isonline:\n self.devices['sofb'] = SOFB(SOFB.DEVICES.BO)\nself.model = ring if ring is not None else bo.create_accelerator()\nself.simul_model = sim_mod if sim_mod is not None else self.model[:]\ninjp = pyaccel.lattice.find_indices(self.model, 'fam_name', 'InjKckr')\... | <|body_start_0|>
super().__init__(isonline=isonline)
if self.isonline:
self.devices['sofb'] = SOFB(SOFB.DEVICES.BO)
self.model = ring if ring is not None else bo.create_accelerator()
self.simul_model = sim_mod if sim_mod is not None else self.model[:]
injp = pyaccel.l... | Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2.0e-3, 0.0e-3, 0.0e-3, 0.0, -0.01 >>> trajx, trajy, trajsum = fit_traj.simulate... | BOFitInjTraj | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BOFitInjTraj:
"""Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2.0e-3, 0.0e-3, 0.0e-3, 0.0, -0.01 >>> t... | stack_v2_sparse_classes_75kplus_train_005045 | 13,202 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, ring=None, sim_mod=None, isonline=True)"
},
{
"docstring": ".",
"name": "calc_init_vals",
"signature": "def calc_init_vals(self, trajx, trajy)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031442 | Implement the Python class `BOFitInjTraj` described below.
Class description:
Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2... | Implement the Python class `BOFitInjTraj` described below.
Class description:
Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class BOFitInjTraj:
"""Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2.0e-3, 0.0e-3, 0.0e-3, 0.0, -0.01 >>> t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BOFitInjTraj:
"""Fit injection trajectories in the Sirius booster. Examples: --------- >>> import numpy as np >>> from apsuite.commisslib.inj_traj_fitting import BOFitInjTraj >>> np.random.seed(42) >>> fit_traj = BOFitInjTraj() >>> x0, xl0, y0, yl0, de0 = -2.0e-3, 0.0e-3, 0.0e-3, 0.0, -0.01 >>> trajx, trajy, ... | the_stack_v2_python_sparse | apsuite/commisslib/inj_traj_fitting.py | lnls-fac/apsuite | train | 1 |
1cc0a83392147b06631e69d6a56a2ace7e36c513 | [
"res = super(OnHold, self).default_get(fields)\nticket_id = self.env.context.get('active_id') or self.env.context.get('default_ticket_id')\nif ticket_id:\n ticket = self.env['flspticketsystem.ticket'].browse(ticket_id)\nif ticket.exists():\n if 'ticket_id' in fields:\n res['ticket_id'] = ticket.id\nres... | <|body_start_0|>
res = super(OnHold, self).default_get(fields)
ticket_id = self.env.context.get('active_id') or self.env.context.get('default_ticket_id')
if ticket_id:
ticket = self.env['flspticketsystem.ticket'].browse(ticket_id)
if ticket.exists():
if 'ticket_id... | Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga | OnHold | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket mo... | stack_v2_sparse_classes_75kplus_train_005046 | 3,998 | no_license | [
{
"docstring": "Purpose: to get the default values from the ticket model and load in the wizard",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "Purpose: Button used in wizard put ticket onhold",
"name": "onhold",
"signature": "def onhold(self)"
... | 2 | stack_v2_sparse_classes_30k_train_023489 | Implement the Python class `OnHold` described below.
Class description:
Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga
Method signatures and docstrings:
- def default_get(self, field... | Implement the Python class `OnHold` described below.
Class description:
Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga
Method signatures and docstrings:
- def default_get(self, field... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket model and load ... | the_stack_v2_python_sparse | flsp_tktonhold/models/flsp_onhold.py | odoo-smg/firstlight | train | 3 |
afec23cc3de1e4c8bada1084c886fe75b9722626 | [
"super(DiceLoss, self).__init__()\nself.sum_kwargs = {}\nif dim is not None:\n self.sum_kwargs['dim'] = dim\nself.weight = weight",
"dice_loss = 1.0 - 2.0 * ((labels * predictions).sum(**self.sum_kwargs) / ((labels ** 2 + predictions ** 2).sum(**self.sum_kwargs) + EPS))\ndice_loss = self.weight * dice_loss.mea... | <|body_start_0|>
super(DiceLoss, self).__init__()
self.sum_kwargs = {}
if dim is not None:
self.sum_kwargs['dim'] = dim
self.weight = weight
<|end_body_0|>
<|body_start_1|>
dice_loss = 1.0 - 2.0 * ((labels * predictions).sum(**self.sum_kwargs) / ((labels ** 2 + predi... | Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. This version of the Dice loss supports multi-class segmentation (although in ... | DiceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceLoss:
"""Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. This version of the Dice loss supports mu... | stack_v2_sparse_classes_75kplus_train_005047 | 1,755 | permissive | [
{
"docstring": ":param weight: absolute weight of this loss :type weight: float <json> [ {\"name\": \"input_names\", \"type\": \"list:string\", \"value\": \"['predictions', 'labels']\"}, {\"name\": \"output_names\", \"type\": \"list:string\", \"value\": \"['dice_loss']\"}, {\"name\": \"weight\", \"type\": \"flo... | 2 | stack_v2_sparse_classes_30k_val_001888 | Implement the Python class `DiceLoss` described below.
Class description:
Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. Th... | Implement the Python class `DiceLoss` described below.
Class description:
Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. Th... | 02ab7dc4cc7e3e21fd48da2bc1a91ce474922804 | <|skeleton|>
class DiceLoss:
"""Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. This version of the Dice loss supports mu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiceLoss:
"""Dice loss is often used in segmentation tasks to optimize the overlap between the ground truth contour and the prediction. Dice loss is robust to class imbalance and therefore suitable to segment small foreground regions in images or volumes. This version of the Dice loss supports multi-class seg... | the_stack_v2_python_sparse | eisen/ops/losses/dice.py | canerozer/eisen-core | train | 0 |
121f45e7b0f0687e7f037da6eb5f71e7b6304bd7 | [
"self.N = N\nself.size = size\nself.cosmology_mass = cosmology_mass\nself.BC = boundaryCondition\nself.get_x0(set_x0)\nself.get_v0(v0_max, set_v0)\nself.get_m0(set_m0, soft)\nself.particles = np.asarray([ptcl(m, x[0], x[1], x[2], vx=v[0], vy=v[1], vz=v[2]) for m, x, v in zip(self.m, self.x, self.v)])",
"if self.B... | <|body_start_0|>
self.N = N
self.size = size
self.cosmology_mass = cosmology_mass
self.BC = boundaryCondition
self.get_x0(set_x0)
self.get_v0(v0_max, set_v0)
self.get_m0(set_m0, soft)
self.particles = np.asarray([ptcl(m, x[0], x[1], x[2], vx=v[0], vy=v[1],... | Nparticle_system | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nparticle_system:
def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosmology_mass=False):
"""Initialize a system of N particles with grid dimensions specified by 'size' Can specify initial values for mass, position and veloc... | stack_v2_sparse_classes_75kplus_train_005048 | 5,011 | no_license | [
{
"docstring": "Initialize a system of N particles with grid dimensions specified by 'size' Can specify initial values for mass, position and velocity",
"name": "__init__",
"signature": "def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosm... | 4 | stack_v2_sparse_classes_30k_train_009990 | Implement the Python class `Nparticle_system` described below.
Class description:
Implement the Nparticle_system class.
Method signatures and docstrings:
- def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosmology_mass=False): Initialize a system of N p... | Implement the Python class `Nparticle_system` described below.
Class description:
Implement the Nparticle_system class.
Method signatures and docstrings:
- def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosmology_mass=False): Initialize a system of N p... | 086e72fbebfa823edea5fe0be596a21c6da9104a | <|skeleton|>
class Nparticle_system:
def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosmology_mass=False):
"""Initialize a system of N particles with grid dimensions specified by 'size' Can specify initial values for mass, position and veloc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nparticle_system:
def __init__(self, N, size, set_m0, set_x0=None, set_v0=None, v0_max=1, boundaryCondition='Periodic', soft=None, cosmology_mass=False):
"""Initialize a system of N particles with grid dimensions specified by 'size' Can specify initial values for mass, position and velocity"""
... | the_stack_v2_python_sparse | Project/NBody_systemInitialize3D.py | nlefrancois6/Phys512 | train | 0 | |
1fe2be8d6cd1f3f58f203370110d6feff5382e1a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FollowupFlag()",
"from .date_time_time_zone import DateTimeTimeZone\nfrom .followup_flag_status import FollowupFlagStatus\nfrom .date_time_time_zone import DateTimeTimeZone\nfrom .followup_flag_status import FollowupFlagStatus\nfields:... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FollowupFlag()
<|end_body_0|>
<|body_start_1|>
from .date_time_time_zone import DateTimeTimeZone
from .followup_flag_status import FollowupFlagStatus
from .date_time_time_zone im... | FollowupFlag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_75kplus_train_005049 | 3,941 | 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: FollowupFlag",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_train_036643 | Implement the Python class `FollowupFlag` described below.
Class description:
Implement the FollowupFlag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `FollowupFlag` described below.
Class description:
Implement the FollowupFlag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""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: FollowupFlag""... | the_stack_v2_python_sparse | msgraph/generated/models/followup_flag.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
eb25d567e7d7e5cad66ecabbfd34512f96383a31 | [
"if root.val >= val:\n if root.left:\n self.insertIntoBST(root.left, val)\n else:\n node = TreeNode(val)\n root.left = node\nelif root.right:\n self.insertIntoBST(root.right, val)\nelse:\n node = TreeNode(val)\n root.right = node\nreturn root",
"if not root:\n return TreeNod... | <|body_start_0|>
if root.val >= val:
if root.left:
self.insertIntoBST(root.left, val)
else:
node = TreeNode(val)
root.left = node
elif root.right:
self.insertIntoBST(root.right, val)
else:
node = Tree... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _insertIntoBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def __insertIntoBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_1|>
def ___insertIntoBST(self, ro... | stack_v2_sparse_classes_75kplus_train_005050 | 4,559 | permissive | [
{
"docstring": ":type root: TreeNode :type val: int :rtype: TreeNode",
"name": "_insertIntoBST",
"signature": "def _insertIntoBST(self, root, val)"
},
{
"docstring": ":type root: TreeNode :type val: int :rtype: TreeNode",
"name": "__insertIntoBST",
"signature": "def __insertIntoBST(self,... | 5 | stack_v2_sparse_classes_30k_train_013226 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _insertIntoBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def __insertIntoBST(self, root, val): :type root: TreeNode :type val: int :rtype: Tree... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _insertIntoBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def __insertIntoBST(self, root, val): :type root: TreeNode :type val: int :rtype: Tree... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _insertIntoBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def __insertIntoBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_1|>
def ___insertIntoBST(self, ro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _insertIntoBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
if root.val >= val:
if root.left:
self.insertIntoBST(root.left, val)
else:
node = TreeNode(val)
root.left = node
... | the_stack_v2_python_sparse | 701.insert-into-a-binary-search-tree.py | windard/leeeeee | train | 0 | |
ec0fccfa0f216e1ea26ef1635305ad6550aa4de9 | [
"self.snow_sleet.data[1, 1] = np.nan\nmsg = 'The reference cube contains np.nan data'\nwith self.assertRaisesRegex(ValueError, msg):\n InterpolateUsingDifference()._check_inputs(self.sleet_rain, self.snow_sleet, None)",
"self.snow_sleet.units = 's'\nmsg = 'Reference cube and/or limit do not have units compatib... | <|body_start_0|>
self.snow_sleet.data[1, 1] = np.nan
msg = 'The reference cube contains np.nan data'
with self.assertRaisesRegex(ValueError, msg):
InterpolateUsingDifference()._check_inputs(self.sleet_rain, self.snow_sleet, None)
<|end_body_0|>
<|body_start_1|>
self.snow_sle... | Tests for the private _check_inputs method. | Test__check_inputs | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__check_inputs:
"""Tests for the private _check_inputs method."""
def test_incomplete_reference_data(self):
"""Test an exception is raised if the reference field is incomplete."""
<|body_0|>
def test_incompatible_reference_cube_units(self):
"""Test an excepti... | stack_v2_sparse_classes_75kplus_train_005051 | 12,269 | permissive | [
{
"docstring": "Test an exception is raised if the reference field is incomplete.",
"name": "test_incomplete_reference_data",
"signature": "def test_incomplete_reference_data(self)"
},
{
"docstring": "Test an exception is raised if the reference cube has units that are incompatible with the inpu... | 4 | stack_v2_sparse_classes_30k_test_002369 | Implement the Python class `Test__check_inputs` described below.
Class description:
Tests for the private _check_inputs method.
Method signatures and docstrings:
- def test_incomplete_reference_data(self): Test an exception is raised if the reference field is incomplete.
- def test_incompatible_reference_cube_units(s... | Implement the Python class `Test__check_inputs` described below.
Class description:
Tests for the private _check_inputs method.
Method signatures and docstrings:
- def test_incomplete_reference_data(self): Test an exception is raised if the reference field is incomplete.
- def test_incompatible_reference_cube_units(s... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__check_inputs:
"""Tests for the private _check_inputs method."""
def test_incomplete_reference_data(self):
"""Test an exception is raised if the reference field is incomplete."""
<|body_0|>
def test_incompatible_reference_cube_units(self):
"""Test an excepti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__check_inputs:
"""Tests for the private _check_inputs method."""
def test_incomplete_reference_data(self):
"""Test an exception is raised if the reference field is incomplete."""
self.snow_sleet.data[1, 1] = np.nan
msg = 'The reference cube contains np.nan data'
with ... | the_stack_v2_python_sparse | improver_tests/utilities/test_InterpolateUsingDifference.py | metoppv/improver | train | 101 |
a25d3fbb886a2ef59231bf913331dc98f1432946 | [
"if n == 0:\n return 0\nimport math\nfn = 0\nfor i in range(1, int(math.log(n, 5)) + 1):\n fn += int(n / 5 ** i)\nreturn fn",
"count = 0\nwhile n >= 5:\n n = n // 5\n count += n\nreturn count",
"if n == 0:\n return 0\nreturn n // 5 + self.trailingZeroes2(n // 5)"
] | <|body_start_0|>
if n == 0:
return 0
import math
fn = 0
for i in range(1, int(math.log(n, 5)) + 1):
fn += int(n / 5 ** i)
return fn
<|end_body_0|>
<|body_start_1|>
count = 0
while n >= 5:
n = n // 5
count += n
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trailingZeroes1_1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def trailingZeroes1_2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def trailingZeroes2(self, n):
""":type n: int :rtype: int"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_005052 | 1,251 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "trailingZeroes1_1",
"signature": "def trailingZeroes1_1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "trailingZeroes1_2",
"signature": "def trailingZeroes1_2(self, n)"
},
{
"docstring": ":type n: int :rtype: i... | 3 | stack_v2_sparse_classes_30k_test_002774 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trailingZeroes1_1(self, n): :type n: int :rtype: int
- def trailingZeroes1_2(self, n): :type n: int :rtype: int
- def trailingZeroes2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trailingZeroes1_1(self, n): :type n: int :rtype: int
- def trailingZeroes1_2(self, n): :type n: int :rtype: int
- def trailingZeroes2(self, n): :type n: int :rtype: int
<|sk... | 8dfbb10a87d8a3fdde466ab16fff8b67503e41f4 | <|skeleton|>
class Solution:
def trailingZeroes1_1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def trailingZeroes1_2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def trailingZeroes2(self, n):
""":type n: int :rtype: int"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def trailingZeroes1_1(self, n):
""":type n: int :rtype: int"""
if n == 0:
return 0
import math
fn = 0
for i in range(1, int(math.log(n, 5)) + 1):
fn += int(n / 5 ** i)
return fn
def trailingZeroes1_2(self, n):
""":t... | the_stack_v2_python_sparse | easy/0172.factorial-trailing-zeroes.py | codershenghai/PyLeetcode | train | 0 | |
f2e3089fd4f1179f25a16c39cadd49fb3d572b09 | [
"assert check_argument_types()\nsuper(StyleTokenLayer, self).__init__()\ngst_embs = paddle.randn(shape=[gst_tokens, gst_token_dim // gst_heads])\nself.gst_embs = paddle.create_parameter(shape=gst_embs.shape, dtype=str(gst_embs.numpy().dtype), default_initializer=paddle.nn.initializer.Assign(gst_embs))\nself.mha = M... | <|body_start_0|>
assert check_argument_types()
super(StyleTokenLayer, self).__init__()
gst_embs = paddle.randn(shape=[gst_tokens, gst_token_dim // gst_heads])
self.gst_embs = paddle.create_parameter(shape=gst_embs.shape, dtype=str(gst_embs.numpy().dtype), default_initializer=paddle.nn.in... | Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/1803.09017 Parameters ---... | StyleTokenLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleTokenLayer:
"""Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: http... | stack_v2_sparse_classes_75kplus_train_005053 | 10,798 | permissive | [
{
"docstring": "Initilize style token layer module.",
"name": "__init__",
"signature": "def __init__(self, ref_embed_dim: int=128, gst_tokens: int=10, gst_token_dim: int=256, gst_heads: int=4, dropout_rate: float=0.0)"
},
{
"docstring": "Calculate forward propagation. Parameters ---------- ref_e... | 2 | stack_v2_sparse_classes_30k_train_048076 | Implement the Python class `StyleTokenLayer` described below.
Class description:
Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfe... | Implement the Python class `StyleTokenLayer` described below.
Class description:
Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfe... | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | <|skeleton|>
class StyleTokenLayer:
"""Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: http... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StyleTokenLayer:
"""Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org... | the_stack_v2_python_sparse | parakeet/modules/style_encoder.py | PaddlePaddle/Parakeet | train | 609 |
4becf18393dc157d266e77c022864c96567ad973 | [
"super(CenterLineAtYAxis, self).__init__(dim)\nself.output_size = output_size\nself.output_spacing = output_spacing",
"if self.dim == 2:\n return self.get_2d(**kwargs)\nelif self.dim == 3:\n return self.get_3d(**kwargs)",
"input_image = kwargs.get('image')\nline = kwargs.get('line')\noutput_size = kwargs.... | <|body_start_0|>
super(CenterLineAtYAxis, self).__init__(dim)
self.output_size = output_size
self.output_spacing = output_spacing
<|end_body_0|>
<|body_start_1|>
if self.dim == 2:
return self.get_2d(**kwargs)
elif self.dim == 3:
return self.get_3d(**kwarg... | A composite transformation that centers a given line at the y axis. Used in the bone generators. | CenterLineAtYAxis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterLineAtYAxis:
"""A composite transformation that centers a given line at the y axis. Used in the bone generators."""
def __init__(self, dim, output_size, output_spacing):
"""Initializer. :param dim: The dimension. :param output_size: The output image size in pixels. :param outpu... | stack_v2_sparse_classes_75kplus_train_005054 | 7,141 | no_license | [
{
"docstring": "Initializer. :param dim: The dimension. :param output_size: The output image size in pixels. :param output_spacing: The output image spacing in mm.",
"name": "__init__",
"signature": "def __init__(self, dim, output_size, output_spacing)"
},
{
"docstring": "Returns the sitk transf... | 4 | stack_v2_sparse_classes_30k_train_020149 | Implement the Python class `CenterLineAtYAxis` described below.
Class description:
A composite transformation that centers a given line at the y axis. Used in the bone generators.
Method signatures and docstrings:
- def __init__(self, dim, output_size, output_spacing): Initializer. :param dim: The dimension. :param o... | Implement the Python class `CenterLineAtYAxis` described below.
Class description:
A composite transformation that centers a given line at the y axis. Used in the bone generators.
Method signatures and docstrings:
- def __init__(self, dim, output_size, output_spacing): Initializer. :param dim: The dimension. :param o... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class CenterLineAtYAxis:
"""A composite transformation that centers a given line at the y axis. Used in the bone generators."""
def __init__(self, dim, output_size, output_spacing):
"""Initializer. :param dim: The dimension. :param output_size: The output image size in pixels. :param outpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterLineAtYAxis:
"""A composite transformation that centers a given line at the y axis. Used in the bone generators."""
def __init__(self, dim, output_size, output_spacing):
"""Initializer. :param dim: The dimension. :param output_size: The output image size in pixels. :param output_spacing: Th... | the_stack_v2_python_sparse | transformations/spatial/center_line_at_y_axis.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
423fc8ed9a661f05ac89e88953c37e34b867b3de | [
"color_generator = getsvgcolors()\nwork_list = load_work()\ngoals = set()\nfor work in work_list:\n if work.category not in ('snowball',):\n continue\n if not hasattr(work, '_meta'):\n continue\n goal = str(work._meta[0]['goal'])\n goals.add(goal)\nfor goal in sorted(goals):\n color, te... | <|body_start_0|>
color_generator = getsvgcolors()
work_list = load_work()
goals = set()
for work in work_list:
if work.category not in ('snowball',):
continue
if not hasattr(work, '_meta'):
continue
goal = str(work._meta... | GoalGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalGraph:
def create_widgets(self):
"""Creates custom categories"""
<|body_0|>
def work_key(self, work):
"""Returns work goal"""
<|body_1|>
def filter_work(self, work):
"""Filters work"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005055 | 8,363 | no_license | [
{
"docstring": "Creates custom categories",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "Returns work goal",
"name": "work_key",
"signature": "def work_key(self, work)"
},
{
"docstring": "Filters work",
"name": "filter_work",
"signa... | 3 | stack_v2_sparse_classes_30k_train_027163 | Implement the Python class `GoalGraph` described below.
Class description:
Implement the GoalGraph class.
Method signatures and docstrings:
- def create_widgets(self): Creates custom categories
- def work_key(self, work): Returns work goal
- def filter_work(self, work): Filters work | Implement the Python class `GoalGraph` described below.
Class description:
Implement the GoalGraph class.
Method signatures and docstrings:
- def create_widgets(self): Creates custom categories
- def work_key(self, work): Returns work goal
- def filter_work(self, work): Filters work
<|skeleton|>
class GoalGraph:
... | 92997453631f31d7f751861feb9f0d0c76af54d3 | <|skeleton|>
class GoalGraph:
def create_widgets(self):
"""Creates custom categories"""
<|body_0|>
def work_key(self, work):
"""Returns work goal"""
<|body_1|>
def filter_work(self, work):
"""Filters work"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoalGraph:
def create_widgets(self):
"""Creates custom categories"""
color_generator = getsvgcolors()
work_list = load_work()
goals = set()
for work in work_list:
if work.category not in ('snowball',):
continue
if not hasattr(work... | the_stack_v2_python_sparse | notebooks/graph.py | dew-uff/scripts-provenance | train | 1 | |
5f7486ea44e0fdc3586570fe9e60b7dfff53a45f | [
"page = BaiduSearchPage(browser)\npage.search_input('pytest')\npage.search_button()\npage.sleep(1)\ntitle = page.search_title()\nassert title == 'pytest_百度搜索'",
"page = BaiduSearchPage(browser)\npage.search_input(search_key)\npage.search_button()\npage.sleep(2)\ntitle = page.search_title()\nassert title == search... | <|body_start_0|>
page = BaiduSearchPage(browser)
page.search_input('pytest')
page.search_button()
page.sleep(1)
title = page.search_title()
assert title == 'pytest_百度搜索'
<|end_body_0|>
<|body_start_1|>
page = BaiduSearchPage(browser)
page.search_input(sea... | TestSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
<|body_0|>
def test_baidu_search(self, name, search_key, browser):
"""百度搜索 --参数化"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
page = BaiduSearchPage(browser)
page.se... | stack_v2_sparse_classes_75kplus_train_005056 | 1,494 | no_license | [
{
"docstring": "百度搜索:pytest",
"name": "test_baidu_search_case",
"signature": "def test_baidu_search_case(self, browser)"
},
{
"docstring": "百度搜索 --参数化",
"name": "test_baidu_search",
"signature": "def test_baidu_search(self, name, search_key, browser)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043350 | Implement the Python class `TestSearch` described below.
Class description:
Implement the TestSearch class.
Method signatures and docstrings:
- def test_baidu_search_case(self, browser): 百度搜索:pytest
- def test_baidu_search(self, name, search_key, browser): 百度搜索 --参数化 | Implement the Python class `TestSearch` described below.
Class description:
Implement the TestSearch class.
Method signatures and docstrings:
- def test_baidu_search_case(self, browser): 百度搜索:pytest
- def test_baidu_search(self, name, search_key, browser): 百度搜索 --参数化
<|skeleton|>
class TestSearch:
def test_baid... | b3a532d33ddeb8d01fff315bcd59b451befdef23 | <|skeleton|>
class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
<|body_0|>
def test_baidu_search(self, name, search_key, browser):
"""百度搜索 --参数化"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
page = BaiduSearchPage(browser)
page.search_input('pytest')
page.search_button()
page.sleep(1)
title = page.search_title()
assert title == 'pytest_百度搜索'
def test_baidu_search(s... | the_stack_v2_python_sparse | pyautoTest-master(ICF-7.5.0)/test_case/1test_baidu_search.py | lizhuoya1111/Automated_testing_practice | train | 0 | |
a1efa930d7eb420cdb7f493b2a6c912c5ab42ca8 | [
"super(ApplicationCreateForm, self).__init__(*args, **kwargs)\nfor field in self.fields.values():\n field.error_messages = {'required': '{fieldname} は必須です。'.format(fieldname=field.label)}\n field.widget.attrs['class'] = 'form-control'",
"desired_game_title = self.cleaned_data['desired_game_title']\nif len(d... | <|body_start_0|>
super(ApplicationCreateForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.error_messages = {'required': '{fieldname} は必須です。'.format(fieldname=field.label)}
field.widget.attrs['class'] = 'form-control'
<|end_body_0|>
<|body_start_1|>
... | チームへのリクエストを作成するフォーム。 | ApplicationCreateForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationCreateForm:
"""チームへのリクエストを作成するフォーム。"""
def __init__(self, *args, **kwargs):
"""一括でエラーメッセージを設定する。"""
<|body_0|>
def clean_desired_game_title(self):
"""希望タイトルの選択上限を1つに設定する。"""
<|body_1|>
def clean_desired_job(self):
"""希望枠の選択上限を1つに設定... | stack_v2_sparse_classes_75kplus_train_005057 | 3,179 | no_license | [
{
"docstring": "一括でエラーメッセージを設定する。",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "希望タイトルの選択上限を1つに設定する。",
"name": "clean_desired_game_title",
"signature": "def clean_desired_game_title(self)"
},
{
"docstring": "希望枠の選択上限を1つに設定する。",
"n... | 3 | null | Implement the Python class `ApplicationCreateForm` described below.
Class description:
チームへのリクエストを作成するフォーム。
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 一括でエラーメッセージを設定する。
- def clean_desired_game_title(self): 希望タイトルの選択上限を1つに設定する。
- def clean_desired_job(self): 希望枠の選択上限を1つに設定する。 | Implement the Python class `ApplicationCreateForm` described below.
Class description:
チームへのリクエストを作成するフォーム。
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 一括でエラーメッセージを設定する。
- def clean_desired_game_title(self): 希望タイトルの選択上限を1つに設定する。
- def clean_desired_job(self): 希望枠の選択上限を1つに設定する。
<|skeleton... | 4f1b92b64e63f9d040ea8865b56423da3ec87f5f | <|skeleton|>
class ApplicationCreateForm:
"""チームへのリクエストを作成するフォーム。"""
def __init__(self, *args, **kwargs):
"""一括でエラーメッセージを設定する。"""
<|body_0|>
def clean_desired_game_title(self):
"""希望タイトルの選択上限を1つに設定する。"""
<|body_1|>
def clean_desired_job(self):
"""希望枠の選択上限を1つに設定... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationCreateForm:
"""チームへのリクエストを作成するフォーム。"""
def __init__(self, *args, **kwargs):
"""一括でエラーメッセージを設定する。"""
super(ApplicationCreateForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.error_messages = {'required': '{fieldname} は必須です。'.forma... | the_stack_v2_python_sparse | app/teams/forms/application.py | SHOU6439/CrowdGamers | train | 0 |
782735a0835dd1b5af0b782932155f727ddd16af | [
"processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid='2016091200490210', app_notify_url='http://115.159.122.64:8000/alipay/return/', app_private_key_path=private_key_path, alipay_public_key_path=ali_pub_key_path... | <|body_start_0|>
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid='2016091200490210', app_notify_url='http://115.159.122.64:8000/alipay/return/', app_private_key_path=private_k... | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
<|body_0|>
def post(self, request):
"""Handling Alipay's notify_url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processed_dict = {}
for key, value in request.GET... | stack_v2_sparse_classes_75kplus_train_005058 | 7,420 | no_license | [
{
"docstring": "Handle Alipay's return_url return",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Handling Alipay's notify_url",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016533 | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): Handle Alipay's return_url return
- def post(self, request): Handling Alipay's notify_url | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): Handle Alipay's return_url return
- def post(self, request): Handling Alipay's notify_url
<|skeleton|>
class AlipayView:
def get(self, request):... | 97f48a2a117a52d21143a440e546e2d894ba9244 | <|skeleton|>
class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
<|body_0|>
def post(self, request):
"""Handling Alipay's notify_url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid='2016091200490210', app_notify_ur... | the_stack_v2_python_sparse | apps/orders/views.py | muskanmahajan37/agrowdev_api | train | 0 | |
32df3bfadb7e6c1b4aa092aef6d630b3bff76edf | [
"self.user = user\nself.request_data = request_data\nself.update_response = {'Category': {}, 'Bookmark': {}, 'Page': {}, 'User': {}, 'Design': {}}\nself.delete_response = {'Category': [], 'Bookmark': [], 'Page': []}\nself.delete_category_id_list = [category_id for category_id, _ in self.request_data['Category']['de... | <|body_start_0|>
self.user = user
self.request_data = request_data
self.update_response = {'Category': {}, 'Bookmark': {}, 'Page': {}, 'User': {}, 'Design': {}}
self.delete_response = {'Category': [], 'Bookmark': [], 'Page': []}
self.delete_category_id_list = [category_id for cat... | APIManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIManager:
def __init__(self, user, request_data):
"""初期設定"""
<|body_0|>
def run_sync(self):
"""同期実行 # 追加や更新、削除などで重複データがあれば解消させる(優先順位: 削除 > 更新 > 追加)"""
<|body_1|>
def delete_duplicate_date(self, request_data):
"""重複しているデータを消す"""
<|body_2... | stack_v2_sparse_classes_75kplus_train_005059 | 3,271 | no_license | [
{
"docstring": "初期設定",
"name": "__init__",
"signature": "def __init__(self, user, request_data)"
},
{
"docstring": "同期実行 # 追加や更新、削除などで重複データがあれば解消させる(優先順位: 削除 > 更新 > 追加)",
"name": "run_sync",
"signature": "def run_sync(self)"
},
{
"docstring": "重複しているデータを消す",
"name": "delete_d... | 3 | null | Implement the Python class `APIManager` described below.
Class description:
Implement the APIManager class.
Method signatures and docstrings:
- def __init__(self, user, request_data): 初期設定
- def run_sync(self): 同期実行 # 追加や更新、削除などで重複データがあれば解消させる(優先順位: 削除 > 更新 > 追加)
- def delete_duplicate_date(self, request_data): 重複してい... | Implement the Python class `APIManager` described below.
Class description:
Implement the APIManager class.
Method signatures and docstrings:
- def __init__(self, user, request_data): 初期設定
- def run_sync(self): 同期実行 # 追加や更新、削除などで重複データがあれば解消させる(優先順位: 削除 > 更新 > 追加)
- def delete_duplicate_date(self, request_data): 重複してい... | d70a0c21858e5d37a3cf3fca81b69ea7f73af661 | <|skeleton|>
class APIManager:
def __init__(self, user, request_data):
"""初期設定"""
<|body_0|>
def run_sync(self):
"""同期実行 # 追加や更新、削除などで重複データがあれば解消させる(優先順位: 削除 > 更新 > 追加)"""
<|body_1|>
def delete_duplicate_date(self, request_data):
"""重複しているデータを消す"""
<|body_2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIManager:
def __init__(self, user, request_data):
"""初期設定"""
self.user = user
self.request_data = request_data
self.update_response = {'Category': {}, 'Bookmark': {}, 'Page': {}, 'User': {}, 'Design': {}}
self.delete_response = {'Category': [], 'Bookmark': [], 'Page':... | the_stack_v2_python_sparse | application/module/client_api/api/manager.py | fujimisakari/otherbu | train | 0 | |
f3f5b9e62ee52e27b31c4f82c13e3e6d12c299c6 | [
"self.env = env\nself.writer = writer\nself.max_ep_len = max_ep_len\nself.action = target_action\nself.da = env.action_space.shape[0]",
"ep_ret_list = list()\nfor _ in tqdm(range(100), desc='testing model'):\n s, d, ep_ret, ep_len = (self.env.reset(), False, 0, 0)\n while not (d or ep_len == self.max_ep_len... | <|body_start_0|>
self.env = env
self.writer = writer
self.max_ep_len = max_ep_len
self.action = target_action
self.da = env.action_space.shape[0]
<|end_body_0|>
<|body_start_1|>
ep_ret_list = list()
for _ in tqdm(range(100), desc='testing model'):
s, ... | Encapsulates function to test trained model in separate environment. | TestAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAgent:
"""Encapsulates function to test trained model in separate environment."""
def __init__(self, env, writer, max_ep_len, target_action):
"""Initializes testing agent. @param env: Open AI gym environment @param writer: SummaryWriter from tensorboard for logging @param max_ep_... | stack_v2_sparse_classes_75kplus_train_005060 | 6,328 | no_license | [
{
"docstring": "Initializes testing agent. @param env: Open AI gym environment @param writer: SummaryWriter from tensorboard for logging @param max_ep_len: maximum length of episode while testing @param target_action: encapsulated model function to perform actions for evaluation",
"name": "__init__",
"s... | 2 | stack_v2_sparse_classes_30k_train_022407 | Implement the Python class `TestAgent` described below.
Class description:
Encapsulates function to test trained model in separate environment.
Method signatures and docstrings:
- def __init__(self, env, writer, max_ep_len, target_action): Initializes testing agent. @param env: Open AI gym environment @param writer: ... | Implement the Python class `TestAgent` described below.
Class description:
Encapsulates function to test trained model in separate environment.
Method signatures and docstrings:
- def __init__(self, env, writer, max_ep_len, target_action): Initializes testing agent. @param env: Open AI gym environment @param writer: ... | 24f8f66682d122bcccf38db1c8ade07c89a639b6 | <|skeleton|>
class TestAgent:
"""Encapsulates function to test trained model in separate environment."""
def __init__(self, env, writer, max_ep_len, target_action):
"""Initializes testing agent. @param env: Open AI gym environment @param writer: SummaryWriter from tensorboard for logging @param max_ep_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAgent:
"""Encapsulates function to test trained model in separate environment."""
def __init__(self, env, writer, max_ep_len, target_action):
"""Initializes testing agent. @param env: Open AI gym environment @param writer: SummaryWriter from tensorboard for logging @param max_ep_len: maximum ... | the_stack_v2_python_sparse | mpo/core/helper_fn.py | freiberg-roman/mpo | train | 0 |
ac51b2379658b61ddb28ff94b5e0a10996c385dc | [
"self.id = id\nself.name = name\nself.customer_number = customer_number\nself.mva_number = mva_number\nself.company_phone = company_phone\nself.company_email = company_email\nself.company_url = company_url\nself.onboarding = onboarding\nself.additional_properties = additional_properties",
"if dictionary is None:\... | <|body_start_0|>
self.id = id
self.name = name
self.customer_number = customer_number
self.mva_number = mva_number
self.company_phone = company_phone
self.company_email = company_email
self.company_url = company_url
self.onboarding = onboarding
sel... | Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string): TODO: type description here. company_phone (string): TODO: type descrip... | Dealer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dealer:
"""Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string): TODO: type description here. company_... | stack_v2_sparse_classes_75kplus_train_005061 | 3,682 | permissive | [
{
"docstring": "Constructor for the Dealer class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, customer_number=None, mva_number=None, company_phone=None, company_email=None, company_url=None, onboarding=None, additional_properties={})"
},
{
"docstring": "Creates an i... | 2 | stack_v2_sparse_classes_30k_train_036169 | Implement the Python class `Dealer` described below.
Class description:
Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string)... | Implement the Python class `Dealer` described below.
Class description:
Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string)... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Dealer:
"""Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string): TODO: type description here. company_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dealer:
"""Implementation of the 'Dealer' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. name (string): TODO: type description here. customer_number (int): TODO: type description here. mva_number (string): TODO: type description here. company_phone (string... | the_stack_v2_python_sparse | idfy_rest_client/models/dealer.py | dealflowteam/Idfy | train | 0 |
6024dceec80014bea850cd9fc3715568c37530bf | [
"dic = dict()\nfor loc in range(len(intervals)):\n dic[loc] = intervals[loc]\nif len(intervals) <= 1:\n return intervals\ni = 0\nwhile True:\n one_interval = dic[i]\n if i >= len(intervals) - 1:\n break\n for j in range(i + 1, len(intervals)):\n two_interval = dic[j]\n if self.ch... | <|body_start_0|>
dic = dict()
for loc in range(len(intervals)):
dic[loc] = intervals[loc]
if len(intervals) <= 1:
return intervals
i = 0
while True:
one_interval = dic[i]
if i >= len(intervals) - 1:
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def check_two_interval_intersect(self, one, two):
"""尝试改进1: 改进这个函数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dic = dict()
f... | stack_v2_sparse_classes_75kplus_train_005062 | 1,943 | no_license | [
{
"docstring": ":type intervals: List[List[int]] :rtype: List[List[int]]",
"name": "merge",
"signature": "def merge(self, intervals)"
},
{
"docstring": "尝试改进1: 改进这个函数",
"name": "check_two_interval_intersect",
"signature": "def check_two_interval_intersect(self, one, two)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]
- def check_two_interval_intersect(self, one, two): 尝试改进1: 改进这个函数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[List[int]] :rtype: List[List[int]]
- def check_two_interval_intersect(self, one, two): 尝试改进1: 改进这个函数
<|skeleton|>
class Solutio... | f1a3930c571a6d062208ee1c1aadfe93a5684c40 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def check_two_interval_intersect(self, one, two):
"""尝试改进1: 改进这个函数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge(self, intervals):
""":type intervals: List[List[int]] :rtype: List[List[int]]"""
dic = dict()
for loc in range(len(intervals)):
dic[loc] = intervals[loc]
if len(intervals) <= 1:
return intervals
i = 0
while True:
... | the_stack_v2_python_sparse | solution/problem 19.py | Fay321/leetcode-exercise | train | 0 | |
8221e0d4d952aa7fe98ede580172dfef7f89c456 | [
"super(CNN, self).__init__()\nself.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(... | <|body_start_0|>
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_si... | CNN. | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels... | stack_v2_sparse_classes_75kplus_train_005063 | 6,668 | no_license | [
{
"docstring": "CNN Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006697 | Implement the Python class `CNN` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward. | Implement the Python class `CNN` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward.
<|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, ... | c41fee1dd4d86f152748590887f7e4d0a95c89c8 | <|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size... | the_stack_v2_python_sparse | core/cifar10_net.py | zero-one-loss/scd_github | train | 1 |
d4bb48a59e901403ec1aab75b8983dac7f391fdb | [
"self.src = src\nself.exe = exe\nself.cond = cond\nself.dest = dest\nself.mode = mode\nself.optional = optional\nself.strip = strip\nself.blacklist = self.DEFAULT_BLACKLIST\nif blacklist is not None:\n self.blacklist += tuple(blacklist)",
"for pattern in self.blacklist:\n if re.match(pattern, path):\n ... | <|body_start_0|>
self.src = src
self.exe = exe
self.cond = cond
self.dest = dest
self.mode = mode
self.optional = optional
self.strip = strip
self.blacklist = self.DEFAULT_BLACKLIST
if blacklist is not None:
self.blacklist += tuple(blac... | Represents an artifact to be copied from build dir to staging dir. | Path | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Path:
"""Represents an artifact to be copied from build dir to staging dir."""
def __init__(self, src, exe=False, cond=None, dest=None, mode=None, optional=False, strip=True, blacklist=None):
"""Initializes the object. Args: src: The relative path of the artifact. Can be a file or a ... | stack_v2_sparse_classes_75kplus_train_005064 | 16,433 | permissive | [
{
"docstring": "Initializes the object. Args: src: The relative path of the artifact. Can be a file or a directory. Can be a glob pattern. exe: Identifes the path as either being an executable or containing executables. Executables may be stripped during copy, and have special permissions set. We currently only... | 3 | stack_v2_sparse_classes_30k_train_027583 | Implement the Python class `Path` described below.
Class description:
Represents an artifact to be copied from build dir to staging dir.
Method signatures and docstrings:
- def __init__(self, src, exe=False, cond=None, dest=None, mode=None, optional=False, strip=True, blacklist=None): Initializes the object. Args: sr... | Implement the Python class `Path` described below.
Class description:
Represents an artifact to be copied from build dir to staging dir.
Method signatures and docstrings:
- def __init__(self, src, exe=False, cond=None, dest=None, mode=None, optional=False, strip=True, blacklist=None): Initializes the object. Args: sr... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class Path:
"""Represents an artifact to be copied from build dir to staging dir."""
def __init__(self, src, exe=False, cond=None, dest=None, mode=None, optional=False, strip=True, blacklist=None):
"""Initializes the object. Args: src: The relative path of the artifact. Can be a file or a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Path:
"""Represents an artifact to be copied from build dir to staging dir."""
def __init__(self, src, exe=False, cond=None, dest=None, mode=None, optional=False, strip=True, blacklist=None):
"""Initializes the object. Args: src: The relative path of the artifact. Can be a file or a directory. Ca... | the_stack_v2_python_sparse | third_party/chromite/lib/chrome_util.py | metux/chromium-suckless | train | 5 |
5503910e27f95c1467b63509bf58b58756f84fd0 | [
"super().__init__(augment_fn=affine_image_transform, keys=keys, grad=grad, **kwargs)\nself.matrix = matrix\nself.register_sampler('output_size', output_size)\nself.adjust_size = adjust_size\nself.interpolation_mode = interpolation_mode\nself.padding_mode = padding_mode\nself.align_corners = align_corners\nself.reve... | <|body_start_0|>
super().__init__(augment_fn=affine_image_transform, keys=keys, grad=grad, **kwargs)
self.matrix = matrix
self.register_sampler('output_size', output_size)
self.adjust_size = adjust_size
self.interpolation_mode = interpolation_mode
self.padding_mode = padd... | Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`. | Affine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Affine:
"""Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`."""
def __init__(self, matrix: Optional[Union[torch.Tensor, Sequence[Sequence[float]]]]=None, keys: Sequence=('data',), grad: bool... | stack_v2_sparse_classes_75kplus_train_005065 | 32,610 | permissive | [
{
"docstring": "Args: matrix: if given, overwrites the parameters for :attr:`scale`, :attr:rotation` and :attr:`translation`. Should be a matrix of shape [(BATCHSIZE,) NDIM, NDIM(+1)] This matrix represents the whole transformation matrix keys: keys which should be augmented grad: enable gradient computation in... | 5 | stack_v2_sparse_classes_30k_train_019778 | Implement the Python class `Affine` described below.
Class description:
Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`.
Method signatures and docstrings:
- def __init__(self, matrix: Optional[Union[torch.Tensor, Se... | Implement the Python class `Affine` described below.
Class description:
Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`.
Method signatures and docstrings:
- def __init__(self, matrix: Optional[Union[torch.Tensor, Se... | ab6fbcfe7215c2a5b8e401b70909f6a32d0d167b | <|skeleton|>
class Affine:
"""Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`."""
def __init__(self, matrix: Optional[Union[torch.Tensor, Sequence[Sequence[float]]]]=None, keys: Sequence=('data',), grad: bool... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Affine:
"""Class Performing an Affine Transformation on a given sample dict. The transformation will be applied to all the dict-entries specified in :attr:`keys`."""
def __init__(self, matrix: Optional[Union[torch.Tensor, Sequence[Sequence[float]]]]=None, keys: Sequence=('data',), grad: bool=False, outpu... | the_stack_v2_python_sparse | rising/transforms/affine.py | PhoenixDL/rising | train | 318 |
71b830cd732ddb7ee23f8c634cd1bf878856036e | [
"self.name = name\nself.content = c_list\nself.father = f\nself.child = c\nself.pwd = '%s/%s/' % (self.father.name, self.name)\nfor item in self.content:\n if isinstance(item, Folder):\n mk_dir(item.name)\n else:\n mk_file(item)",
"try:\n self.content = self.content.extend(s_list)\nexcept V... | <|body_start_0|>
self.name = name
self.content = c_list
self.father = f
self.child = c
self.pwd = '%s/%s/' % (self.father.name, self.name)
for item in self.content:
if isinstance(item, Folder):
mk_dir(item.name)
else:
... | Folder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Folder:
def __init__(self, name, c_list=[], f=None, c=None):
"""The constrcutor method for creating new Folder object. We will add the basic information data here."""
<|body_0|>
def add_content(self, s_list):
"""This is a public method for adding new content in the c... | stack_v2_sparse_classes_75kplus_train_005066 | 1,908 | no_license | [
{
"docstring": "The constrcutor method for creating new Folder object. We will add the basic information data here.",
"name": "__init__",
"signature": "def __init__(self, name, c_list=[], f=None, c=None)"
},
{
"docstring": "This is a public method for adding new content in the current folder obj... | 4 | stack_v2_sparse_classes_30k_train_042520 | Implement the Python class `Folder` described below.
Class description:
Implement the Folder class.
Method signatures and docstrings:
- def __init__(self, name, c_list=[], f=None, c=None): The constrcutor method for creating new Folder object. We will add the basic information data here.
- def add_content(self, s_lis... | Implement the Python class `Folder` described below.
Class description:
Implement the Folder class.
Method signatures and docstrings:
- def __init__(self, name, c_list=[], f=None, c=None): The constrcutor method for creating new Folder object. We will add the basic information data here.
- def add_content(self, s_lis... | 056e1ee50e2534df35ff3ff5d9a813ab89207209 | <|skeleton|>
class Folder:
def __init__(self, name, c_list=[], f=None, c=None):
"""The constrcutor method for creating new Folder object. We will add the basic information data here."""
<|body_0|>
def add_content(self, s_list):
"""This is a public method for adding new content in the c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Folder:
def __init__(self, name, c_list=[], f=None, c=None):
"""The constrcutor method for creating new Folder object. We will add the basic information data here."""
self.name = name
self.content = c_list
self.father = f
self.child = c
self.pwd = '%s/%s/' % (se... | the_stack_v2_python_sparse | Head_First/folder.py | macnc/PythonL | train | 0 | |
c07584d731116917c651a973040025ecdb7ddc50 | [
"super(AttnDecoderRNN, self).__init__()\nself.hidden_size = hidden_size\nself.output_voc_size = output_voc_size\nself.dropout_p = dropout_p\nself.max_length = max_length\nself.encoder_bidirectional = encoder_bidirectional\nself.embedding = nn.Embedding(self.output_voc_size, self.hidden_size)\nif self.encoder_bidire... | <|body_start_0|>
super(AttnDecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.output_voc_size = output_voc_size
self.dropout_p = dropout_p
self.max_length = max_length
self.encoder_bidirectional = encoder_bidirectional
self.embedding = nn.Embedding(s... | GRU Attention Decoder for Encoder-Decoder. | AttnDecoderRNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttnDecoderRNN:
"""GRU Attention Decoder for Encoder-Decoder."""
def __init__(self, hidden_size, output_voc_size, dropout_p=0.1, max_length=10, encoder_bidirectional=True):
"""Initializes an Decoder network based on a Gated Recurrent Unit. :param hidden_size: length of embedding vect... | stack_v2_sparse_classes_75kplus_train_005067 | 7,831 | permissive | [
{
"docstring": "Initializes an Decoder network based on a Gated Recurrent Unit. :param hidden_size: length of embedding vectors. :param output_voc_size: size of the vocabulary set to be embedded by the Embedding layer. :param dropout_p: probability of an element to be zeroed for the Dropout layer. :param max_le... | 2 | stack_v2_sparse_classes_30k_train_022813 | Implement the Python class `AttnDecoderRNN` described below.
Class description:
GRU Attention Decoder for Encoder-Decoder.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_voc_size, dropout_p=0.1, max_length=10, encoder_bidirectional=True): Initializes an Decoder network based on a Gated Rec... | Implement the Python class `AttnDecoderRNN` described below.
Class description:
GRU Attention Decoder for Encoder-Decoder.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_voc_size, dropout_p=0.1, max_length=10, encoder_bidirectional=True): Initializes an Decoder network based on a Gated Rec... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class AttnDecoderRNN:
"""GRU Attention Decoder for Encoder-Decoder."""
def __init__(self, hidden_size, output_voc_size, dropout_p=0.1, max_length=10, encoder_bidirectional=True):
"""Initializes an Decoder network based on a Gated Recurrent Unit. :param hidden_size: length of embedding vect... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttnDecoderRNN:
"""GRU Attention Decoder for Encoder-Decoder."""
def __init__(self, hidden_size, output_voc_size, dropout_p=0.1, max_length=10, encoder_bidirectional=True):
"""Initializes an Decoder network based on a Gated Recurrent Unit. :param hidden_size: length of embedding vectors. :param o... | the_stack_v2_python_sparse | models/text2text/attn_decoder.py | aasseman/mi-prometheus | train | 0 |
a0554d2ddbd412dedde8bf2210634a9f14447df1 | [
"pre = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\nreturn pre",
"n_l1, n_l2 = (self.reverseList(l1), self.reverseList(l2))\ncarry = 0\ndummy = cur = ListNode(0)\nwhile n_l1 or n_l2:\n if not n_l1:\n val1 = 0\n else:\n val1 = n_l1.val\n ... | <|body_start_0|>
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
<|end_body_0|>
<|body_start_1|>
n_l1, n_l2 = (self.reverseList(l1), self.reverseList(l2))
carry = 0
dumm... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = None
... | stack_v2_sparse_classes_75kplus_train_005068 | 1,941 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049374 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>
class S... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def addTwoNumbers(self, l1, l2):
... | the_stack_v2_python_sparse | 剑指 Offer II 025. 链表中的两数相加.py | yangyuxiang1996/leetcode | train | 0 | |
83d8934243fca224c7e1a80afeeea578b846d601 | [
"self.random_init = cgmm is None\nself.obs = np.einsum('mft->fmt', obs)\nF, M, T = self.obs.shape\nlogger.info(f'CGMM instance: F = {F:d}, T = {T:}, M = {M}')\nif self.random_init:\n cg = CgDistribution()\n if gamma is None:\n Rs = np.einsum('...dt,...et->...de', self.obs, self.obs.conj()) / T\n ... | <|body_start_0|>
self.random_init = cgmm is None
self.obs = np.einsum('mft->fmt', obs)
F, M, T = self.obs.shape
logger.info(f'CGMM instance: F = {F:d}, T = {T:}, M = {M}')
if self.random_init:
cg = CgDistribution()
if gamma is None:
Rs = np... | Cgmm Trainer | CgmmTrainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
<|body_0|>
def train(self, num_epoches=20):
"""Train in EM progress"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_005069 | 16,663 | permissive | [
{
"docstring": "Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T",
"name": "__init__",
"signature": "def __init__(self, obs, gamma=None, cgmm=None)"
},
{
"docstring": "Train in EM progress",
"name": "train",
"signature": "def train(self, num_epoches=20)"
}... | 2 | stack_v2_sparse_classes_30k_train_021531 | Implement the Python class `CgmmTrainer` described below.
Class description:
Cgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, gamma=None, cgmm=None): Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T
- def train(self, num_epoches=20): Train in EM progress | Implement the Python class `CgmmTrainer` described below.
Class description:
Cgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, gamma=None, cgmm=None): Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T
- def train(self, num_epoches=20): Train in EM progress
<|skelet... | e9fd899c50e266e7101c41da646982c4d0777dce | <|skeleton|>
class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
<|body_0|>
def train(self, num_epoches=20):
"""Train in EM progress"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
self.random_init = cgmm is None
self.obs = np.einsum('mft->fmt', obs)
F, M, T = self.obs.shape
logge... | the_stack_v2_python_sparse | scripts/sptk/libs/cluster.py | JusperLee/setk | train | 1 |
5c2665991f1c6144cdf761f8368d2a5989c39c99 | [
"intervals.sort(key=lambda x: x.start)\nans = []\nfor i in range(len(intervals)):\n if ans == []:\n ans.append(intervals[i])\n else:\n currlen = len(ans)\n if ans[currlen - 1].start <= intervals[i].start <= ans[currlen - 1].end:\n ans[currlen - 1].end = max(ans[currlen - 1].end... | <|body_start_0|>
intervals.sort(key=lambda x: x.start)
ans = []
for i in range(len(intervals)):
if ans == []:
ans.append(intervals[i])
else:
currlen = len(ans)
if ans[currlen - 1].start <= intervals[i].start <= ans[currlen -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge_no_class(self, intervals, newInterval):
""":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_005070 | 1,941 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge",
"signature": "def merge(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]",
"name": "merge_no_class",
"signature": "def merge_no... | 2 | stack_v2_sparse_classes_30k_train_025125 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge_no_class(self, intervals, newInterval): :type intervals: List[Interval] :type newIn... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge_no_class(self, intervals, newInterval): :type intervals: List[Interval] :type newIn... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge_no_class(self, intervals, newInterval):
""":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
intervals.sort(key=lambda x: x.start)
ans = []
for i in range(len(intervals)):
if ans == []:
ans.append(intervals[i])
else:
... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00056.Merge Intervals.py | roger6blog/LeetCode | train | 0 | |
caff6b37710cb08ea0a0151ad5a56fe455425f81 | [
"payload = request.get_json(silent=True)\nif not payload:\n return response_builder(dict(message='Data for creation must be provided.', status='fail'), 400)\nresult, errors = new_activity_type_schema.load(payload)\nif errors:\n status_code = new_activity_type_schema.context.get('status_code')\n validation_... | <|body_start_0|>
payload = request.get_json(silent=True)
if not payload:
return response_builder(dict(message='Data for creation must be provided.', status='fail'), 400)
result, errors = new_activity_type_schema.load(payload)
if errors:
status_code = new_activity_... | Activity Categories Resource. | ActivityTypesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityTypesAPI:
"""Activity Categories Resource."""
def post(cls):
"""Create new activity type."""
<|body_0|>
def get(cls, act_types_id=None):
"""Get information on activity types."""
<|body_1|>
def put(cls, act_types_id=None):
"""Edit info... | stack_v2_sparse_classes_75kplus_train_005071 | 4,914 | permissive | [
{
"docstring": "Create new activity type.",
"name": "post",
"signature": "def post(cls)"
},
{
"docstring": "Get information on activity types.",
"name": "get",
"signature": "def get(cls, act_types_id=None)"
},
{
"docstring": "Edit information on an activity type.",
"name": "p... | 4 | null | Implement the Python class `ActivityTypesAPI` described below.
Class description:
Activity Categories Resource.
Method signatures and docstrings:
- def post(cls): Create new activity type.
- def get(cls, act_types_id=None): Get information on activity types.
- def put(cls, act_types_id=None): Edit information on an a... | Implement the Python class `ActivityTypesAPI` described below.
Class description:
Activity Categories Resource.
Method signatures and docstrings:
- def post(cls): Create new activity type.
- def get(cls, act_types_id=None): Get information on activity types.
- def put(cls, act_types_id=None): Edit information on an a... | 69842100d8d7c0b946fb328ddc6c8f88d777606d | <|skeleton|>
class ActivityTypesAPI:
"""Activity Categories Resource."""
def post(cls):
"""Create new activity type."""
<|body_0|>
def get(cls, act_types_id=None):
"""Get information on activity types."""
<|body_1|>
def put(cls, act_types_id=None):
"""Edit info... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivityTypesAPI:
"""Activity Categories Resource."""
def post(cls):
"""Create new activity type."""
payload = request.get_json(silent=True)
if not payload:
return response_builder(dict(message='Data for creation must be provided.', status='fail'), 400)
result,... | the_stack_v2_python_sparse | src/api/endpoints/activity_types.py | Gfreedoms/andela-societies-backend | train | 0 |
9461a8a93a2807855e754453b2e56f5c4c675e3f | [
"if ledger_api.identifier == EthereumApi.identifier:\n nonce = ledger_api.api.eth.getTransactionCount(from_address)\n instance = cls.get_instance(ledger_api, contract_address)\n function = instance.functions.approve\n intermediate = function(spender, amount)\n tx = intermediate.buildTransaction({'gas... | <|body_start_0|>
if ledger_api.identifier == EthereumApi.identifier:
nonce = ledger_api.api.eth.getTransactionCount(from_address)
instance = cls.get_instance(ledger_api, contract_address)
function = instance.functions.approve
intermediate = function(spender, amoun... | The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI. | FetERC20 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetERC20:
"""The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI."""
def get_approve_transaction(cls, ledger_api: LedgerApi, contract_address: Address, from_address: Address, spender: Address, amount: int, gas: int=0) -> JSONLike:
"""Get transaction... | stack_v2_sparse_classes_75kplus_train_005072 | 4,154 | permissive | [
{
"docstring": "Get transaction to approve oracle client contract transactions on behalf of sender. :param ledger_api: the ledger apis. :param contract_address: the contract address. :param from_address: the address of the approver. :param spender: the address approved to spend on behalf of sender. :param amoun... | 2 | null | Implement the Python class `FetERC20` described below.
Class description:
The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI.
Method signatures and docstrings:
- def get_approve_transaction(cls, ledger_api: LedgerApi, contract_address: Address, from_address: Address, spender: Addre... | Implement the Python class `FetERC20` described below.
Class description:
The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI.
Method signatures and docstrings:
- def get_approve_transaction(cls, ledger_api: LedgerApi, contract_address: Address, from_address: Address, spender: Addre... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class FetERC20:
"""The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI."""
def get_approve_transaction(cls, ledger_api: LedgerApi, contract_address: Address, from_address: Address, spender: Address, amount: int, gas: int=0) -> JSONLike:
"""Get transaction... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetERC20:
"""The FetERC20 contract class which acts as a bridge between AEA framework and ERC20 ABI."""
def get_approve_transaction(cls, ledger_api: LedgerApi, contract_address: Address, from_address: Address, spender: Address, amount: int, gas: int=0) -> JSONLike:
"""Get transaction to approve o... | the_stack_v2_python_sparse | packages/fetchai/contracts/fet_erc20/contract.py | fetchai/agents-aea | train | 192 |
20d04f2a54e9e137a224cfc8b67185b3a8f3bd45 | [
"self.finished = False\ntitle = 'Demo of textbox: Object with callback'\nmsg = 'This is a demo of the textbox set as an object with a callback, you can configure it and when you are finished, you run it.\\n\\nThere is a typo in it. Find and correct it.'\ntext_snippet = 'Hello'\nbox = textbox(msg, title, text_snippe... | <|body_start_0|>
self.finished = False
title = 'Demo of textbox: Object with callback'
msg = 'This is a demo of the textbox set as an object with a callback, you can configure it and when you are finished, you run it.\n\nThere is a typo in it. Find and correct it.'
text_snippet = 'Hello'... | Program that challenges the user to find a typo | Demo3 | [
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Demo3:
"""Program that challenges the user to find a typo"""
def __init__(self):
"""Set and run the program"""
<|body_0|>
def check_answer(self, box):
"""Callback from TextBox Parameters ---------- box: object object containing parameters and methods to communica... | stack_v2_sparse_classes_75kplus_train_005073 | 17,328 | permissive | [
{
"docstring": "Set and run the program",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Callback from TextBox Parameters ---------- box: object object containing parameters and methods to communicate with the ui Returns ------- nothing: its return is through the box ob... | 2 | null | Implement the Python class `Demo3` described below.
Class description:
Program that challenges the user to find a typo
Method signatures and docstrings:
- def __init__(self): Set and run the program
- def check_answer(self, box): Callback from TextBox Parameters ---------- box: object object containing parameters and... | Implement the Python class `Demo3` described below.
Class description:
Program that challenges the user to find a typo
Method signatures and docstrings:
- def __init__(self): Set and run the program
- def check_answer(self, box): Callback from TextBox Parameters ---------- box: object object containing parameters and... | 81948653565126bad5e8d17953aaa8744fa89d5f | <|skeleton|>
class Demo3:
"""Program that challenges the user to find a typo"""
def __init__(self):
"""Set and run the program"""
<|body_0|>
def check_answer(self, box):
"""Callback from TextBox Parameters ---------- box: object object containing parameters and methods to communica... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Demo3:
"""Program that challenges the user to find a typo"""
def __init__(self):
"""Set and run the program"""
self.finished = False
title = 'Demo of textbox: Object with callback'
msg = 'This is a demo of the textbox set as an object with a callback, you can configure it ... | the_stack_v2_python_sparse | easygui/boxes/text_box.py | robertlugg/easygui | train | 480 |
55a7236e91d68b4fea2ab75fa0ca764aeff6c166 | [
"self.audio_type = audio_type\nself.audio_format = audio_format\nif audio_type in SERIALIZABLE_AUDIO_TYPES:\n self.audio = raw_data if isinstance(raw_data, io.BytesIO) else io.BytesIO(raw_data)\n self.duration = read_duration(audio_type, self.audio)\nelse:\n self.audio = raw_data\n if self.audio_format ... | <|body_start_0|>
self.audio_type = audio_type
self.audio_format = audio_format
if audio_type in SERIALIZABLE_AUDIO_TYPES:
self.audio = raw_data if isinstance(raw_data, io.BytesIO) else io.BytesIO(raw_data)
self.duration = read_duration(audio_type, self.audio)
else... | Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample in seconds | Sample | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"CC-BY-SA-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sample:
"""Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample... | stack_v2_sparse_classes_75kplus_train_005074 | 15,981 | permissive | [
{
"docstring": "Creates a Sample from a raw audio representation. :param audio_type: Audio data representation type CSupported types: - AUDIO_TYPE_OPUS: Memory file representation (BytesIO) of Opus encoded audio wrapped by a custom container format (used in SDBs) - AUDIO_TYPE_WAV: Memory file representation (By... | 2 | stack_v2_sparse_classes_30k_train_001446 | Implement the Python class `Sample` described below.
Class description:
Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duratio... | Implement the Python class `Sample` described below.
Class description:
Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duratio... | 93c4a42c95cd610c76dbd98de480dbb21f484c31 | <|skeleton|>
class Sample:
"""Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sample:
"""Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample in seconds""... | the_stack_v2_python_sparse | galvasr2/align/audio.py | Ciroye/peoples-speech | train | 0 |
a5f316ca2e62f8b002a5126bf16d5b0c1ab04e80 | [
"self.lstm_size = lstm_size\nself.highway_layers = highway_layers\nsuper().__init__(input_shape, num_outputs, **kwargs)",
"self.model = tf.keras.Sequential()\nself.model.add(layers.Bidirectional(layers.LSTM(self.lstm_size), input_shape=self.input_shape, merge_mode='concat'))\nself.model.add(layers.Dropout(0.2))\n... | <|body_start_0|>
self.lstm_size = lstm_size
self.highway_layers = highway_layers
super().__init__(input_shape, num_outputs, **kwargs)
<|end_body_0|>
<|body_start_1|>
self.model = tf.keras.Sequential()
self.model.add(layers.Bidirectional(layers.LSTM(self.lstm_size), input_shape=s... | :param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.estimator.TFEstimatorBase` | HwyBLSTM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HwyBLSTM:
""":param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.estimator.TFEstimatorBase`"""
def __i... | stack_v2_sparse_classes_75kplus_train_005075 | 2,258 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, input_shape, num_outputs, lstm_size=128, highway_layers=6, **kwargs)"
},
{
"docstring": "Construct LSTM++ Model",
"name": "build_model",
"signature": "def build_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001777 | Implement the Python class `HwyBLSTM` described below.
Class description:
:param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.est... | Implement the Python class `HwyBLSTM` described below.
Class description:
:param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.est... | ace1a9fa5496f7176592eb706a458855352b801a | <|skeleton|>
class HwyBLSTM:
""":param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.estimator.TFEstimatorBase`"""
def __i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HwyBLSTM:
""":param input_shape: Shape of matrix that will be passed to model input :type input_shape: tuple :param num_outputs: Number of outputs the model has :type num_outputs: int :param kwargs: optional keyword arguments to pass to :class:`spiegelib.estimator.TFEstimatorBase`"""
def __init__(self, i... | the_stack_v2_python_sparse | src/spiegelib/estimator/hwy_blstm.py | turian/spiegelib | train | 2 |
80e130debf343b1ea7769e77323115739ddc4391 | [
"if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.T = dict()\nfor source in self.graph.iternodes():\n self.T[source] = dict()\n for target in self.graph.iternodes():\n self.T[source][target] = False\n self.T[source][source] = True",
"for step... | <|body_start_0|>
if not graph.is_directed():
raise ValueError('the graph is not directed')
self.graph = graph
self.T = dict()
for source in self.graph.iternodes():
self.T[source] = dict()
for target in self.graph.iternodes():
self.T[sou... | Based on the matrix multiplication, O(V**2 E) time. | TransitiveClosureSimple | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransitiveClosureSimple:
"""Based on the matrix multiplication, O(V**2 E) time."""
def __init__(self, graph):
"""The algorithm initialization, O(V**2) time."""
<|body_0|>
def run(self):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_005076 | 3,816 | permissive | [
{
"docstring": "The algorithm initialization, O(V**2) time.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033943 | Implement the Python class `TransitiveClosureSimple` described below.
Class description:
Based on the matrix multiplication, O(V**2 E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization, O(V**2) time.
- def run(self): Executable pseudocode. | Implement the Python class `TransitiveClosureSimple` described below.
Class description:
Based on the matrix multiplication, O(V**2 E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization, O(V**2) time.
- def run(self): Executable pseudocode.
<|skeleton|>
class Transitive... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class TransitiveClosureSimple:
"""Based on the matrix multiplication, O(V**2 E) time."""
def __init__(self, graph):
"""The algorithm initialization, O(V**2) time."""
<|body_0|>
def run(self):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransitiveClosureSimple:
"""Based on the matrix multiplication, O(V**2 E) time."""
def __init__(self, graph):
"""The algorithm initialization, O(V**2) time."""
if not graph.is_directed():
raise ValueError('the graph is not directed')
self.graph = graph
self.T =... | the_stack_v2_python_sparse | graphtheory/algorithms/closure.py | kgashok/graphs-dict | train | 0 |
361355f6b2717ad5cc4565576590bbcf3bf88a70 | [
"self._inputs = self.build_inputs()\nmoving_image = self._inputs['moving_image']\nfixed_image = self._inputs['fixed_image']\ncontrol_points = self.config['backbone'].pop('control_points', False)\nbackbone_inputs = self.concat_images(moving_image, fixed_image)\nbackbone = REGISTRY.build_backbone(config=self.config['... | <|body_start_0|>
self._inputs = self.build_inputs()
moving_image = self._inputs['moving_image']
fixed_image = self._inputs['fixed_image']
control_points = self.config['backbone'].pop('control_points', False)
backbone_inputs = self.concat_images(moving_image, fixed_image)
... | A registration model predicts DVF. DDF is calculated based on DVF. | DVFModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
<|body_0|>
def build_loss(self):
"""Build losses according to configs."""
<|body_1|>
def postp... | stack_v2_sparse_classes_75kplus_train_005077 | 21,008 | permissive | [
{
"docstring": "Build the model to be saved as self._model.",
"name": "build_model",
"signature": "def build_model(self)"
},
{
"docstring": "Build losses according to configs.",
"name": "build_loss",
"signature": "def build_loss(self)"
},
{
"docstring": "Return a dict used for sa... | 3 | stack_v2_sparse_classes_30k_train_038527 | Implement the Python class `DVFModel` described below.
Class description:
A registration model predicts DVF. DDF is calculated based on DVF.
Method signatures and docstrings:
- def build_model(self): Build the model to be saved as self._model.
- def build_loss(self): Build losses according to configs.
- def postproce... | Implement the Python class `DVFModel` described below.
Class description:
A registration model predicts DVF. DDF is calculated based on DVF.
Method signatures and docstrings:
- def build_model(self): Build the model to be saved as self._model.
- def build_loss(self): Build losses according to configs.
- def postproce... | 650a2f1a88ad3c6932be305d6a98a36e26feedc6 | <|skeleton|>
class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
<|body_0|>
def build_loss(self):
"""Build losses according to configs."""
<|body_1|>
def postp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
self._inputs = self.build_inputs()
moving_image = self._inputs['moving_image']
fixed_image = self._inputs['fixed_imag... | the_stack_v2_python_sparse | deepreg/model/network.py | DeepRegNet/DeepReg | train | 509 |
6e5aea9e8c8a2e0aab693432f798d39812e2776c | [
"assert isinstance(ann_path, str)\nsamples = list()\nfor img_name, instance in self.loader(ann_path):\n samples.append((osp.join(img_dir, osp.basename(img_name)), instance))\nreturn samples",
"tree = ET.parse(file_path)\nroot = tree.getroot()\nfor image in root.findall('image'):\n image_name = image.find('i... | <|body_start_0|>
assert isinstance(ann_path, str)
samples = list()
for img_name, instance in self.loader(ann_path):
samples.append((osp.join(img_dir, osp.basename(img_name)), instance))
return samples
<|end_body_0|>
<|body_start_1|>
tree = ET.parse(file_path)
... | SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1. | SVTTextDetAnnParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVTTextDetAnnParser:
"""SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1."""
def parse_files(self, img_dir: str, ann_path: str) -> List:
"""Parse annotations."""
... | stack_v2_sparse_classes_75kplus_train_005078 | 2,261 | permissive | [
{
"docstring": "Parse annotations.",
"name": "parse_files",
"signature": "def parse_files(self, img_dir: str, ann_path: str) -> List"
},
{
"docstring": "Load annotation from SVT xml format file. See annotation example in dataset_zoo/svt/sample_anno.md. Args: file_path (str): The path of the anno... | 2 | stack_v2_sparse_classes_30k_train_017858 | Implement the Python class `SVTTextDetAnnParser` described below.
Class description:
SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1.
Method signatures and docstrings:
- def parse_files(self, img_d... | Implement the Python class `SVTTextDetAnnParser` described below.
Class description:
SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1.
Method signatures and docstrings:
- def parse_files(self, img_d... | 9551af6e5a2482e72a2af1e3b8597fd54b999d69 | <|skeleton|>
class SVTTextDetAnnParser:
"""SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1."""
def parse_files(self, img_dir: str, ann_path: str) -> List:
"""Parse annotations."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SVTTextDetAnnParser:
"""SVT Text Detection Parser. Args: data_root (str): The root of the dataset. Defaults to None. nproc (int): The number of processes to parse the annotation. Defaults to 1."""
def parse_files(self, img_dir: str, ann_path: str) -> List:
"""Parse annotations."""
assert ... | the_stack_v2_python_sparse | mmocr/datasets/preparers/parsers/svt_parser.py | open-mmlab/mmocr | train | 3,734 |
7188f4eb39c5c7021e91919d10da159d2f547c47 | [
"kw = super(EventTaskView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"context = super(EventTaskView, self).get_context_data(**kwargs)\nevent = get_object_or_404(Event, id=self.kwargs['pk'])\ntasks = event.task_set.all()\ncount = tasks.count()\nidentified_ct ... | <|body_start_0|>
kw = super(EventTaskView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
context = super(EventTaskView, self).get_context_data(**kwargs)
event = get_object_or_404(Event, id=self.kwarg... | Create event task. | EventTaskView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTaskView:
"""Create event task."""
def get_form_kwargs(self):
"""Pass organization to form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return tasks belonging to the story."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kw = sup... | stack_v2_sparse_classes_75kplus_train_005079 | 11,257 | permissive | [
{
"docstring": "Pass organization to form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Return tasks belonging to the story.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032024 | Implement the Python class `EventTaskView` described below.
Class description:
Create event task.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass organization to form.
- def get_context_data(self, **kwargs): Return tasks belonging to the story. | Implement the Python class `EventTaskView` described below.
Class description:
Create event task.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass organization to form.
- def get_context_data(self, **kwargs): Return tasks belonging to the story.
<|skeleton|>
class EventTaskView:
"""Create even... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class EventTaskView:
"""Create event task."""
def get_form_kwargs(self):
"""Pass organization to form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return tasks belonging to the story."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventTaskView:
"""Create event task."""
def get_form_kwargs(self):
"""Pass organization to form."""
kw = super(EventTaskView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
def get_context_data(self, **kwargs):
""... | the_stack_v2_python_sparse | project/editorial/views/tasks.py | ProjectFacet/facet | train | 25 |
323f137b35fe341a868599f7a62c868edeebaf91 | [
"result = {'errcode': 0, 'msg': None}\nid = request.GET.get('id', None)\nqueryset = Menu.objects.only('id', 'title').all()\nrole = Role.objects.filter(id=id).first()\nper_list = []\nif role:\n role_menus = role.menu.only('id', 'title').all()\n menu_ids = [ru.id for ru in role_menus]\n for m in queryset:\n ... | <|body_start_0|>
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', None)
queryset = Menu.objects.only('id', 'title').all()
role = Role.objects.filter(id=id).first()
per_list = []
if role:
role_menus = role.menu.only('id', 'title').all()
... | GetRoleAllMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
<|body_0|>
def post(self, request, **kwargs):
"""修改 角色的用户信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', N... | stack_v2_sparse_classes_75kplus_train_005080 | 6,998 | no_license | [
{
"docstring": "获取当前角色的所有权限",
"name": "get",
"signature": "def get(self, request, **kwargs)"
},
{
"docstring": "修改 角色的用户信息",
"name": "post",
"signature": "def post(self, request, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017055 | Implement the Python class `GetRoleAllMenu` described below.
Class description:
Implement the GetRoleAllMenu class.
Method signatures and docstrings:
- def get(self, request, **kwargs): 获取当前角色的所有权限
- def post(self, request, **kwargs): 修改 角色的用户信息 | Implement the Python class `GetRoleAllMenu` described below.
Class description:
Implement the GetRoleAllMenu class.
Method signatures and docstrings:
- def get(self, request, **kwargs): 获取当前角色的所有权限
- def post(self, request, **kwargs): 修改 角色的用户信息
<|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs... | 9ceeecd85fdfd52fb90ebac7cc17092476877640 | <|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
<|body_0|>
def post(self, request, **kwargs):
"""修改 角色的用户信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', None)
queryset = Menu.objects.only('id', 'title').all()
role = Role.objects.filter(id=id).first()
per_list = []
if role:
... | the_stack_v2_python_sparse | user/api.py | vanwt/ttcmdb | train | 1 | |
d8ac46f4ced2a12901f93470ff6907512a5ca8f3 | [
"self.dims = dims\nself.size = size\nif self.dims == 1:\n self.grid = torch.arange(self.size)\n self.side = self.size\nelif self.dims == 2:\n self.side = int(math.sqrt(self.size))\n t = torch.arange(self.side)\n meshgrids = torch.meshgrid(t, t, indexing='ij')\n self.grid = torch.stack([x.reshape(-... | <|body_start_0|>
self.dims = dims
self.size = size
if self.dims == 1:
self.grid = torch.arange(self.size)
self.side = self.size
elif self.dims == 2:
self.side = int(math.sqrt(self.size))
t = torch.arange(self.side)
meshgrids = t... | This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point. | RadialBasis | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadialBasis:
"""This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point."""
def __init__(self, size, dims):
"""This function creates a radial grid with a given size and dimensionality. Args: size... | stack_v2_sparse_classes_75kplus_train_005081 | 5,180 | permissive | [
{
"docstring": "This function creates a radial grid with a given size and dimensionality. Args: size (int): The size of the radial grid. dims (int): The dimensionality of the grid (1 for 1D, 2 for 2D).",
"name": "__init__",
"signature": "def __init__(self, size, dims)"
},
{
"docstring": "Args: i... | 2 | stack_v2_sparse_classes_30k_train_027932 | Implement the Python class `RadialBasis` described below.
Class description:
This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point.
Method signatures and docstrings:
- def __init__(self, size, dims): This function creates a rad... | Implement the Python class `RadialBasis` described below.
Class description:
This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point.
Method signatures and docstrings:
- def __init__(self, size, dims): This function creates a rad... | 307c93ea4965a57b31531e50a338ac6721b832a6 | <|skeleton|>
class RadialBasis:
"""This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point."""
def __init__(self, size, dims):
"""This function creates a radial grid with a given size and dimensionality. Args: size... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RadialBasis:
"""This code creates a radial grid in either 1D or 2D based on a given centroid. It can be used to generate a grid of points around a central point."""
def __init__(self, size, dims):
"""This function creates a radial grid with a given size and dimensionality. Args: size (int): The s... | the_stack_v2_python_sparse | src/stm/topological_maps.py | francesco-mannella/Supervised-Topological-Maps | train | 0 |
5432d8a8cf5abb8343191e164ca0ba0c4fd7f482 | [
"self.compute_backends = REANA_COMPUTE_BACKENDS.values()\nself.statuses = [JobStatus.running, JobStatus.finished, JobStatus.failed, JobStatus.queued]\nsuper().__init__(from_=from_, until=until, user=user)",
"query = Session.query(Job).filter(Job.status == status)\nif compute_backend:\n query = query.filter(Job... | <|body_start_0|>
self.compute_backends = REANA_COMPUTE_BACKENDS.values()
self.statuses = [JobStatus.running, JobStatus.finished, JobStatus.failed, JobStatus.queued]
super().__init__(from_=from_, until=until, user=user)
<|end_body_0|>
<|body_start_1|>
query = Session.query(Job).filter(Jo... | Class to retrieve statistics related to REANA cluster jobs. | JobsStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobsStatus:
"""Class to retrieve statistics related to REANA cluster jobs."""
def __init__(self, from_=None, until=None, user=None):
"""Initialise PodStatus class. :param from_: From which moment in time to collect information. Not implemented yet. :param until: Until which moment in... | stack_v2_sparse_classes_75kplus_train_005082 | 24,874 | permissive | [
{
"docstring": "Initialise PodStatus class. :param from_: From which moment in time to collect information. Not implemented yet. :param until: Until which moment in time to collect information. Not implemented yet. :param user: A REANA-DB user model. :type from_: datetime :type until: datetime :type user: reana... | 5 | stack_v2_sparse_classes_30k_train_046207 | Implement the Python class `JobsStatus` described below.
Class description:
Class to retrieve statistics related to REANA cluster jobs.
Method signatures and docstrings:
- def __init__(self, from_=None, until=None, user=None): Initialise PodStatus class. :param from_: From which moment in time to collect information.... | Implement the Python class `JobsStatus` described below.
Class description:
Class to retrieve statistics related to REANA cluster jobs.
Method signatures and docstrings:
- def __init__(self, from_=None, until=None, user=None): Initialise PodStatus class. :param from_: From which moment in time to collect information.... | b72bc727adaa87e371d982b5e9f20f9361ecbc12 | <|skeleton|>
class JobsStatus:
"""Class to retrieve statistics related to REANA cluster jobs."""
def __init__(self, from_=None, until=None, user=None):
"""Initialise PodStatus class. :param from_: From which moment in time to collect information. Not implemented yet. :param until: Until which moment in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobsStatus:
"""Class to retrieve statistics related to REANA cluster jobs."""
def __init__(self, from_=None, until=None, user=None):
"""Initialise PodStatus class. :param from_: From which moment in time to collect information. Not implemented yet. :param until: Until which moment in time to coll... | the_stack_v2_python_sparse | reana_server/status.py | reanahub/reana-server | train | 5 |
c641e64d4c9f91e85b7e8a0ceeaf350f8b219c50 | [
"config.setdefault('password', None)\nconfig.setdefault('private_key', None)\nconfig.setdefault('private_key_pass', None)\nconfig.setdefault('host_key', None)\nconfig.setdefault('dirs', ['.'])\nreturn config",
"config = cls.prepare_config(config)\nfiles_only: bool = config['files_only']\ndirs_only: bool = config[... | <|body_start_0|>
config.setdefault('password', None)
config.setdefault('private_key', None)
config.setdefault('private_key_pass', None)
config.setdefault('host_key', None)
config.setdefault('dirs', ['.'])
return config
<|end_body_0|>
<|body_start_1|>
config = cls... | Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: The password to use. Optional if a private key is provided. private_key: Path... | SftpList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SftpList:
"""Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: The password to use. Optional if a privat... | stack_v2_sparse_classes_75kplus_train_005083 | 15,674 | permissive | [
{
"docstring": "Sets defaults for the provided configuration",
"name": "prepare_config",
"signature": "def prepare_config(config: dict) -> dict"
},
{
"docstring": "Input task handler",
"name": "on_task_input",
"signature": "def on_task_input(cls, task: Task, config: dict) -> List[Entry]"... | 2 | stack_v2_sparse_classes_30k_val_000216 | Implement the Python class `SftpList` described below.
Class description:
Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: Th... | Implement the Python class `SftpList` described below.
Class description:
Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: Th... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class SftpList:
"""Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: The password to use. Optional if a privat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SftpList:
"""Generate entries from SFTP. This plugin requires the pysftp Python module and its dependencies. Configuration: host: Host to connect to. port: Port the remote SSH server is listening on (default 22). username: Username to log in as. password: The password to use. Optional if a private key is prov... | the_stack_v2_python_sparse | flexget/components/ftp/sftp.py | BrutuZ/Flexget | train | 1 |
0fe7a2aef4f0155879ca243bc0bdd24eb1c9e249 | [
"esave2_prod_models = [eSaveCountry, eSaveProjects, eSaveBanks, eSaveUskpSectors]\nif model in esave2_prod_models:\n return 'esave'\nreturn None",
"esave2_prod_models = [eSaveCountry, eSaveProjects, eSaveBanks, eSaveUskpSectors]\nif model in esave2_prod_models:\n return 'esave'\nreturn None"
] | <|body_start_0|>
esave2_prod_models = [eSaveCountry, eSaveProjects, eSaveBanks, eSaveUskpSectors]
if model in esave2_prod_models:
return 'esave'
return None
<|end_body_0|>
<|body_start_1|>
esave2_prod_models = [eSaveCountry, eSaveProjects, eSaveBanks, eSaveUskpSectors]
... | MyDBRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading SomeModel from otherdb"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing SomeModel to otherdb"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
esave2_prod_models = [eSaveCou... | stack_v2_sparse_classes_75kplus_train_005084 | 647 | no_license | [
{
"docstring": "reading SomeModel from otherdb",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "writing SomeModel to otherdb",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042238 | Implement the Python class `MyDBRouter` described below.
Class description:
Implement the MyDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading SomeModel from otherdb
- def db_for_write(self, model, **hints): writing SomeModel to otherdb | Implement the Python class `MyDBRouter` described below.
Class description:
Implement the MyDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading SomeModel from otherdb
- def db_for_write(self, model, **hints): writing SomeModel to otherdb
<|skeleton|>
class MyDBRouter:
... | e88f93fde29a0e7a86651b9a11a1c90e5ad92ba9 | <|skeleton|>
class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading SomeModel from otherdb"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing SomeModel to otherdb"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyDBRouter:
def db_for_read(self, model, **hints):
"""reading SomeModel from otherdb"""
esave2_prod_models = [eSaveCountry, eSaveProjects, eSaveBanks, eSaveUskpSectors]
if model in esave2_prod_models:
return 'esave'
return None
def db_for_write(self, model, **h... | the_stack_v2_python_sparse | survey/dbrouters.py | Sava95/Sava95-SDG-evaluation-platform- | train | 0 | |
27898a397048c435e3dd37ba7242e9c85ca90742 | [
"corium.init()\npg.init()\nself._core_data = CoreData()\nself._graphics = Graphics(self._core_data, visual)\nself._canvas = Canvas(self._core_data, self._graphics)\nself._ui = UI(self._core_data, self._graphics)\nself._controller = Controller(self._core_data, self._graphics, self._canvas, self._ui)\ncoreutils.load_... | <|body_start_0|>
corium.init()
pg.init()
self._core_data = CoreData()
self._graphics = Graphics(self._core_data, visual)
self._canvas = Canvas(self._core_data, self._graphics)
self._ui = UI(self._core_data, self._graphics)
self._controller = Controller(self._core_... | The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The current UI object controller (Controller): The current controller object | Core | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Core:
"""The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The current UI object controller (Controller)... | stack_v2_sparse_classes_75kplus_train_005085 | 2,042 | no_license | [
{
"docstring": "Initialize the Core object and start the program. Parameters: program: An assembly program to load into memory (default None)",
"name": "__init__",
"signature": "def __init__(self, program: List[str]=None, execute_n: int=0, visual: bool=True)"
},
{
"docstring": "Main program loop... | 2 | stack_v2_sparse_classes_30k_train_019965 | Implement the Python class `Core` described below.
Class description:
The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The cu... | Implement the Python class `Core` described below.
Class description:
The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The cu... | 0b360801545e459d616b35435788fddbb958a626 | <|skeleton|>
class Core:
"""The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The current UI object controller (Controller)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Core:
"""The main program object that manages the graphics, controller, and canvas/ui. Attributes: core_data (CoreData): The current core state object graphics (Graphics): The current graphics object canvas (Canvas): The current canvas object ui (UI): The current UI object controller (Controller): The current... | the_stack_v2_python_sparse | core/core.py | bwiswell/py-virpu | train | 1 |
45abd6834cdbea4275daa493e8c13c8328d86b92 | [
"request = Request.find(reqid)\nreviews = cls._find_reviews(request, info)\nif reviews:\n cls._change_review_state(renderer, request, reviews[0], method, message, info, supersede_id)",
"request = Request.find(reqid)\nif message is None:\n message = edit_message()\nkwargs = {'comment': message, 'by_user': in... | <|body_start_0|>
request = Request.find(reqid)
reviews = cls._find_reviews(request, info)
if reviews:
cls._change_review_state(renderer, request, reviews[0], method, message, info, supersede_id)
<|end_body_0|>
<|body_start_1|>
request = Request.find(reqid)
if message... | Concrete ReviewController. | ReviewController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewController:
"""Concrete ReviewController."""
def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None):
"""Changes the state of a review. method is the method which is called on the retrieved request object. If message is None $EDITOR is opened."""... | stack_v2_sparse_classes_75kplus_train_005086 | 7,734 | no_license | [
{
"docstring": "Changes the state of a review. method is the method which is called on the retrieved request object. If message is None $EDITOR is opened.",
"name": "change_review_state",
"signature": "def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000638 | Implement the Python class `ReviewController` described below.
Class description:
Concrete ReviewController.
Method signatures and docstrings:
- def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None): Changes the state of a review. method is the method which is called on the retrieved... | Implement the Python class `ReviewController` described below.
Class description:
Concrete ReviewController.
Method signatures and docstrings:
- def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None): Changes the state of a review. method is the method which is called on the retrieved... | fd75a75371ae33740a68913ca8ab64a9e8e6654a | <|skeleton|>
class ReviewController:
"""Concrete ReviewController."""
def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None):
"""Changes the state of a review. method is the method which is called on the retrieved request object. If message is None $EDITOR is opened."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReviewController:
"""Concrete ReviewController."""
def change_review_state(cls, renderer, reqid, method, message, info, supersede_id=None):
"""Changes the state of a review. method is the method which is called on the retrieved request object. If message is None $EDITOR is opened."""
requ... | the_stack_v2_python_sparse | osc2/cli/review/review.py | openSUSE/osc2 | train | 16 |
8375a8115960fe64b3495ebd13dd5b2cbb7ca508 | [
"self._path = db_path\nself._funds = funds\nself._last = LastStored(self._path)\nself._now = datetime.now().date()",
"for fund in self._funds:\n try:\n filename = '{0}.csv'.format(fund)\n filepath = os.path.join(self._path, filename)\n header = False if os.path.isfile(filepath) else True\n... | <|body_start_0|>
self._path = db_path
self._funds = funds
self._last = LastStored(self._path)
self._now = datetime.now().date()
<|end_body_0|>
<|body_start_1|>
for fund in self._funds:
try:
filename = '{0}.csv'.format(fund)
filepath = ... | Stores NAV timeseries of funds down to csv files. | Store | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Store:
"""Stores NAV timeseries of funds down to csv files."""
def __init__(self, db_path, funds):
"""Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a dictionary of fund_name : timeseries of NAV values"""
... | stack_v2_sparse_classes_75kplus_train_005087 | 1,187 | no_license | [
{
"docstring": "Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a dictionary of fund_name : timeseries of NAV values",
"name": "__init__",
"signature": "def __init__(self, db_path, funds)"
},
{
"docstring": "Iterates thr... | 2 | stack_v2_sparse_classes_30k_train_017301 | Implement the Python class `Store` described below.
Class description:
Stores NAV timeseries of funds down to csv files.
Method signatures and docstrings:
- def __init__(self, db_path, funds): Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a... | Implement the Python class `Store` described below.
Class description:
Stores NAV timeseries of funds down to csv files.
Method signatures and docstrings:
- def __init__(self, db_path, funds): Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a... | c11ad5923a305526f63b093f7a7cd4063794a63b | <|skeleton|>
class Store:
"""Stores NAV timeseries of funds down to csv files."""
def __init__(self, db_path, funds):
"""Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a dictionary of fund_name : timeseries of NAV values"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Store:
"""Stores NAV timeseries of funds down to csv files."""
def __init__(self, db_path, funds):
"""Creates a Store object :param db_path: The path to file directory where fund csv files are going to be stored :param funds: a dictionary of fund_name : timeseries of NAV values"""
self._p... | the_stack_v2_python_sparse | common/Store.py | engelvinter/Xtrend | train | 0 |
863777be6a8136dd8144abda04eea8a9265533b8 | [
"if not data:\n data = []\nif not opt or len(opt) != 2:\n opt = (1, 1)\nif len(data) < opt[1]:\n data.extend([0 for _ in range(opt[1] - len(data))])\nreturn b''.join((SMPayloadTypeINT.encode(d, opt[0]) for d in data))",
"if not opt or len(opt) != 2:\n opt = (1, 1)\nif len(payload) < opt[0] * opt[1]:\n... | <|body_start_0|>
if not data:
data = []
if not opt or len(opt) != 2:
opt = (1, 1)
if len(data) < opt[1]:
data.extend([0 for _ in range(opt[1] - len(data))])
return b''.join((SMPayloadTypeINT.encode(d, opt[0]) for d in data))
<|end_body_0|>
<|body_star... | List of integer | SMPayloadTypeINTLIST | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\... | stack_v2_sparse_classes_75kplus_train_005088 | 14,049 | permissive | [
{
"docstring": "Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\\\x02\\\\x05' >>> SMPayloadTypeINTLIST.encode([1], opt=(1, 2)) # zero padding b'\\\\x01\\\\... | 2 | stack_v2_sparse_classes_30k_train_030995 | Implement the Python class `SMPayloadTypeINTLIST` described below.
Class description:
List of integer
Method signatures and docstrings:
- def encode(data, opt=None): Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>>... | Implement the Python class `SMPayloadTypeINTLIST` described below.
Class description:
List of integer
Method signatures and docstrings:
- def encode(data, opt=None): Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>>... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\\x05' >>> SMP... | the_stack_v2_python_sparse | smserver/smutils/smpacket/smencoder.py | Moutix/stepmania-server | train | 4 |
ce40315c58d45fb76b96f66e2f225908a7f1820c | [
"self.norm = norm\nself.daily_target = DailyAggTarget(data_key=daily_data_key, col=col, horizon=smooth_horizon, foo=np.mean, n_jobs=n_jobs)\nself.prev_quarter_date_target = QuarterlyTarget(data_key=quarterly_data_key, col='date', quarter_shift=-1, n_jobs=n_jobs)",
"last_date_df = self.prev_quarter_date_target.cal... | <|body_start_0|>
self.norm = norm
self.daily_target = DailyAggTarget(data_key=daily_data_key, col=col, horizon=smooth_horizon, foo=np.mean, n_jobs=n_jobs)
self.prev_quarter_date_target = QuarterlyTarget(data_key=quarterly_data_key, col='date', quarter_shift=-1, n_jobs=n_jobs)
<|end_body_0|>
<|b... | Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices. | DailySmoothedQuarterlyDiffTarget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DailySmoothedQuarterlyDiffTarget:
"""Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices."""
def __init__(self, daily_data_key: str, quarterly_data_key: str, col: str, smooth_horizon: int=30, norm: bool=True, n... | stack_v2_sparse_classes_75kplus_train_005089 | 21,437 | no_license | [
{
"docstring": "Parameters ---------- daily_data_key: key of dataloader in ``data`` argument during :func:`~ml_investment.targets.DailySmoothedQuarterlyDiffTarget.calculate` for daily data loading quarterly_data_key: key of dataloader in ``data`` argument during :func:`~ml_investment.targets.DailySmoothedQuarte... | 2 | null | Implement the Python class `DailySmoothedQuarterlyDiffTarget` described below.
Class description:
Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices.
Method signatures and docstrings:
- def __init__(self, daily_data_key: str, quarterly... | Implement the Python class `DailySmoothedQuarterlyDiffTarget` described below.
Class description:
Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices.
Method signatures and docstrings:
- def __init__(self, daily_data_key: str, quarterly... | 886df75952e408df2e93b92ebf57170823506c12 | <|skeleton|>
class DailySmoothedQuarterlyDiffTarget:
"""Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices."""
def __init__(self, daily_data_key: str, quarterly_data_key: str, col: str, smooth_horizon: int=30, norm: bool=True, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DailySmoothedQuarterlyDiffTarget:
"""Feature calculator getting difference between current and last quarter smoothed daily column values. Work with company quarter slices."""
def __init__(self, daily_data_key: str, quarterly_data_key: str, col: str, smooth_horizon: int=30, norm: bool=True, n_jobs: int=cp... | the_stack_v2_python_sparse | ml_investment/targets.py | LinarAbdrazakov/ml_investment | train | 0 |
432a57348a4a1d18a0242f56411c0987b0a7dd9d | [
"start, end, l, r = (-1, -1, 0, len(nums) - 1)\nwhile l <= r:\n mid = l + r >> 1\n if nums[mid] > target:\n r = mid - 1\n elif nums[mid] < target:\n l = mid + 1\n else:\n start = mid\n break\nif start != -1:\n l, r = (start, start)\n while nums[l] == nums[start] and l >... | <|body_start_0|>
start, end, l, r = (-1, -1, 0, len(nums) - 1)
while l <= r:
mid = l + r >> 1
if nums[mid] > target:
r = mid - 1
elif nums[mid] < target:
l = mid + 1
else:
start = mid
break
... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
<|body_0|>
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary search twice and the time is... | stack_v2_sparse_classes_75kplus_train_005090 | 1,864 | permissive | [
{
"docstring": "Binary Search + expand The best time is O(logN) and the worst is O(N)",
"name": "searchRange",
"signature": "def searchRange(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Binary search twice and the time is O(2logN)",
"name": "searchRange",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_048115 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums: List[int], target: int) -> List[int]: Binary Search + expand The best time is O(logN) and the worst is O(N)
- def searchRange(self, nums: List[int], t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums: List[int], target: int) -> List[int]: Binary Search + expand The best time is O(logN) and the worst is O(N)
- def searchRange(self, nums: List[int], t... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
<|body_0|>
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary search twice and the time is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
start, end, l, r = (-1, -1, 0, len(nums) - 1)
while l <= r:
mid = l + r >> 1
if nums[mid] > target:
... | the_stack_v2_python_sparse | Leetcode/Intermediate/Sort and search/34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
6ddbd8d7ed307d91d245ff2505927accb29986a4 | [
"result = []\nself.restore(s, 4, '', result)\nreturn result",
"if seg_no == 1:\n if int(s) > 255 or (s[0] == '0' and len(s) > 1):\n return None\n else:\n cur_ip += '.' + s\n ip_list.append(cur_ip[1:])\n return s\nfor i in range(0, len(s) - seg_no + 1):\n ip_seg = s[0:i + 1]\n ... | <|body_start_0|>
result = []
self.restore(s, 4, '', result)
return result
<|end_body_0|>
<|body_start_1|>
if seg_no == 1:
if int(s) > 255 or (s[0] == '0' and len(s) > 1):
return None
else:
cur_ip += '.' + s
ip_list.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def restoreIpAddresses(self, s):
"""使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]"""
<|body_0|>
def restore(self, s, seg_no, cur_ip, ip_list):
"""递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param... | stack_v2_sparse_classes_75kplus_train_005091 | 1,787 | no_license | [
{
"docstring": "使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]",
"name": "restoreIpAddresses",
"signature": "def restoreIpAddresses(self, s)"
},
{
"docstring": "递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param ip_list: 最终结果存放列表 :retur... | 2 | stack_v2_sparse_classes_30k_train_030004 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def restoreIpAddresses(self, s): 使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]
- def restore(self, s, seg_no, cur_ip, ip_list): 递归主体 :param s: 字符串 :param seg_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def restoreIpAddresses(self, s): 使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]
- def restore(self, s, seg_no, cur_ip, ip_list): 递归主体 :param s: 字符串 :param seg_... | 68a09a1ea2fb5083d62d8188c7ef213b2cc315cd | <|skeleton|>
class Solution:
def restoreIpAddresses(self, s):
"""使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]"""
<|body_0|>
def restore(self, s, seg_no, cur_ip, ip_list):
"""递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def restoreIpAddresses(self, s):
"""使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]"""
result = []
self.restore(s, 4, '', result)
return result
def restore(self, s, seg_no, cur_ip, ip_list):
"""递归主体 :param s: 字符串 :param seg_no: 当前ip片段的id... | the_stack_v2_python_sparse | leetcode081-100/leetcode93-restore-ip-addresses.py | linshuang/code4fun | train | 0 | |
4938dcbf091290061db6406f50ab802edf3959a6 | [
"def search(node, total, current, output):\n if node and (not node.left) and (not node.right) and (total == node.val):\n output.append(current + [node.val])\n elif node:\n current.append(node.val)\n search(node.left, total - node.val, current, output)\n search(node.right, total - n... | <|body_start_0|>
def search(node, total, current, output):
if node and (not node.left) and (not node.right) and (total == node.val):
output.append(current + [node.val])
elif node:
current.append(node.val)
search(node.left, total - node.val,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_0|>
def pathSum_verbose(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_005092 | 2,451 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"name": "pathSum_verbose",
"signature": "def pathSum_verbose(self,... | 2 | stack_v2_sparse_classes_30k_train_022450 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]]
- def pathSum_verbose(self, root, sum): :type root: TreeNode :type sum: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]]
- def pathSum_verbose(self, root, sum): :type root: TreeNode :type sum: int :rtype: List... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_0|>
def pathSum_verbose(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
def search(node, total, current, output):
if node and (not node.left) and (not node.right) and (total == node.val):
output.append(current + [node.val])
... | the_stack_v2_python_sparse | src/lt_113.py | oxhead/CodingYourWay | train | 0 | |
f7b171259e783729546445ea8ae4b95094e1e6fc | [
"self.array = None\nself.pose = None\nself.inference_time = None\nself.model = model\nself.redis = redis\nself.redis.set('reps', 0)\nself.redis.set('pace', 0)",
"self.array = array\nself.pose, self.inference_time = self.model.DetectPosesInImage(self.array)\nif self.pose:\n self.pose = max(self.pose, key=lambda... | <|body_start_0|>
self.array = None
self.pose = None
self.inference_time = None
self.model = model
self.redis = redis
self.redis.set('reps', 0)
self.redis.set('pace', 0)
<|end_body_0|>
<|body_start_1|>
self.array = array
self.pose, self.inference_t... | Custom streaming output for the PiCamera | StreamOutput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamOutput:
"""Custom streaming output for the PiCamera"""
def setup(self, model, redis):
"""Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient."""
<|body_0|>
def analyze(self, array):
"""While recording is in progress, analyzes incoming arr... | stack_v2_sparse_classes_75kplus_train_005093 | 3,781 | permissive | [
{
"docstring": "Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient.",
"name": "setup",
"signature": "def setup(self, model, redis)"
},
{
"docstring": "While recording is in progress, analyzes incoming array data",
"name": "analyze",
"signature": "def analyze(self, arr... | 2 | stack_v2_sparse_classes_30k_train_033763 | Implement the Python class `StreamOutput` described below.
Class description:
Custom streaming output for the PiCamera
Method signatures and docstrings:
- def setup(self, model, redis): Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient.
- def analyze(self, array): While recording is in progress, ... | Implement the Python class `StreamOutput` described below.
Class description:
Custom streaming output for the PiCamera
Method signatures and docstrings:
- def setup(self, model, redis): Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient.
- def analyze(self, array): While recording is in progress, ... | 530beb9e3b8516e0e93960b99521c23a523ef546 | <|skeleton|>
class StreamOutput:
"""Custom streaming output for the PiCamera"""
def setup(self, model, redis):
"""Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient."""
<|body_0|>
def analyze(self, array):
"""While recording is in progress, analyzes incoming arr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamOutput:
"""Custom streaming output for the PiCamera"""
def setup(self, model, redis):
"""Args: model: PoseEngine for TensorFlow Lite models. redis: RedisClient."""
self.array = None
self.pose = None
self.inference_time = None
self.model = model
self.r... | the_stack_v2_python_sparse | hiitpi-master/hiitpi/camera.py | babiato/flaskapp1 | train | 0 |
d7de809cb6ec6c52b1835df62a2df121ee02c79e | [
"author = g.user\nnotes = NoteModel.get_all_notes(author, archive='all')\nif not notes:\n abort(404, error=f'You have no notes yet')\nreturn (notes, 200)",
"author = g.user\nnote = NoteModel(author_id=author.id, **kwargs)\nnote.save()\nreturn (note, 201)"
] | <|body_start_0|>
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have no notes yet')
return (notes, 200)
<|end_body_0|>
<|body_start_1|>
author = g.user
note = NoteModel(author_id=author.id, **kwargs... | NoteListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_75kplus_train_005094 | 11,305 | no_license | [
{
"docstring": "Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Создает заметку пользователя. Требуется аутентификация. :param kwargs: параметры для создания заметк... | 2 | stack_v2_sparse_classes_30k_train_047706 | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have... | the_stack_v2_python_sparse | api/resources/note.py | UshakovAleksandr/Blog | train | 1 | |
51fec0c1da2e974523fe0fa284ad1a8515876935 | [
"host = f'{account_name}.obsrvbl.com'\nsuper().__init__(host=host)\nself.base_url = f'https://{self.host}/api/v3'\nself.headers['Authorization'] = f'ApiKey {email}:{api_key}'",
"account_name = os.environ.get('SWC_ACCOUNT')\nif not account_name:\n raise ValueError('Env var SWC_ACCOUNT not specified')\nemail = o... | <|body_start_0|>
host = f'{account_name}.obsrvbl.com'
super().__init__(host=host)
self.base_url = f'https://{self.host}/api/v3'
self.headers['Authorization'] = f'ApiKey {email}:{api_key}'
<|end_body_0|>
<|body_start_1|>
account_name = os.environ.get('SWC_ACCOUNT')
if not... | Declaration of Cisco Stealthwatch Cloud (SWC) SDK class. | CiscoSWCloud | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CiscoSWCloud:
"""Declaration of Cisco Stealthwatch Cloud (SWC) SDK class."""
def __init__(self, account_name, email, api_key):
"""Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic auth) with the user's email address and API key"""
... | stack_v2_sparse_classes_75kplus_train_005095 | 2,015 | no_license | [
{
"docstring": "Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic auth) with the user's email address and API key",
"name": "__init__",
"signature": "def __init__(self, account_name, email, api_key)"
},
{
"docstring": "Static class-level helper met... | 2 | stack_v2_sparse_classes_30k_val_001908 | Implement the Python class `CiscoSWCloud` described below.
Class description:
Declaration of Cisco Stealthwatch Cloud (SWC) SDK class.
Method signatures and docstrings:
- def __init__(self, account_name, email, api_key): Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic... | Implement the Python class `CiscoSWCloud` described below.
Class description:
Declaration of Cisco Stealthwatch Cloud (SWC) SDK class.
Method signatures and docstrings:
- def __init__(self, account_name, email, api_key): Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic... | 37aeff8e5cb5de99506195fce3d9bb119041cc2b | <|skeleton|>
class CiscoSWCloud:
"""Declaration of Cisco Stealthwatch Cloud (SWC) SDK class."""
def __init__(self, account_name, email, api_key):
"""Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic auth) with the user's email address and API key"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CiscoSWCloud:
"""Declaration of Cisco Stealthwatch Cloud (SWC) SDK class."""
def __init__(self, account_name, email, api_key):
"""Constructor to create a new object. SWC uses a custom Authorization header (similar to HTTP basic auth) with the user's email address and API key"""
host = f'{... | the_stack_v2_python_sparse | sauto3/m3/cisco_sw_cloud.py | ncnetworkcloud/pluralsight | train | 0 |
a928f0a3a6a3d97139ab81f5761d7129cd1a5d6f | [
"super().__init__()\nself.num = desc['num']\nself.pos_fraction = desc['pos_fraction']\nself.neg_pos_ub = desc['neg_pos_ub'] if 'neg_pos_ub' in desc else -1\nself.add_gt_as_proposals = desc['add_gt_as_proposals'] if 'add_gt_as_proposals' in desc else True",
"pos_inds = torch.nonzero(assign_result.gt_inds > 0)\nif ... | <|body_start_0|>
super().__init__()
self.num = desc['num']
self.pos_fraction = desc['pos_fraction']
self.neg_pos_ub = desc['neg_pos_ub'] if 'neg_pos_ub' in desc else -1
self.add_gt_as_proposals = desc['add_gt_as_proposals'] if 'add_gt_as_proposals' in desc else True
<|end_body_0|... | Random sampler. | RandomSampler | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSampler:
"""Random sampler."""
def __init__(self, desc):
"""Init sampler. :param desc: config dict"""
<|body_0|>
def _sample_pos(self, assign_result, num_expected, **kwargs):
"""Randomly sample some positive samples. :param assign_result: assign result :par... | stack_v2_sparse_classes_75kplus_train_005096 | 4,405 | permissive | [
{
"docstring": "Init sampler. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Randomly sample some positive samples. :param assign_result: assign result :param num_expected: num expect :return: positive object index",
"name": "_sample... | 5 | null | Implement the Python class `RandomSampler` described below.
Class description:
Random sampler.
Method signatures and docstrings:
- def __init__(self, desc): Init sampler. :param desc: config dict
- def _sample_pos(self, assign_result, num_expected, **kwargs): Randomly sample some positive samples. :param assign_resul... | Implement the Python class `RandomSampler` described below.
Class description:
Random sampler.
Method signatures and docstrings:
- def __init__(self, desc): Init sampler. :param desc: config dict
- def _sample_pos(self, assign_result, num_expected, **kwargs): Randomly sample some positive samples. :param assign_resul... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class RandomSampler:
"""Random sampler."""
def __init__(self, desc):
"""Init sampler. :param desc: config dict"""
<|body_0|>
def _sample_pos(self, assign_result, num_expected, **kwargs):
"""Randomly sample some positive samples. :param assign_result: assign result :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomSampler:
"""Random sampler."""
def __init__(self, desc):
"""Init sampler. :param desc: config dict"""
super().__init__()
self.num = desc['num']
self.pos_fraction = desc['pos_fraction']
self.neg_pos_ub = desc['neg_pos_ub'] if 'neg_pos_ub' in desc else -1
... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/utils/bbox_utils/sampler/random_sampler.py | Huawei-Ascend/modelzoo | train | 1 |
2aee99df7590ac9a3497af616c93d882ecadc554 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | service | ImageServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageServiceServicer:
"""service"""
def GetImageStream(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetShm(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|... | stack_v2_sparse_classes_75kplus_train_005097 | 10,385 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetImageStream",
"signature": "def GetImageStream(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetShm",
"signature": "def GetShm(self, re... | 2 | stack_v2_sparse_classes_30k_train_002273 | Implement the Python class `ImageServiceServicer` described below.
Class description:
service
Method signatures and docstrings:
- def GetImageStream(self, request, context): Missing associated documentation comment in .proto file.
- def GetShm(self, request, context): Missing associated documentation comment in .prot... | Implement the Python class `ImageServiceServicer` described below.
Class description:
service
Method signatures and docstrings:
- def GetImageStream(self, request, context): Missing associated documentation comment in .proto file.
- def GetShm(self, request, context): Missing associated documentation comment in .prot... | a83a60c40eda7051a73363f67cb806ad73637e7a | <|skeleton|>
class ImageServiceServicer:
"""service"""
def GetImageStream(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetShm(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageServiceServicer:
"""service"""
def GetImageStream(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method n... | the_stack_v2_python_sparse | sap-toolkit/sap_toolkit/generated/eval_server_pb2_grpc.py | jelasus/sap-starterkit | train | 0 |
e6ece2ef8a8102d44d63fc4776b807be6786e36d | [
"super(ListMemberGoals, self).__init__(*args, **kwargs)\nself.endpoint = 'lists'\nself.list_id = None\nself.subscriber_hash = None",
"subscriber_hash = check_subscriber_hash(subscriber_hash)\nself.list_id = list_id\nself.subscriber_hash = subscriber_hash\nreturn self._mc_client._get(url=self._build_path(list_id, ... | <|body_start_0|>
super(ListMemberGoals, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.subscriber_hash = None
<|end_body_0|>
<|body_start_1|>
subscriber_hash = check_subscriber_hash(subscriber_hash)
self.list_id = list_id
self.su... | Get information about recent goal events for a specific list member. | ListMemberGoals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListMemberGoals:
"""Get information about recent goal events for a specific list member."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, list_id, subscriber_hash, **queryparams):
"""Get the last 50 Goal events for a ... | stack_v2_sparse_classes_75kplus_train_005098 | 1,561 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get the last 50 Goal events for a member on a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The ... | 2 | stack_v2_sparse_classes_30k_train_032159 | Implement the Python class `ListMemberGoals` described below.
Class description:
Get information about recent goal events for a specific list member.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, list_id, subscriber_hash, **queryparams): Get the last ... | Implement the Python class `ListMemberGoals` described below.
Class description:
Get information about recent goal events for a specific list member.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, list_id, subscriber_hash, **queryparams): Get the last ... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ListMemberGoals:
"""Get information about recent goal events for a specific list member."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, list_id, subscriber_hash, **queryparams):
"""Get the last 50 Goal events for a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListMemberGoals:
"""Get information about recent goal events for a specific list member."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(ListMemberGoals, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.su... | the_stack_v2_python_sparse | mailchimp3/entities/listmembergoals.py | VingtCinq/python-mailchimp | train | 190 |
9dafb7f600742f003de59ab3b7e007f9272c6daa | [
"if social_login.account.provider != 'discord':\n add_message(request, ERROR, ERROR_CONNECT_DISCORD)\n raise ImmediateHttpResponse(redirect(reverse('home')))\ntry:\n user = DiscordUser.objects.get(id=int(social_login.account.uid))\nexcept DiscordUser.DoesNotExist:\n add_message(request, ERROR, ERROR_JOI... | <|body_start_0|>
if social_login.account.provider != 'discord':
add_message(request, ERROR, ERROR_CONNECT_DISCORD)
raise ImmediateHttpResponse(redirect(reverse('home')))
try:
user = DiscordUser.objects.get(id=int(social_login.account.uid))
except DiscordUser.D... | An Allauth SocialAccount adapter that prevents signups via non-Discord connections. | SocialAccountAdapter | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialAccountAdapter:
"""An Allauth SocialAccount adapter that prevents signups via non-Discord connections."""
def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool:
"""Checks whether or not the site is open for signups. We override this method in ord... | stack_v2_sparse_classes_75kplus_train_005099 | 3,334 | permissive | [
{
"docstring": "Checks whether or not the site is open for signups. We override this method in order to prevent users from creating a new account using a non-Discord connection, as we require this connection for our users.",
"name": "is_open_for_signup",
"signature": "def is_open_for_signup(self, reques... | 2 | null | Implement the Python class `SocialAccountAdapter` described below.
Class description:
An Allauth SocialAccount adapter that prevents signups via non-Discord connections.
Method signatures and docstrings:
- def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool: Checks whether or not the... | Implement the Python class `SocialAccountAdapter` described below.
Class description:
An Allauth SocialAccount adapter that prevents signups via non-Discord connections.
Method signatures and docstrings:
- def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool: Checks whether or not the... | 2c9c31c887cb1cb6de8fc7d65a11440467376bad | <|skeleton|>
class SocialAccountAdapter:
"""An Allauth SocialAccount adapter that prevents signups via non-Discord connections."""
def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool:
"""Checks whether or not the site is open for signups. We override this method in ord... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocialAccountAdapter:
"""An Allauth SocialAccount adapter that prevents signups via non-Discord connections."""
def is_open_for_signup(self, request: HttpRequest, social_login: SocialLogin) -> bool:
"""Checks whether or not the site is open for signups. We override this method in order to prevent... | the_stack_v2_python_sparse | pydis_site/utils/account.py | RohanJnr/site | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.