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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f564963b538367b78933f9442a263a5ba8fbbc91 | [
"study_id = filter_params.pop('study_id', None)\nq = BiospecimenGenomicFile.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import Biospecimen\nif study_id:\n q = q.join(BiospecimenGenomicFile.biospecimen).join(Biospecimen.part... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
q = BiospecimenGenomicFile.query.filter_by(**filter_params)
from dataservice.api.participant.models import Participant
from dataservice.api.biospecimen.models import Biospecimen
if study_id:
q = q.join(Bi... | BiospecimenGenomicFile List API | BiospecimenGenomicFileListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiospecimenGenomicFileListAPI:
"""BiospecimenGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGenomicFile"""
<|body_0|>
def post(self):
... | stack_v2_sparse_classes_75kplus_train_007800 | 5,154 | permissive | [
{
"docstring": "Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGenomicFile",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new biospecimen_genomic_file --- template: path: new_reso... | 2 | stack_v2_sparse_classes_30k_train_045226 | Implement the Python class `BiospecimenGenomicFileListAPI` described below.
Class description:
BiospecimenGenomicFile List API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGen... | Implement the Python class `BiospecimenGenomicFileListAPI` described below.
Class description:
BiospecimenGenomicFile List API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGen... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class BiospecimenGenomicFileListAPI:
"""BiospecimenGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGenomicFile"""
<|body_0|>
def post(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiospecimenGenomicFileListAPI:
"""BiospecimenGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated biospecimen_genomic_files --- template: path: get_list.yml properties: resource: BiospecimenGenomicFile"""
study_id = filter_params.pop('study_id', None)
... | the_stack_v2_python_sparse | dataservice/api/biospecimen_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
44cac26ddbdeca3c605b08761a1713e76baefc15 | [
"self.h_n = 0\nself.b = []\nself.y = 0.0\nself.w = []\nself.beta = []\nself.c = []\nself.lr = 0.05",
"import numpy as np\nself.h_n = nh\nself.b = np.zeros(self.h_n)\nself.c = centers\nself.w = np.zeros(self.h_n)\nself.beta = np.zeros(self.h_n)\nfor h in range(self.h_n):\n self.w[h] = rand(0, 1)\n self.beta[... | <|body_start_0|>
self.h_n = 0
self.b = []
self.y = 0.0
self.w = []
self.beta = []
self.c = []
self.lr = 0.05
<|end_body_0|>
<|body_start_1|>
import numpy as np
self.h_n = nh
self.b = np.zeros(self.h_n)
self.c = centers
self... | the definition of BP network class | RBP_network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBP_network:
"""the definition of BP network class"""
def __init__(self):
"""initial variables"""
<|body_0|>
def CreateNN(self, nh, centers, learningrate):
"""build a RBF network structure and initial parameters @param nh : the neuron number of in layer @param ce... | stack_v2_sparse_classes_75kplus_train_007801 | 4,295 | no_license | [
{
"docstring": "initial variables",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "build a RBF network structure and initial parameters @param nh : the neuron number of in layer @param centers: matrix [h_n * i_n] the center parameters object to hidden layer neurons @par... | 6 | stack_v2_sparse_classes_30k_train_013583 | Implement the Python class `RBP_network` described below.
Class description:
the definition of BP network class
Method signatures and docstrings:
- def __init__(self): initial variables
- def CreateNN(self, nh, centers, learningrate): build a RBF network structure and initial parameters @param nh : the neuron number ... | Implement the Python class `RBP_network` described below.
Class description:
the definition of BP network class
Method signatures and docstrings:
- def __init__(self): initial variables
- def CreateNN(self, nh, centers, learningrate): build a RBF network structure and initial parameters @param nh : the neuron number ... | 1cbda9c5e2dbac2e487afb102d963a670d3c1260 | <|skeleton|>
class RBP_network:
"""the definition of BP network class"""
def __init__(self):
"""initial variables"""
<|body_0|>
def CreateNN(self, nh, centers, learningrate):
"""build a RBF network structure and initial parameters @param nh : the neuron number of in layer @param ce... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RBP_network:
"""the definition of BP network class"""
def __init__(self):
"""initial variables"""
self.h_n = 0
self.b = []
self.y = 0.0
self.w = []
self.beta = []
self.c = []
self.lr = 0.05
def CreateNN(self, nh, centers, learningrate):... | the_stack_v2_python_sparse | 03、Neural Networks/RBF For XOR/RBF_BP.py | EvilCalf/Machine-Learning | train | 3 |
7740d476d7cc1b61a9786784769380751a38135c | [
"if self.action == 'list':\n permission_classes = [permissions.IsAuthenticated]\nelse:\n return super().get_permissions()\nreturn [permission() for permission in permission_classes]",
"context = super().get_serializer_context()\ncontext['organization_id'] = self.kwargs['organization_id']\nreturn context",
... | <|body_start_0|>
if self.action == 'list':
permission_classes = [permissions.IsAuthenticated]
else:
return super().get_permissions()
return [permission() for permission in permission_classes]
<|end_body_0|>
<|body_start_1|>
context = super().get_serializer_contex... | API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization access if an id is provided. POST /api/<organization_id>/accesses/ with expected data: - user... | OrganizationAccessViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationAccessViewSet:
"""API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization access if an id is provided. POST /api/<... | stack_v2_sparse_classes_75kplus_train_007802 | 30,756 | permissive | [
{
"docstring": "User only needs to be authenticated to list organization accesses",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Extra context provided to the serializer class.",
"name": "get_serializer_context",
"signature": "def get_serializer_... | 3 | stack_v2_sparse_classes_30k_train_054761 | Implement the Python class `OrganizationAccessViewSet` described below.
Class description:
API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization a... | Implement the Python class `OrganizationAccessViewSet` described below.
Class description:
API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization a... | 6571a67d020715358fec807a1137f89bdf4b305a | <|skeleton|>
class OrganizationAccessViewSet:
"""API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization access if an id is provided. POST /api/<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationAccessViewSet:
"""API ViewSet for all interactions with organization accesses. GET /api/organization/<organization_id>/accesses/:<organization_access_id> Return list of all organization accesses related to the logged-in user or one organization access if an id is provided. POST /api/<organization_... | the_stack_v2_python_sparse | src/backend/joanie/core/api/client.py | openfun/joanie | train | 13 |
348cfe629b6ed755224750827778d7ea7206ec6b | [
"if not root:\n return ''\ntodo = [root]\nans = []\nwhile todo:\n nextTodo = []\n for node in todo:\n if node.val != None:\n ans.append(str(node.val))\n if node.left:\n nextTodo.append(node.left)\n else:\n nextTodo.append(TreeNode(None))... | <|body_start_0|>
if not root:
return ''
todo = [root]
ans = []
while todo:
nextTodo = []
for node in todo:
if node.val != None:
ans.append(str(node.val))
if node.left:
next... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_007803 | 2,122 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_041063 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 76d767ec001649b2df07aac211ac4b43b415ebdd | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
todo = [root]
ans = []
while todo:
nextTodo = []
for node in todo:
if node.val != None:... | the_stack_v2_python_sparse | leetcode297 Serialize and Deserialize Binary Tree.py | whglamrock/leetcode_series | train | 2 | |
1aaddf45d4a3ee8cfe7bdcd7366062735e914f2b | [
"path = app.config['USER_HOME_PATH']\nusers = [o for o in os.listdir(path) if os.path.isdir(path + '/' + o) and (not os.path.islink(path + '/' + o))]\nfor user in users:\n User(user)",
"home_path = app.config['USER_HOME_PATH']\ntemp_path = app.config['USER_TEMP_PATH']\nusers = [(o, False) for o in os.listdir(h... | <|body_start_0|>
path = app.config['USER_HOME_PATH']
users = [o for o in os.listdir(path) if os.path.isdir(path + '/' + o) and (not os.path.islink(path + '/' + o))]
for user in users:
User(user)
<|end_body_0|>
<|body_start_1|>
home_path = app.config['USER_HOME_PATH']
... | User service class | UserService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
"""User service class"""
def find_users_in_home_path():
"""Create a new user for every user in home path"""
<|body_0|>
def sync_users():
"""Create a new index if a new filesystem is found and sync it. Delete the index if the filesystem has been remov... | stack_v2_sparse_classes_75kplus_train_007804 | 2,958 | permissive | [
{
"docstring": "Create a new user for every user in home path",
"name": "find_users_in_home_path",
"signature": "def find_users_in_home_path()"
},
{
"docstring": "Create a new index if a new filesystem is found and sync it. Delete the index if the filesystem has been removed.",
"name": "sync... | 2 | stack_v2_sparse_classes_30k_train_051582 | Implement the Python class `UserService` described below.
Class description:
User service class
Method signatures and docstrings:
- def find_users_in_home_path(): Create a new user for every user in home path
- def sync_users(): Create a new index if a new filesystem is found and sync it. Delete the index if the file... | Implement the Python class `UserService` described below.
Class description:
User service class
Method signatures and docstrings:
- def find_users_in_home_path(): Create a new user for every user in home path
- def sync_users(): Create a new index if a new filesystem is found and sync it. Delete the index if the file... | ed59a95071455abaf53dca5bb999364509fd9fcd | <|skeleton|>
class UserService:
"""User service class"""
def find_users_in_home_path():
"""Create a new user for every user in home path"""
<|body_0|>
def sync_users():
"""Create a new index if a new filesystem is found and sync it. Delete the index if the filesystem has been remov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserService:
"""User service class"""
def find_users_in_home_path():
"""Create a new user for every user in home path"""
path = app.config['USER_HOME_PATH']
users = [o for o in os.listdir(path) if os.path.isdir(path + '/' + o) and (not os.path.islink(path + '/' + o))]
for ... | the_stack_v2_python_sparse | services/user_service.py | olavgg/py-sth | train | 0 |
d550940d2d4bc669dfd7d292845277599e4995b9 | [
"self.chunkArray = []\nfor i in range(self.chunksHigh):\n for j in range(self.chunksWide):\n self.chunkArray.append(chunk.Chunk([(i, j)]))\nrandom.shuffle(self.chunkArray)",
"for c in self.chunkArray:\n if not c.filled:\n height = image.shape[0] / self.chunksHigh\n width = image.shape[1... | <|body_start_0|>
self.chunkArray = []
for i in range(self.chunksHigh):
for j in range(self.chunksWide):
self.chunkArray.append(chunk.Chunk([(i, j)]))
random.shuffle(self.chunkArray)
<|end_body_0|>
<|body_start_1|>
for c in self.chunkArray:
if not ... | Grid mode fills the image with random chunks in a random order | Mode_Grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mode_Grid:
"""Grid mode fills the image with random chunks in a random order"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks"""
<|body_0|>
def fillNextChunk(self, image):
... | stack_v2_sparse_classes_75kplus_train_007805 | 1,579 | no_license | [
{
"docstring": "Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks",
"name": "_createChunkArray",
"signature": "def _createChunkArray(self)"
},
{
"docstring": "Take the current chunk array and fill a chunk if it needs to be done Arguments... | 2 | stack_v2_sparse_classes_30k_train_037535 | Implement the Python class `Mode_Grid` described below.
Class description:
Grid mode fills the image with random chunks in a random order
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks
- def ... | Implement the Python class `Mode_Grid` described below.
Class description:
Grid mode fills the image with random chunks in a random order
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks
- def ... | b87c1d826485695565f7f4ff22fb3b78db4f43d0 | <|skeleton|>
class Mode_Grid:
"""Grid mode fills the image with random chunks in a random order"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks"""
<|body_0|>
def fillNextChunk(self, image):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mode_Grid:
"""Grid mode fills the image with random chunks in a random order"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with randomly ordered random chunks"""
self.chunkArray = []
for i in range(self.chunksHigh):
... | the_stack_v2_python_sparse | Python/mode_grid.py | SNAP-SAPIENT/plotting-time-and-space | train | 0 |
2a71fe77e01501ba8090738a579d089ba7e03841 | [
"if hasattr(spider, 'category'):\n fname = '{}_{}'.format(spider.name, spider.category)\nelse:\n fname = spider.name\ndata_dir = spider.settings.get('PIPELINE_DATA_DIR')\nfpath = os.path.join(data_dir, fname)\nself.file = open('{}.json'.format(fpath), 'w')\nself.file.truncate(0)\nself._items = []",
"self.fi... | <|body_start_0|>
if hasattr(spider, 'category'):
fname = '{}_{}'.format(spider.name, spider.category)
else:
fname = spider.name
data_dir = spider.settings.get('PIPELINE_DATA_DIR')
fpath = os.path.join(data_dir, fname)
self.file = open('{}.json'.format(fpat... | Customized json outputer pipeline. | JsonPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonPipeline:
"""Customized json outputer pipeline."""
def open_spider(self, spider):
"""Open buffer."""
<|body_0|>
def close_spider(self, spider):
"""Close file."""
<|body_1|>
def process_item(self, item, spider):
"""Process single item."""
... | stack_v2_sparse_classes_75kplus_train_007806 | 2,083 | permissive | [
{
"docstring": "Open buffer.",
"name": "open_spider",
"signature": "def open_spider(self, spider)"
},
{
"docstring": "Close file.",
"name": "close_spider",
"signature": "def close_spider(self, spider)"
},
{
"docstring": "Process single item.",
"name": "process_item",
"sig... | 3 | null | Implement the Python class `JsonPipeline` described below.
Class description:
Customized json outputer pipeline.
Method signatures and docstrings:
- def open_spider(self, spider): Open buffer.
- def close_spider(self, spider): Close file.
- def process_item(self, item, spider): Process single item. | Implement the Python class `JsonPipeline` described below.
Class description:
Customized json outputer pipeline.
Method signatures and docstrings:
- def open_spider(self, spider): Open buffer.
- def close_spider(self, spider): Close file.
- def process_item(self, item, spider): Process single item.
<|skeleton|>
clas... | 8515fcc4c86ef0a96f34278d90419e5fad2b48d3 | <|skeleton|>
class JsonPipeline:
"""Customized json outputer pipeline."""
def open_spider(self, spider):
"""Open buffer."""
<|body_0|>
def close_spider(self, spider):
"""Close file."""
<|body_1|>
def process_item(self, item, spider):
"""Process single item."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonPipeline:
"""Customized json outputer pipeline."""
def open_spider(self, spider):
"""Open buffer."""
if hasattr(spider, 'category'):
fname = '{}_{}'.format(spider.name, spider.category)
else:
fname = spider.name
data_dir = spider.settings.get('P... | the_stack_v2_python_sparse | plantstuff/scraping/scrapers/pipelines.py | christabor/plantstuff | train | 8 |
4e2f1b2cc7e7927bd92c2cc90293bb57c456ca5d | [
"log = QchemLog(os.path.join(os.path.dirname(__file__), 'files', 'npropyl.out'))\nself.assertEqual(log.getNumberOfAtoms(), 10)\nlog = QchemLog(os.path.join(os.path.dirname(__file__), 'files', 'co.out'))\nself.assertEqual(log.getNumberOfAtoms(), 2)",
"log = QchemLog(os.path.join(os.path.dirname(__file__), 'files',... | <|body_start_0|>
log = QchemLog(os.path.join(os.path.dirname(__file__), 'files', 'npropyl.out'))
self.assertEqual(log.getNumberOfAtoms(), 10)
log = QchemLog(os.path.join(os.path.dirname(__file__), 'files', 'co.out'))
self.assertEqual(log.getNumberOfAtoms(), 2)
<|end_body_0|>
<|body_star... | Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files. | QChemTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QChemTest:
"""Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files."""
def testNumberOfAtomsFromQchemLog(self):
"""Uses a Qchem log files to test that number of atoms can be properly read."""
<|body_0|>
def testEnergyFromQchemLog(s... | stack_v2_sparse_classes_75kplus_train_007807 | 4,585 | permissive | [
{
"docstring": "Uses a Qchem log files to test that number of atoms can be properly read.",
"name": "testNumberOfAtomsFromQchemLog",
"signature": "def testNumberOfAtomsFromQchemLog(self)"
},
{
"docstring": "Uses a Qchem log files to test that molecular energies can be properly read.",
"name"... | 6 | stack_v2_sparse_classes_30k_train_048180 | Implement the Python class `QChemTest` described below.
Class description:
Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files.
Method signatures and docstrings:
- def testNumberOfAtomsFromQchemLog(self): Uses a Qchem log files to test that number of atoms can be properly read... | Implement the Python class `QChemTest` described below.
Class description:
Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files.
Method signatures and docstrings:
- def testNumberOfAtomsFromQchemLog(self): Uses a Qchem log files to test that number of atoms can be properly read... | 80deaebddcbb14b7c41e232b67e1c973e0b18324 | <|skeleton|>
class QChemTest:
"""Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files."""
def testNumberOfAtomsFromQchemLog(self):
"""Uses a Qchem log files to test that number of atoms can be properly read."""
<|body_0|>
def testEnergyFromQchemLog(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QChemTest:
"""Contains unit tests for the chempy.io.qchem module, used for reading and writing Qchem files."""
def testNumberOfAtomsFromQchemLog(self):
"""Uses a Qchem log files to test that number of atoms can be properly read."""
log = QchemLog(os.path.join(os.path.dirname(__file__), 'f... | the_stack_v2_python_sparse | rmgpy/cantherm/qchemTest.py | nateharms/RMG-Py | train | 1 |
5d6f6476206b064d1a570186d7527ff88993fa20 | [
"super(TopicRank, self).__init__()\nself.graph = nx.Graph()\n' The topic graph. '\nself.topics = []\n' The topic container. '",
"if pos is None:\n pos = {'NOUN', 'PROPN', 'ADJ'}\nself.longest_pos_sequence_selection(valid_pos=pos)\nif stoplist is None:\n stoplist = self.stoplist\nself.candidate_filtering(sto... | <|body_start_0|>
super(TopicRank, self).__init__()
self.graph = nx.Graph()
' The topic graph. '
self.topics = []
' The topic container. '
<|end_body_0|>
<|body_start_1|>
if pos is None:
pos = {'NOUN', 'PROPN', 'ADJ'}
self.longest_pos_sequence_selectio... | TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extractor.load_document(input='path/to/input.xml') # 3. select the longest sequences... | TopicRank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicRank:
"""TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extractor.load_document(input='path/to/input.xm... | stack_v2_sparse_classes_75kplus_train_007808 | 8,080 | permissive | [
{
"docstring": "Redefining initializer for TopicRank.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Selects longest sequences of nouns and adjectives as keyphrase candidates. Args: pos (set): the set of valid POS tags, defaults to ('NOUN', 'PROPN', 'ADJ'). stoplist (... | 6 | stack_v2_sparse_classes_30k_train_019190 | Implement the Python class `TopicRank` described below.
Class description:
TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extracto... | Implement the Python class `TopicRank` described below.
Class description:
TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extracto... | d16bf09e21521a6854ff3c7fe6eb271412914960 | <|skeleton|>
class TopicRank:
"""TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extractor.load_document(input='path/to/input.xm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopicRank:
"""TopicRank keyphrase extraction model. Parameterized example:: import pke import string from nltk.corpus import stopwords # 1. create a TopicRank extractor. extractor = pke.unsupervised.TopicRank() # 2. load the content of the document. extractor.load_document(input='path/to/input.xml') # 3. sele... | the_stack_v2_python_sparse | onmt/keyphrase/pke/unsupervised/graph_based/topicrank.py | memray/OpenNMT-kpg-release | train | 222 |
d41851637760815e8a3cd8de0970edc7a8c1090d | [
"super().__init__(channel)\nself._is_counter: bool = counter\nif self._is_counter:\n self._attr_unique_id = f'{self._attr_unique_id}-counter'\nif self._is_counter:\n self._attr_name = f'{self._attr_name}-counter'\nif self._is_counter:\n self._attr_device_class = SensorDeviceClass.POWER\nelif channel.is_cou... | <|body_start_0|>
super().__init__(channel)
self._is_counter: bool = counter
if self._is_counter:
self._attr_unique_id = f'{self._attr_unique_id}-counter'
if self._is_counter:
self._attr_name = f'{self._attr_name}-counter'
if self._is_counter:
s... | Representation of a sensor. | VelbusSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VelbusSensor:
"""Representation of a sensor."""
def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None:
"""Initialize a sensor Velbus entity."""
<|body_0|>
def native_value(self) -> float | int | None:
"... | stack_v2_sparse_classes_75kplus_train_007809 | 2,811 | permissive | [
{
"docstring": "Initialize a sensor Velbus entity.",
"name": "__init__",
"signature": "def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_018701 | Implement the Python class `VelbusSensor` described below.
Class description:
Representation of a sensor.
Method signatures and docstrings:
- def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None: Initialize a sensor Velbus entity.
- def native_value(self) ... | Implement the Python class `VelbusSensor` described below.
Class description:
Representation of a sensor.
Method signatures and docstrings:
- def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None: Initialize a sensor Velbus entity.
- def native_value(self) ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class VelbusSensor:
"""Representation of a sensor."""
def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None:
"""Initialize a sensor Velbus entity."""
<|body_0|>
def native_value(self) -> float | int | None:
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VelbusSensor:
"""Representation of a sensor."""
def __init__(self, channel: ButtonCounter | Temperature | LightSensor | SensorNumber, counter: bool=False) -> None:
"""Initialize a sensor Velbus entity."""
super().__init__(channel)
self._is_counter: bool = counter
if self._... | the_stack_v2_python_sparse | homeassistant/components/velbus/sensor.py | home-assistant/core | train | 35,501 |
412234f3cc68d56bb498c294609ed195b1fdab85 | [
"if self.is_db:\n return get_tables(self.db_url)\nreturn []",
"if self.is_db:\n ds = get_table(self.db_url, self.table)\nelse:\n ds = pd.read_csv(self.dataset.file)\nreturn ds.columns.to_list()"
] | <|body_start_0|>
if self.is_db:
return get_tables(self.db_url)
return []
<|end_body_0|>
<|body_start_1|>
if self.is_db:
ds = get_table(self.db_url, self.table)
else:
ds = pd.read_csv(self.dataset.file)
return ds.columns.to_list()
<|end_body_1|... | Scenario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBMS"""
<|body_0|>
def columns(self):
"""Return columns in selected dataset"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.is_db:
return get_tables(self.db_url)
return []
<|... | stack_v2_sparse_classes_75kplus_train_007810 | 2,759 | permissive | [
{
"docstring": "Return table in DBMS",
"name": "tables",
"signature": "def tables(self)"
},
{
"docstring": "Return columns in selected dataset",
"name": "columns",
"signature": "def columns(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032596 | Implement the Python class `Scenario` described below.
Class description:
Implement the Scenario class.
Method signatures and docstrings:
- def tables(self): Return table in DBMS
- def columns(self): Return columns in selected dataset | Implement the Python class `Scenario` described below.
Class description:
Implement the Scenario class.
Method signatures and docstrings:
- def tables(self): Return table in DBMS
- def columns(self): Return columns in selected dataset
<|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBM... | 4299f09a338209fb6f03cc7c0806f8cc01447fe0 | <|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBMS"""
<|body_0|>
def columns(self):
"""Return columns in selected dataset"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scenario:
def tables(self):
"""Return table in DBMS"""
if self.is_db:
return get_tables(self.db_url)
return []
def columns(self):
"""Return columns in selected dataset"""
if self.is_db:
ds = get_table(self.db_url, self.table)
else:
... | the_stack_v2_python_sparse | msp/models.py | softlab-unimore/MASQ | train | 1 | |
0a482f6731b03f6286617f939eeaaa7dc55604f1 | [
"with MongoDBConnection() as mongo:\n database = mongo.connection.hp_norton\n product_count, product_errors = self.import_csv(directory_name, product_file, database)\n LOGGER.debug('%s database successfully created.', product_file)\n customer_count, customer_errors = self.import_csv(directory_name, cust... | <|body_start_0|>
with MongoDBConnection() as mongo:
database = mongo.connection.hp_norton
product_count, product_errors = self.import_csv(directory_name, product_file, database)
LOGGER.debug('%s database successfully created.', product_file)
customer_count, custom... | Class to insert data into database | HPNortonData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HPNortonData:
"""Class to insert data into database"""
def import_data(self, directory_name, product_file, customer_file, rentals_file):
"""Import data file and return 2 tuples: the first with a record count of the number of products, customers and rentals added (in that order); the ... | stack_v2_sparse_classes_75kplus_train_007811 | 7,916 | no_license | [
{
"docstring": "Import data file and return 2 tuples: the first with a record count of the number of products, customers and rentals added (in that order); the second with a count of any errors that occurred, in the same order.",
"name": "import_data",
"signature": "def import_data(self, directory_name,... | 6 | stack_v2_sparse_classes_30k_train_022654 | Implement the Python class `HPNortonData` described below.
Class description:
Class to insert data into database
Method signatures and docstrings:
- def import_data(self, directory_name, product_file, customer_file, rentals_file): Import data file and return 2 tuples: the first with a record count of the number of pr... | Implement the Python class `HPNortonData` described below.
Class description:
Class to insert data into database
Method signatures and docstrings:
- def import_data(self, directory_name, product_file, customer_file, rentals_file): Import data file and return 2 tuples: the first with a record count of the number of pr... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class HPNortonData:
"""Class to insert data into database"""
def import_data(self, directory_name, product_file, customer_file, rentals_file):
"""Import data file and return 2 tuples: the first with a record count of the number of products, customers and rentals added (in that order); the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HPNortonData:
"""Class to insert data into database"""
def import_data(self, directory_name, product_file, customer_file, rentals_file):
"""Import data file and return 2 tuples: the first with a record count of the number of products, customers and rentals added (in that order); the second with a... | the_stack_v2_python_sparse | students/stellie/lesson10/assignment/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
654d1d3cc6e6dc4341c4c2ae4627f6b58877500d | [
"self.psum = []\ns = 0\nfor n in w:\n s += n\n self.psum.append(s)\nself.total = s",
"target = math.floor(self.total * random.random())\ni, j = (0, len(self.psum) - 1)\nwhile i + 1 < j:\n mid = (i + j) / 2\n if self.psum[mid] > target:\n j = mid\n else:\n i = mid\nif self.psum[i] > ta... | <|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
<|end_body_0|>
<|body_start_1|>
target = math.floor(self.total * random.random())
i, j = (0, len(self.psum) - 1)
while i + 1 < j:
mid =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append... | stack_v2_sparse_classes_75kplus_train_007812 | 1,609 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024942 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 6aaf58b1e1170a994affd6330d90b89aaaf582d9 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
def pickIndex(self):
""":rtype: int"""
target = math.floor(self.total * random.random())
... | the_stack_v2_python_sparse | Python/528.py | skywhat/leetcode | train | 82 | |
aa47fea00191988df92216098e43cab93958d3c8 | [
"self.name = name\nself.enc_size = enc_size\nself.dec_size = dec_size\nself.hid_size = hid_size\nself.activ = activ\nwith tf.variable_scope(name):\n self.dec = tf.get_variable('dec', shape=[dec_size, hid_size])\n self.enc = tf.get_variable('enc', shape=[enc_size, hid_size])\n self.vec = tf.get_variable('ve... | <|body_start_0|>
self.name = name
self.enc_size = enc_size
self.dec_size = dec_size
self.hid_size = hid_size
self.activ = activ
with tf.variable_scope(name):
self.dec = tf.get_variable('dec', shape=[dec_size, hid_size])
self.enc = tf.get_variable('... | AttentionLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionLayer:
def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh):
"""A basic layer that computes attention weights and response"""
<|body_0|>
def __call__(self, enc, dec, inp_mask):
"""Computes attention response and weights Input shapes: enc: [b... | stack_v2_sparse_classes_75kplus_train_007813 | 14,497 | no_license | [
{
"docstring": "A basic layer that computes attention weights and response",
"name": "__init__",
"signature": "def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh)"
},
{
"docstring": "Computes attention response and weights Input shapes: enc: [batch_size, ninp, enc_size] dec: [b... | 2 | null | Implement the Python class `AttentionLayer` described below.
Class description:
Implement the AttentionLayer class.
Method signatures and docstrings:
- def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh): A basic layer that computes attention weights and response
- def __call__(self, enc, dec, inp_m... | Implement the Python class `AttentionLayer` described below.
Class description:
Implement the AttentionLayer class.
Method signatures and docstrings:
- def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh): A basic layer that computes attention weights and response
- def __call__(self, enc, dec, inp_m... | 43c6a73dea76aa0b086c140ebd16c5bc2ea63bb0 | <|skeleton|>
class AttentionLayer:
def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh):
"""A basic layer that computes attention weights and response"""
<|body_0|>
def __call__(self, enc, dec, inp_mask):
"""Computes attention response and weights Input shapes: enc: [b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttentionLayer:
def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh):
"""A basic layer that computes attention weights and response"""
self.name = name
self.enc_size = enc_size
self.dec_size = dec_size
self.hid_size = hid_size
self.activ = activ... | the_stack_v2_python_sparse | lib/layers.py | TIXFeniks/babelSolution | train | 1 | |
14fd2dcf32edba90cfb3f9fcccde8b83374b1f46 | [
"self.index = 0\nself.length = len(A) // 2\nself.summ = [0] * self.length\nself.values = [0] * self.length\ntemp = 0\nfor i in range(0, self.length):\n times = A[i * 2]\n temp += times\n self.summ[i] = temp\n self.values[i] = A[i * 2 + 1]",
"self.index += n\nif self.index > self.summ[-1]:\n return ... | <|body_start_0|>
self.index = 0
self.length = len(A) // 2
self.summ = [0] * self.length
self.values = [0] * self.length
temp = 0
for i in range(0, self.length):
times = A[i * 2]
temp += times
self.summ[i] = temp
self.values[... | # memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(self, n): ''' :type n: int :rtype: int ''' self.index+=n if self.index<len(self... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
"""# memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(self, n): ''' :type n: int :rtype: int '... | stack_v2_sparse_classes_75kplus_train_007814 | 1,527 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | null | Implement the Python class `RLEIterator` described below.
Class description:
# memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(s... | Implement the Python class `RLEIterator` described below.
Class description:
# memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(s... | 4348bc3e41640675beb3efdf5b50068612e1999b | <|skeleton|>
class RLEIterator:
"""# memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(self, n): ''' :type n: int :rtype: int '... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RLEIterator:
"""# memory limit solution def __init__(self, A): ''' :type A: List[int] ''' # print(A) self.arr = [] self.index = 0 for i in range(0, len(A), 2): times, val = A[i], A[i+1] for j in range(times): self.arr.append(val) # print(self.arr) def next(self, n): ''' :type n: int :rtype: int ''' self.index... | the_stack_v2_python_sparse | 900-RLE_iterator/solution.py | frankShih/LeetCodePractice | train | 1 |
8cc9b9062ba3bbf2d38ce4cce5e1efa4a6b46d68 | [
"super(CNNConstraintChecker, self).__init__(max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, min_num_units_per_layer)\nself.max_num_2strides = max_num_2strides\nself.constraint_names.append('max_num_2strides')",
"img_inv_sizes = [piis for p... | <|body_start_0|>
super(CNNConstraintChecker, self).__init__(max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, min_num_units_per_layer)
self.max_num_2strides = max_num_2strides
self.constraint_names.append('max_num_2strides'... | A class for checking if a CNN satisfies constraints. | CNNConstraintChecker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNConstraintChecker:
"""A class for checking if a CNN satisfies constraints."""
def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, min_num_units_per_layer, max_num_2strides=None):
"""Construct... | stack_v2_sparse_classes_75kplus_train_007815 | 9,463 | permissive | [
{
"docstring": "Constructor. max_num_2strides is the maximum number of 2-strides (either via pooling or conv operations) that the image can go through in the network.",
"name": "__init__",
"signature": "def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree,... | 2 | null | Implement the Python class `CNNConstraintChecker` described below.
Class description:
A class for checking if a CNN satisfies constraints.
Method signatures and docstrings:
- def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, m... | Implement the Python class `CNNConstraintChecker` described below.
Class description:
A class for checking if a CNN satisfies constraints.
Method signatures and docstrings:
- def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, m... | 3eef7d30bcc2e56f2221a624bd8ec7f933f81e40 | <|skeleton|>
class CNNConstraintChecker:
"""A class for checking if a CNN satisfies constraints."""
def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, min_num_units_per_layer, max_num_2strides=None):
"""Construct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNNConstraintChecker:
"""A class for checking if a CNN satisfies constraints."""
def __init__(self, max_num_layers, min_num_layers, max_mass, min_mass, max_in_degree, max_out_degree, max_num_edges, max_num_units_per_layer, min_num_units_per_layer, max_num_2strides=None):
"""Constructor. max_num_2... | the_stack_v2_python_sparse | dragonfly/nn/nn_domains.py | dragonfly/dragonfly | train | 868 |
b4f7e2212b4b22a17b8771713ab4761ca709f65b | [
"path = os.path.join(BASE_DIR, 'librairy/test_files')\nrecursive_import(path)\npicts = Picture.objects.all().count()\nself.assertEqual(picts, 3)",
"path = os.path.join(BASE_DIR, 'librairy/test_files/test.zip')\nrecursive_import(path)\npicts = Picture.objects.all().count()\nself.assertEqual(picts, 1)",
"recursiv... | <|body_start_0|>
path = os.path.join(BASE_DIR, 'librairy/test_files')
recursive_import(path)
picts = Picture.objects.all().count()
self.assertEqual(picts, 3)
<|end_body_0|>
<|body_start_1|>
path = os.path.join(BASE_DIR, 'librairy/test_files/test.zip')
recursive_import(pa... | Command line import test class. | RecursiveImportTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecursiveImportTest:
"""Command line import test class."""
def test_with_folder(self):
"""Test with one folder path as argument."""
<|body_0|>
def test_with_zip_archive(self):
"""Test with one archive as argument."""
<|body_1|>
def test_with_picture(... | stack_v2_sparse_classes_75kplus_train_007816 | 44,838 | no_license | [
{
"docstring": "Test with one folder path as argument.",
"name": "test_with_folder",
"signature": "def test_with_folder(self)"
},
{
"docstring": "Test with one archive as argument.",
"name": "test_with_zip_archive",
"signature": "def test_with_zip_archive(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_002673 | Implement the Python class `RecursiveImportTest` described below.
Class description:
Command line import test class.
Method signatures and docstrings:
- def test_with_folder(self): Test with one folder path as argument.
- def test_with_zip_archive(self): Test with one archive as argument.
- def test_with_picture(self... | Implement the Python class `RecursiveImportTest` described below.
Class description:
Command line import test class.
Method signatures and docstrings:
- def test_with_folder(self): Test with one folder path as argument.
- def test_with_zip_archive(self): Test with one archive as argument.
- def test_with_picture(self... | ed2e458dfb6247d7fe487f4795a855a5275cfe5f | <|skeleton|>
class RecursiveImportTest:
"""Command line import test class."""
def test_with_folder(self):
"""Test with one folder path as argument."""
<|body_0|>
def test_with_zip_archive(self):
"""Test with one archive as argument."""
<|body_1|>
def test_with_picture(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecursiveImportTest:
"""Command line import test class."""
def test_with_folder(self):
"""Test with one folder path as argument."""
path = os.path.join(BASE_DIR, 'librairy/test_files')
recursive_import(path)
picts = Picture.objects.all().count()
self.assertEqual(pi... | the_stack_v2_python_sparse | src/api/librairy/tests.py | Fenykepy/phiroom | train | 1 |
84577c5a6a4b00c68d535fa9ecd937f18d80b2b0 | [
"safe_mkfdir(file_path)\nhparams_to_save = self._get_simple_attrs()\nf = codecs.open(file_path, encoding=encoding, mode='w')\njson.dump(hparams_to_save, f, indent=2)\nlogger.debug(\"Extracted the following hparams: '%s'.\" % ' '.join(hparams_to_save.keys()))\nlogger.info(\"Saved hyper-parameters to '%s'.\" % file_p... | <|body_start_0|>
safe_mkfdir(file_path)
hparams_to_save = self._get_simple_attrs()
f = codecs.open(file_path, encoding=encoding, mode='w')
json.dump(hparams_to_save, f, indent=2)
logger.debug("Extracted the following hparams: '%s'." % ' '.join(hparams_to_save.keys()))
log... | Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string, integer, boolean, float, list, etc. | BaseHp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHp:
"""Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string, integer, boolean, float, list, etc."""... | stack_v2_sparse_classes_75kplus_train_007817 | 3,112 | permissive | [
{
"docstring": "Saves hyper-params object as a json file.",
"name": "save",
"signature": "def save(self, file_path, encoding='utf-8')"
},
{
"docstring": "Loads hyper-params from a json file.",
"name": "load",
"signature": "def load(self, file_path, encoding='utf-8')"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_005887 | Implement the Python class `BaseHp` described below.
Class description:
Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string,... | Implement the Python class `BaseHp` described below.
Class description:
Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string,... | acc192bafc66b7661d541ef4f604b5e5ab7df5ca | <|skeleton|>
class BaseHp:
"""Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string, integer, boolean, float, list, etc."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseHp:
"""Children objects of this class can be used to store default hyper-parameters override then when necessary through loading, and then save them to a json file. Not all hyper-param fields can be saved and loaded, only of simple types, such as string, integer, boolean, float, list, etc."""
def sav... | the_stack_v2_python_sparse | mlmo/utils/tools/base_hp.py | DanielGutmann/mltoolkit | train | 0 |
cf84c3d572c10e281bac5f75e61ed3f432e71777 | [
"super().__init__()\nkwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_seasonality': daily_seasonality, ... | <|body_start_0|>
super().__init__()
kwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_season... | OutlierProphet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_75kplus_train_007818 | 8,498 | permissive | [
{
"docstring": "Outlier detector for time series data using fbprophet. See https://facebook.github.io/prophet/ for more details. Parameters ---------- threshold Width of the uncertainty intervals of the forecast, used as outlier threshold. Equivalent to `interval_width`. If the instance lies outside of the unce... | 4 | stack_v2_sparse_classes_30k_train_023074 | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_seasonality: Uni... | the_stack_v2_python_sparse | alibi_detect/od/prophet.py | SeldonIO/alibi-detect | train | 1,922 | |
b087de4988bdfd99d2c3610f3806a500aacf169e | [
"if not s:\n return False\na = (s + s)[1:-1]\nreturn s in a",
"len_s = len(s)\ngap = 2\nwhile gap <= len_s:\n if len_s % gap != 0:\n gap += 1\n continue\n step = len_s / gap\n start = 0\n while start <= len_s - 2 * step:\n if s[start:start + step] != s[start + step:start + 2 * ... | <|body_start_0|>
if not s:
return False
a = (s + s)[1:-1]
return s in a
<|end_body_0|>
<|body_start_1|>
len_s = len(s)
gap = 2
while gap <= len_s:
if len_s % gap != 0:
gap += 1
continue
step = len_s / ga... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def ____repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def ___repeatedSubstringPattern(self, s):
""":type s: str :rtype: bo... | stack_v2_sparse_classes_75kplus_train_007819 | 14,863 | permissive | [
{
"docstring": ":type s: str :rtype: bool",
"name": "repeatedSubstringPattern",
"signature": "def repeatedSubstringPattern(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "____repeatedSubstringPattern",
"signature": "def ____repeatedSubstringPattern(self, s)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_035106 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def ____repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def ___repeatedSubstringPattern(self, s)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def ____repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def ___repeatedSubstringPattern(self, s)... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def ____repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def ___repeatedSubstringPattern(self, s):
""":type s: str :rtype: bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
if not s:
return False
a = (s + s)[1:-1]
return s in a
def ____repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
len_s = len(s)
gap = 2
... | the_stack_v2_python_sparse | 459.repeated-substring-pattern.py | windard/leeeeee | train | 0 | |
8506068dfebcad06906f4f2a08004d41faeef545 | [
"if not head:\n return head\nnewHead = head\ntail = head\nlength = 1\nwhile tail.next:\n tail = tail.next\n length += 1\ntail.next = head\nk = k % length\nif k:\n for i in range(length - k):\n tail = tail.next\nnewHead = tail.next\ntail.next = None\nreturn newHead",
"if not head or k == 0:\n ... | <|body_start_0|>
if not head:
return head
newHead = head
tail = head
length = 1
while tail.next:
tail = tail.next
length += 1
tail.next = head
k = k % length
if k:
for i in range(length - k):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight_self(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007820 | 1,498 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight_self",
"signature": "def rotateRight_self(self, head, k)"... | 2 | stack_v2_sparse_classes_30k_train_034621 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight_self(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight_self(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|sk... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight_self(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if not head:
return head
newHead = head
tail = head
length = 1
while tail.next:
tail = tail.next
length += 1
tail.next ... | the_stack_v2_python_sparse | 61_rotate_list/sol.py | lianke123321/leetcode_sol | train | 0 | |
9e4b268afffe19e25278214c982f35b872917655 | [
"self.m = m\nself.k = k\nself.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)]",
"output = []\nfor idx, vc in enumerate(value_counts):\n hashers = self.hashers[idx * self.k:(idx + 1) * self.k]\n for h in hashers:\n hist = [0 for i in range(2 ** self.m)]... | <|body_start_0|>
self.m = m
self.k = k
self.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)]
<|end_body_0|>
<|body_start_1|>
output = []
for idx, vc in enumerate(value_counts):
hashers = self.hashers[idx * self.k:(idx +... | HistogramClones | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistogramClones:
def __init__(self, m, k):
"""Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones"""
<|body_0|>
def value_counts_to_hists(self, value_counts):
"""convert value counts of columns to histogram clones Arguments: value_counts {... | stack_v2_sparse_classes_75kplus_train_007821 | 4,897 | no_license | [
{
"docstring": "Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones",
"name": "__init__",
"signature": "def __init__(self, m, k)"
},
{
"docstring": "convert value counts of columns to histogram clones Arguments: value_counts {list of Counters} Returns: [type] -- [desc... | 3 | stack_v2_sparse_classes_30k_val_002923 | Implement the Python class `HistogramClones` described below.
Class description:
Implement the HistogramClones class.
Method signatures and docstrings:
- def __init__(self, m, k): Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones
- def value_counts_to_hists(self, value_counts): convert v... | Implement the Python class `HistogramClones` described below.
Class description:
Implement the HistogramClones class.
Method signatures and docstrings:
- def __init__(self, m, k): Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones
- def value_counts_to_hists(self, value_counts): convert v... | aa46c84169b8c6c4fb0deefb453e5d4d9e80dc0f | <|skeleton|>
class HistogramClones:
def __init__(self, m, k):
"""Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones"""
<|body_0|>
def value_counts_to_hists(self, value_counts):
"""convert value counts of columns to histogram clones Arguments: value_counts {... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HistogramClones:
def __init__(self, m, k):
"""Arguments: m {int} -- hash function length (2 ** m) k {int} -- number of clones"""
self.m = m
self.k = k
self.hashers = [HashFunction(seed=i, length=m) for i in range(len(hist_cols)) for j in range(self.k)]
def value_counts_to_... | the_stack_v2_python_sparse | histogram/compute_kl.py | Narkle/UGR_Experiments | train | 0 | |
3077e02aedcefa71ae1deca322044b8e143c0513 | [
"super(TorchVisionSSLPIRL, self).__init__()\nself.model_function = get_object_from_path(config.cfg['model']['model_function_path'])\nself.pretrained = config.cfg['model']['pretrained']\nself.num_classes = config.cfg['model']['classes_count']\nnet = self.model_function(pretrained=self.pretrained)\nnet_list = list(ne... | <|body_start_0|>
super(TorchVisionSSLPIRL, self).__init__()
self.model_function = get_object_from_path(config.cfg['model']['model_function_path'])
self.pretrained = config.cfg['model']['pretrained']
self.num_classes = config.cfg['model']['classes_count']
net = self.model_function... | The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network. | TorchVisionSSLPIRL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchVisionSSLPIRL:
"""The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model :param config: Configuration c... | stack_v2_sparse_classes_75kplus_train_007822 | 4,152 | permissive | [
{
"docstring": "Constructor, the function parse the config and initialize the layers of the corresponding model :param config: Configuration class object",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "The function implements the forward pass of the model. :par... | 2 | null | Implement the Python class `TorchVisionSSLPIRL` described below.
Class description:
The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the config and initialize the layers ... | Implement the Python class `TorchVisionSSLPIRL` described below.
Class description:
The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the config and initialize the layers ... | 9a4bf0a112b818caca8794868a903dc736839a43 | <|skeleton|>
class TorchVisionSSLPIRL:
"""The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model :param config: Configuration c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TorchVisionSSLPIRL:
"""The class adds constrastive SSL based PIRL as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model :param config: Configuration class object""... | the_stack_v2_python_sparse | model/torchvision_ssl_pirl.py | Niousha12/ssl_for_fgvc | train | 0 |
0983b76ee3aac647289d9a6947d3ff3a0ecc7b04 | [
"self.env = env\nself.func = self.RIS if type == 'RIS' else self.OIS\nself.isMAML = isMAML\nself.D = None",
"total_reward = 0\nstate = self.env.reset()\ncounter = 0\nOIS = {'pi_e': [], 'pi_k': []}\nois = []\nwhile True:\n action, prob_behv = behavior_agent.get_action(behavior_agent.Q, state, eps=0)\n _, pro... | <|body_start_0|>
self.env = env
self.func = self.RIS if type == 'RIS' else self.OIS
self.isMAML = isMAML
self.D = None
<|end_body_0|>
<|body_start_1|>
total_reward = 0
state = self.env.reset()
counter = 0
OIS = {'pi_e': [], 'pi_k': []}
ois = []
... | Class to implement different Importance Sampling functions | IS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IS:
"""Class to implement different Importance Sampling functions"""
def __init__(self, env, isMAML, type='OIS'):
"""Define Importance Sampling function type"""
<|body_0|>
def OIS(self, evaluation_agent: Agent, behavior_agent: Agent):
"""> Calculates ordinary imp... | stack_v2_sparse_classes_75kplus_train_007823 | 6,055 | no_license | [
{
"docstring": "Define Importance Sampling function type",
"name": "__init__",
"signature": "def __init__(self, env, isMAML, type='OIS')"
},
{
"docstring": "> Calculates ordinary importance sampling between behavior agent and evaluation agent > Calculates Return value (total reward) for behavior... | 5 | stack_v2_sparse_classes_30k_train_031422 | Implement the Python class `IS` described below.
Class description:
Class to implement different Importance Sampling functions
Method signatures and docstrings:
- def __init__(self, env, isMAML, type='OIS'): Define Importance Sampling function type
- def OIS(self, evaluation_agent: Agent, behavior_agent: Agent): > Ca... | Implement the Python class `IS` described below.
Class description:
Class to implement different Importance Sampling functions
Method signatures and docstrings:
- def __init__(self, env, isMAML, type='OIS'): Define Importance Sampling function type
- def OIS(self, evaluation_agent: Agent, behavior_agent: Agent): > Ca... | 84c79dcf1bfe39b27dad0021e11f0a31f6774599 | <|skeleton|>
class IS:
"""Class to implement different Importance Sampling functions"""
def __init__(self, env, isMAML, type='OIS'):
"""Define Importance Sampling function type"""
<|body_0|>
def OIS(self, evaluation_agent: Agent, behavior_agent: Agent):
"""> Calculates ordinary imp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IS:
"""Class to implement different Importance Sampling functions"""
def __init__(self, env, isMAML, type='OIS'):
"""Define Importance Sampling function type"""
self.env = env
self.func = self.RIS if type == 'RIS' else self.OIS
self.isMAML = isMAML
self.D = None
... | the_stack_v2_python_sparse | TD/code/estimator.py | hercules261188/off-policy-evaluation | train | 0 |
c81485b12e0f5b88bd2ddec7325e0bd1e3335c2a | [
"self.mutate_max_count = mutate_max_count\nself.mutate_funcs = MANGLE_FUNCS\nself.mutate_func_count = len(MANGLE_FUNCS)\nself.callback = callback\nmangle.TOKEN = token",
"if fuzz_rate == 1 or len(data) < 20:\n count = random.randint(1, self.mutate_max_count)\n for i in xrange(count):\n func = self.mu... | <|body_start_0|>
self.mutate_max_count = mutate_max_count
self.mutate_funcs = MANGLE_FUNCS
self.mutate_func_count = len(MANGLE_FUNCS)
self.callback = callback
mangle.TOKEN = token
<|end_body_0|>
<|body_start_1|>
if fuzz_rate == 1 or len(data) < 20:
count = ra... | 随机选取变异函数,对数据进行变异 | Mutater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mutater:
"""随机选取变异函数,对数据进行变异"""
def __init__(self, mutate_max_count=3, token=[], callback=None):
""":param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面"""
<|body_0|>
def mutate(self, data, maxlen=4294967295, fuzz_rate=1):
... | stack_v2_sparse_classes_75kplus_train_007824 | 2,889 | no_license | [
{
"docstring": ":param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面",
"name": "__init__",
"signature": "def __init__(self, mutate_max_count=3, token=[], callback=None)"
},
{
"docstring": "对 data 进行变异 :param data: 待变异的数据 :param callback: 对变异后的数据进行修正的callb... | 2 | stack_v2_sparse_classes_30k_train_024292 | Implement the Python class `Mutater` described below.
Class description:
随机选取变异函数,对数据进行变异
Method signatures and docstrings:
- def __init__(self, mutate_max_count=3, token=[], callback=None): :param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面
- def mutate(self, data, maxlen=4... | Implement the Python class `Mutater` described below.
Class description:
随机选取变异函数,对数据进行变异
Method signatures and docstrings:
- def __init__(self, mutate_max_count=3, token=[], callback=None): :param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面
- def mutate(self, data, maxlen=4... | e301033a52473a14c4454274331102270228d5f5 | <|skeleton|>
class Mutater:
"""随机选取变异函数,对数据进行变异"""
def __init__(self, mutate_max_count=3, token=[], callback=None):
""":param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面"""
<|body_0|>
def mutate(self, data, maxlen=4294967295, fuzz_rate=1):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mutater:
"""随机选取变异函数,对数据进行变异"""
def __init__(self, mutate_max_count=3, token=[], callback=None):
""":param mutate_max_count: 最大变异次数,程序会从 1,mutate_max_count 选取每次的变异次数 :param token: 用于插入一些常量到数据里面"""
self.mutate_max_count = mutate_max_count
self.mutate_funcs = MANGLE_FUNCS
se... | the_stack_v2_python_sparse | cpf/mutate/Mutater.py | hac425xxx/cpf | train | 1 |
6003accda62ffb0b7e417a4d05400e8e3a67154d | [
"lst = [['royal', _('decree_type_royal', 'urban', context=self.REQUEST)], ['regent', _('decree_type_regent', 'urban', context=self.REQUEST)], ['departmental', _('decree_type_departmental', 'urban', context=self.REQUEST)], ['municipal', _('decree_type_municipal', 'urban', context=self.REQUEST)]]\nvocab = []\nfor elt... | <|body_start_0|>
lst = [['royal', _('decree_type_royal', 'urban', context=self.REQUEST)], ['regent', _('decree_type_regent', 'urban', context=self.REQUEST)], ['departmental', _('decree_type_departmental', 'urban', context=self.REQUEST)], ['municipal', _('decree_type_municipal', 'urban', context=self.REQUEST)]]
... | PcaTerm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PcaTerm:
def listDecreeTypes(self):
"""Return a list of decree types"""
<|body_0|>
def updateTitle(self):
"""Override the Title method to display several data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lst = [['royal', _('decree_type_royal', 'u... | stack_v2_sparse_classes_75kplus_train_007825 | 4,681 | no_license | [
{
"docstring": "Return a list of decree types",
"name": "listDecreeTypes",
"signature": "def listDecreeTypes(self)"
},
{
"docstring": "Override the Title method to display several data",
"name": "updateTitle",
"signature": "def updateTitle(self)"
}
] | 2 | null | Implement the Python class `PcaTerm` described below.
Class description:
Implement the PcaTerm class.
Method signatures and docstrings:
- def listDecreeTypes(self): Return a list of decree types
- def updateTitle(self): Override the Title method to display several data | Implement the Python class `PcaTerm` described below.
Class description:
Implement the PcaTerm class.
Method signatures and docstrings:
- def listDecreeTypes(self): Return a list of decree types
- def updateTitle(self): Override the Title method to display several data
<|skeleton|>
class PcaTerm:
def listDecree... | 4d1cc1ab86fbf5e18d745b9297f0c6326c0f4811 | <|skeleton|>
class PcaTerm:
def listDecreeTypes(self):
"""Return a list of decree types"""
<|body_0|>
def updateTitle(self):
"""Override the Title method to display several data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PcaTerm:
def listDecreeTypes(self):
"""Return a list of decree types"""
lst = [['royal', _('decree_type_royal', 'urban', context=self.REQUEST)], ['regent', _('decree_type_regent', 'urban', context=self.REQUEST)], ['departmental', _('decree_type_departmental', 'urban', context=self.REQUEST)], [... | the_stack_v2_python_sparse | src/Products/urban/PcaTerm.py | IMIO/Products.urban | train | 1 | |
16d2159a79e1bf886a49d7db52e067aa0a2b22f3 | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(FullProductForm, self).__init__(*args, **kwargs)\nself.fields['product'].label = 'Produkt'\nself.fields['amount'].label = u'Ilość'\nself.fields['product'].empty_label = None\nself.fields['product'].queryset = Product.objects.filter(caf... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(FullProductForm, self).__init__(*args, **kwargs)
self.fields['product'].label = 'Produkt'
self.fields['amount'].label = u'Ilość'
self.fields['product'].empty_label = None
... | Responsible for setting up a FullProduct - Product with its amount. | FullProductForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullProductForm:
"""Responsible for setting up a FullProduct - Product with its amount."""
def __init__(self, *args, **kwargs):
"""Initialize all FullProduct's fields."""
<|body_0|>
def save(self, commit=True):
"""Override of save method, to add Caffe relation.""... | stack_v2_sparse_classes_75kplus_train_007826 | 5,569 | permissive | [
{
"docstring": "Initialize all FullProduct's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Override of save method, to add Caffe relation.",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011027 | Implement the Python class `FullProductForm` described below.
Class description:
Responsible for setting up a FullProduct - Product with its amount.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all FullProduct's fields.
- def save(self, commit=True): Override of save method, to ... | Implement the Python class `FullProductForm` described below.
Class description:
Responsible for setting up a FullProduct - Product with its amount.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all FullProduct's fields.
- def save(self, commit=True): Override of save method, to ... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class FullProductForm:
"""Responsible for setting up a FullProduct - Product with its amount."""
def __init__(self, *args, **kwargs):
"""Initialize all FullProduct's fields."""
<|body_0|>
def save(self, commit=True):
"""Override of save method, to add Caffe relation.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FullProductForm:
"""Responsible for setting up a FullProduct - Product with its amount."""
def __init__(self, *args, **kwargs):
"""Initialize all FullProduct's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(FullProductForm, self)._... | the_stack_v2_python_sparse | caffe/reports/forms.py | VirrageS/io-kawiarnie | train | 3 |
83d1a74a776e03ecc4f71603960235fbd8a9f7c0 | [
"self.ctx = TritonContext()\nself.ctx.setArchitecture(ARCH.X86)\ninst1 = Instruction(b'\\xbc\\x00\\xfe\\x19\\x00')\ninst2 = Instruction(b'\\xc7\\x04$\\x11\\x11\\x11\\x11')\ninst3 = Instruction(b'\\x8f\\x04$')\nself.ctx.processing(inst1)\nself.ctx.processing(inst2)\nself.ctx.processing(inst3)\nself.assertEqual(inst3... | <|body_start_0|>
self.ctx = TritonContext()
self.ctx.setArchitecture(ARCH.X86)
inst1 = Instruction(b'\xbc\x00\xfe\x19\x00')
inst2 = Instruction(b'\xc7\x04$\x11\x11\x11\x11')
inst3 = Instruction(b'\x8f\x04$')
self.ctx.processing(inst1)
self.ctx.processing(inst2)
... | Test processing for some error prone instruction. | TestProcessing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProcessing:
"""Test processing for some error prone instruction."""
def test_pop_esp(self):
"""Check pop on esp processing."""
<|body_0|>
def test_pop(self):
"""Check the pop instruction processing."""
<|body_1|>
def test_mov_xmm_to_memory(self):... | stack_v2_sparse_classes_75kplus_train_007827 | 14,500 | permissive | [
{
"docstring": "Check pop on esp processing.",
"name": "test_pop_esp",
"signature": "def test_pop_esp(self)"
},
{
"docstring": "Check the pop instruction processing.",
"name": "test_pop",
"signature": "def test_pop(self)"
},
{
"docstring": "Check move and xmm register to memory d... | 4 | null | Implement the Python class `TestProcessing` described below.
Class description:
Test processing for some error prone instruction.
Method signatures and docstrings:
- def test_pop_esp(self): Check pop on esp processing.
- def test_pop(self): Check the pop instruction processing.
- def test_mov_xmm_to_memory(self): Che... | Implement the Python class `TestProcessing` described below.
Class description:
Test processing for some error prone instruction.
Method signatures and docstrings:
- def test_pop_esp(self): Check pop on esp processing.
- def test_pop(self): Check the pop instruction processing.
- def test_mov_xmm_to_memory(self): Che... | a61651ce331ac53ec09e1d8fef5eab744e98c9de | <|skeleton|>
class TestProcessing:
"""Test processing for some error prone instruction."""
def test_pop_esp(self):
"""Check pop on esp processing."""
<|body_0|>
def test_pop(self):
"""Check the pop instruction processing."""
<|body_1|>
def test_mov_xmm_to_memory(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProcessing:
"""Test processing for some error prone instruction."""
def test_pop_esp(self):
"""Check pop on esp processing."""
self.ctx = TritonContext()
self.ctx.setArchitecture(ARCH.X86)
inst1 = Instruction(b'\xbc\x00\xfe\x19\x00')
inst2 = Instruction(b'\xc7\... | the_stack_v2_python_sparse | src/testers/unittests/test_instruction.py | JonathanSalwan/Triton | train | 3,163 |
22151e931bb257f03b15915f228ef012e09576e4 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"a = np.sum(X1 ** 2, 1).reshape(-1, 1)\nsqdist = a + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\nreturn self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)"
] | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
a = np.sum(X1 ** 2, 1).reshape(-1, 1)
sqdist = a + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
return sel... | Gaussian Class | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Gaussian Class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init (np.ndarray): shape (t, 1) representing the outputs of th... | stack_v2_sparse_classes_75kplus_train_007828 | 1,354 | no_license | [
{
"docstring": "Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init (np.ndarray): shape (t, 1) representing the outputs of the black-box function for each input in X_init. l (int): the length parameter for the kernel. sigma_f (int... | 2 | stack_v2_sparse_classes_30k_train_010742 | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian Class
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init ... | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian Class
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init ... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class GaussianProcess:
"""Gaussian Class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init (np.ndarray): shape (t, 1) representing the outputs of th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcess:
"""Gaussian Class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor Args: X_init (np.ndarray): shape (t, 1) representing the inputs already sampled with the black-box function. Y_init (np.ndarray): shape (t, 1) representing the outputs of the black-box f... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
e4be1aa0047dc304797bd6914941038245f5307f | [
"a = ReadModels.Distribution.Flat(10)\nfor i in a:\n self.assert_(i == 1, 'Values in Flat array are not equal to 1.')\nself.assert_(len(a) == 10, 'Flat array is not the right size ')",
"a = ReadModels.Distribution.Triangle(50, 100, 150)\nz = 1\nfor i in a:\n self.assert_(i <= z, 'Values must not rise in Tri... | <|body_start_0|>
a = ReadModels.Distribution.Flat(10)
for i in a:
self.assert_(i == 1, 'Values in Flat array are not equal to 1.')
self.assert_(len(a) == 10, 'Flat array is not the right size ')
<|end_body_0|>
<|body_start_1|>
a = ReadModels.Distribution.Triangle(50, 100, 15... | Unit tests for Read Models | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
<|body_0|>
def testTriangle(self):
"""test the triangle model"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = ReadModels.Distribution.Flat(10)
f... | stack_v2_sparse_classes_75kplus_train_007829 | 927 | no_license | [
{
"docstring": "test out the flat model",
"name": "testFlat",
"signature": "def testFlat(self)"
},
{
"docstring": "test the triangle model",
"name": "testTriangle",
"signature": "def testTriangle(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003898 | Implement the Python class `Test` described below.
Class description:
Unit tests for Read Models
Method signatures and docstrings:
- def testFlat(self): test out the flat model
- def testTriangle(self): test the triangle model | Implement the Python class `Test` described below.
Class description:
Unit tests for Read Models
Method signatures and docstrings:
- def testFlat(self): test out the flat model
- def testTriangle(self): test the triangle model
<|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
... | a6db43f36afd71f7e31fd4b071f73db0878b10e3 | <|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
<|body_0|>
def testTriangle(self):
"""test the triangle model"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
a = ReadModels.Distribution.Flat(10)
for i in a:
self.assert_(i == 1, 'Values in Flat array are not equal to 1.')
self.assert_(len(a) == 10, 'Flat array is not the right si... | the_stack_v2_python_sparse | Epigenetics/WaveGenerator/Utilities/TestReadModels.py | jmrinaldi/epigenetics-software | train | 0 |
abe769ab570ea811d806c45d727005c4fe3fd36c | [
"shortcut = data\nbn1 = BatchNormalization(axis=chan_dim, epsilon=bn_epsilon, momentum=bn_momentum)(data)\nact1 = Activation('relu')(bn1)\nconv1 = Conv2D(int(K * 0.25), (1, 1), use_bias=False, kernel_regularizer=l2(regularization))(act1)\nbn2 = BatchNormalization(axis=chan_dim, epsilon=bn_epsilon, momentum=bn_momen... | <|body_start_0|>
shortcut = data
bn1 = BatchNormalization(axis=chan_dim, epsilon=bn_epsilon, momentum=bn_momentum)(data)
act1 = Activation('relu')(bn1)
conv1 = Conv2D(int(K * 0.25), (1, 1), use_bias=False, kernel_regularizer=l2(regularization))(act1)
bn2 = BatchNormalization(axis... | ResNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chan_dim, reduce=False, regularization=0.0001, bn_epsilon=2e-05, bn_momentum=0.9):
"""残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv 的 kernel 个数就是 K/4 :param stride: conv 的 stride :param chan_dim: channel 的维度序号, tf 就是 -1 :param... | stack_v2_sparse_classes_75kplus_train_007830 | 5,715 | no_license | [
{
"docstring": "残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv 的 kernel 个数就是 K/4 :param stride: conv 的 stride :param chan_dim: channel 的维度序号, tf 就是 -1 :param reduce: 是否减少维度 :param regularization: 不太懂 :param bn_epsilon: 不太懂,防止除 0 :param bn_momentum: 不太懂 :return:",
"name": "residual_module",
... | 2 | stack_v2_sparse_classes_30k_train_017949 | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chan_dim, reduce=False, regularization=0.0001, bn_epsilon=2e-05, bn_momentum=0.9): 残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv... | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chan_dim, reduce=False, regularization=0.0001, bn_epsilon=2e-05, bn_momentum=0.9): 残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv... | b342635c7499d7ff507c630e84faa0621e8cd10a | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chan_dim, reduce=False, regularization=0.0001, bn_epsilon=2e-05, bn_momentum=0.9):
"""残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv 的 kernel 个数就是 K/4 :param stride: conv 的 stride :param chan_dim: channel 的维度序号, tf 就是 -1 :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet:
def residual_module(data, K, stride, chan_dim, reduce=False, regularization=0.0001, bn_epsilon=2e-05, bn_momentum=0.9):
"""残缺模块 :param data: 输入 :param K: 最后一个 conv 的 kernel 个数, 前两个 conv 的 kernel 个数就是 K/4 :param stride: conv 的 stride :param chan_dim: channel 的维度序号, tf 就是 -1 :param reduce: 是否减少维... | the_stack_v2_python_sparse | nn/cnn/resnet.py | xuannianc/spinach | train | 0 | |
3ef678a1342741e610ad44441e2cd5f629f57173 | [
"self.__dataset_path = dataset_path\nself.__trainX = None\nself.__trainY = None\nself.__testX = None\nself.__testY = None\nself.__valX = None\nself.__valY = None\nself.__lb = LabelBinarizer()\nself.__data = []\nself.__labels = []",
"self.__loading_Images()\nself.__scale_Pixels()\nself.__divide_data()\nreturn (sel... | <|body_start_0|>
self.__dataset_path = dataset_path
self.__trainX = None
self.__trainY = None
self.__testX = None
self.__testY = None
self.__valX = None
self.__valY = None
self.__lb = LabelBinarizer()
self.__data = []
self.__labels = []
<|e... | LoadData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadData:
def __init__(self, dataset_path):
"""Create the HandleData class object. :param dataset_path: string :return: None"""
<|body_0|>
def handle_dataset(self):
"""this function manage the HandleData class :param: None :return self.__trainX: array :return self.__... | stack_v2_sparse_classes_75kplus_train_007831 | 5,531 | no_license | [
{
"docstring": "Create the HandleData class object. :param dataset_path: string :return: None",
"name": "__init__",
"signature": "def __init__(self, dataset_path)"
},
{
"docstring": "this function manage the HandleData class :param: None :return self.__trainX: array :return self.__trainY: array ... | 5 | stack_v2_sparse_classes_30k_train_000308 | Implement the Python class `LoadData` described below.
Class description:
Implement the LoadData class.
Method signatures and docstrings:
- def __init__(self, dataset_path): Create the HandleData class object. :param dataset_path: string :return: None
- def handle_dataset(self): this function manage the HandleData cl... | Implement the Python class `LoadData` described below.
Class description:
Implement the LoadData class.
Method signatures and docstrings:
- def __init__(self, dataset_path): Create the HandleData class object. :param dataset_path: string :return: None
- def handle_dataset(self): this function manage the HandleData cl... | 9b7f035dca04e9ac4d20d4d9fa9e687ce583603b | <|skeleton|>
class LoadData:
def __init__(self, dataset_path):
"""Create the HandleData class object. :param dataset_path: string :return: None"""
<|body_0|>
def handle_dataset(self):
"""this function manage the HandleData class :param: None :return self.__trainX: array :return self.__... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadData:
def __init__(self, dataset_path):
"""Create the HandleData class object. :param dataset_path: string :return: None"""
self.__dataset_path = dataset_path
self.__trainX = None
self.__trainY = None
self.__testX = None
self.__testY = None
self.__va... | the_stack_v2_python_sparse | python files/load_data.py | maayan121/project_python_letters-DL | train | 0 | |
da1bbca654699c81c25baa88de537412c1017b5d | [
"if not type(url_feed) is str:\n raise TypeError(f\"Parameter 'url_feed' is of type {type(url_feed)}. This attribute must be an instance of string.\")\nself._url_feed = url_feed",
"if not self._url_feed:\n raise RuntimeError(\"No 'url_feed' found. Please, call configure before usage. \")\nresults = []\nfeed... | <|body_start_0|>
if not type(url_feed) is str:
raise TypeError(f"Parameter 'url_feed' is of type {type(url_feed)}. This attribute must be an instance of string.")
self._url_feed = url_feed
<|end_body_0|>
<|body_start_1|>
if not self._url_feed:
raise RuntimeError("No 'url... | A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed | RssFeedsPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RssFeedsPlugin:
"""A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed"""
def configure(self, url_feed):
"""Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: string"""
<|body_0|>
def get_articles(self):... | stack_v2_sparse_classes_75kplus_train_007832 | 1,681 | no_license | [
{
"docstring": "Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: string",
"name": "configure",
"signature": "def configure(self, url_feed)"
},
{
"docstring": "Gets articles from a RSS feed :return: articles from RSS feed :rtype: list of dictionaries pos... | 2 | stack_v2_sparse_classes_30k_train_022723 | Implement the Python class `RssFeedsPlugin` described below.
Class description:
A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed
Method signatures and docstrings:
- def configure(self, url_feed): Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: ... | Implement the Python class `RssFeedsPlugin` described below.
Class description:
A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed
Method signatures and docstrings:
- def configure(self, url_feed): Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: ... | 09186dc7edb3cd39d54969c33ddde6dd14c32ee6 | <|skeleton|>
class RssFeedsPlugin:
"""A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed"""
def configure(self, url_feed):
"""Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: string"""
<|body_0|>
def get_articles(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RssFeedsPlugin:
"""A plugin that reads rss feeds Attributes: _url_feed: a valid url of a rss feed"""
def configure(self, url_feed):
"""Configures the plugin with url of rss feed :param url_feed: valid url for rss feed :return: string"""
if not type(url_feed) is str:
raise Type... | the_stack_v2_python_sparse | plugins/rss_feeds_plugin.py | willsimoes/projeto-final | train | 0 |
14b0ec57320083bc44b3a228ac206941b7b9e587 | [
"files = self.files.getlist('file_field')\nfor file in files:\n validators.validate_filename(file.name)\n if not file:\n raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})\nfor file in files:\n if file.size > ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT:\n... | <|body_start_0|>
files = self.files.getlist('file_field')
for file in files:
validators.validate_filename(file.name)
if not file:
raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})
for file in files:
... | Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root. | UploadFilesForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
<|body_0|>
def perform_action(self):
... | stack_v2_sparse_classes_75kplus_train_007833 | 39,361 | permissive | [
{
"docstring": "Check for file name, size limits and whether they are readable",
"name": "clean_file_field",
"signature": "def clean_file_field(self)"
},
{
"docstring": "Upload the files",
"name": "perform_action",
"signature": "def perform_action(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013247 | Implement the Python class `UploadFilesForm` described below.
Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.
Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readabl... | Implement the Python class `UploadFilesForm` described below.
Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.
Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readabl... | e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57 | <|skeleton|>
class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
<|body_0|>
def perform_action(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
files = self.files.getlist('file_field')
for file... | the_stack_v2_python_sparse | physionet-django/project/forms.py | tompollard/physionet-build | train | 0 |
6a505393b08982f1b59fcd653d1bad95c616619c | [
"url = '/graphs/%s/tasks/%d' % (_cfg.graph_name, id)\ncode, res = Request(auth=auth).request(method='get', path=url)\nreturn (code, res)",
"url = '/graphs/%s/tasks' % _cfg.graph_name\ncode, res = Request(auth=auth).request(method='get', path=url, params=param)\nreturn (code, res)",
"url = '/graphs/%s/tasks/%s?a... | <|body_start_0|>
url = '/graphs/%s/tasks/%d' % (_cfg.graph_name, id)
code, res = Request(auth=auth).request(method='get', path=url)
return (code, res)
<|end_body_0|>
<|body_start_1|>
url = '/graphs/%s/tasks' % _cfg.graph_name
code, res = Request(auth=auth).request(method='get', ... | task接口 | Task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""task接口"""
def get_task(self, id, auth=None):
"""查看某个异步任务 :param auth: :param id: taskId :return:"""
<|body_0|>
def get_tasks(self, param, auth=None):
"""获取所有的异步任务 :param auth:"""
<|body_1|>
def put_task(self, task_id, auth=None):
"""... | stack_v2_sparse_classes_75kplus_train_007834 | 37,941 | no_license | [
{
"docstring": "查看某个异步任务 :param auth: :param id: taskId :return:",
"name": "get_task",
"signature": "def get_task(self, id, auth=None)"
},
{
"docstring": "获取所有的异步任务 :param auth:",
"name": "get_tasks",
"signature": "def get_tasks(self, param, auth=None)"
},
{
"docstring": "验证:task... | 4 | null | Implement the Python class `Task` described below.
Class description:
task接口
Method signatures and docstrings:
- def get_task(self, id, auth=None): 查看某个异步任务 :param auth: :param id: taskId :return:
- def get_tasks(self, param, auth=None): 获取所有的异步任务 :param auth:
- def put_task(self, task_id, auth=None): 验证:task写权限 (取消t... | Implement the Python class `Task` described below.
Class description:
task接口
Method signatures and docstrings:
- def get_task(self, id, auth=None): 查看某个异步任务 :param auth: :param id: taskId :return:
- def get_tasks(self, param, auth=None): 获取所有的异步任务 :param auth:
- def put_task(self, task_id, auth=None): 验证:task写权限 (取消t... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Task:
"""task接口"""
def get_task(self, id, auth=None):
"""查看某个异步任务 :param auth: :param id: taskId :return:"""
<|body_0|>
def get_tasks(self, param, auth=None):
"""获取所有的异步任务 :param auth:"""
<|body_1|>
def put_task(self, task_id, auth=None):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Task:
"""task接口"""
def get_task(self, id, auth=None):
"""查看某个异步任务 :param auth: :param id: taskId :return:"""
url = '/graphs/%s/tasks/%d' % (_cfg.graph_name, id)
code, res = Request(auth=auth).request(method='get', path=url)
return (code, res)
def get_tasks(self, param... | the_stack_v2_python_sparse | src/common/server_api.py | hugegraph/hugegraph-test | train | 1 |
cfb1963edf232b2e2b029d7f88d1e6dccb6b7366 | [
"self.currency = currency\nself.available_amount = available_amount\nself.recipient = recipient\nself.waiting_funds_amount = waiting_funds_amount\nself.transferred_amount = transferred_amount",
"if dictionary is None:\n return None\ncurrency = dictionary.get('currency')\navailable_amount = dictionary.get('avai... | <|body_start_0|>
self.currency = currency
self.available_amount = available_amount
self.recipient = recipient
self.waiting_funds_amount = waiting_funds_amount
self.transferred_amount = transferred_amount
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (long|int): TODO: type description here. transferred_amount (long|int): TODO: type des... | GetBalanceResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetBalanceResponse:
"""Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (long|int): TODO: type description here.... | stack_v2_sparse_classes_75kplus_train_007835 | 2,724 | permissive | [
{
"docstring": "Constructor for the GetBalanceResponse class",
"name": "__init__",
"signature": "def __init__(self, currency=None, available_amount=None, waiting_funds_amount=None, transferred_amount=None, recipient=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Ar... | 2 | null | Implement the Python class `GetBalanceResponse` described below.
Class description:
Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (... | Implement the Python class `GetBalanceResponse` described below.
Class description:
Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class GetBalanceResponse:
"""Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (long|int): TODO: type description here.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetBalanceResponse:
"""Implementation of the 'GetBalanceResponse' model. Balance Attributes: currency (string): Currency available_amount (long|int): Amount available for transferring recipient (Recipient): TODO: type description here. waiting_funds_amount (long|int): TODO: type description here. transferred_... | the_stack_v2_python_sparse | mundiapi/models/get_balance_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
684710d8b3e5fda9ec855ba73efbd6443531772d | [
"super(DelayAuto, self).__init__()\nself.a = array_check(a, 1)\nself.tau = None",
"self.tau = int_check(tau, 0)\nn = self.a.size\n_sum = 0\nfor i in range(n - self.tau):\n _sum += (self.a[i] - self.a.mean()) * (self.a[i + self.tau] - self.a.mean()) / self.a.var()\nself.statistics = _sum / (n - self.tau)\nretur... | <|body_start_0|>
super(DelayAuto, self).__init__()
self.a = array_check(a, 1)
self.tau = None
<|end_body_0|>
<|body_start_1|>
self.tau = int_check(tau, 0)
n = self.a.size
_sum = 0
for i in range(n - self.tau):
_sum += (self.a[i] - self.a.mean()) * (se... | Auto correlation coefficient and t-test | DelayAuto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate auto correlation. :param tau: int delay length :return: class self"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_007836 | 8,613 | no_license | [
{
"docstring": ":param a: array_like",
"name": "__init__",
"signature": "def __init__(self, a: array_like)"
},
{
"docstring": "Calculate auto correlation. :param tau: int delay length :return: class self",
"name": "__call__",
"signature": "def __call__(self, tau: int)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_003954 | Implement the Python class `DelayAuto` described below.
Class description:
Auto correlation coefficient and t-test
Method signatures and docstrings:
- def __init__(self, a: array_like): :param a: array_like
- def __call__(self, tau: int): Calculate auto correlation. :param tau: int delay length :return: class self
- ... | Implement the Python class `DelayAuto` described below.
Class description:
Auto correlation coefficient and t-test
Method signatures and docstrings:
- def __init__(self, a: array_like): :param a: array_like
- def __call__(self, tau: int): Calculate auto correlation. :param tau: int delay length :return: class self
- ... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate auto correlation. :param tau: int delay length :return: class self"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
super(DelayAuto, self).__init__()
self.a = array_check(a, 1)
self.tau = None
def __call__(self, tau: int):
"""Calculate auto correlation. :pa... | the_stack_v2_python_sparse | statistics/correlation.py | qliu0/PythonInAirSeaScience | train | 0 |
3dc529a4dff3b8b7923d29326e2f176172a42e0c | [
"dic = set()\ndummy = node = ListNode(0)\nnode.next = head\nwhile node.next:\n if node.next.val in dic:\n node.next = node.next.next\n else:\n dic.add(node.next.val)\n node = node.next\nreturn dummy.next",
"d = set()\nhh = head\nbf = ''\nwhile head:\n if head.val not in d:\n d... | <|body_start_0|>
dic = set()
dummy = node = ListNode(0)
node.next = head
while node.next:
if node.next.val in dic:
node.next = node.next.next
else:
dic.add(node.next.val)
node = node.next
return dummy.next
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
<|body_0|>
def removeDuplicateNodes2(self, head):
"""更快的"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dic = set()
dummy = node = ListNode(0)
... | stack_v2_sparse_classes_75kplus_train_007837 | 1,493 | no_license | [
{
"docstring": "思路:每次判断node.next",
"name": "removeDuplicateNodes1",
"signature": "def removeDuplicateNodes1(self, head: ListNode) -> ListNode"
},
{
"docstring": "更快的",
"name": "removeDuplicateNodes2",
"signature": "def removeDuplicateNodes2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020375 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicateNodes1(self, head: ListNode) -> ListNode: 思路:每次判断node.next
- def removeDuplicateNodes2(self, head): 更快的 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicateNodes1(self, head: ListNode) -> ListNode: 思路:每次判断node.next
- def removeDuplicateNodes2(self, head): 更快的
<|skeleton|>
class Solution:
def removeDuplicateN... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
<|body_0|>
def removeDuplicateNodes2(self, head):
"""更快的"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicateNodes1(self, head: ListNode) -> ListNode:
"""思路:每次判断node.next"""
dic = set()
dummy = node = ListNode(0)
node.next = head
while node.next:
if node.next.val in dic:
node.next = node.next.next
else:
... | the_stack_v2_python_sparse | LeetCode/链表(Linked list)/面试题 02.01. 移除重复节点.py | yiming1012/MyLeetCode | train | 2 | |
569923170ca20907b2fd81531243201ef4511f84 | [
"self.trainval = trainval\nself.log = logging.getLogger('avalanche')\nif os.path.isabs(data_folder):\n self.data_folder = data_folder\nelse:\n self.data_folder = os.path.join(os.path.dirname(__file__), data_folder)\ntry:\n os.makedirs(self.data_folder, exist_ok=True)\n self.log.info('Directory %s create... | <|body_start_0|>
self.trainval = trainval
self.log = logging.getLogger('avalanche')
if os.path.isabs(data_folder):
self.data_folder = data_folder
else:
self.data_folder = os.path.join(os.path.dirname(__file__), data_folder)
try:
os.makedirs(sel... | INATURALIST downloader. | INATURALIST_DATA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
<|body_0|>
def download_inaturalist(self):
"""Download and extract inaturali... | stack_v2_sparse_classes_75kplus_train_007838 | 6,358 | permissive | [
{
"docstring": "Args: data_folder (string): folder in which to download inaturalist dataset.",
"name": "__init__",
"signature": "def __init__(self, data_folder='data/', trainval=True)"
},
{
"docstring": "Download and extract inaturalist data :param extra: download also additional INATURALIST dat... | 2 | stack_v2_sparse_classes_30k_train_038067 | Implement the Python class `INATURALIST_DATA` described below.
Class description:
INATURALIST downloader.
Method signatures and docstrings:
- def __init__(self, data_folder='data/', trainval=True): Args: data_folder (string): folder in which to download inaturalist dataset.
- def download_inaturalist(self): Download ... | Implement the Python class `INATURALIST_DATA` described below.
Class description:
INATURALIST downloader.
Method signatures and docstrings:
- def __init__(self, data_folder='data/', trainval=True): Args: data_folder (string): folder in which to download inaturalist dataset.
- def download_inaturalist(self): Download ... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
<|body_0|>
def download_inaturalist(self):
"""Download and extract inaturali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
self.trainval = trainval
self.log = logging.getLogger('avalanche')
if os.path.isabs(da... | the_stack_v2_python_sparse | avalanche/benchmarks/datasets/inaturalist/inaturalist_data.py | ContinualAI/avalanche | train | 1,424 |
19032d33e00413af0650ce1dd18f00764441df01 | [
"self.rx = rx\nself.ry = ry\nself.rz = rz\nself.wn_sigma = np.radians(wn_sigma)\nself.bias = [np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias))]\nself.bias_instability_var = np.radians(bias_instability_var)\nself.bias_instability = [0, 0, 0]\nrotatio... | <|body_start_0|>
self.rx = rx
self.ry = ry
self.rz = rz
self.wn_sigma = np.radians(wn_sigma)
self.bias = [np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias))]
self.bias_instability_var = np.radians(bias_insta... | A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measurement bias_instability : double the ... | Gyroscope | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measu... | stack_v2_sparse_classes_75kplus_train_007839 | 13,401 | no_license | [
{
"docstring": "Parameters ---------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] axis : str axis about which the rotation between the gyroscope RF and the robot RF is given rotation : double rotation between the reference frames about the axis given in \"axis\" [degrees] b... | 2 | stack_v2_sparse_classes_30k_train_007374 | Implement the Python class `Gyroscope` described below.
Class description:
A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of th... | Implement the Python class `Gyroscope` described below.
Class description:
A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of th... | 5789011d0a7617844d7e8e6e3e758c415a945a5e | <|skeleton|>
class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measurement bias_i... | the_stack_v2_python_sparse | Code/sensormodel.py | astroHaoPeng/thesis | train | 0 |
3f88cf905fc7746190bb261a2a9c90965a2def0d | [
"self.resources_path = resources_path\nself.num_samples = num_samples\nself.beam_size = beam_size\nself.num_workers = num_workers\nself._seed = seed\nself.sigma = sigma\nself.seed_smiles = [smi for smi in seed_smiles.split('.') if Chem.MolFromSmiles(smi) is not None]\nself.scaffolds = [scaffold for scaffold in scaf... | <|body_start_0|>
self.resources_path = resources_path
self.num_samples = num_samples
self.beam_size = beam_size
self.num_workers = num_workers
self._seed = seed
self.sigma = sigma
self.seed_smiles = [smi for smi in seed_smiles.split('.') if Chem.MolFromSmiles(smi)... | Interface for MoLeR generator. | MoLeRGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoLeRGenerator:
"""Interface for MoLeR generator."""
def __init__(self, resources_path: str, scaffolds: str, num_samples: int, beam_size: int, seed: int, num_workers: int, seed_smiles: str, sigma: float) -> None:
"""Instantiate a MoLeR generator. Args: resources_path: path to the res... | stack_v2_sparse_classes_75kplus_train_007840 | 4,599 | permissive | [
{
"docstring": "Instantiate a MoLeR generator. Args: resources_path: path to the resources for model loading. scaffolds: scaffolds as '.'-separated SMILES. If empty, no scaffolds are used. num_samples: Number of molecules to sample per call. beam_size: beam size to use during decoding. seed: seed used for rando... | 2 | stack_v2_sparse_classes_30k_train_012235 | Implement the Python class `MoLeRGenerator` described below.
Class description:
Interface for MoLeR generator.
Method signatures and docstrings:
- def __init__(self, resources_path: str, scaffolds: str, num_samples: int, beam_size: int, seed: int, num_workers: int, seed_smiles: str, sigma: float) -> None: Instantiate... | Implement the Python class `MoLeRGenerator` described below.
Class description:
Interface for MoLeR generator.
Method signatures and docstrings:
- def __init__(self, resources_path: str, scaffolds: str, num_samples: int, beam_size: int, seed: int, num_workers: int, seed_smiles: str, sigma: float) -> None: Instantiate... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class MoLeRGenerator:
"""Interface for MoLeR generator."""
def __init__(self, resources_path: str, scaffolds: str, num_samples: int, beam_size: int, seed: int, num_workers: int, seed_smiles: str, sigma: float) -> None:
"""Instantiate a MoLeR generator. Args: resources_path: path to the res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoLeRGenerator:
"""Interface for MoLeR generator."""
def __init__(self, resources_path: str, scaffolds: str, num_samples: int, beam_size: int, seed: int, num_workers: int, seed_smiles: str, sigma: float) -> None:
"""Instantiate a MoLeR generator. Args: resources_path: path to the resources for mo... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/moler/implementation.py | GT4SD/gt4sd-core | train | 239 |
9145e3c8ce4e3017011f68168f33f9ae6d0e9fbd | [
"self.resource_id = resource_id\nself.loading_id = loading_id\nself.parameters = parameters",
"dict_obj = {'resource_id': self.resource_id, 'loading_id': self.loading_id, 'parameters': []}\nfor parameter in self.parameters:\n dict_obj['parameters'].append({'name': parameter.name, 'value': parameter.value})\njs... | <|body_start_0|>
self.resource_id = resource_id
self.loading_id = loading_id
self.parameters = parameters
<|end_body_0|>
<|body_start_1|>
dict_obj = {'resource_id': self.resource_id, 'loading_id': self.loading_id, 'parameters': []}
for parameter in self.parameters:
d... | Request to retrieve a new dataset | DatasetRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetRequest:
"""Request to retrieve a new dataset"""
def __init__(self, loading_id: str, resource_id: str, parameters: list):
"""Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading process. :param resource_id: The identifier of the resource to... | stack_v2_sparse_classes_75kplus_train_007841 | 2,122 | no_license | [
{
"docstring": "Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading process. :param resource_id: The identifier of the resource to load :param parameters: A list of DatasetRequestParameter objects",
"name": "__init__",
"signature": "def __init__(self, loading_id: st... | 2 | null | Implement the Python class `DatasetRequest` described below.
Class description:
Request to retrieve a new dataset
Method signatures and docstrings:
- def __init__(self, loading_id: str, resource_id: str, parameters: list): Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading proce... | Implement the Python class `DatasetRequest` described below.
Class description:
Request to retrieve a new dataset
Method signatures and docstrings:
- def __init__(self, loading_id: str, resource_id: str, parameters: list): Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading proce... | 281bb6ef6efa0153babe0399d5bbe846ed576c7f | <|skeleton|>
class DatasetRequest:
"""Request to retrieve a new dataset"""
def __init__(self, loading_id: str, resource_id: str, parameters: list):
"""Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading process. :param resource_id: The identifier of the resource to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetRequest:
"""Request to retrieve a new dataset"""
def __init__(self, loading_id: str, resource_id: str, parameters: list):
"""Initializes a new DatasetRequest object. :param loading_id: The identifier of the loading process. :param resource_id: The identifier of the resource to load :param ... | the_stack_v2_python_sparse | reactome_analysis_utils/reactome_analysis_utils/models/dataset_request.py | reactome/gsa-backend | train | 3 |
40c5a626e4fe4b62fc6c156024c945a51baea327 | [
"WallFunction.__init__(self, value, isUnifrom)\nself.cmu = Cmu\nself.kappa = kappa\nself.e = E",
"_d = OrderedDict()\n_d['type'] = str(self.type)\n_d['value'] = str(self.value)\nif self.cmu:\n _d['Cmu'] = str(self.cmu)\nif self.kappa:\n _d['kappa'] = str(self.kappa)\nif self.e:\n _d['E'] = str(self.e)\nr... | <|body_start_0|>
WallFunction.__init__(self, value, isUnifrom)
self.cmu = Cmu
self.kappa = kappa
self.e = E
<|end_body_0|>
<|body_start_1|>
_d = OrderedDict()
_d['type'] = str(self.type)
_d['value'] = str(self.value)
if self.cmu:
_d['Cmu'] = s... | EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None) | EpsilonWallFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpsilonWallFunction:
"""EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None)"""
def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True):
"""Init EpsilonWallFunction."""
<|body_0|>
def valueDict(self):
""... | stack_v2_sparse_classes_75kplus_train_007842 | 9,882 | no_license | [
{
"docstring": "Init EpsilonWallFunction.",
"name": "__init__",
"signature": "def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True)"
},
{
"docstring": "Get fields as a dictionary.",
"name": "valueDict",
"signature": "def valueDict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000481 | Implement the Python class `EpsilonWallFunction` described below.
Class description:
EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None)
Method signatures and docstrings:
- def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True): Init EpsilonWallFunction.
-... | Implement the Python class `EpsilonWallFunction` described below.
Class description:
EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None)
Method signatures and docstrings:
- def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True): Init EpsilonWallFunction.
-... | 330e96867fc3df530ad21c11de01c54562745e65 | <|skeleton|>
class EpsilonWallFunction:
"""EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None)"""
def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True):
"""Init EpsilonWallFunction."""
<|body_0|>
def valueDict(self):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EpsilonWallFunction:
"""EpsilonWallFunction. Args: value: Cmu: (default: None) kappa: (default: None) E: (default: None)"""
def __init__(self, value, Cmu=None, kappa=None, E=None, isUnifrom=True):
"""Init EpsilonWallFunction."""
WallFunction.__init__(self, value, isUnifrom)
self.c... | the_stack_v2_python_sparse | samples/fields.py | aKarm1905/PythonMSC | train | 0 |
849568607de25b2fd252ecd1a10e291c598003e5 | [
"existing = User.objects.filter(username__iexact=self.cleaned_data['username'])\nif existing.exists():\n raise forms.ValidationError(_('A user with that username already exists.'))\nelse:\n return self.cleaned_data['username']",
"existing = User.objects.filter(email__iexact=self.cleaned_data['email'])\nif e... | <|body_start_0|>
existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(_('A user with that username already exists.'))
else:
return self.cleaned_data['username']
<|end_body_0|>
<|body_start_1|>
... | PatronForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatronForm:
def clean_username(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_0|>
def clean_email(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_1|>
def clean(self):
... | stack_v2_sparse_classes_75kplus_train_007843 | 3,884 | no_license | [
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_email",
"signature": "def cl... | 3 | stack_v2_sparse_classes_30k_train_000850 | Implement the Python class `PatronForm` described below.
Class description:
Implement the PatronForm class.
Method signatures and docstrings:
- def clean_username(self): Validate that the username is alphanumeric and is not already in use.
- def clean_email(self): Validate that the username is alphanumeric and is not... | Implement the Python class `PatronForm` described below.
Class description:
Implement the PatronForm class.
Method signatures and docstrings:
- def clean_username(self): Validate that the username is alphanumeric and is not already in use.
- def clean_email(self): Validate that the username is alphanumeric and is not... | 649157cf334875b79309f4dccd9e2470110277fe | <|skeleton|>
class PatronForm:
def clean_username(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_0|>
def clean_email(self):
"""Validate that the username is alphanumeric and is not already in use."""
<|body_1|>
def clean(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PatronForm:
def clean_username(self):
"""Validate that the username is alphanumeric and is not already in use."""
existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(_('A user with that username al... | the_stack_v2_python_sparse | ils/forms.py | ratna1234/nerp | train | 0 | |
bd46ffc6d823f2679cfefcdf03638ff274353b2c | [
"start = 0\nend = len(arr) - 1\nwhile end >= start:\n mid = (start + end) // 2\n if arr[mid] < value:\n start = mid + 1\n elif arr[mid] > value:\n end = mid - 1\n else:\n return mid\nreturn -1",
"left = self.binarySearch(arr, value)\nif left == -1:\n return -1\nelse:\n i = l... | <|body_start_0|>
start = 0
end = len(arr) - 1
while end >= start:
mid = (start + end) // 2
if arr[mid] < value:
start = mid + 1
elif arr[mid] > value:
end = mid - 1
else:
return mid
return -1
... | SolutionSearchRange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
<|body_0|>
def leftIndex(self, arr, value):
"""Returns the index(left) of the first occurence of the element"... | stack_v2_sparse_classes_75kplus_train_007844 | 2,036 | no_license | [
{
"docstring": "Returns the index position of the target element if found Returns -1 if target is not in array",
"name": "binarySearch",
"signature": "def binarySearch(self, arr, value)"
},
{
"docstring": "Returns the index(left) of the first occurence of the element",
"name": "leftIndex",
... | 4 | stack_v2_sparse_classes_30k_train_016157 | Implement the Python class `SolutionSearchRange` described below.
Class description:
Implement the SolutionSearchRange class.
Method signatures and docstrings:
- def binarySearch(self, arr, value): Returns the index position of the target element if found Returns -1 if target is not in array
- def leftIndex(self, arr... | Implement the Python class `SolutionSearchRange` described below.
Class description:
Implement the SolutionSearchRange class.
Method signatures and docstrings:
- def binarySearch(self, arr, value): Returns the index position of the target element if found Returns -1 if target is not in array
- def leftIndex(self, arr... | f7c7fcf27751f740c232a87b234d6a74e5ac30bb | <|skeleton|>
class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
<|body_0|>
def leftIndex(self, arr, value):
"""Returns the index(left) of the first occurence of the element"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionSearchRange:
def binarySearch(self, arr, value):
"""Returns the index position of the target element if found Returns -1 if target is not in array"""
start = 0
end = len(arr) - 1
while end >= start:
mid = (start + end) // 2
if arr[mid] < value:
... | the_stack_v2_python_sparse | Algorithms Python/searchRange.py | wittywatz/Algorithms | train | 0 | |
1fe6f6081fc719fa73e5f0a68e81e2565fcc606e | [
"clean_pattern = self.pattern_cleaner(pattern)\nif string == '' and clean_pattern == '*':\n return True\nmemoize = {str(len(string)) + '.' + str(len(clean_pattern)): True}\n\ndef _isMatch(string: str, s_pointer: int, pattern: str, p_pointer: int) -> bool:\n \"\"\"Solve isMatch with dynamic programing\"\"\"\n ... | <|body_start_0|>
clean_pattern = self.pattern_cleaner(pattern)
if string == '' and clean_pattern == '*':
return True
memoize = {str(len(string)) + '.' + str(len(clean_pattern)): True}
def _isMatch(string: str, s_pointer: int, pattern: str, p_pointer: int) -> bool:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, string: str, pattern: str) -> bool:
"""Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to match with string Output: True -- if pattern matches string"""
<|body_0|>
def pattern_cl... | stack_v2_sparse_classes_75kplus_train_007845 | 4,068 | no_license | [
{
"docstring": "Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to match with string Output: True -- if pattern matches string",
"name": "isMatch",
"signature": "def isMatch(self, string: str, pattern: str) -> bool"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_017514 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, string: str, pattern: str) -> bool: Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to matc... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, string: str, pattern: str) -> bool: Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to matc... | 452245e0e5a86f712d99df189821331a0a91db94 | <|skeleton|>
class Solution:
def isMatch(self, string: str, pattern: str) -> bool:
"""Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to match with string Output: True -- if pattern matches string"""
<|body_0|>
def pattern_cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isMatch(self, string: str, pattern: str) -> bool:
"""Check if pattern is an exact match to string Input: :string: str -- the string to match :pattern: str -- the pattern to match with string Output: True -- if pattern matches string"""
clean_pattern = self.pattern_cleaner(pattern... | the_stack_v2_python_sparse | algorithm/44.1_wildcard_matching.py | potatoHVAC/leetcode_challenges | train | 2 | |
796efbf524fea67734297c6e0adc3efa6fd50716 | [
"m = len(matrix) if matrix else -1\nn = len(matrix[0]) if m > 0 else -1\nif m < 1 or n < 1:\n return False\nfor row in range(m):\n left = 0\n right = n - 1\n while left <= right:\n mid = left + right >> 1\n if matrix[row][mid] < target:\n left = mid + 1\n elif matrix[row]... | <|body_start_0|>
m = len(matrix) if matrix else -1
n = len(matrix[0]) if m > 0 else -1
if m < 1 or n < 1:
return False
for row in range(m):
left = 0
right = n - 1
while left <= right:
mid = left + right >> 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_twopointers(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_007846 | 2,427 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix_twopointers",
"signature": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_twopointers(self, matrix, target): :type matrix: List[List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_twopointers(self, matrix, target): :type matrix: List[List... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_twopointers(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
m = len(matrix) if matrix else -1
n = len(matrix[0]) if m > 0 else -1
if m < 1 or n < 1:
return False
for row in range(m):
left =... | the_stack_v2_python_sparse | src/lt_240.py | oxhead/CodingYourWay | train | 0 | |
df292b649fb33d2812388ad9a3634022996c8cf6 | [
"try:\n validate_email(value)\n return True\nexcept ValidationError:\n return False",
"row_chunks = slice_iterable_into_chunks(rows, self.consent_page_size)\nfor chunk in row_chunks:\n '\\n Loop over the chunks and extract the email and item.\\n Save the item because the iterator... | <|body_start_0|>
try:
validate_email(value)
return True
except ValidationError:
return False
<|end_body_0|>
<|body_start_1|>
row_chunks = slice_iterable_into_chunks(rows, self.consent_page_size)
for chunk in row_chunks:
'\n Loop... | Company search export view. | SearchContactExportAPIView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchContactExportAPIView:
"""Company search export view."""
def _is_valid_email(self, value):
"""Validate if emails are valid and return a boolean flag."""
<|body_0|>
def _add_consent_response(self, rows):
"""Transforms iterable to add user consent from the con... | stack_v2_sparse_classes_75kplus_train_007847 | 6,797 | permissive | [
{
"docstring": "Validate if emails are valid and return a boolean flag.",
"name": "_is_valid_email",
"signature": "def _is_valid_email(self, value)"
},
{
"docstring": "Transforms iterable to add user consent from the consent service. The consent lookup makes an external API call to return consen... | 3 | stack_v2_sparse_classes_30k_train_001905 | Implement the Python class `SearchContactExportAPIView` described below.
Class description:
Company search export view.
Method signatures and docstrings:
- def _is_valid_email(self, value): Validate if emails are valid and return a boolean flag.
- def _add_consent_response(self, rows): Transforms iterable to add user... | Implement the Python class `SearchContactExportAPIView` described below.
Class description:
Company search export view.
Method signatures and docstrings:
- def _is_valid_email(self, value): Validate if emails are valid and return a boolean flag.
- def _add_consent_response(self, rows): Transforms iterable to add user... | a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e | <|skeleton|>
class SearchContactExportAPIView:
"""Company search export view."""
def _is_valid_email(self, value):
"""Validate if emails are valid and return a boolean flag."""
<|body_0|>
def _add_consent_response(self, rows):
"""Transforms iterable to add user consent from the con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchContactExportAPIView:
"""Company search export view."""
def _is_valid_email(self, value):
"""Validate if emails are valid and return a boolean flag."""
try:
validate_email(value)
return True
except ValidationError:
return False
def _a... | the_stack_v2_python_sparse | datahub/search/contact/views.py | cgsunkel/data-hub-api | train | 0 |
9e1befd7481e644033bfb62a1bf5266bc149385a | [
"if config is None:\n config = Config()\nif shape is None:\n shape = (config.source_sizes[0],) * 2\nsed, morph = self._make_initial(center, img, shape, psf, config, tiny)\nif constraints is None:\n constraints = (sc.SimpleConstraint(normalization), sc.DirectMonotonicityConstraint(use_nearest=False), sc.Dir... | <|body_start_0|>
if config is None:
config = Config()
if shape is None:
shape = (config.source_sizes[0],) * 2
sed, morph = self._make_initial(center, img, shape, psf, config, tiny)
if constraints is None:
constraints = (sc.SimpleConstraint(normalizatio... | Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotonicity. | PointSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointSource:
"""Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotonicity."""
def __init__(self, center... | stack_v2_sparse_classes_75kplus_train_007848 | 20,174 | permissive | [
{
"docstring": "Initialize This implementation initializes the sed from the pixel in the center of the frame and sets morphology to only comprise that pixel, which works well for point sources and poorly resolved galaxies. See :class:`~scarlet.source.Source` for parameter descriptions not listed below. Paramete... | 2 | stack_v2_sparse_classes_30k_test_002510 | Implement the Python class `PointSource` described below.
Class description:
Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotoni... | Implement the Python class `PointSource` described below.
Class description:
Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotoni... | f25985720fc1534fe0860297ac4e255934c827ba | <|skeleton|>
class PointSource:
"""Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotonicity."""
def __init__(self, center... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointSource:
"""Create a point source. Point sources are initialized with the SED of the center pixel, and the morphology of a single pixel (the center) turned on. While the source can have any `constraints`, the default constraints are symmetry and monotonicity."""
def __init__(self, center, img, shape=... | the_stack_v2_python_sparse | scarlet/source.py | sowmyakth/scarlet | train | 0 |
d9a3bc826b4b0d2dc17465bf06427d4f6ad785e2 | [
"super().__init__(initial_class_observations, parent_node, random_state)\nself.fMAE_M = 0.0\nself.fMAE_P = 0.0\nself.fMAE_SP = 0.0",
"normalized_sample = rht.normalize_sample(X)\nnormalized_base_pred = self._predict_base(normalized_sample)\n_, n_features = get_dimensions(X)\n_, n_targets = get_dimensions(y)\nnorm... | <|body_start_0|>
super().__init__(initial_class_observations, parent_node, random_state)
self.fMAE_M = 0.0
self.fMAE_P = 0.0
self.fMAE_SP = 0.0
<|end_body_0|>
<|body_start_1|>
normalized_sample = rht.normalize_sample(X)
normalized_base_pred = self._predict_base(normalize... | Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics to be stored by the leaf node. It contains the following ele... | SSTInactiveLearningNodeAdaptive | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics t... | stack_v2_sparse_classes_75kplus_train_007849 | 3,710 | permissive | [
{
"docstring": "SSTInactiveLearningNodeAdaptive class constructor.",
"name": "__init__",
"signature": "def __init__(self, initial_class_observations, parent_node=None, random_state=None)"
},
{
"docstring": "Update the perceptron weights Parameters ---------- X: numpy.ndarray of length equal to t... | 2 | stack_v2_sparse_classes_30k_train_005338 | Implement the Python class `SSTInactiveLearningNodeAdaptive` described below.
Class description:
Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary contai... | Implement the Python class `SSTInactiveLearningNodeAdaptive` described below.
Class description:
Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary contai... | bfe504b4ca24b77e211fd55dc42844fc494671d7 | <|skeleton|>
class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSTInactiveLearningNodeAdaptive:
"""Inactive Multi-target regression learning node for SST-HT that keeps track of mean, perceptron, and stacked perceptrons predictors for each target. Parameters ---------- initial_class_observations: dict A dictionary containing the set of sufficient statistics to be stored b... | the_stack_v2_python_sparse | src/skmultiflow/trees/nodes/sst_inactive_learning_node_adaptive.py | jacobmontiel/scikit-multiflow | train | 1 |
82913eeca02f0d88b7a24185007fd1ff3fbb3f35 | [
"self._discovery_info: BluetoothServiceInfoBleak | None = None\nself._discovered_device: Aranet4Advertisement | None = None\nself._discovered_devices: dict[str, tuple[str, Aranet4Advertisement]] = {}",
"if not adv.manufacturer_data or adv.manufacturer_data.version < MIN_VERSION:\n raise AbortFlow('outdated_ver... | <|body_start_0|>
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_device: Aranet4Advertisement | None = None
self._discovered_devices: dict[str, tuple[str, Aranet4Advertisement]] = {}
<|end_body_0|>
<|body_start_1|>
if not adv.manufacturer_data or adv.manuf... | Handle a config flow for Aranet. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
<|body_0|>
def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None:
"""Raise any configuration errors that apply to an a... | stack_v2_sparse_classes_75kplus_train_007850 | 4,638 | permissive | [
{
"docstring": "Set up a new config flow for Aranet.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Raise any configuration errors that apply to an advertisement.",
"name": "_raise_for_advertisement_errors",
"signature": "def _raise_for_advertisement_e... | 5 | stack_v2_sparse_classes_30k_train_014878 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aranet.
Method signatures and docstrings:
- def __init__(self) -> None: Set up a new config flow for Aranet.
- def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None: Raise any configuration erro... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aranet.
Method signatures and docstrings:
- def __init__(self) -> None: Set up a new config flow for Aranet.
- def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None: Raise any configuration erro... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
<|body_0|>
def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None:
"""Raise any configuration errors that apply to an a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_device: Aranet4Advertisement | None = None
self._discovered_devices: dic... | the_stack_v2_python_sparse | homeassistant/components/aranet/config_flow.py | home-assistant/core | train | 35,501 |
9cba50c729d3f384102b9dc431c55bbf36b7cc8f | [
"self.sc = sc\nself._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticRegressionModel), SKL_LinearRegression: ClassNames('org.apache.spark.ml.regression.LinearRegressionModel', LinearRegressionModel)}\nself._supported_skl_types = self._skl... | <|body_start_0|>
self.sc = sc
self._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticRegressionModel), SKL_LinearRegression: ClassNames('org.apache.spark.ml.regression.LinearRegressionModel', LinearRegressionModel)}
sel... | Class for converting between scikit-learn and Spark ML models | Converter | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Class for converting between scikit-learn and Spark ML models"""
def __init__(self, sc):
""":param sc: SparkContext"""
<|body_0|>
def toSpark(self, model):
"""Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Curren... | stack_v2_sparse_classes_75kplus_train_007851 | 6,928 | permissive | [
{
"docstring": ":param sc: SparkContext",
"name": "__init__",
"signature": "def __init__(self, sc)"
},
{
"docstring": "Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Currently supported models: - sklearn.linear_model.LogisticRegression (binary classification ... | 6 | stack_v2_sparse_classes_30k_train_035371 | Implement the Python class `Converter` described below.
Class description:
Class for converting between scikit-learn and Spark ML models
Method signatures and docstrings:
- def __init__(self, sc): :param sc: SparkContext
- def toSpark(self, model): Convert a scikit-learn model to a Spark ML model from the Pipelines A... | Implement the Python class `Converter` described below.
Class description:
Class for converting between scikit-learn and Spark ML models
Method signatures and docstrings:
- def __init__(self, sc): :param sc: SparkContext
- def toSpark(self, model): Convert a scikit-learn model to a Spark ML model from the Pipelines A... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class Converter:
"""Class for converting between scikit-learn and Spark ML models"""
def __init__(self, sc):
""":param sc: SparkContext"""
<|body_0|>
def toSpark(self, model):
"""Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Curren... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Converter:
"""Class for converting between scikit-learn and Spark ML models"""
def __init__(self, sc):
""":param sc: SparkContext"""
self.sc = sc
self._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticReg... | the_stack_v2_python_sparse | lib/python2.7/site-packages/spark_sklearn/converter.py | wangyum/Anaconda | train | 11 |
7fa1f11e0ed3ad74d66fb62d86a4720ed925e146 | [
"bad_lines = []\nif not content:\n raise SkipComponent('Empty content.')\nif len(content) < 5:\n raise ParseException(\"Wrong content in table: '{0}'.\".format(content))\ndata = {}\nfor _l in content[3:-1]:\n l = _l.strip()\n if not (l.startswith('|') and l.endswith('|')):\n bad_lines.append(_l)\... | <|body_start_0|>
bad_lines = []
if not content:
raise SkipComponent('Empty content.')
if len(content) < 5:
raise ParseException("Wrong content in table: '{0}'.".format(content))
data = {}
for _l in content[3:-1]:
l = _l.strip()
if n... | The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored in the ``bad_lines`` property list. Example: >>> output.get('version') '5.5.56-Mar... | MysqladminVars | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MysqladminVars:
"""The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored in the ``bad_lines`` property list. Exam... | stack_v2_sparse_classes_75kplus_train_007852 | 4,351 | permissive | [
{
"docstring": "Parse output content table of command ``/bin/mysqladmin variables``. Set each variable as an class attribute.",
"name": "parse_content",
"signature": "def parse_content(self, content)"
},
{
"docstring": "Get value for specified keyword, use default if keyword not found. Example: ... | 2 | stack_v2_sparse_classes_30k_train_007736 | Implement the Python class `MysqladminVars` described below.
Class description:
The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored i... | Implement the Python class `MysqladminVars` described below.
Class description:
The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored i... | b0ea07fc3f4dd8801b505fe70e9b36e628152c4a | <|skeleton|>
class MysqladminVars:
"""The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored in the ``bad_lines`` property list. Exam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MysqladminVars:
"""The output of command ``/bin/mysqladmin variables`` is in mysql table format, contains 'Variable_name' and 'Value' two columns. This parser will parse the table and set each variable as an class attribute. The unparsable lines are stored in the ``bad_lines`` property list. Example: >>> outp... | the_stack_v2_python_sparse | insights/parsers/mysqladmin.py | RedHatInsights/insights-core | train | 144 |
e549d1b8b9bbb6bf4f63bcc1010b79549316baaf | [
"if not isinstance(user_events, list):\n user_events = cast(List[Optional[user_event.UserEvent]], [user_events])\nvisitors = []\nfor event in user_events:\n visitor = cls._create_visitor(event, logger)\n if visitor:\n visitors.append(visitor)\nif len(visitors) == 0:\n return None\nfirst_event = u... | <|body_start_0|>
if not isinstance(user_events, list):
user_events = cast(List[Optional[user_event.UserEvent]], [user_events])
visitors = []
for event in user_events:
visitor = cls._create_visitor(event, logger)
if visitor:
visitors.append(visi... | EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api/index.html") | EventFactory | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventFactory:
"""EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api/index.html")"""
def create_log_ev... | stack_v2_sparse_classes_75kplus_train_007853 | 7,195 | permissive | [
{
"docstring": "Create LogEvent instance. Args: user_events: A single UserEvent instance or a list of UserEvent instances. logger: Provides a logger instance. Returns: LogEvent instance.",
"name": "create_log_event",
"signature": "def create_log_event(cls, user_events: Sequence[Optional[user_event.UserE... | 3 | stack_v2_sparse_classes_30k_train_038120 | Implement the Python class `EventFactory` described below.
Class description:
EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api... | Implement the Python class `EventFactory` described below.
Class description:
EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api... | bf000e737f391270f9adec97606646ce4761ecd8 | <|skeleton|>
class EventFactory:
"""EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api/index.html")"""
def create_log_ev... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventFactory:
"""EventFactory builds LogEvent object from a given UserEvent. This class serves to separate concerns between events in the SDK and the API used to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api/index.html")"""
def create_log_event(cls, user... | the_stack_v2_python_sparse | optimizely/event/event_factory.py | optimizely/python-sdk | train | 34 |
8a11dc62c58145b6788693ef8d5eb54bb68ee311 | [
"if not head:\n return True\nmid = self.middleNode(head)\nl1 = head\nl2 = mid.next\nmid.next = None\nl2 = self.reverseList(l2)\nwhile l2:\n if l1.val != l2.val:\n return False\n l1 = l1.next\n l2 = l2.next\nreturn True",
"slow = fast = head\nwhile fast.next and fast.next.next:\n fast = fast.... | <|body_start_0|>
if not head:
return True
mid = self.middleNode(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = self.reverseList(l2)
while l2:
if l1.val != l2.val:
return False
l1 = l1.next
l2 = l2... | 快慢指针,找中点翻转列表 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def middleNode(self, head: ListNode) -> ListNode:
"""查找中点 :param head: :return:"""
<|body_1|>
def reverseList(self, head: ListNode) -> ListN... | stack_v2_sparse_classes_75kplus_train_007854 | 1,891 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": "查找中点 :param head: :return:",
"name": "middleNode",
"signature": "def middleNode(self, head: ListNode) -> ListNode"
},
{
"docstring": "翻转列表 :p... | 3 | stack_v2_sparse_classes_30k_val_000725 | Implement the Python class `Solution` described below.
Class description:
快慢指针,找中点翻转列表
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def middleNode(self, head: ListNode) -> ListNode: 查找中点 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode:... | Implement the Python class `Solution` described below.
Class description:
快慢指针,找中点翻转列表
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def middleNode(self, head: ListNode) -> ListNode: 查找中点 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode:... | aeaa6c84033a1a02dba0c6dfe194f5bd6d82bce5 | <|skeleton|>
class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def middleNode(self, head: ListNode) -> ListNode:
"""查找中点 :param head: :return:"""
<|body_1|>
def reverseList(self, head: ListNode) -> ListN... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
if not head:
return True
mid = self.middleNode(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = self.reverseList(l2)
while l2:
... | the_stack_v2_python_sparse | letcode_234_回文链表.py | a313071162/letcode | train | 3 |
b3848755c624fb80b6eb08a9726e88cf6710d559 | [
"super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)\nself._nFrames = 1\nself._framesPerSecond = 1\nself._initial_position = position",
"self.setPosition(self.getPosition() + Vector2(2, 0))\nif self.getPosition().x > self._initial_position.x + 4:\n if self.getPositi... | <|body_start_0|>
super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)
self._nFrames = 1
self._framesPerSecond = 1
self._initial_position = position
<|end_body_0|>
<|body_start_1|>
self.setPosition(self.getPosition() + Vector2(2, 0))
... | EnemyDrop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
<|body_0|>
def update(self, ticks):
"""Player moves two pixels per update method. Returns the index of... | stack_v2_sparse_classes_75kplus_train_007855 | 1,110 | no_license | [
{
"docstring": "\"This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen",
"name": "__init__",
"signature": "def __init__(self, position, anim_sequence_pos, trainer)"
},
{
"docstring": "Player moves two pixels per update method. Returns the index of the next Ani... | 2 | stack_v2_sparse_classes_30k_train_022031 | Implement the Python class `EnemyDrop` described below.
Class description:
Implement the EnemyDrop class.
Method signatures and docstrings:
- def __init__(self, position, anim_sequence_pos, trainer): "This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen
- def update(self, ticks): P... | Implement the Python class `EnemyDrop` described below.
Class description:
Implement the EnemyDrop class.
Method signatures and docstrings:
- def __init__(self, position, anim_sequence_pos, trainer): "This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen
- def update(self, ticks): P... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
<|body_0|>
def update(self, ticks):
"""Player moves two pixels per update method. Returns the index of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnemyDrop:
def __init__(self, position, anim_sequence_pos, trainer):
""""This is enemies equivalent of a TrainerToss. The enemy simply moves right off the screen"""
super().__init__(join('trainers', trainer.name.lower() + '_b.png'), position, anim_sequence_pos)
self._nFrames = 1
... | the_stack_v2_python_sparse | pokered/modules/animations/enemy_drop.py | surranc20/pokered | train | 44 | |
d1586c3f1a6d786326695085812004056a71fd90 | [
"self.ctrl = ctrl\nself.session = session\nself.path = path\nself.params = params\nself.headers = headers\nself.code = 500\nself.response_headers = {'Content-Type': 'text/plain; charset=utf-8'}\nself.response = 'Endpoint set no response'",
"val = self.params[x]\nif type == int:\n if not isinstance(val, str):\n... | <|body_start_0|>
self.ctrl = ctrl
self.session = session
self.path = path
self.params = params
self.headers = headers
self.code = 500
self.response_headers = {'Content-Type': 'text/plain; charset=utf-8'}
self.response = 'Endpoint set no response'
<|end_bod... | Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HTTP headers of the request. code: The HTTP response status code. response_headers: ... | EndpointContext | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EndpointContext:
"""Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HTTP headers of the request. code: The HT... | stack_v2_sparse_classes_75kplus_train_007856 | 17,273 | permissive | [
{
"docstring": "Constructor. Args: ctrl: The controller. session: The client's session data. path: The path. params: The parameters of the request. headers: The HTTP headers.",
"name": "__init__",
"signature": "def __init__(self, ctrl: 'Controller', session: SessionData, path: List[str], params: Dict[st... | 4 | stack_v2_sparse_classes_30k_train_024035 | Implement the Python class `EndpointContext` described below.
Class description:
Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HT... | Implement the Python class `EndpointContext` described below.
Class description:
Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HT... | 7f7737923e5d8441bbc65cafedf29db14e750860 | <|skeleton|>
class EndpointContext:
"""Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HTTP headers of the request. code: The HT... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EndpointContext:
"""Contains contextual information about the request. Attributes: ctrl: The controller which handles the endpoint. session: The session data of the client. path: The path of the request. params: The parameters of the request. headers: The HTTP headers of the request. code: The HTTP response s... | the_stack_v2_python_sparse | src/nussschale/leafs/endpoint.py | RealFloorIsJava/KgF | train | 0 |
93aa1e7f2a36b78f38e8f809d3527c49fa576cf4 | [
"self.gensim_model = None\nself.num_topics = num_topics\nself.id2word = id2word\nself.chunksize = chunksize\nself.decay = decay\nself.onepass = onepass\nself.extra_samples = extra_samples\nself.power_iters = power_iters",
"if sparse.issparse(X):\n corpus = matutils.Sparse2Corpus(sparse=X, documents_columns=Fal... | <|body_start_0|>
self.gensim_model = None
self.num_topics = num_topics
self.id2word = id2word
self.chunksize = chunksize
self.decay = decay
self.onepass = onepass
self.extra_samples = extra_samples
self.power_iters = power_iters
<|end_body_0|>
<|body_star... | Base LSI module | LsiTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LsiTransformer:
"""Base LSI module"""
def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100):
"""Sklearn wrapper for LSI model. See gensim.model.LsiModel for parameter details."""
<|body_0|>
def fit(se... | stack_v2_sparse_classes_75kplus_train_007857 | 3,449 | permissive | [
{
"docstring": "Sklearn wrapper for LSI model. See gensim.model.LsiModel for parameter details.",
"name": "__init__",
"signature": "def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100)"
},
{
"docstring": "Fit the model accor... | 4 | null | Implement the Python class `LsiTransformer` described below.
Class description:
Base LSI module
Method signatures and docstrings:
- def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100): Sklearn wrapper for LSI model. See gensim.model.LsiModel for... | Implement the Python class `LsiTransformer` described below.
Class description:
Base LSI module
Method signatures and docstrings:
- def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100): Sklearn wrapper for LSI model. See gensim.model.LsiModel for... | 1bc3390770ddafbba2e2779ba91998643df6d9ec | <|skeleton|>
class LsiTransformer:
"""Base LSI module"""
def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100):
"""Sklearn wrapper for LSI model. See gensim.model.LsiModel for parameter details."""
<|body_0|>
def fit(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LsiTransformer:
"""Base LSI module"""
def __init__(self, num_topics=200, id2word=None, chunksize=20000, decay=1.0, onepass=True, power_iters=2, extra_samples=100):
"""Sklearn wrapper for LSI model. See gensim.model.LsiModel for parameter details."""
self.gensim_model = None
self.n... | the_stack_v2_python_sparse | p3/Lib/site-packages/gensim/sklearn_api/lsimodel.py | fpark7/Native2Native | train | 1 |
4d543e5de1575f22fe75e1b06f3cea0b2e8df3d3 | [
"self._interface = interface\nself.datapath = datapath\nself.gather_tokens = gather_tokens\nself.gather_internal_transactions = gather_internal_transactions\nself.max_workers = max_workers",
"LOG.info('Getting blocks from blockchain')\nblock_tx_cmd = 'ethereumetl export_blocks_and_transactions --start-block {} --... | <|body_start_0|>
self._interface = interface
self.datapath = datapath
self.gather_tokens = gather_tokens
self.gather_internal_transactions = gather_internal_transactions
self.max_workers = max_workers
<|end_body_0|>
<|body_start_1|>
LOG.info('Getting blocks from blockcha... | Retrieves raw data from the blockchain. | DataRetriever | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataRetriever:
"""Retrieves raw data from the blockchain."""
def __init__(self, interface: str, datapath: str, gather_tokens: bool, gather_internal_transactions: bool, max_workers: int) -> None:
"""Initialization. Args: interface: Path to the Geth blockchain node. datapath: Path for ... | stack_v2_sparse_classes_75kplus_train_007858 | 7,593 | permissive | [
{
"docstring": "Initialization. Args: interface: Path to the Geth blockchain node. datapath: Path for temporary file created in DB creation. gather_tokens: Whether to also gather tokens. gather_internal_transactions: Whether to also gather internal transactions. max_workers: Maximum workers in Ethereum ETL.",
... | 4 | stack_v2_sparse_classes_30k_val_001476 | Implement the Python class `DataRetriever` described below.
Class description:
Retrieves raw data from the blockchain.
Method signatures and docstrings:
- def __init__(self, interface: str, datapath: str, gather_tokens: bool, gather_internal_transactions: bool, max_workers: int) -> None: Initialization. Args: interfa... | Implement the Python class `DataRetriever` described below.
Class description:
Retrieves raw data from the blockchain.
Method signatures and docstrings:
- def __init__(self, interface: str, datapath: str, gather_tokens: bool, gather_internal_transactions: bool, max_workers: int) -> None: Initialization. Args: interfa... | 5dd752fcbf6bde8c4bbeac54a62519e9b91112d9 | <|skeleton|>
class DataRetriever:
"""Retrieves raw data from the blockchain."""
def __init__(self, interface: str, datapath: str, gather_tokens: bool, gather_internal_transactions: bool, max_workers: int) -> None:
"""Initialization. Args: interface: Path to the Geth blockchain node. datapath: Path for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataRetriever:
"""Retrieves raw data from the blockchain."""
def __init__(self, interface: str, datapath: str, gather_tokens: bool, gather_internal_transactions: bool, max_workers: int) -> None:
"""Initialization. Args: interface: Path to the Geth blockchain node. datapath: Path for temporary fil... | the_stack_v2_python_sparse | src/updater/data_retriever.py | querti/ethereum-blockchain-explorer | train | 3 |
878935b47df44f09108fff3720df4c511f22bc33 | [
"if nums:\n self.nums = [nums[0]]\n for i in range(1, len(nums)):\n self.nums.append(self.nums[-1] + nums[i])",
"if i == 0:\n return self.nums[j]\nreturn self.nums[j] - self.nums[i - 1]"
] | <|body_start_0|>
if nums:
self.nums = [nums[0]]
for i in range(1, len(nums)):
self.nums.append(self.nums[-1] + nums[i])
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.nums[j]
return self.nums[j] - self.nums[i - 1]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_007859 | 1,087 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | stack_v2_sparse_classes_30k_train_041292 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | 2df1a58aa9474f2ecec2ee7c45ebf12466181391 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
if nums:
self.nums = [nums[0]]
for i in range(1, len(nums)):
self.nums.append(self.nums[-1] + nums[i])
def sumRange(self, i, j):
"""sum of e... | the_stack_v2_python_sparse | RangeSumQuery-Immutable.py | zjuzpz/Algorithms | train | 2 | |
058c066f7261d3affd1b42b068472f55dd8489aa | [
"x0, y0 = pos\nx1, x2 = (x0 - length / 2.0, x0 + length / 2.0)\ny1, y2 = (y0 - height, y0)\nself.cv = cv\nself.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)",
"x1, y1, x2, y2 = self.cv.coords(self.item)\nx0, y0 = ((x1 + x2) / 2, y2)\ndx, dy = (x - x0, y - y0)\nd = (dx ** 2 + dy ** 2) *... | <|body_start_0|>
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
self.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)
<|end_body_0|>
<|body_start_1|>
x1, y1, x2, y2 = self.cv.coords(self.item)... | Movable Rectangle on a Tkinter Canvas | Disc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is i... | stack_v2_sparse_classes_75kplus_train_007860 | 11,212 | no_license | [
{
"docstring": "creates disc on given Canvas cv at given pos-ition",
"name": "__init__",
"signature": "def __init__(self, cv, pos, length, height, colour)"
},
{
"docstring": "moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10",
"name": "move_to",
... | 2 | stack_v2_sparse_classes_30k_train_043111 | Implement the Python class `Disc` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given pos-ition
- def move_to(self, x, y, speed): moves bottom center of disc to posit... | Implement the Python class `Disc` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given pos-ition
- def move_to(self, x, y, speed): moves bottom center of disc to posit... | eba9cc094f28ec7e26cbd85b1a42d3dccb560233 | <|skeleton|>
class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
... | the_stack_v2_python_sparse | src/Unisa/Exemplos de programas em Python/hanoi.py | carlosDevPinheiro/Python | train | 0 |
14a6524dbbb3b3d755f46bb09d4a654a9a0a2c9c | [
"self.verbose = verbose\nself.atl02 = atl02\nself.delta_time_name = delta_time_name\nself.delta_times = self.atl02[delta_time_name].value\nself.start = self.delta_times[0]\nself.end = self.delta_times[-1]",
"self.min_start = self.atl02['quality_assessment/summary/delta_time_start'].value[0]\nself.max_end = self.a... | <|body_start_0|>
self.verbose = verbose
self.atl02 = atl02
self.delta_time_name = delta_time_name
self.delta_times = self.atl02[delta_time_name].value
self.start = self.delta_times[0]
self.end = self.delta_times[-1]
<|end_body_0|>
<|body_start_1|>
self.min_start ... | DeltaTime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeltaTime:
def __init__(self, delta_time_name, atl02, verbose=True):
"""DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H5 file of ATL02."""
<|body_0|>
def check_limits(self, limit_tolerance=0.5):
"... | stack_v2_sparse_classes_75kplus_train_007861 | 3,950 | no_license | [
{
"docstring": "DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H5 file of ATL02.",
"name": "__init__",
"signature": "def __init__(self, delta_time_name, atl02, verbose=True)"
},
{
"docstring": "Checks that limits of delta_time... | 3 | stack_v2_sparse_classes_30k_train_040018 | Implement the Python class `DeltaTime` described below.
Class description:
Implement the DeltaTime class.
Method signatures and docstrings:
- def __init__(self, delta_time_name, atl02, verbose=True): DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H... | Implement the Python class `DeltaTime` described below.
Class description:
Implement the DeltaTime class.
Method signatures and docstrings:
- def __init__(self, delta_time_name, atl02, verbose=True): DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H... | fee1cfcacda7b1c73000f475eec65b9bacecac0c | <|skeleton|>
class DeltaTime:
def __init__(self, delta_time_name, atl02, verbose=True):
"""DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H5 file of ATL02."""
<|body_0|>
def check_limits(self, limit_tolerance=0.5):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeltaTime:
def __init__(self, delta_time_name, atl02, verbose=True):
"""DeltaTime object. Parameters ---------- delta_time_name : str The H5 path name to the delta_time field. atl02 : Open H5 file of ATL02."""
self.verbose = verbose
self.atl02 = atl02
self.delta_time_name = del... | the_stack_v2_python_sparse | atl02v/shared/delta_time.py | cgosmeyer/atl02v | train | 0 | |
87ae9a44f57c448574c79c961c32b747b8bfac5e | [
"xy = points.data[..., :2]\nz = points.z\nuv = (xy.T @ diag(z).inverse()).T if len(z.shape) else xy.T * 1 / z\nreturn Vector2(uv)",
"if isinstance(depth, (float, int)):\n depth = Tensor([depth])\nreturn Vector3.from_coords(points.x * depth, points.y * depth, depth)"
] | <|body_start_0|>
xy = points.data[..., :2]
z = points.z
uv = (xy.T @ diag(z).inverse()).T if len(z.shape) else xy.T * 1 / z
return Vector2(uv)
<|end_body_0|>
<|body_start_1|>
if isinstance(depth, (float, int)):
depth = Tensor([depth])
return Vector3.from_coor... | Z1Projection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Z1Projection:
def project(self, points: Vector3) -> Vector2:
"""Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: Vector3 representing the points to project. Returns: Vector2 representing the projected points. Examp... | stack_v2_sparse_classes_75kplus_train_007862 | 1,838 | permissive | [
{
"docstring": "Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: Vector3 representing the points to project. Returns: Vector2 representing the projected points. Example: >>> points = Vector3.from_coords(1., 2., 3.) >>> Z1Projection().proj... | 2 | stack_v2_sparse_classes_30k_train_041407 | Implement the Python class `Z1Projection` described below.
Class description:
Implement the Z1Projection class.
Method signatures and docstrings:
- def project(self, points: Vector3) -> Vector2: Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: ... | Implement the Python class `Z1Projection` described below.
Class description:
Implement the Z1Projection class.
Method signatures and docstrings:
- def project(self, points: Vector3) -> Vector2: Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: ... | 1e0f8baa7318c05b17ea6dbb48605691bca8972f | <|skeleton|>
class Z1Projection:
def project(self, points: Vector3) -> Vector2:
"""Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: Vector3 representing the points to project. Returns: Vector2 representing the projected points. Examp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Z1Projection:
def project(self, points: Vector3) -> Vector2:
"""Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division. Args: points: Vector3 representing the points to project. Returns: Vector2 representing the projected points. Example: >>> points... | the_stack_v2_python_sparse | kornia/sensors/camera/projection_model.py | kornia/kornia | train | 7,351 | |
89241cbd37bb66fbfbac218bd6c3dc2a21f8076b | [
"for input_key in self.input:\n with self.input.load(input_key) as f:\n offset = 0\n line = f.readline()\n while line:\n if self.send_as_input:\n yield line.strip()\n else:\n yield (input_key + (offset,))\n offset = f.tell()\n ... | <|body_start_0|>
for input_key in self.input:
with self.input.load(input_key) as f:
offset = 0
line = f.readline()
while line:
if self.send_as_input:
yield line.strip()
else:
... | LineFileSlicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineFileSlicer:
def __iter__(self):
"""generates a key == parent_key + (offset, ), where offset is a line position in file"""
<|body_0|>
def _load(self, key):
"""reads particular line in file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for input... | stack_v2_sparse_classes_75kplus_train_007863 | 5,653 | no_license | [
{
"docstring": "generates a key == parent_key + (offset, ), where offset is a line position in file",
"name": "__iter__",
"signature": "def __iter__(self)"
},
{
"docstring": "reads particular line in file",
"name": "_load",
"signature": "def _load(self, key)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022728 | Implement the Python class `LineFileSlicer` described below.
Class description:
Implement the LineFileSlicer class.
Method signatures and docstrings:
- def __iter__(self): generates a key == parent_key + (offset, ), where offset is a line position in file
- def _load(self, key): reads particular line in file | Implement the Python class `LineFileSlicer` described below.
Class description:
Implement the LineFileSlicer class.
Method signatures and docstrings:
- def __iter__(self): generates a key == parent_key + (offset, ), where offset is a line position in file
- def _load(self, key): reads particular line in file
<|skele... | 9696819fcebfc175969d680bbf58a70d615c4f07 | <|skeleton|>
class LineFileSlicer:
def __iter__(self):
"""generates a key == parent_key + (offset, ), where offset is a line position in file"""
<|body_0|>
def _load(self, key):
"""reads particular line in file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LineFileSlicer:
def __iter__(self):
"""generates a key == parent_key + (offset, ), where offset is a line position in file"""
for input_key in self.input:
with self.input.load(input_key) as f:
offset = 0
line = f.readline()
while line... | the_stack_v2_python_sparse | pydra/cluster/tasks/slicer.py | kreneskyp/Pydra | train | 2 | |
08f1e53a604334dca670ce7230514f5ad3e77fce | [
"if not force:\n data_available = True\n warn_about_field = False\n try:\n self.get_path\n except FieldNotSetError:\n data_available = False\n except FileDoesNotExistError:\n data_available = False\n warn_about_field = True\n if data_available:\n return\n if w... | <|body_start_0|>
if not force:
data_available = True
warn_about_field = False
try:
self.get_path
except FieldNotSetError:
data_available = False
except FileDoesNotExistError:
data_available = False
... | TacHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TacHandler:
def calculate(self, force=False, verbose=True, **kwargs):
"""Wrapper around calculate_contacts"""
<|body_0|>
def set_manual_params_if_needed(self, force=False, n_frames=4, interactive=True, **kwargs):
"""Display a subset of video frames to set fol_x and f... | stack_v2_sparse_classes_75kplus_train_007864 | 11,535 | no_license | [
{
"docstring": "Wrapper around calculate_contacts",
"name": "calculate",
"signature": "def calculate(self, force=False, verbose=True, **kwargs)"
},
{
"docstring": "Display a subset of video frames to set fol_x and fol_y",
"name": "set_manual_params_if_needed",
"signature": "def set_manua... | 3 | stack_v2_sparse_classes_30k_test_000744 | Implement the Python class `TacHandler` described below.
Class description:
Implement the TacHandler class.
Method signatures and docstrings:
- def calculate(self, force=False, verbose=True, **kwargs): Wrapper around calculate_contacts
- def set_manual_params_if_needed(self, force=False, n_frames=4, interactive=True,... | Implement the Python class `TacHandler` described below.
Class description:
Implement the TacHandler class.
Method signatures and docstrings:
- def calculate(self, force=False, verbose=True, **kwargs): Wrapper around calculate_contacts
- def set_manual_params_if_needed(self, force=False, n_frames=4, interactive=True,... | a04ca4c663649549a78c857252a98d8acf8faf31 | <|skeleton|>
class TacHandler:
def calculate(self, force=False, verbose=True, **kwargs):
"""Wrapper around calculate_contacts"""
<|body_0|>
def set_manual_params_if_needed(self, force=False, n_frames=4, interactive=True, **kwargs):
"""Display a subset of video frames to set fol_x and f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TacHandler:
def calculate(self, force=False, verbose=True, **kwargs):
"""Wrapper around calculate_contacts"""
if not force:
data_available = True
warn_about_field = False
try:
self.get_path
except FieldNotSetError:
... | the_stack_v2_python_sparse | Handlers/TacHandler.py | cxrodgers/whiskvid | train | 0 | |
7921b65d53e57572cf831c2a95ece3bc5b17b037 | [
"if len(people) == 0 or len(people) == 1:\n return people\ndata = np.array(people)\nindex = np.lexsort([data[:, 1], -1 * data[:, 0]])\nsorted_people = data[index, :]\nresult = [[sorted_people[0][0], sorted_people[0][1]]]\nfor index in range(1, len(sorted_people)):\n h = sorted_people[index][0]\n k = sorted... | <|body_start_0|>
if len(people) == 0 or len(people) == 1:
return people
data = np.array(people)
index = np.lexsort([data[:, 1], -1 * data[:, 0]])
sorted_people = data[index, :]
result = [[sorted_people[0][0], sorted_people[0][1]]]
for index in range(1, len(sor... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reconstructQueue_1(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_007865 | 2,453 | no_license | [
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue_1",
"signature": "def reconstructQueue_1(self, people)"
},
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue",
"signature": "def reconstructQu... | 2 | stack_v2_sparse_classes_30k_train_034592 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue_1(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue_1(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[... | 163b376acab84e28c74cb784d10fe39f11510921 | <|skeleton|>
class Solution:
def reconstructQueue_1(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue(self, people):
""":type people: List[List[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 reconstructQueue_1(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
if len(people) == 0 or len(people) == 1:
return people
data = np.array(people)
index = np.lexsort([data[:, 1], -1 * data[:, 0]])
sorted_people = data[... | the_stack_v2_python_sparse | code/406. Queue Reconstruction by Height.py | cathyxingchang/leetcode | train | 2 | |
417751cbc63799caadc83cf82c6f85502c9a15e1 | [
"self.model = model\nself.X = X\nself.rule_layer_map = rule_layer_map\nself.output_dir_path = output_dir_path",
"cache_filename = f'{self.output_dir_path}/results.pickle'\nif os.path.isfile(cache_filename):\n print('Using cached results')\n with open(cache_filename, 'rb') as f:\n return pickle.load(f... | <|body_start_0|>
self.model = model
self.X = X
self.rule_layer_map = rule_layer_map
self.output_dir_path = output_dir_path
<|end_body_0|>
<|body_start_1|>
cache_filename = f'{self.output_dir_path}/results.pickle'
if os.path.isfile(cache_filename):
print('Usin... | Boilerplatte code for preparing the experiments and avoid repetition. | Experiments | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Experiments:
"""Boilerplatte code for preparing the experiments and avoid repetition."""
def __init__(self, model: torch.nn.Module, X: torch.Tensor, rule_layer_map: List[Tuple[List[str], rules.LrpRule, Dict[str, Union[torch.Tensor, float]]]], output_dir_path: str) -> None:
"""Store b... | stack_v2_sparse_classes_75kplus_train_007866 | 3,645 | permissive | [
{
"docstring": "Store base variables. :param model: Model to be explained :param X: Input data :param rule_layer_map: List of tuples containing layer names and LRP rule :param output_dir_path: Path to directory where artifacts will be stored",
"name": "__init__",
"signature": "def __init__(self, model: ... | 2 | stack_v2_sparse_classes_30k_test_002070 | Implement the Python class `Experiments` described below.
Class description:
Boilerplatte code for preparing the experiments and avoid repetition.
Method signatures and docstrings:
- def __init__(self, model: torch.nn.Module, X: torch.Tensor, rule_layer_map: List[Tuple[List[str], rules.LrpRule, Dict[str, Union[torch.... | Implement the Python class `Experiments` described below.
Class description:
Boilerplatte code for preparing the experiments and avoid repetition.
Method signatures and docstrings:
- def __init__(self, model: torch.nn.Module, X: torch.Tensor, rule_layer_map: List[Tuple[List[str], rules.LrpRule, Dict[str, Union[torch.... | a2b6bd164df3e7f44e96f534e16b3df2ff8224ac | <|skeleton|>
class Experiments:
"""Boilerplatte code for preparing the experiments and avoid repetition."""
def __init__(self, model: torch.nn.Module, X: torch.Tensor, rule_layer_map: List[Tuple[List[str], rules.LrpRule, Dict[str, Union[torch.Tensor, float]]]], output_dir_path: str) -> None:
"""Store b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Experiments:
"""Boilerplatte code for preparing the experiments and avoid repetition."""
def __init__(self, model: torch.nn.Module, X: torch.Tensor, rule_layer_map: List[Tuple[List[str], rules.LrpRule, Dict[str, Union[torch.Tensor, float]]]], output_dir_path: str) -> None:
"""Store base variables... | the_stack_v2_python_sparse | experiments/notebooks/1-grid-search/experiments.py | rodrigobdz/lrp | train | 5 |
bea0e4c3a70fbd82de8d172ace6ba764887b5c9c | [
"self.value = value\nif self.value not in PERTURBATION_SPECS_DICT:\n raise ValueError(f'Unknown data_augmentation: {self.value}; possible choices: {PERTURBATION_SPECS_DICT.keys()}')",
"def create_run_spec(aug_name: str, perturbation_specs: List[PerturbationSpec]) -> RunSpec:\n data_augmenter_spec: DataAugme... | <|body_start_0|>
self.value = value
if self.value not in PERTURBATION_SPECS_DICT:
raise ValueError(f'Unknown data_augmentation: {self.value}; possible choices: {PERTURBATION_SPECS_DICT.keys()}')
<|end_body_0|>
<|body_start_1|>
def create_run_spec(aug_name: str, perturbation_specs: L... | Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augmentation with multiple perturbations (e.g., all), and others map to a list of data augmentatio... | DataAugmentationRunExpander | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataAugmentationRunExpander:
"""Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augmentation with multiple perturbations (e... | stack_v2_sparse_classes_75kplus_train_007867 | 34,308 | permissive | [
{
"docstring": "Args: value (str): Comma-separated list of perturbations.",
"name": "__init__",
"signature": "def __init__(self, value)"
},
{
"docstring": "Return `run_spec` with data augmentations.",
"name": "expand",
"signature": "def expand(self, run_spec: RunSpec) -> List[RunSpec]"
... | 2 | null | Implement the Python class `DataAugmentationRunExpander` described below.
Class description:
Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augm... | Implement the Python class `DataAugmentationRunExpander` described below.
Class description:
Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augm... | d69a6e696e156ec175a4b6d33e18faf4e2686a7e | <|skeleton|>
class DataAugmentationRunExpander:
"""Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augmentation with multiple perturbations (e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataAugmentationRunExpander:
"""Applies a list of data augmentations, where the list of data augmentations is given by a name (see the keys to `PERTURBATION_SPECS_DICT` above). **Example:** data_augmentation=all Note that some names map to a single data augmentation with multiple perturbations (e.g., all), an... | the_stack_v2_python_sparse | src/helm/benchmark/run_expander.py | closerforever/helm | train | 0 |
0c182cc34dcfb17b1a7574b13638b481f87fd6da | [
"self.group = {}\nself.first = sys.maxsize\nself.last = -1",
"self.group[experience.time] = experience\nself.first = min(self.first, experience.time)\nself.last = max(self.last, experience.time)"
] | <|body_start_0|>
self.group = {}
self.first = sys.maxsize
self.last = -1
<|end_body_0|>
<|body_start_1|>
self.group[experience.time] = experience
self.first = min(self.first, experience.time)
self.last = max(self.last, experience.time)
<|end_body_1|>
| A group of Experiences. | ExperienceGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperienceGroup:
"""A group of Experiences."""
def __init__(self):
""":return: ExperienceGroup An empty group."""
<|body_0|>
def add(self, experience):
"""Add an experience to this group. Parameters ---------- :param experience: Experience The Experience to add t... | stack_v2_sparse_classes_75kplus_train_007868 | 700 | no_license | [
{
"docstring": ":return: ExperienceGroup An empty group.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add an experience to this group. Parameters ---------- :param experience: Experience The Experience to add to this group. Returns ------- :return: None",
"name"... | 2 | stack_v2_sparse_classes_30k_val_002604 | Implement the Python class `ExperienceGroup` described below.
Class description:
A group of Experiences.
Method signatures and docstrings:
- def __init__(self): :return: ExperienceGroup An empty group.
- def add(self, experience): Add an experience to this group. Parameters ---------- :param experience: Experience Th... | Implement the Python class `ExperienceGroup` described below.
Class description:
A group of Experiences.
Method signatures and docstrings:
- def __init__(self): :return: ExperienceGroup An empty group.
- def add(self, experience): Add an experience to this group. Parameters ---------- :param experience: Experience Th... | 501d93b047eb394b7c585faceb836cb3ce124e95 | <|skeleton|>
class ExperienceGroup:
"""A group of Experiences."""
def __init__(self):
""":return: ExperienceGroup An empty group."""
<|body_0|>
def add(self, experience):
"""Add an experience to this group. Parameters ---------- :param experience: Experience The Experience to add t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperienceGroup:
"""A group of Experiences."""
def __init__(self):
""":return: ExperienceGroup An empty group."""
self.group = {}
self.first = sys.maxsize
self.last = -1
def add(self, experience):
"""Add an experience to this group. Parameters ---------- :para... | the_stack_v2_python_sparse | qbrain/core/ExperienceGroup.py | Marek-Arnold/QBrain | train | 0 |
179a19a4ed70b7df48bb8346d33c255fcdec476e | [
"if cls._context_managed_task_group:\n cls._previous_context_managed_task_groups.append(cls._context_managed_task_group)\ncls._context_managed_task_group = task_group\ncls.active = True",
"old_task_group = cls._context_managed_task_group\nif cls._previous_context_managed_task_groups:\n cls._context_managed_... | <|body_start_0|>
if cls._context_managed_task_group:
cls._previous_context_managed_task_groups.append(cls._context_managed_task_group)
cls._context_managed_task_group = task_group
cls.active = True
<|end_body_0|>
<|body_start_1|>
old_task_group = cls._context_managed_task_gr... | TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager. | TaskGroupContext | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
<|body_0|>
def pop_conte... | stack_v2_sparse_classes_75kplus_train_007869 | 29,383 | permissive | [
{
"docstring": "Push a TaskGroup into the list of managed TaskGroups.",
"name": "push_context_managed_task_group",
"signature": "def push_context_managed_task_group(cls, task_group: TaskGroup)"
},
{
"docstring": "Pops the last TaskGroup from the list of manged TaskGroups and update the current T... | 3 | stack_v2_sparse_classes_30k_train_053316 | Implement the Python class `TaskGroupContext` described below.
Class description:
TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.
Method signatures and docstrings:
- def push_context_managed_task_group(cls, task_group: TaskGroup): Push a TaskGroup into the list of man... | Implement the Python class `TaskGroupContext` described below.
Class description:
TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.
Method signatures and docstrings:
- def push_context_managed_task_group(cls, task_group: TaskGroup): Push a TaskGroup into the list of man... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
<|body_0|>
def pop_conte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
if cls._context_managed_task_group:
... | the_stack_v2_python_sparse | airflow/utils/task_group.py | apache/airflow | train | 22,756 |
e9467da874a3d25fc155315bfa2722f9824ef0b9 | [
"super(LSTMDiscriminator, self).__init__()\nself.hidden_dim = hidden_dim\nself.layer_dim = 2\ninput_dim = 2 * obs_dim + act_dim\nself.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)\nself.fc = nn.Linear(hidden_dim, 1)",
"x = x.unsqueeze(0)\nh0 = to.zeros(self.layer_dim, x.size(0), self.hid... | <|body_start_0|>
super(LSTMDiscriminator, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = 2
input_dim = 2 * obs_dim + act_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, 1)
<|end_body_0|>
<|b... | LSTM-based discriminator | LSTMDiscriminator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_007870 | 6,086 | permissive | [
{
"docstring": "Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size",
"name": "__init__",
"signature": "def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128)"
},
{
"docstring": ":param x: A Tensor which... | 2 | stack_v2_sparse_classes_30k_train_053635 | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
super(LSTMDiscriminator, self)._... | the_stack_v2_python_sparse | Pyrado/pyrado/algorithms/adr_discriminator.py | jacarvalho/SimuRLacra | train | 0 |
3dc7eb937908b065c847c757ff7b957bd573cdd2 | [
"heap = PriorityHeap()\nheap.push(5, 'c')\nheap.push(4, 'y')\nheap.push(3, 'n')\nheap.push(2, 'd')\nheap.push(5, 'y')\nassert len(heap._data) == 5\nassert min(heap._data[:5]) == heap._data[0]\nassert heap._data[1] < heap._data[3]\nassert heap._data[1] < heap._data[4]\nheap.push(6, 'y')\nassert heap._data[2] < heap.... | <|body_start_0|>
heap = PriorityHeap()
heap.push(5, 'c')
heap.push(4, 'y')
heap.push(3, 'n')
heap.push(2, 'd')
heap.push(5, 'y')
assert len(heap._data) == 5
assert min(heap._data[:5]) == heap._data[0]
assert heap._data[1] < heap._data[3]
as... | TestProject6 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProject6:
def test_push(self):
"""simple push cases, requires functioning top"""
<|body_0|>
def test_pop(self):
"""simple pop cases, requires functioning top, push, empty"""
<|body_1|>
def test_min_child(self):
"""simple min child test, requi... | stack_v2_sparse_classes_75kplus_train_007871 | 3,871 | no_license | [
{
"docstring": "simple push cases, requires functioning top",
"name": "test_push",
"signature": "def test_push(self)"
},
{
"docstring": "simple pop cases, requires functioning top, push, empty",
"name": "test_pop",
"signature": "def test_pop(self)"
},
{
"docstring": "simple min c... | 6 | stack_v2_sparse_classes_30k_train_042011 | Implement the Python class `TestProject6` described below.
Class description:
Implement the TestProject6 class.
Method signatures and docstrings:
- def test_push(self): simple push cases, requires functioning top
- def test_pop(self): simple pop cases, requires functioning top, push, empty
- def test_min_child(self):... | Implement the Python class `TestProject6` described below.
Class description:
Implement the TestProject6 class.
Method signatures and docstrings:
- def test_push(self): simple push cases, requires functioning top
- def test_pop(self): simple pop cases, requires functioning top, push, empty
- def test_min_child(self):... | 7ffb65e9435dc02b488e11b9c7bb5675f4e45678 | <|skeleton|>
class TestProject6:
def test_push(self):
"""simple push cases, requires functioning top"""
<|body_0|>
def test_pop(self):
"""simple pop cases, requires functioning top, push, empty"""
<|body_1|>
def test_min_child(self):
"""simple min child test, requi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProject6:
def test_push(self):
"""simple push cases, requires functioning top"""
heap = PriorityHeap()
heap.push(5, 'c')
heap.push(4, 'y')
heap.push(3, 'n')
heap.push(2, 'd')
heap.push(5, 'y')
assert len(heap._data) == 5
assert min(he... | the_stack_v2_python_sparse | Project6/mimir_testcases.py | nsnider7/CSE331Repo | train | 0 | |
ec57858c8f7e9d6052fd7b2c82c36a6e697016d9 | [
"builder_name = builder_name_schema.BuilderNameFromObject(self, is_trybot)\nif is_trybot:\n scheduler_name = utils.TRY_SCHEDULERS_STR\nelse:\n scheduler_name = self.scheduler\nhelper.Builder(builder_name, 'f_%s' % builder_name, scheduler=scheduler_name)\nhelper.Factory('f_%s' % builder_name, self.factory_type... | <|body_start_0|>
builder_name = builder_name_schema.BuilderNameFromObject(self, is_trybot)
if is_trybot:
scheduler_name = utils.TRY_SCHEDULERS_STR
else:
scheduler_name = self.scheduler
helper.Builder(builder_name, 'f_%s' % builder_name, scheduler=scheduler_name)
... | BaseBuilder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseBuilder:
def _create(self, helper, do_upload_render_results, do_upload_bench_results, is_trybot=False):
"""Internal method used by create() to set up a builder. Args: helper: instance of utils.SkiaHelper do_upload_render_results: bool; whether the builder should upload its render res... | stack_v2_sparse_classes_75kplus_train_007872 | 23,471 | permissive | [
{
"docstring": "Internal method used by create() to set up a builder. Args: helper: instance of utils.SkiaHelper do_upload_render_results: bool; whether the builder should upload its render results. do_upload_bench_results: bool; whether the builder should upload its bench results. is_trybot: bool; whether or n... | 2 | stack_v2_sparse_classes_30k_train_003353 | Implement the Python class `BaseBuilder` described below.
Class description:
Implement the BaseBuilder class.
Method signatures and docstrings:
- def _create(self, helper, do_upload_render_results, do_upload_bench_results, is_trybot=False): Internal method used by create() to set up a builder. Args: helper: instance ... | Implement the Python class `BaseBuilder` described below.
Class description:
Implement the BaseBuilder class.
Method signatures and docstrings:
- def _create(self, helper, do_upload_render_results, do_upload_bench_results, is_trybot=False): Internal method used by create() to set up a builder. Args: helper: instance ... | 199badf0f15ecac0b0ad37cd0309c7f0d19650ee | <|skeleton|>
class BaseBuilder:
def _create(self, helper, do_upload_render_results, do_upload_bench_results, is_trybot=False):
"""Internal method used by create() to set up a builder. Args: helper: instance of utils.SkiaHelper do_upload_render_results: bool; whether the builder should upload its render res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseBuilder:
def _create(self, helper, do_upload_render_results, do_upload_bench_results, is_trybot=False):
"""Internal method used by create() to set up a builder. Args: helper: instance of utils.SkiaHelper do_upload_render_results: bool; whether the builder should upload its render results. do_uploa... | the_stack_v2_python_sparse | master/master_builders_cfg.py | weaver-viii/skia-buildbot | train | 0 | |
c1186443007106adf8bd6295902d5f13a075f874 | [
"dp = [[0] * len(grid[0]) for _ in range(len(grid))]\nfor r in range(len(grid)):\n for w in range(len(grid[0])):\n if r > 0:\n if w > 0:\n dp[r][w] = min(dp[r - 1][w], dp[r][w - 1]) + grid[r][w]\n else:\n dp[r][w] = dp[r - 1][w] + grid[r][w]\n eli... | <|body_start_0|>
dp = [[0] * len(grid[0]) for _ in range(len(grid))]
for r in range(len(grid)):
for w in range(len(grid[0])):
if r > 0:
if w > 0:
dp[r][w] = min(dp[r - 1][w], dp[r][w - 1]) + grid[r][w]
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[0] * len(grid[0]) for _ in ... | stack_v2_sparse_classes_75kplus_train_007873 | 2,305 | permissive | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "_minPathSum",
"signature": "def _minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047092 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
dp = [[0] * len(grid[0]) for _ in range(len(grid))]
for r in range(len(grid)):
for w in range(len(grid[0])):
if r > 0:
if w > 0:
... | the_stack_v2_python_sparse | 64.minimum-path-sum.py | windard/leeeeee | train | 0 | |
ea743e350cd4d1e5dca2ebe0c063294c1935659e | [
"self.num_frames = num_frames\nself.target_fps = target_fps\nself.sample_mode = sample_mode\nself.sample_interval = sample_interval\nself.sample_minus_interval = sample_minus_interval\nself.repeat = repeat",
"meta = item['meta']\nvideo_path = meta['video_path'] if 'prefix' not in meta else osp.join(meta['prefix']... | <|body_start_0|>
self.num_frames = num_frames
self.target_fps = target_fps
self.sample_mode = sample_mode
self.sample_interval = sample_interval
self.sample_minus_interval = sample_minus_interval
self.repeat = repeat
<|end_body_0|>
<|body_start_1|>
meta = item['m... | DecodeVideoToTensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodeVideoToTensor:
def __init__(self, num_frames, target_fps=30, sample_mode='interval', sample_interval=4, sample_minus_interval=False, repeat=1):
"""DecodeVideoToTensor Args: num_frames (int): Decode frames number. target_fps (int): Decode frames fps, default is 30. sample_mode (str)... | stack_v2_sparse_classes_75kplus_train_007874 | 6,920 | permissive | [
{
"docstring": "DecodeVideoToTensor Args: num_frames (int): Decode frames number. target_fps (int): Decode frames fps, default is 30. sample_mode (str): Interval or segment sampling, default is interval. sample_interval (int): Sample interval between output frames for interval sample mode, default is 4. sample_... | 2 | stack_v2_sparse_classes_30k_train_028973 | Implement the Python class `DecodeVideoToTensor` described below.
Class description:
Implement the DecodeVideoToTensor class.
Method signatures and docstrings:
- def __init__(self, num_frames, target_fps=30, sample_mode='interval', sample_interval=4, sample_minus_interval=False, repeat=1): DecodeVideoToTensor Args: n... | Implement the Python class `DecodeVideoToTensor` described below.
Class description:
Implement the DecodeVideoToTensor class.
Method signatures and docstrings:
- def __init__(self, num_frames, target_fps=30, sample_mode='interval', sample_interval=4, sample_minus_interval=False, repeat=1): DecodeVideoToTensor Args: n... | cfb49fa51a13373e4afc74f8800ec8284c41b8d2 | <|skeleton|>
class DecodeVideoToTensor:
def __init__(self, num_frames, target_fps=30, sample_mode='interval', sample_interval=4, sample_minus_interval=False, repeat=1):
"""DecodeVideoToTensor Args: num_frames (int): Decode frames number. target_fps (int): Decode frames fps, default is 30. sample_mode (str)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecodeVideoToTensor:
def __init__(self, num_frames, target_fps=30, sample_mode='interval', sample_interval=4, sample_minus_interval=False, repeat=1):
"""DecodeVideoToTensor Args: num_frames (int): Decode frames number. target_fps (int): Decode frames fps, default is 30. sample_mode (str): Interval or ... | the_stack_v2_python_sparse | papers/CVPR2021-MOSI/impls/transforms/load_video.py | hrb518/EssentialMC2 | train | 1 | |
9d5340268ca9d3a669ec8ba8c60f1d92730ab88d | [
"super(GrayScale, self).__init__(scope=scope, **kwargs)\nself.weights = weights or (0.299, 0.587, 0.114)\nself.last_rank = len(self.weights)\nself.keep_rank = keep_rank",
"images_shape = get_shape(images)\nassert images_shape[-1] == self.last_rank, \"ERROR: Given image's shape ({}) does not match number of weight... | <|body_start_0|>
super(GrayScale, self).__init__(scope=scope, **kwargs)
self.weights = weights or (0.299, 0.587, 0.114)
self.last_rank = len(self.weights)
self.keep_rank = keep_rank
<|end_body_0|>
<|body_start_1|>
images_shape = get_shape(images)
assert images_shape[-1] ... | A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D). | GrayScale | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GrayScale:
"""A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D)."""
def __init__(self, weights=None, keep_rank=False, scope='grayscale', **kwargs):
"""Args: weights (Optional[tuple,list]): A list/tuple of three items indicating the weights... | stack_v2_sparse_classes_75kplus_train_007875 | 2,897 | permissive | [
{
"docstring": "Args: weights (Optional[tuple,list]): A list/tuple of three items indicating the weights to apply to the 3 color channels (RGB). keep_rank (bool): Whether to keep the color-depth rank in the pre-processed tensor (default: False).",
"name": "__init__",
"signature": "def __init__(self, wei... | 2 | stack_v2_sparse_classes_30k_val_002960 | Implement the Python class `GrayScale` described below.
Class description:
A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D).
Method signatures and docstrings:
- def __init__(self, weights=None, keep_rank=False, scope='grayscale', **kwargs): Args: weights (Optional[tuple,l... | Implement the Python class `GrayScale` described below.
Class description:
A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D).
Method signatures and docstrings:
- def __init__(self, weights=None, keep_rank=False, scope='grayscale', **kwargs): Args: weights (Optional[tuple,l... | ff7d4768579c0e30aa6ceb932cd16f1e51940010 | <|skeleton|>
class GrayScale:
"""A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D)."""
def __init__(self, weights=None, keep_rank=False, scope='grayscale', **kwargs):
"""Args: weights (Optional[tuple,list]): A list/tuple of three items indicating the weights... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GrayScale:
"""A simple grayscale converter for RGB images of arbitrary dimensions (normally, an image is 2D)."""
def __init__(self, weights=None, keep_rank=False, scope='grayscale', **kwargs):
"""Args: weights (Optional[tuple,list]): A list/tuple of three items indicating the weights to apply to ... | the_stack_v2_python_sparse | yarl/components/layers/preprocessing/grayscale.py | pascalwhoop/YARL | train | 0 |
98622b1f23d7e2811ca5992810ecc57ed6fe18e3 | [
"num_stations = len(gas)\ngain_at_each_station = []\nfor i in range(num_stations):\n gain_at_each_station.append(gas[i] - cost[i])\ni = 0\nwhile i < num_stations:\n end = self.canCompleteCircuitWithStart(gain_at_each_station, i)\n if end == i + num_stations:\n return i\n elif i < num_stations:\n ... | <|body_start_0|>
num_stations = len(gas)
gain_at_each_station = []
for i in range(num_stations):
gain_at_each_station.append(gas[i] - cost[i])
i = 0
while i < num_stations:
end = self.canCompleteCircuitWithStart(gain_at_each_station, i)
if end ... | pointer | Solution2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
"""pointer"""
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuitWithStart(self, gain_at_each_station, start):
""":rtype: the end index"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_007876 | 2,721 | permissive | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":rtype: the end index",
"name": "canCompleteCircuitWithStart",
"signature": "def canCompleteCircuitWithStart(se... | 2 | stack_v2_sparse_classes_30k_train_051854 | Implement the Python class `Solution2` described below.
Class description:
pointer
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuitWithStart(self, gain_at_each_station, start): :rtype: the end index | Implement the Python class `Solution2` described below.
Class description:
pointer
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuitWithStart(self, gain_at_each_station, start): :rtype: the end index
<|skeleton... | 1ed22267156fb968671731c2e983b0e65f670750 | <|skeleton|>
class Solution2:
"""pointer"""
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuitWithStart(self, gain_at_each_station, start):
""":rtype: the end index"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution2:
"""pointer"""
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
num_stations = len(gas)
gain_at_each_station = []
for i in range(num_stations):
gain_at_each_station.append(gas[i] - cost[i])
... | the_stack_v2_python_sparse | leetcode/134.py | pingrunhuang/CodeChallenge | train | 0 |
9f36fc4dee7fef4ff76ff39992ba012bcf394447 | [
"page = convert_safely(int, request.args.get('page'), 1)\nfeatures = FeatureDB.query.paginate(page, per_page=LIMIT_PER_PAGE, error_out=False).items\nreturn (features, HTTPStatus.OK)",
"feature = FeatureDB.get_by_name(api.payload.get('name'))\ntry:\n if feature:\n feature.add_users(api.payload.get('users... | <|body_start_0|>
page = convert_safely(int, request.args.get('page'), 1)
features = FeatureDB.query.paginate(page, per_page=LIMIT_PER_PAGE, error_out=False).items
return (features, HTTPStatus.OK)
<|end_body_0|>
<|body_start_1|>
feature = FeatureDB.get_by_name(api.payload.get('name'))
... | List and Add features. | ListFeatures | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListFeatures:
"""List and Add features."""
def get(self):
"""List of paginated features"""
<|body_0|>
def post(self):
"""Add new feature, update it with users if name is identical"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
page = convert_sa... | stack_v2_sparse_classes_75kplus_train_007877 | 3,855 | permissive | [
{
"docstring": "List of paginated features",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add new feature, update it with users if name is identical",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038098 | Implement the Python class `ListFeatures` described below.
Class description:
List and Add features.
Method signatures and docstrings:
- def get(self): List of paginated features
- def post(self): Add new feature, update it with users if name is identical | Implement the Python class `ListFeatures` described below.
Class description:
List and Add features.
Method signatures and docstrings:
- def get(self): List of paginated features
- def post(self): Add new feature, update it with users if name is identical
<|skeleton|>
class ListFeatures:
"""List and Add features... | 18e9ed6d2a660a9fe188881d4af79af3638cdd73 | <|skeleton|>
class ListFeatures:
"""List and Add features."""
def get(self):
"""List of paginated features"""
<|body_0|>
def post(self):
"""Add new feature, update it with users if name is identical"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListFeatures:
"""List and Add features."""
def get(self):
"""List of paginated features"""
page = convert_safely(int, request.args.get('page'), 1)
features = FeatureDB.query.paginate(page, per_page=LIMIT_PER_PAGE, error_out=False).items
return (features, HTTPStatus.OK)
... | the_stack_v2_python_sparse | requester/api/endpoints/features.py | mrf345/flask_restful_api_production_example | train | 1 |
ea9855a1fbe8f96781fc4f93c805061ada7f9683 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)\nself.reqparser.add_argument('attribute_id', required=True, type=str, help='Attribute Id missing')",
"args = self.reqparser.parse_args()\nif 'user_id' not in args:\n user = Users.fi... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('attribute_id', required=True, type=str, help='Attribute Id missing')
<|end_body_0|>
<|body_start_1|>
args = self.... | Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id. | CheckAlerts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate req... | stack_v2_sparse_classes_75kplus_train_007878 | 3,224 | permissive | [
{
"docstring": "Instantiate reqpase.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Check for triggered alerts. :return: On success, an HTTP response with a JSON body content containing the maximum and minimum alerts that have been exceeded with an HTTP status... | 2 | stack_v2_sparse_classes_30k_train_002160 | Implement the Python class `CheckAlerts` described below.
Class description:
Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id.
Method signatures and ... | Implement the Python class `CheckAlerts` described below.
Class description:
Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id.
Method signatures and ... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate reqpase."""
... | the_stack_v2_python_sparse | Analytics/resources/alerts/check_alerts.py | thanosbnt/SharingCitiesDashboard | train | 0 |
81cbd61c160f72cb07ac36d61713ddaf5a9e5e85 | [
"self.emission = [em for em in emission]\nself.alphabet = alphabet\nx = 0\nself.alphabetDict = {i: 0 for i in alphabet}\nfor i in self.alphabetDict:\n self.alphabetDict[i] = x\n x += 1\nself.states = states\ny = 0\nself.statesDict = {i: 0 for i in states}\nfor i in self.statesDict:\n self.statesDict[i] = x... | <|body_start_0|>
self.emission = [em for em in emission]
self.alphabet = alphabet
x = 0
self.alphabetDict = {i: 0 for i in alphabet}
for i in self.alphabetDict:
self.alphabetDict[i] = x
x += 1
self.states = states
y = 0
self.statesD... | Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emission of an HMM (Σ, States, Transition, Emission). Output: A path that maximize... | softDecode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class softDecode:
"""Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emission of an HMM (Σ, States, Transition, E... | stack_v2_sparse_classes_75kplus_train_007879 | 5,221 | no_license | [
{
"docstring": "Constructor: saves attributes from the input file.",
"name": "__init__",
"signature": "def __init__(self, emission, alphabet, states, transMatrix, emisMatrix)"
},
{
"docstring": "Calculate forward probabilities.",
"name": "forwardAlgo",
"signature": "def forwardAlgo(self)... | 5 | stack_v2_sparse_classes_30k_train_046515 | Implement the Python class `softDecode` described below.
Class description:
Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emiss... | Implement the Python class `softDecode` described below.
Class description:
Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emiss... | efe83914cbe193c151504a1b2fe81b8b53055816 | <|skeleton|>
class softDecode:
"""Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emission of an HMM (Σ, States, Transition, E... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class softDecode:
"""Compute the The conditional probability Pr(x|π) that will be emitted by the HMM. Input: A string x, followed by the alphabet Σ from which x was constructed, followed by the states States, transition matrix Transition, and emission matrix Emission of an HMM (Σ, States, Transition, Emission). Out... | the_stack_v2_python_sparse | HMMfwd_BwdDecode.py | zmmason/BINF | train | 6 |
2af819793db950b4c307979a0c93cf32a6f4d1a3 | [
"size = len(nums)\nres = [1] * size\nleft = 1\nfor i in range(size):\n res[i] *= left\n left *= nums[i]\nright = 1\nfor i in range(size - 1, -1, -1):\n res[i] *= right\n right *= nums[i]\nreturn res",
"n = len(nums)\np = 1\nres = []\nfor i in range(n):\n res.append(p)\n p *= nums[i]\np = 1\nfor ... | <|body_start_0|>
size = len(nums)
res = [1] * size
left = 1
for i in range(size):
res[i] *= left
left *= nums[i]
right = 1
for i in range(size - 1, -1, -1):
res[i] *= right
right *= nums[i]
return res
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf_v0(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(nums)
... | stack_v2_sparse_classes_75kplus_train_007880 | 3,952 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf_v0",
"signature": "def productExceptSelf_v0(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029406 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_v0(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 productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_v0(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Sol... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf_v0(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 productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
size = len(nums)
res = [1] * size
left = 1
for i in range(size):
res[i] *= left
left *= nums[i]
right = 1
for i in range(size - 1, -1, -1):... | the_stack_v2_python_sparse | python/238_Product_of_Array_Except_Self.py | Moby5/myleetcode | train | 2 | |
05bcbaab1de52bc8b8eae0993df6bfa219402023 | [
"super(Message, self).__init__(type)\nself.no_reply = no_reply\nself.no_auto_start = no_auto_start\nif serial is not None:\n self.serial = serial\nif reply_serial is not None:\n self.reply_serial = reply_serial\nif path is not None:\n self.path = path\nif interface is not None:\n self.interface = interf... | <|body_start_0|>
super(Message, self).__init__(type)
self.no_reply = no_reply
self.no_auto_start = no_auto_start
if serial is not None:
self.serial = serial
if reply_serial is not None:
self.reply_serial = reply_serial
if path is not None:
... | A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class. | Message | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class."""
def __init__(self, type, no_reply=False, no_auto_start=False, serial=None, reply_serial=None, path=None, inte... | stack_v2_sparse_classes_75kplus_train_007881 | 4,446 | permissive | [
{
"docstring": "Create a new message. Only the *type* argument is mandatory, all other arguments are optional. The arguments have the same meaning as their respective class attributes. When using this constructor, it is your responsibility to check that the required arguments for the specific message type are s... | 5 | null | Implement the Python class `Message` described below.
Class description:
A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class.
Method signatures and docstrings:
- def __init__(self, type, no_reply=False, ... | Implement the Python class `Message` described below.
Class description:
A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class.
Method signatures and docstrings:
- def __init__(self, type, no_reply=False, ... | 7c05fb4876fa09f1719c19f494083b60812d17cc | <|skeleton|>
class Message:
"""A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class."""
def __init__(self, type, no_reply=False, no_auto_start=False, serial=None, reply_serial=None, path=None, inte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Message:
"""A Message that is sent or received on a D-BUS connection. A message consists of header fields and arguments. Both are exposed as attributes on instances of this class."""
def __init__(self, type, no_reply=False, no_auto_start=False, serial=None, reply_serial=None, path=None, interface=None, m... | the_stack_v2_python_sparse | lib/dbusx/message.py | geertj/python-dbusx | train | 1 |
41372ddf335dfb87f6f959934ffa1a968dbe5b0e | [
"index = 1\nrepeat = A\nwhile True:\n if B in repeat:\n return index\n if len(repeat) > len(B) * 2 and index > 5:\n return -1\n index += 1\n repeat += A",
"if B in A:\n return 1\nimport math\nif A in B:\n mi = int(math.ceil(len(B) / float(len(A))))\n if B in mi * A:\n ret... | <|body_start_0|>
index = 1
repeat = A
while True:
if B in repeat:
return index
if len(repeat) > len(B) * 2 and index > 5:
return -1
index += 1
repeat += A
<|end_body_0|>
<|body_start_1|>
if B in A:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_0|>
def repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
index = 1
re... | stack_v2_sparse_classes_75kplus_train_007882 | 1,895 | permissive | [
{
"docstring": ":type A: str :type B: str :rtype: int",
"name": "_repeatedStringMatch",
"signature": "def _repeatedStringMatch(self, A, B)"
},
{
"docstring": ":type A: str :type B: str :rtype: int",
"name": "repeatedStringMatch",
"signature": "def repeatedStringMatch(self, A, B)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int
- def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int
- def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int
<|skeleton|>
class Solut... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_0|>
def repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
index = 1
repeat = A
while True:
if B in repeat:
return index
if len(repeat) > len(B) * 2 and index > 5:
return -1
ind... | the_stack_v2_python_sparse | 686.repeated-string-match.py | windard/leeeeee | train | 0 | |
2ec5dc71f2fea35f44c36c0f35c60dd891547321 | [
"if not vals.get('created_by') or not vals.get('date') or (not vals.get('submittal_id')):\n sub_revision = self.env['tech.submittal.revision'].search([('id', '=', vals.get('revision_id'))], limit=1)\n if not vals.get('created_by'):\n vals.update({'created_by': sub_revision.submitted_by.id})\n if not... | <|body_start_0|>
if not vals.get('created_by') or not vals.get('date') or (not vals.get('submittal_id')):
sub_revision = self.env['tech.submittal.revision'].search([('id', '=', vals.get('revision_id'))], limit=1)
if not vals.get('created_by'):
vals.update({'created_by': s... | Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revision of same document will refer tech.submittal.revision.document on field document_id state: ... | SubmittalDocumentRevision | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubmittalDocumentRevision:
"""Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revision of same document will refer tech.sub... | stack_v2_sparse_classes_75kplus_train_007883 | 6,641 | no_license | [
{
"docstring": "ORM Create override :param vals: Dict of create fields values",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "Revise drawing from :return : new wizard with default value to revise a document",
"name": "doc_revision",
"signature": "def doc_revi... | 3 | null | Implement the Python class `SubmittalDocumentRevision` described below.
Class description:
Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revisi... | Implement the Python class `SubmittalDocumentRevision` described below.
Class description:
Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revisi... | 69792668849d9b851d64487db52db4df91867304 | <|skeleton|>
class SubmittalDocumentRevision:
"""Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revision of same document will refer tech.sub... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubmittalDocumentRevision:
"""Document Revision Information Note: document_id inherited tech.submittal.revision.document ( Please refer : Inheritance and extension Section in ODOO Documentation) New Document creates it information in both classes then revision of same document will refer tech.submittal.revisi... | the_stack_v2_python_sparse | cicon_tech/models/tech_submittal_revision_document.py | sajinaziz/cicon_addons_11 | train | 1 |
54cc47145c7dbb42c270432a4dbb8f12c5b962fe | [
"limit = request.GET.get('limit', 0)\npage = request.GET.get('page', 0)\nread = request.GET.get('read')\nevent_types = request.GET.getlist('eventTypes')\nquery_params = {}\nif read is not None:\n query_params['read'] = read\nif event_types:\n notifs = Notification.objects.filter(event_type__in=event_types, de... | <|body_start_0|>
limit = request.GET.get('limit', 0)
page = request.GET.get('page', 0)
read = request.GET.get('read')
event_types = request.GET.getlist('eventTypes')
query_params = {}
if read is not None:
query_params['read'] = read
if event_types:
... | ManageNotificationsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageNotificationsView:
def get(self, request, *args, **kwargs):
"""List all notifications of a certain event type."""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""Mark notifications as read."""
<|body_1|>
def delete(self, request, pk, *args... | stack_v2_sparse_classes_75kplus_train_007884 | 3,880 | no_license | [
{
"docstring": "List all notifications of a certain event type.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Mark notifications as read.",
"name": "patch",
"signature": "def patch(self, request, *args, **kwargs)"
},
{
"docstring": "Ma... | 3 | stack_v2_sparse_classes_30k_train_050664 | Implement the Python class `ManageNotificationsView` described below.
Class description:
Implement the ManageNotificationsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): List all notifications of a certain event type.
- def patch(self, request, *args, **kwargs): Mark notificat... | Implement the Python class `ManageNotificationsView` described below.
Class description:
Implement the ManageNotificationsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): List all notifications of a certain event type.
- def patch(self, request, *args, **kwargs): Mark notificat... | 83f452436d5586b99ef2a9f327aab833ee794d1e | <|skeleton|>
class ManageNotificationsView:
def get(self, request, *args, **kwargs):
"""List all notifications of a certain event type."""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""Mark notifications as read."""
<|body_1|>
def delete(self, request, pk, *args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManageNotificationsView:
def get(self, request, *args, **kwargs):
"""List all notifications of a certain event type."""
limit = request.GET.get('limit', 0)
page = request.GET.get('page', 0)
read = request.GET.get('read')
event_types = request.GET.getlist('eventTypes')
... | the_stack_v2_python_sparse | server/portal/apps/notifications/views.py | Avila0000/Core-Portal | train | 0 | |
de2bacade3595d3106bb748fc29bf2292edc6cba | [
"modelParams = {'learning_rate': learnRate}\ntf.logging.set_verbosity(tf.logging.INFO)\nself.__logger = State().getLogger('DetectionCore_Component_Logger')\nself.preditcionToClassificationFn = preditcionToClassificationFn\nself.__cnnClassifier = tf.estimator.Estimator(model_fn=cnnModelFn, model_dir=modelDir, params... | <|body_start_0|>
modelParams = {'learning_rate': learnRate}
tf.logging.set_verbosity(tf.logging.INFO)
self.__logger = State().getLogger('DetectionCore_Component_Logger')
self.preditcionToClassificationFn = preditcionToClassificationFn
self.__cnnClassifier = tf.estimator.Estimator... | CnnModelSuit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnnModelSuit:
def __init__(self, cnnModelFn, preditcionToClassificationFn, modelDir='/tmp/cnn_model', learnRate=0.001):
"""Constructor, initialisiert Membervariablen. :param cnnModelFn : function Ein CnnModel mit den Methoden train, predict, evaluate. :param predictedClassesToClassificat... | stack_v2_sparse_classes_75kplus_train_007885 | 4,908 | no_license | [
{
"docstring": "Constructor, initialisiert Membervariablen. :param cnnModelFn : function Ein CnnModel mit den Methoden train, predict, evaluate. :param predictedClassesToClassificationFn : function Eine Funktion um die Klassifizierung der cnnModelFn zu interpretieren, :param modelDir : string Pfad unter welchem... | 4 | null | Implement the Python class `CnnModelSuit` described below.
Class description:
Implement the CnnModelSuit class.
Method signatures and docstrings:
- def __init__(self, cnnModelFn, preditcionToClassificationFn, modelDir='/tmp/cnn_model', learnRate=0.001): Constructor, initialisiert Membervariablen. :param cnnModelFn : ... | Implement the Python class `CnnModelSuit` described below.
Class description:
Implement the CnnModelSuit class.
Method signatures and docstrings:
- def __init__(self, cnnModelFn, preditcionToClassificationFn, modelDir='/tmp/cnn_model', learnRate=0.001): Constructor, initialisiert Membervariablen. :param cnnModelFn : ... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class CnnModelSuit:
def __init__(self, cnnModelFn, preditcionToClassificationFn, modelDir='/tmp/cnn_model', learnRate=0.001):
"""Constructor, initialisiert Membervariablen. :param cnnModelFn : function Ein CnnModel mit den Methoden train, predict, evaluate. :param predictedClassesToClassificat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CnnModelSuit:
def __init__(self, cnnModelFn, preditcionToClassificationFn, modelDir='/tmp/cnn_model', learnRate=0.001):
"""Constructor, initialisiert Membervariablen. :param cnnModelFn : function Ein CnnModel mit den Methoden train, predict, evaluate. :param predictedClassesToClassificationFn : functi... | the_stack_v2_python_sparse | SheetMusicScanner/DetectionCore_Component/Classifier/CnnModels/CnnModelSuit.py | jadeskon/score-scan | train | 0 | |
38603ef08b999a2ea644b28054d4b631ceac36f1 | [
"if inst is None:\n return self\nname = Nature.singlestrand.name\nval = next((i for i in inst.bindings if i.nature == name), None)\nif val is None:\n return Binding(max(inst.positions) * self.SINGLE_STRAND_FACTOR, onrate=0.0, offrate=0.0, nature=Nature.singlestrand)\nreturn val",
"val = _BindingsDescriptor.... | <|body_start_0|>
if inst is None:
return self
name = Nature.singlestrand.name
val = next((i for i in inst.bindings if i.nature == name), None)
if val is None:
return Binding(max(inst.positions) * self.SINGLE_STRAND_FACTOR, onrate=0.0, offrate=0.0, nature=Nature.si... | _SingleStrandBinding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
<|body_0|>
def __set__(self, inst, value):
"""set the single strand binding"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if inst is None:
ret... | stack_v2_sparse_classes_75kplus_train_007886 | 26,924 | no_license | [
{
"docstring": "return the single strand binding",
"name": "__get__",
"signature": "def __get__(self, inst, owner)"
},
{
"docstring": "set the single strand binding",
"name": "__set__",
"signature": "def __set__(self, inst, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005325 | Implement the Python class `_SingleStrandBinding` described below.
Class description:
Implement the _SingleStrandBinding class.
Method signatures and docstrings:
- def __get__(self, inst, owner): return the single strand binding
- def __set__(self, inst, value): set the single strand binding | Implement the Python class `_SingleStrandBinding` described below.
Class description:
Implement the _SingleStrandBinding class.
Method signatures and docstrings:
- def __get__(self, inst, owner): return the single strand binding
- def __set__(self, inst, value): set the single strand binding
<|skeleton|>
class _Sing... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
<|body_0|>
def __set__(self, inst, value):
"""set the single strand binding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
if inst is None:
return self
name = Nature.singlestrand.name
val = next((i for i in inst.bindings if i.nature == name), None)
if val is None:
return Bind... | the_stack_v2_python_sparse | src/simulator/bindings.py | depixusgenome/trackanalysis | train | 0 | |
05bba5aa4ea1cbe2a52f4232e42693ebf5acd2e2 | [
"self.tasks = tasks\nlog.debug(f'HPCWorker ready with {len(self.tasks)}')\nself.job_num = num\nself.job_id = job_id\nself.job_status = 'unknown'\nself.moddir = Path(tasks[0].envvars['MODDIR'])\nself.toppar = tasks[0].envvars['TOPPAR']\nself.cns_folder = tasks[0].envvars['MODULE']\nmodule_name = Path(tasks[0].envvar... | <|body_start_0|>
self.tasks = tasks
log.debug(f'HPCWorker ready with {len(self.tasks)}')
self.job_num = num
self.job_id = job_id
self.job_status = 'unknown'
self.moddir = Path(tasks[0].envvars['MODDIR'])
self.toppar = tasks[0].envvars['TOPPAR']
self.cns_fo... | Defines the HPC Job. | HPCWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_75kplus_train_007887 | 11,076 | permissive | [
{
"docstring": "Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker.",
"name": "__init__",
"signature": "def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None)"
},
{
"docstring": "Prepare the job file... | 5 | stack_v2_sparse_classes_30k_train_045342 | Implement the Python class `HPCWorker` described below.
Class description:
Defines the HPC Job.
Method signatures and docstrings:
- def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None): Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The num... | Implement the Python class `HPCWorker` described below.
Class description:
Defines the HPC Job.
Method signatures and docstrings:
- def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None): Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The num... | e770b786cdfee8011ff4cc8c00520946b25a35e3 | <|skeleton|>
class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
self.tasks = tasks
log.debug(f'H... | the_stack_v2_python_sparse | src/haddock/libs/libhpc.py | haddocking/haddock3 | train | 59 |
3c5933a670e1886aabbfc54dc39fa073aa11ea96 | [
"assert state_num == 4 or state_num == 2, 'Only scalar and point supported, Check state_num please.'\nself.state_num = state_num\nself.measure_num = measure_num\nself.filter = cv2.KalmanFilter(state_num, measure_num, 0)\nself.state = np.zeros((state_num, 1), dtype=np.float32)\nself.measurement = np.array((measure_n... | <|body_start_0|>
assert state_num == 4 or state_num == 2, 'Only scalar and point supported, Check state_num please.'
self.state_num = state_num
self.measure_num = measure_num
self.filter = cv2.KalmanFilter(state_num, measure_num, 0)
self.state = np.zeros((state_num, 1), dtype=np.... | Using Kalman filter as a point stabilizer. | Stabilizer | [
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stabilizer:
"""Using Kalman filter as a point stabilizer."""
def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1):
"""Initialization"""
<|body_0|>
def update(self, measurement):
"""Update the filter"""
<|body_1|>
def se... | stack_v2_sparse_classes_75kplus_train_007888 | 4,823 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1)"
},
{
"docstring": "Update the filter",
"name": "update",
"signature": "def update(self, measurement)"
},
{
"docstring": "Set new... | 3 | stack_v2_sparse_classes_30k_train_004574 | Implement the Python class `Stabilizer` described below.
Class description:
Using Kalman filter as a point stabilizer.
Method signatures and docstrings:
- def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1): Initialization
- def update(self, measurement): Update the filter
- def set_q_... | Implement the Python class `Stabilizer` described below.
Class description:
Using Kalman filter as a point stabilizer.
Method signatures and docstrings:
- def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1): Initialization
- def update(self, measurement): Update the filter
- def set_q_... | ff08e6e8ab095d98e96fc4a136ad5cbccc75fcf9 | <|skeleton|>
class Stabilizer:
"""Using Kalman filter as a point stabilizer."""
def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1):
"""Initialization"""
<|body_0|>
def update(self, measurement):
"""Update the filter"""
<|body_1|>
def se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stabilizer:
"""Using Kalman filter as a point stabilizer."""
def __init__(self, state_num=4, measure_num=2, cov_process=0.0001, cov_measure=0.1):
"""Initialization"""
assert state_num == 4 or state_num == 2, 'Only scalar and point supported, Check state_num please.'
self.state_num... | the_stack_v2_python_sparse | 025_head_pose_estimation/03_integer_quantization/stabilizer.py | PINTO0309/PINTO_model_zoo | train | 2,849 |
b362a0e417f7b65a00ffe0a5e38b4348bd9e75fc | [
"super(ConvolutionalBoxPredictor, self).__init__(is_training, num_classes, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=inplace_batchnorm_update, name=name)\nif min_depth > max_depth:\n raise ValueError('min_depth should be less than or equal to max_depth')\nif len(box_prediction_heads) != len(cla... | <|body_start_0|>
super(ConvolutionalBoxPredictor, self).__init__(is_training, num_classes, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=inplace_batchnorm_update, name=name)
if min_depth > max_depth:
raise ValueError('min_depth should be less than or equal to max_depth')
... | Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across classes --- that is each anchor makes box predictions w... | ConvolutionalBoxPredictor | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across cl... | stack_v2_sparse_classes_75kplus_train_007889 | 21,160 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned ... | 3 | stack_v2_sparse_classes_30k_train_051935 | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes ... | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes ... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across classes --- tha... | the_stack_v2_python_sparse | models/research/object_detection/predictors/convolutional_keras_box_predictor.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
e05cad1cab749d9a8a861a820eefac67bf0cca81 | [
"batch = batch.to(self.device)\ntokens_bos, _ = batch.tokens_bos\npred = self.hparams.model(tokens_bos)\nreturn pred",
"batch = batch.to(self.device)\ntokens_eos, tokens_len = batch.tokens_eos\nloss = self.hparams.compute_cost(predictions, tokens_eos, length=tokens_len)\nreturn loss",
"predictions = self.comput... | <|body_start_0|>
batch = batch.to(self.device)
tokens_bos, _ = batch.tokens_bos
pred = self.hparams.model(tokens_bos)
return pred
<|end_body_0|>
<|body_start_1|>
batch = batch.to(self.device)
tokens_eos, tokens_len = batch.tokens_eos
loss = self.hparams.compute_c... | Class that manages the training loop. See speechbrain.core.Brain. | LM | [
"Apache-2.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage :... | stack_v2_sparse_classes_75kplus_train_007890 | 9,669 | permissive | [
{
"docstring": "Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage : sb.Stage One of sb.Stage.TRAIN, sb.Stage.VALID, or sb.Stage.TEST. Returns ------- predictions : torch.Tensor A tensor containing th... | 4 | stack_v2_sparse_classes_30k_train_001360 | Implement the Python class `LM` described below.
Class description:
Class that manages the training loop. See speechbrain.core.Brain.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object c... | Implement the Python class `LM` described below.
Class description:
Class that manages the training loop. See speechbrain.core.Brain.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object c... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LM:
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Predicts the next word given the previous ones. Arguments --------- batch : PaddedBatch This batch object contains all the relevant tensors for computation. stage : sb.Stage One... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/templates/speech_recognition/LM/train.py | Ascend/ModelZoo-PyTorch | train | 23 |
87a368408756c0dfec2f5f4fd0813045dbd19d0b | [
"self.num_capsules = num_capsules\nself.capsule_dim = capsule_dim\nself.routing_iters = routing_iters\nself._activation = activation\nself.input_probability_fn = input_probability_fn\nself.recurrent_probability_fn = recurrent_probability_fn\nself.rec_only_vote = rec_only_vote\nself.logits_prior = logits_prior\nself... | <|body_start_0|>
self.num_capsules = num_capsules
self.capsule_dim = capsule_dim
self.routing_iters = routing_iters
self._activation = activation
self.input_probability_fn = input_probability_fn
self.recurrent_probability_fn = recurrent_probability_fn
self.rec_onl... | a Bidirectional recurrent capsule layer | BRCapsuleLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BRCapsuleLayer:
"""a Bidirectional recurrent capsule layer"""
def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, logits_prior=False, accumulate_input_logits=True, accumulate_state_logi... | stack_v2_sparse_classes_75kplus_train_007891 | 49,091 | permissive | [
{
"docstring": "BRCapsuleLayer constructor Args: TODO",
"name": "__init__",
"signature": "def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, logits_prior=False, accumulate_input_logits=True, accum... | 2 | null | Implement the Python class `BRCapsuleLayer` described below.
Class description:
a Bidirectional recurrent capsule layer
Method signatures and docstrings:
- def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, log... | Implement the Python class `BRCapsuleLayer` described below.
Class description:
a Bidirectional recurrent capsule layer
Method signatures and docstrings:
- def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, log... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class BRCapsuleLayer:
"""a Bidirectional recurrent capsule layer"""
def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, logits_prior=False, accumulate_input_logits=True, accumulate_state_logi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BRCapsuleLayer:
"""a Bidirectional recurrent capsule layer"""
def __init__(self, num_capsules, capsule_dim, routing_iters=3, activation=None, input_probability_fn=None, recurrent_probability_fn=None, rec_only_vote=False, logits_prior=False, accumulate_input_logits=True, accumulate_state_logits=True):
... | the_stack_v2_python_sparse | nabu/neuralnetworks/components/layer.py | JeroenZegers/Nabu-MSSS | train | 19 |
2c24936b8102342df824bdf480b9a0a0fd9879cf | [
"self.dic = {}\nself.reverseDic = {}\nself.count = 0",
"if val not in self.reverseDic:\n self.count += 1\n self.dic[self.count] = val\n self.reverseDic[val] = self.count\n return True\nelse:\n return False",
"if val in self.reverseDic:\n self.dic[self.reverseDic[val]] = self.dic[self.count]\n ... | <|body_start_0|>
self.dic = {}
self.reverseDic = {}
self.count = 0
<|end_body_0|>
<|body_start_1|>
if val not in self.reverseDic:
self.count += 1
self.dic[self.count] = val
self.reverseDic[val] = self.count
return True
else:
... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_007892 | 14,870 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | null | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | 2711bc08f15266bec4ca135e8e3e629df46713eb | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.dic = {}
self.reverseDic = {}
self.count = 0
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: i... | the_stack_v2_python_sparse | 0.算法/20180813.py | unlimitediw/CheckCode | train | 0 | |
37d3680cab9c36cd6eca9020b5b0c393ceebf8c9 | [
"redis_conn = get_redis_connection('history')\nsku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)\nskus = []\nfor sku_id in sku_ids:\n sku = SKU.objects.get(id=sku_id)\n skus.append({'id': sku.id, 'name': sku.name, 'default_image_url': sku.default_image.url, 'price': sku.price})\nreturn http.J... | <|body_start_0|>
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)
skus = []
for sku_id in sku_ids:
sku = SKU.objects.get(id=sku_id)
skus.append({'id': sku.id, 'name': sku.name, 'default_image_url': sku... | 商品浏览记录 | UserBrowseHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistory:
"""商品浏览记录"""
def get(self, request):
"""查询商品浏览记录"""
<|body_0|>
def post(self, request):
"""商品浏览记录保存"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.lran... | stack_v2_sparse_classes_75kplus_train_007893 | 23,067 | no_license | [
{
"docstring": "查询商品浏览记录",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "商品浏览记录保存",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034113 | Implement the Python class `UserBrowseHistory` described below.
Class description:
商品浏览记录
Method signatures and docstrings:
- def get(self, request): 查询商品浏览记录
- def post(self, request): 商品浏览记录保存 | Implement the Python class `UserBrowseHistory` described below.
Class description:
商品浏览记录
Method signatures and docstrings:
- def get(self, request): 查询商品浏览记录
- def post(self, request): 商品浏览记录保存
<|skeleton|>
class UserBrowseHistory:
"""商品浏览记录"""
def get(self, request):
"""查询商品浏览记录"""
<|body_... | f22b87b5029905fa07fbf556af545a90b0c57f14 | <|skeleton|>
class UserBrowseHistory:
"""商品浏览记录"""
def get(self, request):
"""查询商品浏览记录"""
<|body_0|>
def post(self, request):
"""商品浏览记录保存"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserBrowseHistory:
"""商品浏览记录"""
def get(self, request):
"""查询商品浏览记录"""
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)
skus = []
for sku_id in sku_ids:
sku = SKU.objects.get(id=sku_id)
... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | GongLai/MeiDuoProject | train | 2 |
ba9e6a60a395a9118514acefe21a1a677c0c9edd | [
"Message.__init__(self)\nself.transaction_id = transaction_id\nself.ack = ack\nself.passport = ''\nself.friendly_name = ''",
"message = Message.__str__(self)\ncommand = 'MSG %u %s %u\\r\\n' % (self.transaction_id, self.ack, len(message))\nreturn command + message",
"message = Message.__repr__(self)\nlength = le... | <|body_start_0|>
Message.__init__(self)
self.transaction_id = transaction_id
self.ack = ack
self.passport = ''
self.friendly_name = ''
<|end_body_0|>
<|body_start_1|>
message = Message.__str__(self)
command = 'MSG %u %s %u\r\n' % (self.transaction_id, self.ack, l... | Build MSG commands destined to be sent. | OutgoingMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutgoingMessage:
"""Build MSG commands destined to be sent."""
def __init__(self, transaction_id, ack):
"""Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @type ack: L{message.MessageAcknowledgement}"""
<|bod... | stack_v2_sparse_classes_75kplus_train_007894 | 6,280 | no_license | [
{
"docstring": "Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @type ack: L{message.MessageAcknowledgement}",
"name": "__init__",
"signature": "def __init__(self, transaction_id, ack)"
},
{
"docstring": "Represents the message ... | 3 | stack_v2_sparse_classes_30k_train_050632 | Implement the Python class `OutgoingMessage` described below.
Class description:
Build MSG commands destined to be sent.
Method signatures and docstrings:
- def __init__(self, transaction_id, ack): Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @typ... | Implement the Python class `OutgoingMessage` described below.
Class description:
Build MSG commands destined to be sent.
Method signatures and docstrings:
- def __init__(self, transaction_id, ack): Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @typ... | 16043edb5070b0755ed79b0aa02cba399d3d839d | <|skeleton|>
class OutgoingMessage:
"""Build MSG commands destined to be sent."""
def __init__(self, transaction_id, ack):
"""Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @type ack: L{message.MessageAcknowledgement}"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutgoingMessage:
"""Build MSG commands destined to be sent."""
def __init__(self, transaction_id, ack):
"""Initializer @param transaction_id: the transaction ID @type transaction_id: integer @param ack: Acknowledgment type @type ack: L{message.MessageAcknowledgement}"""
Message.__init__(s... | the_stack_v2_python_sparse | pymsn.rewrite/pymsn.rewrite/pymsn/msnp/message.py | Zacchy/nickcheng-python | train | 0 |
122af4a4f60ba4a624be2f73f956b6ab90e2eb01 | [
"self.x = x\nself.y = y\nself.name = name\nself.char = char\nself.color = color\nself.description = description\nself.blocks = blocks\nself.render_order = render_order\nself.components = components\nfor i in self.components:\n self.components.get(i).set_owner(self)",
"dx = other.x - self.x\ndy = other.y - self... | <|body_start_0|>
self.x = x
self.y = y
self.name = name
self.char = char
self.color = color
self.description = description
self.blocks = blocks
self.render_order = render_order
self.components = components
for i in self.components:
... | Entity class to be used by all entities. | Entity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Entity:
"""Entity class to be used by all entities."""
def __init__(self, x, y, name, char, color, description, blocks=False, render_order=Render_Order.CORPSE, components={}):
"""Initialize entity x -- starting x coordinate y -- starting y coordinate name -- entity name char -- chara... | stack_v2_sparse_classes_75kplus_train_007895 | 1,433 | no_license | [
{
"docstring": "Initialize entity x -- starting x coordinate y -- starting y coordinate name -- entity name char -- character used to represent entity within the world color -- color of all entity representations description -- short description of the entity blocks -- boolean value for whetyher the entity bloc... | 2 | stack_v2_sparse_classes_30k_test_002453 | Implement the Python class `Entity` described below.
Class description:
Entity class to be used by all entities.
Method signatures and docstrings:
- def __init__(self, x, y, name, char, color, description, blocks=False, render_order=Render_Order.CORPSE, components={}): Initialize entity x -- starting x coordinate y -... | Implement the Python class `Entity` described below.
Class description:
Entity class to be used by all entities.
Method signatures and docstrings:
- def __init__(self, x, y, name, char, color, description, blocks=False, render_order=Render_Order.CORPSE, components={}): Initialize entity x -- starting x coordinate y -... | 9cea1fcbc61362d930adc22293c950c0cfc3ad66 | <|skeleton|>
class Entity:
"""Entity class to be used by all entities."""
def __init__(self, x, y, name, char, color, description, blocks=False, render_order=Render_Order.CORPSE, components={}):
"""Initialize entity x -- starting x coordinate y -- starting y coordinate name -- entity name char -- chara... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Entity:
"""Entity class to be used by all entities."""
def __init__(self, x, y, name, char, color, description, blocks=False, render_order=Render_Order.CORPSE, components={}):
"""Initialize entity x -- starting x coordinate y -- starting y coordinate name -- entity name char -- character used to ... | the_stack_v2_python_sparse | entities/entity_classes.py | JarrodDoyle/Shattered-Strongholds | train | 0 |
96362371067820cfb803329d38ccedc098fe7d59 | [
"try:\n return phonenumbers.format_number(obj, phonenumbers.PhoneNumberFormat.NATIONAL)\nexcept Exception as e:\n return None",
"try:\n obj = phonenumbers.parse(text, 'CA')\n return phonenumbers.format_number(obj, phonenumbers.PhoneNumberFormat.NATIONAL)\nexcept Exception as e:\n return None"
] | <|body_start_0|>
try:
return phonenumbers.format_number(obj, phonenumbers.PhoneNumberFormat.NATIONAL)
except Exception as e:
return None
<|end_body_0|>
<|body_start_1|>
try:
obj = phonenumbers.parse(text, 'CA')
return phonenumbers.format_number(ob... | Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library. | PhoneNumberField | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneNumberField:
"""Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library."""
def to_representation(self, obj):
"""Function used to convert the PhoneNumber object to text string representation."""
<|bo... | stack_v2_sparse_classes_75kplus_train_007896 | 1,880 | permissive | [
{
"docstring": "Function used to convert the PhoneNumber object to text string representation.",
"name": "to_representation",
"signature": "def to_representation(self, obj)"
},
{
"docstring": "Function used to conver the text into the PhoneNumber object representation.",
"name": "to_internal... | 2 | stack_v2_sparse_classes_30k_train_009481 | Implement the Python class `PhoneNumberField` described below.
Class description:
Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library.
Method signatures and docstrings:
- def to_representation(self, obj): Function used to convert the PhoneNum... | Implement the Python class `PhoneNumberField` described below.
Class description:
Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library.
Method signatures and docstrings:
- def to_representation(self, obj): Function used to convert the PhoneNum... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class PhoneNumberField:
"""Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library."""
def to_representation(self, obj):
"""Function used to convert the PhoneNumber object to text string representation."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhoneNumberField:
"""Class used to convert the "PhoneNumber" objects "to" and "from" strings. This objects is from the "python-phonenumbers" library."""
def to_representation(self, obj):
"""Function used to convert the PhoneNumber object to text string representation."""
try:
... | the_stack_v2_python_sparse | mikaponics/foundation/custom/drf/fields.py | mikaponics/mikaponics-back | train | 4 |
7d9706c85340a4e0d2cb7b3022f73aa784904160 | [
"if isinstance(command, str):\n command = shlex.split(command)\nself.command = command",
"def target(**kwargs):\n try:\n self.process = subprocess.Popen(self.command, **kwargs)\n self.output, self.error = self.process.communicate()\n self.status = self.process.returncode\n if isi... | <|body_start_0|>
if isinstance(command, str):
command = shlex.split(command)
self.command = command
<|end_body_0|>
<|body_start_1|>
def target(**kwargs):
try:
self.process = subprocess.Popen(self.command, **kwargs)
self.output, self.error ... | Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933. | Command | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-hdf5"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933."""
def __init__(self, command):
... | stack_v2_sparse_classes_75kplus_train_007897 | 6,280 | permissive | [
{
"docstring": "initialize the object. Args: command: command to run",
"name": "__init__",
"signature": "def __init__(self, command)"
},
{
"docstring": "Run the command. Args: timeout (float): timeout kwargs (dict) Returns: (status, output, error)",
"name": "run",
"signature": "def run(s... | 2 | null | Implement the Python class `Command` described below.
Class description:
Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933.
Metho... | Implement the Python class `Command` described below.
Class description:
Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933.
Metho... | 579bcf411196ce0bebb4f04ccd2410c091c966cf | <|skeleton|>
class Command:
"""Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933."""
def __init__(self, command):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""Helper class - run subprocess commands in a different thread with TIMEOUT option. From https://gist.github.com/kirpit/1306188 Based on jcollado's solution: http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933."""
def __init__(self, command):
"""initialize... | the_stack_v2_python_sparse | fireworks/queue/queue_adapter.py | materialsproject/fireworks | train | 298 |
ecdcb371e55fb2393246ec78b7144c3b232021bb | [
"self.model = model\nself.degree = degree\nself.coefficients = None\nself.mean = None\nself.values = np.ones(len(model))\nwave = self.model.wave\nx = (wave - 0.5 * (wave[0] + wave[-1])) / 2.0\nx /= np.max(np.abs(x[~np.isnan(x)]))\nself._legendre = np.zeros((len(x), degree))\nfor k in range(degree):\n self._legen... | <|body_start_0|>
self.model = model
self.degree = degree
self.coefficients = None
self.mean = None
self.values = np.ones(len(model))
wave = self.model.wave
x = (wave - 0.5 * (wave[0] + wave[-1])) / 2.0
x /= np.max(np.abs(x[~np.isnan(x)]))
self._leg... | Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials. | Legendre | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Legendre:
"""Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials."""
def __init__(self, model, degree):
"""Initialize continuum fitter. :param model: Model to use for deriving the continuum. :param degree: Degree of Legendre poly... | stack_v2_sparse_classes_75kplus_train_007898 | 24,181 | permissive | [
{
"docstring": "Initialize continuum fitter. :param model: Model to use for deriving the continuum. :param degree: Degree of Legendre polynomial to use.",
"name": "__init__",
"signature": "def __init__(self, model, degree)"
},
{
"docstring": "Calculate the continuum. Effectively we're searching ... | 2 | stack_v2_sparse_classes_30k_train_018103 | Implement the Python class `Legendre` described below.
Class description:
Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials.
Method signatures and docstrings:
- def __init__(self, model, degree): Initialize continuum fitter. :param model: Model to use for deriv... | Implement the Python class `Legendre` described below.
Class description:
Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials.
Method signatures and docstrings:
- def __init__(self, model, degree): Initialize continuum fitter. :param model: Model to use for deriv... | 648eb1758e3744d9e3d6669edc4a0c4753559f17 | <|skeleton|>
class Legendre:
"""Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials."""
def __init__(self, model, degree):
"""Initialize continuum fitter. :param model: Model to use for deriving the continuum. :param degree: Degree of Legendre poly... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Legendre:
"""Calculate 'continuum' between a given spectrum and a model as a linear combination of Legendre polynomials."""
def __init__(self, model, degree):
"""Initialize continuum fitter. :param model: Model to use for deriving the continuum. :param degree: Degree of Legendre polynomial to use... | the_stack_v2_python_sparse | spexxy/main/paramsfit.py | thusser/spexxy | train | 4 |
4b3aa580dedcc019e2df71cc710e9f6f59553136 | [
"super(TestCase, self).setUp()\nself.log_fixture = self.useFixture(fixtures.FakeLogger())\nself.useFixture(conf_fixture.ConfFixture(CONF))\nself.messaging_conf = messaging_conffixture.ConfFixture(CONF)\nself.messaging_conf.transport_driver = 'fake'\nself.messaging_conf.response_timeout = 15\nself.useFixture(self.me... | <|body_start_0|>
super(TestCase, self).setUp()
self.log_fixture = self.useFixture(fixtures.FakeLogger())
self.useFixture(conf_fixture.ConfFixture(CONF))
self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
self.messaging_conf.transport_driver = 'fake'
self.messag... | Test case base class for all unit tests. | TestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each method to initialize test environment."""
<|body_0|>
def path_get(self, project_file=None):
"""Get the absolute path to a file. Used for testing the API. :param project_f... | stack_v2_sparse_classes_75kplus_train_007899 | 5,724 | permissive | [
{
"docstring": "Run before each method to initialize test environment.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Get the absolute path to a file. Used for testing the API. :param project_file: File whose path to return. Default: None. :returns: path to the specified fi... | 3 | null | Implement the Python class `TestCase` described below.
Class description:
Test case base class for all unit tests.
Method signatures and docstrings:
- def setUp(self): Run before each method to initialize test environment.
- def path_get(self, project_file=None): Get the absolute path to a file. Used for testing the ... | Implement the Python class `TestCase` described below.
Class description:
Test case base class for all unit tests.
Method signatures and docstrings:
- def setUp(self): Run before each method to initialize test environment.
- def path_get(self, project_file=None): Get the absolute path to a file. Used for testing the ... | 4fc303e8349f96ef43e51e135988b3d70d278861 | <|skeleton|>
class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each method to initialize test environment."""
<|body_0|>
def path_get(self, project_file=None):
"""Get the absolute path to a file. Used for testing the API. :param project_f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCase:
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each method to initialize test environment."""
super(TestCase, self).setUp()
self.log_fixture = self.useFixture(fixtures.FakeLogger())
self.useFixture(conf_fixture.ConfFixture(CONF))
... | the_stack_v2_python_sparse | payload/test.py | cmsdesigner/payload | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.