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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f13c5c7b56b0b8a7d7137998ce0eb6a6b08151f2 | [
"levels = len(true_measure)\nif levels != 1:\n raise NotYetImplemented('\\n MeanMC_g tot implemented for multi-level problems.\\n Use CLT stopping criterion with an iid distribution for multi-level problems ')\nself.abs_tol = abs_tol\nself.rel_tol = rel_tol\nself.n_max = n_max\nself... | <|body_start_0|>
levels = len(true_measure)
if levels != 1:
raise NotYetImplemented('\n MeanMC_g tot implemented for multi-level problems.\n Use CLT stopping criterion with an iid distribution for multi-level problems ')
self.abs_tol = abs_tol
se... | Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algorithm terminates without showing any warning messages and provides an answe... | MeanMC_g | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanMC_g:
"""Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algorithm terminates without showing any wa... | stack_v2_sparse_classes_75kplus_train_004100 | 7,665 | no_license | [
{
"docstring": "Args: discrete_distrib true_measure: an instance of DiscreteDistribution inflate: inflation factor when estimating variance alpha: significance level for confidence interval abs_tol: absolute error tolerance rel_tol: relative error tolerance n_init: initial number of samples n_max: maximum numbe... | 3 | null | Implement the Python class `MeanMC_g` described below.
Class description:
Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algo... | Implement the Python class `MeanMC_g` described below.
Class description:
Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algo... | 9f37eb67f74c4b1a4ccfb5547a2b284cb5897d37 | <|skeleton|>
class MeanMC_g:
"""Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algorithm terminates without showing any wa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeanMC_g:
"""Stopping Criterion with garunteed accuracy Guarantee This algorithm attempts to calculate the mean, mu, of a random variable to a prescribed error tolerance, tolfun:= max(abstol,reltol*|mu|), with guaranteed confidence level 1-alpha. If the algorithm terminates without showing any warning message... | the_stack_v2_python_sparse | python_prototype/qmcpy/stopping_criterion/mean_mc_g.py | jagadeesr/QMCSoftware | train | 0 |
bee6a1428ab90c3f7553bc54320a8b5b702361d6 | [
"scaled_scalers = []\nunscaled_scalers = []\nidx_to_remove = []\nfor i, (expt, refl) in enumerate(zip(experiments[:-1], reflections[:-1])):\n try:\n scaler = SingleScalerFactory.create(params, expt, refl, for_multi=True)\n except BadDatasetForScalingException as e:\n logger.info(e)\n idx_... | <|body_start_0|>
scaled_scalers = []
unscaled_scalers = []
idx_to_remove = []
for i, (expt, refl) in enumerate(zip(experiments[:-1], reflections[:-1])):
try:
scaler = SingleScalerFactory.create(params, expt, refl, for_multi=True)
except BadDatasetF... | Factory for creating a targeted scaler for multiple datasets | TargetScalerFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetScalerFactory:
"""Factory for creating a targeted scaler for multiple datasets"""
def create_for_target_against_reference(params, experiments, reflections):
"""Create TargetScaler for case where have a reference datafile or model."""
<|body_0|>
def create(params, e... | stack_v2_sparse_classes_75kplus_train_004101 | 13,194 | permissive | [
{
"docstring": "Create TargetScaler for case where have a reference datafile or model.",
"name": "create_for_target_against_reference",
"signature": "def create_for_target_against_reference(params, experiments, reflections)"
},
{
"docstring": "sort scaled and unscaled datasets to pass to TargetS... | 2 | stack_v2_sparse_classes_30k_train_005317 | Implement the Python class `TargetScalerFactory` described below.
Class description:
Factory for creating a targeted scaler for multiple datasets
Method signatures and docstrings:
- def create_for_target_against_reference(params, experiments, reflections): Create TargetScaler for case where have a reference datafile ... | Implement the Python class `TargetScalerFactory` described below.
Class description:
Factory for creating a targeted scaler for multiple datasets
Method signatures and docstrings:
- def create_for_target_against_reference(params, experiments, reflections): Create TargetScaler for case where have a reference datafile ... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class TargetScalerFactory:
"""Factory for creating a targeted scaler for multiple datasets"""
def create_for_target_against_reference(params, experiments, reflections):
"""Create TargetScaler for case where have a reference datafile or model."""
<|body_0|>
def create(params, e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TargetScalerFactory:
"""Factory for creating a targeted scaler for multiple datasets"""
def create_for_target_against_reference(params, experiments, reflections):
"""Create TargetScaler for case where have a reference datafile or model."""
scaled_scalers = []
unscaled_scalers = []... | the_stack_v2_python_sparse | src/dials/algorithms/scaling/scaler_factory.py | dials/dials | train | 71 |
c9122c226c8d5da89ef9a165a9b7b9152c546465 | [
"self._basedir = basedir\nself._process_fn = process_fn\nself._start_fn = start_fn\nself._resume_fn = resume_fn\nself._num_runs = num_runs\nself._worker_name = worker_name or str(uuid.uuid4())\nself._ping_every = ping_every\nself._ping_stale = ping_every and 2 * ping_every\nself._resume_runs = resume_runs",
"for ... | <|body_start_0|>
self._basedir = basedir
self._process_fn = process_fn
self._start_fn = start_fn
self._resume_fn = resume_fn
self._num_runs = num_runs
self._worker_name = worker_name or str(uuid.uuid4())
self._ping_every = ping_every
self._ping_stale = pin... | Experiment class. | Experiment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Experiment:
"""Experiment class."""
def __init__(self, basedir, process_fn, start_fn=None, resume_fn=None, num_runs=None, worker_name=None, ping_every=30, resume_runs=True):
"""Coordinate experiments with multiple runs processed by multiple workers. The experiment can be iterated ove... | stack_v2_sparse_classes_75kplus_train_004102 | 12,659 | permissive | [
{
"docstring": "Coordinate experiments with multiple runs processed by multiple workers. The experiment can be iterated over to yield runs. Runs can be iterated over to process them and obtain their numbers. When multiple workers create an experiment with the same base directory, they will process different run... | 3 | stack_v2_sparse_classes_30k_train_031225 | Implement the Python class `Experiment` described below.
Class description:
Experiment class.
Method signatures and docstrings:
- def __init__(self, basedir, process_fn, start_fn=None, resume_fn=None, num_runs=None, worker_name=None, ping_every=30, resume_runs=True): Coordinate experiments with multiple runs processe... | Implement the Python class `Experiment` described below.
Class description:
Experiment class.
Method signatures and docstrings:
- def __init__(self, basedir, process_fn, start_fn=None, resume_fn=None, num_runs=None, worker_name=None, ping_every=30, resume_runs=True): Coordinate experiments with multiple runs processe... | a99be65d2fdc0a7ac78b67480e02e58adf2c2eb5 | <|skeleton|>
class Experiment:
"""Experiment class."""
def __init__(self, basedir, process_fn, start_fn=None, resume_fn=None, num_runs=None, worker_name=None, ping_every=30, resume_runs=True):
"""Coordinate experiments with multiple runs processed by multiple workers. The experiment can be iterated ove... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Experiment:
"""Experiment class."""
def __init__(self, basedir, process_fn, start_fn=None, resume_fn=None, num_runs=None, worker_name=None, ping_every=30, resume_runs=True):
"""Coordinate experiments with multiple runs processed by multiple workers. The experiment can be iterated over to yield ru... | the_stack_v2_python_sparse | planet/training/running.py | createamind/Planet | train | 26 |
8791a0c719c6bcd6e25c210b000185e458dad1e1 | [
"for selection in orm.Selection.objects.all():\n if selection.internal_crns == '[]':\n crns = []\n else:\n crns = deserialize_numbers(selection.internal_crns)\n sids = models.SectionProxy.objects.filter(crn__in=crns).values_list('id', flat=True)\n selection.internal_section_ids = serialize... | <|body_start_0|>
for selection in orm.Selection.objects.all():
if selection.internal_crns == '[]':
crns = []
else:
crns = deserialize_numbers(selection.internal_crns)
sids = models.SectionProxy.objects.filter(crn__in=crns).values_list('id', fla... | Migration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for selection in orm.Selection.objects.all():
... | stack_v2_sparse_classes_75kplus_train_004103 | 9,318 | permissive | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001052 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | 6bdb2299905f6321be5de788f16a9464a70a4206 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
for selection in orm.Selection.objects.all():
if selection.internal_crns == '[]':
crns = []
else:
crns = deserialize_numbers(selection.internal_crns)
... | the_stack_v2_python_sparse | scheduler/south_migrations/0006_convert_crns_to_section_ids_for_selections.py | a3r0d7n4m1k/YACS | train | 0 | |
8290e13aba7a140ec3026bc8b727777c3d88a67d | [
"super(PlottingComponent, self).__init__(config)\nself.plot_data_path = None\nself.plot_preparation_path = None\nself.plot_decomposition_path = None\nself.plot_truncation_path = None\nself.plot_photometry_path = None\nself.plot_maps_path = None\nself.plot_fitting_path = None\nself.plot_analysis_path = None",
"sup... | <|body_start_0|>
super(PlottingComponent, self).__init__(config)
self.plot_data_path = None
self.plot_preparation_path = None
self.plot_decomposition_path = None
self.plot_truncation_path = None
self.plot_photometry_path = None
self.plot_maps_path = None
s... | This class... | PlottingComponent | [
"MIT",
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlottingComponent:
"""This class..."""
def __init__(self, config=None):
"""The constructor ... :param config: :return:"""
<|body_0|>
def setup(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(PlottingCom... | stack_v2_sparse_classes_75kplus_train_004104 | 2,884 | permissive | [
{
"docstring": "The constructor ... :param config: :return:",
"name": "__init__",
"signature": "def __init__(self, config=None)"
},
{
"docstring": "This function ... :return:",
"name": "setup",
"signature": "def setup(self)"
}
] | 2 | null | Implement the Python class `PlottingComponent` described below.
Class description:
This class...
Method signatures and docstrings:
- def __init__(self, config=None): The constructor ... :param config: :return:
- def setup(self): This function ... :return: | Implement the Python class `PlottingComponent` described below.
Class description:
This class...
Method signatures and docstrings:
- def __init__(self, config=None): The constructor ... :param config: :return:
- def setup(self): This function ... :return:
<|skeleton|>
class PlottingComponent:
"""This class..."""... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class PlottingComponent:
"""This class..."""
def __init__(self, config=None):
"""The constructor ... :param config: :return:"""
<|body_0|>
def setup(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlottingComponent:
"""This class..."""
def __init__(self, config=None):
"""The constructor ... :param config: :return:"""
super(PlottingComponent, self).__init__(config)
self.plot_data_path = None
self.plot_preparation_path = None
self.plot_decomposition_path = Non... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/plotting/component.py | Stargrazer82301/CAAPR | train | 8 |
ea00a492226e7fdd85c43a7aaac4543a7d627f5f | [
"strfpn = 'simple.test-myversion1:ascii:mydb#1'\nfpn = ccm.FourPartName(strfpn)\nassert fpn.name == 'simple.test'\nassert fpn.version == 'myversion1'\nassert fpn.type == 'ascii'\nassert fpn.instance == 'mydb#1'\nassert strfpn == str(fpn)\nassert strfpn == fpn.objectname",
"strfpn = 'simple test.ext - myversion1 :... | <|body_start_0|>
strfpn = 'simple.test-myversion1:ascii:mydb#1'
fpn = ccm.FourPartName(strfpn)
assert fpn.name == 'simple.test'
assert fpn.version == 'myversion1'
assert fpn.type == 'ascii'
assert fpn.instance == 'mydb#1'
assert strfpn == str(fpn)
assert s... | Unit test case for testing four part name of a ccm project | FourPartNameTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FourPartNameTest:
"""Unit test case for testing four part name of a ccm project"""
def testSimpleFourPartNameParsing(self):
"""Test the parsing of a simple four part name"""
<|body_0|>
def testSpacesFourPartNameParsing(self):
"""Test the parsing of a four part na... | stack_v2_sparse_classes_75kplus_train_004105 | 5,649 | no_license | [
{
"docstring": "Test the parsing of a simple four part name",
"name": "testSimpleFourPartNameParsing",
"signature": "def testSimpleFourPartNameParsing(self)"
},
{
"docstring": "Test the parsing of a four part name that contains spaces",
"name": "testSpacesFourPartNameParsing",
"signature... | 6 | stack_v2_sparse_classes_30k_train_011205 | Implement the Python class `FourPartNameTest` described below.
Class description:
Unit test case for testing four part name of a ccm project
Method signatures and docstrings:
- def testSimpleFourPartNameParsing(self): Test the parsing of a simple four part name
- def testSpacesFourPartNameParsing(self): Test the pars... | Implement the Python class `FourPartNameTest` described below.
Class description:
Unit test case for testing four part name of a ccm project
Method signatures and docstrings:
- def testSimpleFourPartNameParsing(self): Test the parsing of a simple four part name
- def testSpacesFourPartNameParsing(self): Test the pars... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class FourPartNameTest:
"""Unit test case for testing four part name of a ccm project"""
def testSimpleFourPartNameParsing(self):
"""Test the parsing of a simple four part name"""
<|body_0|>
def testSpacesFourPartNameParsing(self):
"""Test the parsing of a four part na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FourPartNameTest:
"""Unit test case for testing four part name of a ccm project"""
def testSimpleFourPartNameParsing(self):
"""Test the parsing of a simple four part name"""
strfpn = 'simple.test-myversion1:ascii:mydb#1'
fpn = ccm.FourPartName(strfpn)
assert fpn.name == 's... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_ccm_4pn.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
4d668431f94d3e85f2899a4f13613e7922235e56 | [
"serialized_data = PlayersSerializer(player).data\nrsp = {'player': serialized_data}\nreturn Response(rsp)",
"if not request.data:\n return Response({'message': 'Body empty'}, status=status.HTTP_404_NOT_FOUND)\nelse:\n serializer = UpdatePlayerSerializer(player, data=request.data)\n if serializer.is_vali... | <|body_start_0|>
serialized_data = PlayersSerializer(player).data
rsp = {'player': serialized_data}
return Response(rsp)
<|end_body_0|>
<|body_start_1|>
if not request.data:
return Response({'message': 'Body empty'}, status=status.HTTP_404_NOT_FOUND)
else:
... | Players By ID API Endpoints | PlayersByIdAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayersByIdAPI:
"""Players By ID API Endpoints"""
def get(self, request, player_id, player, *args, **kwargs):
"""Gets the information of a certain player by it's ID"""
<|body_0|>
def put(self, request, player_id, player, *args, **kwargs):
"""Allows the update of ... | stack_v2_sparse_classes_75kplus_train_004106 | 4,740 | permissive | [
{
"docstring": "Gets the information of a certain player by it's ID",
"name": "get",
"signature": "def get(self, request, player_id, player, *args, **kwargs)"
},
{
"docstring": "Allows the update of a certain player details based on ID",
"name": "put",
"signature": "def put(self, request... | 3 | null | Implement the Python class `PlayersByIdAPI` described below.
Class description:
Players By ID API Endpoints
Method signatures and docstrings:
- def get(self, request, player_id, player, *args, **kwargs): Gets the information of a certain player by it's ID
- def put(self, request, player_id, player, *args, **kwargs): ... | Implement the Python class `PlayersByIdAPI` described below.
Class description:
Players By ID API Endpoints
Method signatures and docstrings:
- def get(self, request, player_id, player, *args, **kwargs): Gets the information of a certain player by it's ID
- def put(self, request, player_id, player, *args, **kwargs): ... | 961107acbcdd93551bcd1b4b0ecd877fb4a7d813 | <|skeleton|>
class PlayersByIdAPI:
"""Players By ID API Endpoints"""
def get(self, request, player_id, player, *args, **kwargs):
"""Gets the information of a certain player by it's ID"""
<|body_0|>
def put(self, request, player_id, player, *args, **kwargs):
"""Allows the update of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlayersByIdAPI:
"""Players By ID API Endpoints"""
def get(self, request, player_id, player, *args, **kwargs):
"""Gets the information of a certain player by it's ID"""
serialized_data = PlayersSerializer(player).data
rsp = {'player': serialized_data}
return Response(rsp)
... | the_stack_v2_python_sparse | footballleagues/views/players.py | RicardoSilveira23/TonicAppChallenge | train | 0 |
3b9f01a78e591d93c940b3d243d3546959221ef4 | [
"super(PCConvLstmNet, self).__init__()\nself.kernel_size = 7\nself.stride = 3\nself.hidden_size = 16\nself.n_layers = 1\nself.n0_features = 4\nself.n1_features = 8\nself.n2_features = 16\nself.conv = nn.Sequential(nn.Conv1d(1, self.n0_features, self.kernel_size, self.stride), nn.BatchNorm1d(self.n0_features), nn.Re... | <|body_start_0|>
super(PCConvLstmNet, self).__init__()
self.kernel_size = 7
self.stride = 3
self.hidden_size = 16
self.n_layers = 1
self.n0_features = 4
self.n1_features = 8
self.n2_features = 16
self.conv = nn.Sequential(nn.Conv1d(1, self.n0_featu... | Class to implement a deep neural model for music performance assessment using pitch contours as input | PCConvLstmNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCConvLstmNet:
"""Class to implement a deep neural model for music performance assessment using pitch contours as input"""
def __init__(self):
"""Initializes the PitchContourAssessor class with internal parameters for the different layers"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus_train_004107 | 7,406 | no_license | [
{
"docstring": "Initializes the PitchContourAssessor class with internal parameters for the different layers",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Defines the forward pass of the PitchContourAssessor module Args: input: torch Variable (mini_batch_size x zero_... | 3 | stack_v2_sparse_classes_30k_train_015258 | Implement the Python class `PCConvLstmNet` described below.
Class description:
Class to implement a deep neural model for music performance assessment using pitch contours as input
Method signatures and docstrings:
- def __init__(self): Initializes the PitchContourAssessor class with internal parameters for the diffe... | Implement the Python class `PCConvLstmNet` described below.
Class description:
Class to implement a deep neural model for music performance assessment using pitch contours as input
Method signatures and docstrings:
- def __init__(self): Initializes the PitchContourAssessor class with internal parameters for the diffe... | 4abeb02ee66ba77c327259c16f6d33d3246aaeb9 | <|skeleton|>
class PCConvLstmNet:
"""Class to implement a deep neural model for music performance assessment using pitch contours as input"""
def __init__(self):
"""Initializes the PitchContourAssessor class with internal parameters for the different layers"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PCConvLstmNet:
"""Class to implement a deep neural model for music performance assessment using pitch contours as input"""
def __init__(self):
"""Initializes the PitchContourAssessor class with internal parameters for the different layers"""
super(PCConvLstmNet, self).__init__()
s... | the_stack_v2_python_sparse | JointEmbedNet/model.py | biboamy/FBA-Fall19 | train | 8 |
b1ce921dea63c8dbb9ebbc5a2bb43e0112deb5b3 | [
"if hasattr(self, 'order'):\n order = self.order\n pivot, pvar = ((1,) + (0,) * (self.number_of_variables - 1), 0)\n for var in range(1, self.number_of_variables):\n vindex = (0,) * var + (1,) + (0,) * (self.number_of_variables - var - 1)\n if order.cmp(pivot, vindex) < 0:\n pivot,... | <|body_start_0|>
if hasattr(self, 'order'):
order = self.order
pivot, pvar = ((1,) + (0,) * (self.number_of_variables - 1), 0)
for var in range(1, self.number_of_variables):
vindex = (0,) * var + (1,) + (0,) * (self.number_of_variables - var - 1)
... | Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction. | NestProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestProvider:
"""Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction."""
def leading_variable(self):
"""Return the position of the leading variable (the leading term among all total degree one terms). The l... | stack_v2_sparse_classes_75kplus_train_004108 | 24,835 | no_license | [
{
"docstring": "Return the position of the leading variable (the leading term among all total degree one terms). The leading term varies with term orders, so does the result. The term order can be specified via the attribute 'order'.",
"name": "leading_variable",
"signature": "def leading_variable(self)... | 3 | stack_v2_sparse_classes_30k_train_019193 | Implement the Python class `NestProvider` described below.
Class description:
Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.
Method signatures and docstrings:
- def leading_variable(self): Return the position of the leading variable (... | Implement the Python class `NestProvider` described below.
Class description:
Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction.
Method signatures and docstrings:
- def leading_variable(self): Return the position of the leading variable (... | a48ae9efcf0d9ad1485c2e9863c948a7f1b20311 | <|skeleton|>
class NestProvider:
"""Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction."""
def leading_variable(self):
"""Return the position of the leading variable (the leading term among all total degree one terms). The l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NestProvider:
"""Provide nest/unnest pair to convert a multivar polynomial to a univar polynomial of polynomial coefficient and opposite direction."""
def leading_variable(self):
"""Return the position of the leading variable (the leading term among all total degree one terms). The leading term v... | the_stack_v2_python_sparse | nzmath/poly/multiutil.py | turkeydonkey/nzmath3 | train | 2 |
db3f4de5d4cf2f2f7474bc34484a3c92005518ac | [
"self.terminalToggle = False\nself.appPrintQueue = list()\nself.buffer_length = buffer_length\nreturn",
"msg = ''.join([str(arg) for arg in args])\nif self.terminalToggle == False:\n self.kernel.write(msg)\nelif len(self.appPrintQueue) < self.buffer_length:\n self.appPrintQueue.append(msg)\nelse:\n self.... | <|body_start_0|>
self.terminalToggle = False
self.appPrintQueue = list()
self.buffer_length = buffer_length
return
<|end_body_0|>
<|body_start_1|>
msg = ''.join([str(arg) for arg in args])
if self.terminalToggle == False:
self.kernel.write(msg)
elif l... | @class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a circular buffer. | SmallIO | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmallIO:
"""@class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a circular buffer."""
def __init__(se... | stack_v2_sparse_classes_75kplus_train_004109 | 2,204 | no_license | [
{
"docstring": "@fucntion __init__() - sets up the terminal toggle and printqueuing veriables.",
"name": "__init__",
"signature": "def __init__(self, buffer_length)"
},
{
"docstring": "@function print() - Prints output to terminal for application display. @param *args - takes in arguments, does ... | 4 | stack_v2_sparse_classes_30k_train_047906 | Implement the Python class `SmallIO` described below.
Class description:
@class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a c... | Implement the Python class `SmallIO` described below.
Class description:
@class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a c... | 5eb78da1a132eafccb0e18511de999a98ecad3f7 | <|skeleton|>
class SmallIO:
"""@class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a circular buffer."""
def __init__(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmallIO:
"""@class smallIO() - controls print Input-Output ***NOTE*** This will probably be moved into the kernal class as a variable. And will most likley be piped into the different processes on a terminal selection basis. TODO: Turn appPrintQueue into a circular buffer."""
def __init__(self, buffer_le... | the_stack_v2_python_sparse | SmallPackage/SmallIO.py | MikiEEE/SmallOS | train | 0 |
01fc727ce3a3df69c8fed9a881f02ea833319c7f | [
"x, y, theta = start_pose\nif curvature == 0.0:\n x += length * cos(theta)\n y += length * sin(theta)\n return (x, y, theta)\nelse:\n tx = cos(theta)\n ty = sin(theta)\n radius = 1.0 / curvature\n xc = x - radius * ty\n yc = y + radius * tx\n angle = length / radius\n cosa = cos(angle)... | <|body_start_0|>
x, y, theta = start_pose
if curvature == 0.0:
x += length * cos(theta)
y += length * sin(theta)
return (x, y, theta)
else:
tx = cos(theta)
ty = sin(theta)
radius = 1.0 / curvature
xc = x - radius... | CurveSegment | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurveSegment:
def end_pose(start_pose, curvature, length):
"""Returns end pose, given start pose, curvature and length."""
<|body_0|>
def segment_points(start_pose, curvature, length, delta_length):
"""Return points of segment, at delta_length intervals."""
<... | stack_v2_sparse_classes_75kplus_train_004110 | 1,212 | permissive | [
{
"docstring": "Returns end pose, given start pose, curvature and length.",
"name": "end_pose",
"signature": "def end_pose(start_pose, curvature, length)"
},
{
"docstring": "Return points of segment, at delta_length intervals.",
"name": "segment_points",
"signature": "def segment_points(... | 2 | stack_v2_sparse_classes_30k_test_002441 | Implement the Python class `CurveSegment` described below.
Class description:
Implement the CurveSegment class.
Method signatures and docstrings:
- def end_pose(start_pose, curvature, length): Returns end pose, given start pose, curvature and length.
- def segment_points(start_pose, curvature, length, delta_length): ... | Implement the Python class `CurveSegment` described below.
Class description:
Implement the CurveSegment class.
Method signatures and docstrings:
- def end_pose(start_pose, curvature, length): Returns end pose, given start pose, curvature and length.
- def segment_points(start_pose, curvature, length, delta_length): ... | 3d7d3c06cc577445a9b5b423f2907f5efa830a0f | <|skeleton|>
class CurveSegment:
def end_pose(start_pose, curvature, length):
"""Returns end pose, given start pose, curvature and length."""
<|body_0|>
def segment_points(start_pose, curvature, length, delta_length):
"""Return points of segment, at delta_length intervals."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurveSegment:
def end_pose(start_pose, curvature, length):
"""Returns end pose, given start pose, curvature and length."""
x, y, theta = start_pose
if curvature == 0.0:
x += length * cos(theta)
y += length * sin(theta)
return (x, y, theta)
el... | the_stack_v2_python_sparse | planning_python/utils/CurveSegment.py | yonetaniryo/planning_python | train | 0 | |
51531e0f4022e8f1be1dd60777de8f5a591476b1 | [
"statement = 'procedure func (param1, param2) a <- 3 endproc'\nself.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')\nself.assertEqual(ycc.parse_ps2py(statement).get('result'), 'def func (param1,param2):\\n\\ta = 3')",
"statement = 'procedure func (param1) a <- 3 return endproc'\nself.assertEqual(ycc.par... | <|body_start_0|>
statement = 'procedure func (param1, param2) a <- 3 endproc'
self.assertEqual(ycc.parse_ps2py(statement).get('errors'), '')
self.assertEqual(ycc.parse_ps2py(statement).get('result'), 'def func (param1,param2):\n\ta = 3')
<|end_body_0|>
<|body_start_1|>
statement = 'proc... | Class for testing procedures. | TestProcs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProcs:
"""Class for testing procedures."""
def test_noReturn(self):
"""Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance"""
<|body_0|>
def test_withReturn(self):
"""Tests procedures with return statement(s). Keyword ... | stack_v2_sparse_classes_75kplus_train_004111 | 9,275 | no_license | [
{
"docstring": "Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance",
"name": "test_noReturn",
"signature": "def test_noReturn(self)"
},
{
"docstring": "Tests procedures with return statement(s). Keyword arguments: self -- the TestProcs instance",
"na... | 3 | stack_v2_sparse_classes_30k_train_014155 | Implement the Python class `TestProcs` described below.
Class description:
Class for testing procedures.
Method signatures and docstrings:
- def test_noReturn(self): Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance
- def test_withReturn(self): Tests procedures with return s... | Implement the Python class `TestProcs` described below.
Class description:
Class for testing procedures.
Method signatures and docstrings:
- def test_noReturn(self): Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance
- def test_withReturn(self): Tests procedures with return s... | 2c0b907f5d9e74265e87ab3e36753f764a965f21 | <|skeleton|>
class TestProcs:
"""Class for testing procedures."""
def test_noReturn(self):
"""Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance"""
<|body_0|>
def test_withReturn(self):
"""Tests procedures with return statement(s). Keyword ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProcs:
"""Class for testing procedures."""
def test_noReturn(self):
"""Tests procedures without return statement. Keyword arguments: self -- the TestProcs instance"""
statement = 'procedure func (param1, param2) a <- 3 endproc'
self.assertEqual(ycc.parse_ps2py(statement).get('... | the_stack_v2_python_sparse | AlgoBooster/ab_ui/ab_main/ab_unittests/parser_unittests.py | danielaboeing/algobooster | train | 0 |
f6cbc7185dc312d0d0442b61a7bb350016d42f82 | [
"canonicalTags = ORM().selectAll(self.tables['canonicalMetaTag'])\nres = []\nfor c in canonicalTags:\n trimname = removeCanon(c.name)\n res.append(trimname)\nreturn res",
"canonicalTags = ORM().selectAll(self.tables['canonicalMetaTag'])\nres = {}\nfor c in canonicalTags:\n trimname = removeCanon(c.name)\... | <|body_start_0|>
canonicalTags = ORM().selectAll(self.tables['canonicalMetaTag'])
res = []
for c in canonicalTags:
trimname = removeCanon(c.name)
res.append(trimname)
return res
<|end_body_0|>
<|body_start_1|>
canonicalTags = ORM().selectAll(self.tables['... | Topics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Topics:
def getCanonicalTagsList(self) -> json:
"""Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }"""
<|body_0|>
def getCanonicalTagsJSON(self) -> json:
"""Get all the canonical tags from DB and Retu... | stack_v2_sparse_classes_75kplus_train_004112 | 1,620 | no_license | [
{
"docstring": "Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }",
"name": "getCanonicalTagsList",
"signature": "def getCanonicalTagsList(self) -> json"
},
{
"docstring": "Get all the canonical tags from DB and Returns a json obj... | 2 | stack_v2_sparse_classes_30k_train_047114 | Implement the Python class `Topics` described below.
Class description:
Implement the Topics class.
Method signatures and docstrings:
- def getCanonicalTagsList(self) -> json: Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }
- def getCanonicalTagsJSON... | Implement the Python class `Topics` described below.
Class description:
Implement the Topics class.
Method signatures and docstrings:
- def getCanonicalTagsList(self) -> json: Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }
- def getCanonicalTagsJSON... | 2dfc387e86928816fb2fdc5e300991cb9c1a3a36 | <|skeleton|>
class Topics:
def getCanonicalTagsList(self) -> json:
"""Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }"""
<|body_0|>
def getCanonicalTagsJSON(self) -> json:
"""Get all the canonical tags from DB and Retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Topics:
def getCanonicalTagsList(self) -> json:
"""Get all the canonical tags from DB and Returns a json obj. Returns ------- JSON { ..., tagName:Default value, ... }"""
canonicalTags = ORM().selectAll(self.tables['canonicalMetaTag'])
res = []
for c in canonicalTags:
... | the_stack_v2_python_sparse | backend/ORM/Topics.py | MEC402/openpipe | train | 5 | |
a435e7f9e41df576c7d3988c7958dc4c57f699dc | [
"self.logger = logging.getLogger(__name__ + '.TokenizedSentences')\nself.logger.addHandler(logging.NullHandler())\nself.filename = self.full_filename(filename)",
"words = []\nwith codecs.open(self.filename, encoding='utf-8') as fid:\n for line in fid:\n words.extend(line.split())\nword_counts = Counter(... | <|body_start_0|>
self.logger = logging.getLogger(__name__ + '.TokenizedSentences')
self.logger.addHandler(logging.NullHandler())
self.filename = self.full_filename(filename)
<|end_body_0|>
<|body_start_1|>
words = []
with codecs.open(self.filename, encoding='utf-8') as fid:
... | Interface to tokenized sentences. | TokenizedSentences | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
<|body_0|>
def count_words(self):
... | stack_v2_sparse_classes_75kplus_train_004113 | 14,008 | permissive | [
{
"docstring": "Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.",
"name": "__init__",
"signature": "def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME)"
},
{
"docstring": "Count words. Returns ------- word_counts : dict Counts for ind... | 2 | stack_v2_sparse_classes_30k_train_031456 | Implement the Python class `TokenizedSentences` described below.
Class description:
Interface to tokenized sentences.
Method signatures and docstrings:
- def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME): Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.
-... | Implement the Python class `TokenizedSentences` described below.
Class description:
Interface to tokenized sentences.
Method signatures and docstrings:
- def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME): Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.
-... | d8d1c5e68aedf758aee1ba83da063f1e0952c21d | <|skeleton|>
class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
<|body_0|>
def count_words(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
self.logger = logging.getLogger(__name__ + '.TokenizedSenten... | the_stack_v2_python_sparse | dasem/fullmonty.py | eaksnes/dasem | train | 0 |
97c48ebc01c91ca0db786bc0fd5d132d3b63ecc4 | [
"Search.__init__(self)\nself.token = token\nself.serviceName = 'YouTube'",
"self.logger.info('Running YouTube search for query %s...', query)\nurl = 'https://www.googleapis.com/youtube/v3/search?q=%s&maxResults=%i&part=snippet&key=%s&relevanceLanguage=%s&type=video' % (query.replace(' ', '+'), maxresults, self.to... | <|body_start_0|>
Search.__init__(self)
self.token = token
self.serviceName = 'YouTube'
<|end_body_0|>
<|body_start_1|>
self.logger.info('Running YouTube search for query %s...', query)
url = 'https://www.googleapis.com/youtube/v3/search?q=%s&maxResults=%i&part=snippet&key=%s&rel... | YouTubeSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YouTubeSearch:
def __init__(self, token):
"""Create a new YouTubeSearch instance. token should be a valid YouTube Data API key."""
<|body_0|>
def search(self, query, maxresults=10, lang='en', **opt):
"""Searches YouTube for videos using the given query. Returns a dic... | stack_v2_sparse_classes_75kplus_train_004114 | 5,488 | no_license | [
{
"docstring": "Create a new YouTubeSearch instance. token should be a valid YouTube Data API key.",
"name": "__init__",
"signature": "def __init__(self, token)"
},
{
"docstring": "Searches YouTube for videos using the given query. Returns a dict of url: title pairs pointing to videos. If maxres... | 2 | stack_v2_sparse_classes_30k_train_045166 | Implement the Python class `YouTubeSearch` described below.
Class description:
Implement the YouTubeSearch class.
Method signatures and docstrings:
- def __init__(self, token): Create a new YouTubeSearch instance. token should be a valid YouTube Data API key.
- def search(self, query, maxresults=10, lang='en', **opt)... | Implement the Python class `YouTubeSearch` described below.
Class description:
Implement the YouTubeSearch class.
Method signatures and docstrings:
- def __init__(self, token): Create a new YouTubeSearch instance. token should be a valid YouTube Data API key.
- def search(self, query, maxresults=10, lang='en', **opt)... | 5fbff4606d50a114613edbb1f360aca070be9226 | <|skeleton|>
class YouTubeSearch:
def __init__(self, token):
"""Create a new YouTubeSearch instance. token should be a valid YouTube Data API key."""
<|body_0|>
def search(self, query, maxresults=10, lang='en', **opt):
"""Searches YouTube for videos using the given query. Returns a dic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YouTubeSearch:
def __init__(self, token):
"""Create a new YouTubeSearch instance. token should be a valid YouTube Data API key."""
Search.__init__(self)
self.token = token
self.serviceName = 'YouTube'
def search(self, query, maxresults=10, lang='en', **opt):
"""Sea... | the_stack_v2_python_sparse | ytsearch.py | fredi-68/Ram | train | 0 | |
c3fc53f60c479cddc019424f262a2bdea70b6115 | [
"request = self.request\nuser = request.user\nuser_groups = user.groups\npayload = request.validated\npayload['source'] = 'customer' if 'g:customers' in user_groups else 'briefy'\nproject = Project.get(payload.get('project_id'))\nadd_order_roles = project.add_order_roles\nif project.order_type.value == 'leadorder':... | <|body_start_0|>
request = self.request
user = request.user
user_groups = user.groups
payload = request.validated
payload['source'] = 'customer' if 'g:customers' in user_groups else 'briefy'
project = Project.get(payload.get('project_id'))
add_order_roles = projec... | Orders service. | OrderService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderService:
"""Orders service."""
def collection_post(self, model=None):
"""Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder."""
<|body_0|>
def filter_allowed_fields(self) -> list:
... | stack_v2_sparse_classes_75kplus_train_004115 | 6,695 | no_license | [
{
"docstring": "Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder.",
"name": "collection_post",
"signature": "def collection_post(self, model=None)"
},
{
"docstring": "List of fields allowed in filtering and sor... | 3 | null | Implement the Python class `OrderService` described below.
Class description:
Orders service.
Method signatures and docstrings:
- def collection_post(self, model=None): Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder.
- def filter_... | Implement the Python class `OrderService` described below.
Class description:
Orders service.
Method signatures and docstrings:
- def collection_post(self, model=None): Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder.
- def filter_... | e85c0ba0992bccb80878e89ec791ee64754646b0 | <|skeleton|>
class OrderService:
"""Orders service."""
def collection_post(self, model=None):
"""Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder."""
<|body_0|>
def filter_allowed_fields(self) -> list:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderService:
"""Orders service."""
def collection_post(self, model=None):
"""Add a new instance of LeadOrder or Order depending of Project.order_type. :returns: Newly created instance of model Order or LeadOrder."""
request = self.request
user = request.user
user_groups =... | the_stack_v2_python_sparse | src/briefy/leica/views/order.py | BriefyHQ/briefy.leica | train | 0 |
d56af17bbe242628cdd8603ffb3d5f7422890b7c | [
"super().__init__(parent)\nself._image = None\n'\\n QImage currently displayed.\\n '\nself.setAutoFillBackground(False)\nself.setAttribute(Qt.WA_NoSystemBackground, True)",
"height, width, byteValue = frame.shape\nbyteValue *= width\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nself._image = QIma... | <|body_start_0|>
super().__init__(parent)
self._image = None
'\n QImage currently displayed.\n '
self.setAutoFillBackground(False)
self.setAttribute(Qt.WA_NoSystemBackground, True)
<|end_body_0|>
<|body_start_1|>
height, width, byteValue = frame.shape
... | Implements the displayer of video frames used by the VideoWidget class. | VideoFrameWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoFrameWidget:
"""Implements the displayer of video frames used by the VideoWidget class."""
def __init__(self, parent=None):
"""Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None."""
<|body_0|>
def setFrame(self, frame):
... | stack_v2_sparse_classes_75kplus_train_004116 | 33,901 | permissive | [
{
"docstring": "Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Sets the image of the video frame to display. Parameters ---------- frame: numpy.ndarray OpenCV's i... | 3 | stack_v2_sparse_classes_30k_train_029764 | Implement the Python class `VideoFrameWidget` described below.
Class description:
Implements the displayer of video frames used by the VideoWidget class.
Method signatures and docstrings:
- def __init__(self, parent=None): Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None.
- ... | Implement the Python class `VideoFrameWidget` described below.
Class description:
Implements the displayer of video frames used by the VideoWidget class.
Method signatures and docstrings:
- def __init__(self, parent=None): Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None.
- ... | 3d3b04bcde5f72c95044caa637114368f9818979 | <|skeleton|>
class VideoFrameWidget:
"""Implements the displayer of video frames used by the VideoWidget class."""
def __init__(self, parent=None):
"""Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None."""
<|body_0|>
def setFrame(self, frame):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoFrameWidget:
"""Implements the displayer of video frames used by the VideoWidget class."""
def __init__(self, parent=None):
"""Class constructor. Parameters ---------- parent: QWidget Parent widget. The default is None."""
super().__init__(parent)
self._image = None
'... | the_stack_v2_python_sparse | fsdk/gui/viewer.py | luigivieira/fsdk | train | 0 |
5479b9f91c9160c693e6abb0a365136f97cb39be | [
"super().__init__(**kwargs)\nself._process = None\nself._hasToFinish = False\nself._lock = Lock()",
"self._lock.acquire()\nself._hasToFinish = True\nself._lock.release()",
"self._lock.acquire()\nt = self._hasToFinish\nself._lock.release()\nreturn t",
"st = False\nself._lock.acquire()\nif self._process is not ... | <|body_start_0|>
super().__init__(**kwargs)
self._process = None
self._hasToFinish = False
self._lock = Lock()
<|end_body_0|>
<|body_start_1|>
self._lock.acquire()
self._hasToFinish = True
self._lock.release()
<|end_body_1|>
<|body_start_2|>
self._lock.a... | Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well | ThreadWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadWrapper:
"""Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well"""
def __init__(self, **kwargs):
"""Constr... | stack_v2_sparse_classes_75kplus_train_004117 | 24,629 | permissive | [
{
"docstring": "Constructor for the class :param kwargs: All of the arguments supported by Thread",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Flags the thread for termination",
"name": "terminate",
"signature": "def terminate(self)"
},
{
"... | 6 | stack_v2_sparse_classes_30k_test_000186 | Implement the Python class `ThreadWrapper` described below.
Class description:
Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well
Method signatur... | Implement the Python class `ThreadWrapper` described below.
Class description:
Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well
Method signatur... | 787b3b060d6a431810c1a29279251cbe9292351b | <|skeleton|>
class ThreadWrapper:
"""Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well"""
def __init__(self, **kwargs):
"""Constr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadWrapper:
"""Wrapper class for Thread This class provides some facilities for the management of subprocesses spawned by threads: it allows for safe monitoring and termination by the main process, handling mutual exclusion issues as well"""
def __init__(self, **kwargs):
"""Constructor for the... | the_stack_v2_python_sparse | fault_injector/injection/thread_pool.py | igabriel85/fault_injector | train | 0 |
0fb6011eb45f9496926db800b39c7fe1c8da4f3d | [
"def build(left, right):\n while left < right:\n return\n middle = (left + right) // 2\n node = TreeNode(nums[middle])\n node.left = build(left, middle - 1)\n node.right = build(middle + 1, right)\n return node\nreturn build(0, len(nums) + 1)",
"if not nums:\n return None\nmiddle = len... | <|body_start_0|>
def build(left, right):
while left < right:
return
middle = (left + right) // 2
node = TreeNode(nums[middle])
node.left = build(left, middle - 1)
node.right = build(middle + 1, right)
return node
ret... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""Every step find middle and give recursive only indexes. R: O(n) S: O(n)"""
<|body_0|>
def sortedArrayToBST_array(self, nums: List[int]) -> Optional[TreeNode]:
"""Every step slice middle a... | stack_v2_sparse_classes_75kplus_train_004118 | 1,289 | permissive | [
{
"docstring": "Every step find middle and give recursive only indexes. R: O(n) S: O(n)",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]"
},
{
"docstring": "Every step slice middle and return array slice. R: O(nlgn) S: O(n)",
"name... | 2 | stack_v2_sparse_classes_30k_train_025713 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: Every step find middle and give recursive only indexes. R: O(n) S: O(n)
- def sortedArrayToBST_array(self, nums... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: Every step find middle and give recursive only indexes. R: O(n) S: O(n)
- def sortedArrayToBST_array(self, nums... | 3b9858f43ef6b7a2b5e565ef58406e4018edbf97 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""Every step find middle and give recursive only indexes. R: O(n) S: O(n)"""
<|body_0|>
def sortedArrayToBST_array(self, nums: List[int]) -> Optional[TreeNode]:
"""Every step slice middle a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""Every step find middle and give recursive only indexes. R: O(n) S: O(n)"""
def build(left, right):
while left < right:
return
middle = (left + right) // 2
node = ... | the_stack_v2_python_sparse | LeetCode/Python/108-Convert_Sorted_Array_to_Binary_Search_Tree.py | IsFilimonov/Interviews | train | 4 | |
3c4bcd1db49e7a36e359d12d9b9820c307f16058 | [
"additional_ex_weight = max(weigh - 1, 0)\nadditional_pkg_weight = max(weigh - 3, 0)\nif self.full_name == 'Москва':\n return {'price': 300, 'time_min': 0, 'time_max': 1}\nif self.full_name in SPECIAL_NAMES:\n return {'price': 300, 'time_min': 1, 'time_max': 2}\nex_price = (self.price_sd_ex_1kg if self.price_... | <|body_start_0|>
additional_ex_weight = max(weigh - 1, 0)
additional_pkg_weight = max(weigh - 3, 0)
if self.full_name == 'Москва':
return {'price': 300, 'time_min': 0, 'time_max': 1}
if self.full_name in SPECIAL_NAMES:
return {'price': 300, 'time_min': 1, 'time_ma... | Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка | SdekCityList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SdekCityList:
"""Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка"""
def get_delivery_data(self, weigh=1):
"""Получение данных по доставке курьером (склад-дверь)"""
<|body_0|>
def get_delivery_data_ss(self, weigh=1):
"""Полу... | stack_v2_sparse_classes_75kplus_train_004119 | 10,122 | no_license | [
{
"docstring": "Получение данных по доставке курьером (склад-дверь)",
"name": "get_delivery_data",
"signature": "def get_delivery_data(self, weigh=1)"
},
{
"docstring": "Получение данных по доставке по тарифу склад-дверь (для пунктов выдачи) - тоже самое что и get_delivery_data",
"name": "ge... | 2 | stack_v2_sparse_classes_30k_train_006498 | Implement the Python class `SdekCityList` described below.
Class description:
Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка
Method signatures and docstrings:
- def get_delivery_data(self, weigh=1): Получение данных по доставке курьером (склад-дверь)
- def get_delivery_data_ss... | Implement the Python class `SdekCityList` described below.
Class description:
Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка
Method signatures and docstrings:
- def get_delivery_data(self, weigh=1): Получение данных по доставке курьером (склад-дверь)
- def get_delivery_data_ss... | b9ca72aef1db01262675274c83a5c5dff4d6e2da | <|skeleton|>
class SdekCityList:
"""Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка"""
def get_delivery_data(self, weigh=1):
"""Получение данных по доставке курьером (склад-дверь)"""
<|body_0|>
def get_delivery_data_ss(self, weigh=1):
"""Полу... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SdekCityList:
"""Список городов сдека ss - склад склад sd - склад дверь ex - express light pkg - посылка"""
def get_delivery_data(self, weigh=1):
"""Получение данных по доставке курьером (склад-дверь)"""
additional_ex_weight = max(weigh - 1, 0)
additional_pkg_weight = max(weigh - ... | the_stack_v2_python_sparse | geo/backend/delivery/models.py | Hagen013/presidentwatches | train | 0 |
759a6025baa3a1cb524d87a5db47a890e3c720a4 | [
"if self.patient != None:\n return 'Appointment with Dr.' + self.doctor.user.last_name + ' and ' + self.patient.user.first_name + ' ' + self.patient.user.last_name\nelse:\n return 'Appointment with Dr.' + self.doctor.user.last_name",
"doctor = self\nresult = [True, 'no message']\nif datetime.datetime.combin... | <|body_start_0|>
if self.patient != None:
return 'Appointment with Dr.' + self.doctor.user.last_name + ' and ' + self.patient.user.first_name + ' ' + self.patient.user.last_name
else:
return 'Appointment with Dr.' + self.doctor.user.last_name
<|end_body_0|>
<|body_start_1|>
... | Appointment model | Appointment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Appointment:
"""Appointment model"""
def __str__(self):
"""Tostring for Appointment :return: appointment description"""
<|body_0|>
def conflict_checker(self, hospital, date, start_time, end_time, old_appointment):
"""Determines whether there is a scheduling confl... | stack_v2_sparse_classes_75kplus_train_004120 | 4,653 | no_license | [
{
"docstring": "Tostring for Appointment :return: appointment description",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Determines whether there is a scheduling conflict :param hospital: specific hospital :param date: specific date :param start_time: specific starting ... | 3 | stack_v2_sparse_classes_30k_train_031748 | Implement the Python class `Appointment` described below.
Class description:
Appointment model
Method signatures and docstrings:
- def __str__(self): Tostring for Appointment :return: appointment description
- def conflict_checker(self, hospital, date, start_time, end_time, old_appointment): Determines whether there ... | Implement the Python class `Appointment` described below.
Class description:
Appointment model
Method signatures and docstrings:
- def __str__(self): Tostring for Appointment :return: appointment description
- def conflict_checker(self, hospital, date, start_time, end_time, old_appointment): Determines whether there ... | 20b446da14ee3b44f9e184c4be48e23805fb5f10 | <|skeleton|>
class Appointment:
"""Appointment model"""
def __str__(self):
"""Tostring for Appointment :return: appointment description"""
<|body_0|>
def conflict_checker(self, hospital, date, start_time, end_time, old_appointment):
"""Determines whether there is a scheduling confl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Appointment:
"""Appointment model"""
def __str__(self):
"""Tostring for Appointment :return: appointment description"""
if self.patient != None:
return 'Appointment with Dr.' + self.doctor.user.last_name + ' and ' + self.patient.user.first_name + ' ' + self.patient.user.last_n... | the_stack_v2_python_sparse | HealthApps/models/Appointment.py | KevKode/HealthNet | train | 0 |
6e231af04127fe9499dbd10a528213a6aa812492 | [
"self.n = n\nself.k = math.ceil(math.log(2.0 / eps))\nself.d = int((math.pow(2, self.k + 1) + 1) * math.pow(math.pow(2, self.k) + 1, n - 1))",
"f = self._compute_f(c.item(0))\nu = np.random.randint(1, self.d + 1, size=n_samples)\nz = np.empty(n_samples)\nfor idx in reversed(range(0, self.n + 1)):\n z[f[idx] >=... | <|body_start_0|>
self.n = n
self.k = math.ceil(math.log(2.0 / eps))
self.d = int((math.pow(2, self.k + 1) + 1) * math.pow(math.pow(2, self.k) + 1, n - 1))
<|end_body_0|>
<|body_start_1|>
f = self._compute_f(c.item(0))
u = np.random.randint(1, self.d + 1, size=n_samples)
... | Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP | TruncatedGeometricMechanism | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TruncatedGeometricMechanism:
"""Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP"""
def __init__(self, eps: float=0.1, ... | stack_v2_sparse_classes_75kplus_train_004121 | 2,380 | permissive | [
{
"docstring": "Args: eps: epsilon n: number of individuals subject to counting query Note: Choosing eps too small or n too large may lead to integer overflow and failure of the mechanism",
"name": "__init__",
"signature": "def __init__(self, eps: float=0.1, n: int=5)"
},
{
"docstring": "Args: c... | 3 | stack_v2_sparse_classes_30k_train_020168 | Implement the Python class `TruncatedGeometricMechanism` described below.
Class description:
Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP
Met... | Implement the Python class `TruncatedGeometricMechanism` described below.
Class description:
Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP
Met... | ee087b2584ca97d1064154db5dd2bda0bb5a8ceb | <|skeleton|>
class TruncatedGeometricMechanism:
"""Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP"""
def __init__(self, eps: float=0.1, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TruncatedGeometricMechanism:
"""Alg. 4.8 "GeoSample" from: V. Balcer and S. Vadhan. 2018. Differential Privacy on Finite Computers arXiv:1709.05396 [cs.DS] According to Thm 4.7 in the above publication, GeoSample(eps, n) is ln(1 + 2^-ceil(ln(2/eps)))-DP"""
def __init__(self, eps: float=0.1, n: int=5):
... | the_stack_v2_python_sparse | dpsniper/mechanisms/geometric.py | zhangzhizheng/dp-sniper | train | 0 |
ece7743102fafd16e9584b70b80324261574c23d | [
"fig = Figure(figsize=(width, height), dpi=dpi)\nself.axes = fig.add_subplot(111)\nFigureCanvas.__init__(self, fig)\nself.setParent(parent)\nFigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\nFigureCanvas.updateGeometry(self)\nself.linePlot()",
"self.axes.cla()\nax = self.figure.add_s... | <|body_start_0|>
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
... | This class is used by MatplotIntegrationExample ,and here matplot figures are plotted. | PlotCanvas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotCanvas:
"""This class is used by MatplotIntegrationExample ,and here matplot figures are plotted."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
"""constructor :param parent: QWidget instance :param width: int :param height: int :param dpi: int"""
<|body_... | stack_v2_sparse_classes_75kplus_train_004122 | 8,168 | no_license | [
{
"docstring": "constructor :param parent: QWidget instance :param width: int :param height: int :param dpi: int",
"name": "__init__",
"signature": "def __init__(self, parent=None, width=5, height=4, dpi=100)"
},
{
"docstring": "plots matplot line :return:",
"name": "linePlot",
"signatur... | 5 | null | Implement the Python class `PlotCanvas` described below.
Class description:
This class is used by MatplotIntegrationExample ,and here matplot figures are plotted.
Method signatures and docstrings:
- def __init__(self, parent=None, width=5, height=4, dpi=100): constructor :param parent: QWidget instance :param width: ... | Implement the Python class `PlotCanvas` described below.
Class description:
This class is used by MatplotIntegrationExample ,and here matplot figures are plotted.
Method signatures and docstrings:
- def __init__(self, parent=None, width=5, height=4, dpi=100): constructor :param parent: QWidget instance :param width: ... | a30389aa4542a23011a955ac61bf5b853c3e7854 | <|skeleton|>
class PlotCanvas:
"""This class is used by MatplotIntegrationExample ,and here matplot figures are plotted."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
"""constructor :param parent: QWidget instance :param width: int :param height: int :param dpi: int"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotCanvas:
"""This class is used by MatplotIntegrationExample ,and here matplot figures are plotted."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
"""constructor :param parent: QWidget instance :param width: int :param height: int :param dpi: int"""
fig = Figure(figsize... | the_stack_v2_python_sparse | others/MatplotIntegrationExample.py | edutilos6666/PythonSciStudentProject | train | 0 |
d8c935d69c0e96a1ff5f5b4b86cf36c59801714f | [
"super().__init__()\nself.user32 = ctypes.WinDLL('user32')\nself.gdi32 = ctypes.WinDLL('gdi32')\nself._set_cfunctions()\nself._set_dpi_awareness()\nself._bbox = {'height': 0, 'width': 0}\nself._data = ctypes.create_string_buffer(0)\nsrcdc = self._get_srcdc()\nif not MSS.memdc:\n MSS.memdc = self.gdi32.CreateComp... | <|body_start_0|>
super().__init__()
self.user32 = ctypes.WinDLL('user32')
self.gdi32 = ctypes.WinDLL('gdi32')
self._set_cfunctions()
self._set_dpi_awareness()
self._bbox = {'height': 0, 'width': 0}
self._data = ctypes.create_string_buffer(0)
srcdc = self._... | Multiple ScreenShots implementation for Microsoft Windows. | MSS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
<|body_0|>
def _set_cfunctions(self):
"""Set all ctypes functions and attach them to attributes."""
<|body_1|>
def _set_dpi_... | stack_v2_sparse_classes_75kplus_train_004123 | 9,348 | permissive | [
{
"docstring": "Windows initialisations.",
"name": "__init__",
"signature": "def __init__(self, **_)"
},
{
"docstring": "Set all ctypes functions and attach them to attributes.",
"name": "_set_cfunctions",
"signature": "def _set_cfunctions(self)"
},
{
"docstring": "Set DPI aware ... | 6 | stack_v2_sparse_classes_30k_train_006052 | Implement the Python class `MSS` described below.
Class description:
Multiple ScreenShots implementation for Microsoft Windows.
Method signatures and docstrings:
- def __init__(self, **_): Windows initialisations.
- def _set_cfunctions(self): Set all ctypes functions and attach them to attributes.
- def _set_dpi_awar... | Implement the Python class `MSS` described below.
Class description:
Multiple ScreenShots implementation for Microsoft Windows.
Method signatures and docstrings:
- def __init__(self, **_): Windows initialisations.
- def _set_cfunctions(self): Set all ctypes functions and attach them to attributes.
- def _set_dpi_awar... | a64ad181b5087f0f0d6d246be0a722015cf447d0 | <|skeleton|>
class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
<|body_0|>
def _set_cfunctions(self):
"""Set all ctypes functions and attach them to attributes."""
<|body_1|>
def _set_dpi_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
super().__init__()
self.user32 = ctypes.WinDLL('user32')
self.gdi32 = ctypes.WinDLL('gdi32')
self._set_cfunctions()
self._set_dpi_a... | the_stack_v2_python_sparse | venv/Lib/site-packages/mss/windows.py | Ramen-Shaman/Reco-PC-Server | train | 0 |
60a6bc4edc2623c992baddf2529b7324c1a8bf47 | [
"def dfs(root):\n if not root:\n return\n res.append(str(root.val) + ',')\n dfs(root.left)\n dfs(root.right)\nres = []\ndfs(root)\nreturn ''.join(res)",
"lst = data.split(',')\nlst.pop()\nstack = []\nhead = None\nfor n in lst:\n n = int(n)\n if not head:\n head = TreeNode(n)\n ... | <|body_start_0|>
def dfs(root):
if not root:
return
res.append(str(root.val) + ',')
dfs(root.left)
dfs(root.right)
res = []
dfs(root)
return ''.join(res)
<|end_body_0|>
<|body_start_1|>
lst = data.split(',')
... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(root)... | stack_v2_sparse_classes_75kplus_train_004124 | 1,478 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_031698 | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class ... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def dfs(root):
if not root:
return
res.append(str(root.val) + ',')
dfs(root.left)
dfs(root.right)
res = []
dfs(root)
... | the_stack_v2_python_sparse | Problems/0400_0499/0449_Serialize_and_Deserialize_BST/Project_Python3/TreeNode/Codec2.py | NobuyukiInoue/LeetCode | train | 0 | |
2094d4152b0808dc5f7127042985085730672c2a | [
"smach.State.__init__(self, outcomes=['done', 'timedout'])\nself._robot = robot\nself._vth = vth\nself._duration = duration\nself._timeout = timeout\nself._first_stamp = None",
"if self._first_stamp is None:\n self._first_stamp = rospy.Time.now()\nif (rospy.Time.now() - self._first_stamp).to_sec() > self._time... | <|body_start_0|>
smach.State.__init__(self, outcomes=['done', 'timedout'])
self._robot = robot
self._vth = vth
self._duration = duration
self._timeout = timeout
self._first_stamp = None
<|end_body_0|>
<|body_start_1|>
if self._first_stamp is None:
sel... | Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long | ForceRotate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForceRotate:
"""Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long"""
def __init__(self, robot, vth, duration, timeout):
"""Constructor :param robot: robot object :param vth: yaw... | stack_v2_sparse_classes_75kplus_train_004125 | 32,974 | no_license | [
{
"docstring": "Constructor :param robot: robot object :param vth: yaw-velocity :param duration: float indicating how long to drive :param timeout: after this, timedout is returned",
"name": "__init__",
"signature": "def __init__(self, robot, vth, duration, timeout)"
},
{
"docstring": "Executes ... | 2 | null | Implement the Python class `ForceRotate` described below.
Class description:
Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long
Method signatures and docstrings:
- def __init__(self, robot, vth, duration, timeout... | Implement the Python class `ForceRotate` described below.
Class description:
Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long
Method signatures and docstrings:
- def __init__(self, robot, vth, duration, timeout... | 092a354315b9b2c08e32cdc049791d82dfd47745 | <|skeleton|>
class ForceRotate:
"""Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long"""
def __init__(self, robot, vth, duration, timeout):
"""Constructor :param robot: robot object :param vth: yaw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForceRotate:
"""Force forth and back. If a timeout is exceeded, we won't do this anymore State is exited with - done: rotated back and forth - timedout: this takes too long"""
def __init__(self, robot, vth, duration, timeout):
"""Constructor :param robot: robot object :param vth: yaw-velocity :pa... | the_stack_v2_python_sparse | challenge_manipulation/src/manipulation.py | tue-robotics/tue_robocup | train | 39 |
07bd16ff43983102d114848fef0fb169aac07eb6 | [
"self.collection = mongo.db.ipassets\nif self.action == 'options':\n return self.options([{'$group': {'_id': 'options', 'source': {'$addToSet': '$source'}, 'region': {'$addToSet': '$source'}, 'status': {'$addToSet': '$source'}}}], {'source': [], 'region': [], 'status': []})\nparser.add_argument('time_range[]', t... | <|body_start_0|>
self.collection = mongo.db.ipassets
if self.action == 'options':
return self.options([{'$group': {'_id': 'options', 'source': {'$addToSet': '$source'}, 'region': {'$addToSet': '$source'}, 'status': {'$addToSet': '$source'}}}], {'source': [], 'region': [], 'status': []})
... | IPAssets | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPAssets:
def get(self):
"""" :return:"""
<|body_0|>
def post(self):
"""新建、更新 IP资产 :return:"""
<|body_1|>
def delete(self):
"""删除 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.collection = mongo.db.ipassets
... | stack_v2_sparse_classes_75kplus_train_004126 | 3,135 | permissive | [
{
"docstring": "\" :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新建、更新 IP资产 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "删除 :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_002633 | Implement the Python class `IPAssets` described below.
Class description:
Implement the IPAssets class.
Method signatures and docstrings:
- def get(self): " :return:
- def post(self): 新建、更新 IP资产 :return:
- def delete(self): 删除 :return: | Implement the Python class `IPAssets` described below.
Class description:
Implement the IPAssets class.
Method signatures and docstrings:
- def get(self): " :return:
- def post(self): 新建、更新 IP资产 :return:
- def delete(self): 删除 :return:
<|skeleton|>
class IPAssets:
def get(self):
"""" :return:"""
... | de6c7fa3ded6b936328e6fc678f2e6f7b098de39 | <|skeleton|>
class IPAssets:
def get(self):
"""" :return:"""
<|body_0|>
def post(self):
"""新建、更新 IP资产 :return:"""
<|body_1|>
def delete(self):
"""删除 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPAssets:
def get(self):
"""" :return:"""
self.collection = mongo.db.ipassets
if self.action == 'options':
return self.options([{'$group': {'_id': 'options', 'source': {'$addToSet': '$source'}, 'region': {'$addToSet': '$source'}, 'status': {'$addToSet': '$source'}}}], {'sou... | the_stack_v2_python_sparse | server/pmon/resource/ipassets.py | yolylight/PMon | train | 0 | |
e7f2bdf4ed29a2a57c82c75843a286abf2086bd4 | [
"send_mock = self.PatchObject(alerts.SmtpServer, 'Send')\nalerts.SendEmail('mail', 'root@localhost')\nself.assertEqual(send_mock.call_count, 1)",
"send_mock = self.PatchObject(alerts.GmailServer, 'Send')\nalerts.SendEmail('mail', 'root@localhost', server=alerts.GmailServer(token_cache_file='fakefile'))\nself.asse... | <|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmail('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
<|end_body_0|>
<|body_start_1|>
send_mock = self.PatchObject(alerts.GmailServer, 'Send')
alerts.SendEmail('mail', 'root@l... | Tests for SendEmail. | SendEmailTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')... | stack_v2_sparse_classes_75kplus_train_004127 | 6,312 | permissive | [
{
"docstring": "Smtp sanity check.",
"name": "testSmtp",
"signature": "def testSmtp(self)"
},
{
"docstring": "Gmail sanity check.",
"name": "testGmail",
"signature": "def testGmail(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023734 | Implement the Python class `SendEmailTest` described below.
Class description:
Tests for SendEmail.
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check. | Implement the Python class `SendEmailTest` described below.
Class description:
Tests for SendEmail.
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check.
<|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmail('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
def testGmail(self):
"""Gmail sa... | the_stack_v2_python_sparse | third_party/chromite/lib/alerts_unittest.py | metux/chromium-suckless | train | 5 |
4f269fa2b4643d3ed9ccf440409cc35c9d4788aa | [
"if not self.key.id():\n return\noriginal_alert = self.key.get(use_cache=False)\nif original_alert is None:\n return\nif not self.group:\n return\nif self.group.kind() != 'AlertGroup':\n self.group = None\n return\ngroup = self.group.get()\nif not group:\n return\nalert_class = self.__class__\nif ... | <|body_start_0|>
if not self.key.id():
return
original_alert = self.key.get(use_cache=False)
if original_alert is None:
return
if not self.group:
return
if self.group.kind() != 'AlertGroup':
self.group = None
return
... | General base class for alerts. | Alert | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Alert:
"""General base class for alerts."""
def _pre_put_hook(self):
"""Updates the alert's group."""
<|body_0|>
def _RemoveFromGroup(self, grouped_alerts):
"""Removes an alert from its group and updates the group's properties. Args: grouped_alerts: The list of a... | stack_v2_sparse_classes_75kplus_train_004128 | 6,488 | permissive | [
{
"docstring": "Updates the alert's group.",
"name": "_pre_put_hook",
"signature": "def _pre_put_hook(self)"
},
{
"docstring": "Removes an alert from its group and updates the group's properties. Args: grouped_alerts: The list of alerts in |group| used to calculate new revision range; none are m... | 3 | stack_v2_sparse_classes_30k_train_040506 | Implement the Python class `Alert` described below.
Class description:
General base class for alerts.
Method signatures and docstrings:
- def _pre_put_hook(self): Updates the alert's group.
- def _RemoveFromGroup(self, grouped_alerts): Removes an alert from its group and updates the group's properties. Args: grouped_... | Implement the Python class `Alert` described below.
Class description:
General base class for alerts.
Method signatures and docstrings:
- def _pre_put_hook(self): Updates the alert's group.
- def _RemoveFromGroup(self, grouped_alerts): Removes an alert from its group and updates the group's properties. Args: grouped_... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class Alert:
"""General base class for alerts."""
def _pre_put_hook(self):
"""Updates the alert's group."""
<|body_0|>
def _RemoveFromGroup(self, grouped_alerts):
"""Removes an alert from its group and updates the group's properties. Args: grouped_alerts: The list of a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Alert:
"""General base class for alerts."""
def _pre_put_hook(self):
"""Updates the alert's group."""
if not self.key.id():
return
original_alert = self.key.get(use_cache=False)
if original_alert is None:
return
if not self.group:
... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/models/alert.py | zenoalbisser/chromium | train | 0 |
b40537f5129f8c49c0d87ba73ee8d37125904444 | [
"self.events = events_queue\nself.prices = prices\nself.spread = spread\nself.execute_on = execute_on\nself.orders = []\nself.ticket = 0",
"if event.type == 'ORDER':\n if event.order_type == 'market':\n if self.execute_on == 'close':\n self.ticket += 1\n spread = self.spread if eve... | <|body_start_0|>
self.events = events_queue
self.prices = prices
self.spread = spread
self.execute_on = execute_on
self.orders = []
self.ticket = 0
<|end_body_0|>
<|body_start_1|>
if event.type == 'ORDER':
if event.order_type == 'market':
... | The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementation with a more sophisticated execution handler | SimulatedExecution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatedExecution:
"""The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementation with a more sophisticated execution ... | stack_v2_sparse_classes_75kplus_train_004129 | 7,146 | no_license | [
{
"docstring": "Initialises the handler. Parameters: events - The Queue of Event object. prices - The prices feed spread - Spread added to each trade, default:0 execute_on - Whether to execute on close or on next open. values('close' or 'open'), default:'close'",
"name": "__init__",
"signature": "def __... | 2 | null | Implement the Python class `SimulatedExecution` described below.
Class description:
The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementati... | Implement the Python class `SimulatedExecution` described below.
Class description:
The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementati... | 4ee2313528139cff36c43f112fc88e8a78769184 | <|skeleton|>
class SimulatedExecution:
"""The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementation with a more sophisticated execution ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulatedExecution:
"""The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency or fill-ratio issues. This allows a straightforward 'first-go' test of any strategy, before implementation with a more sophisticated execution handler"""
... | the_stack_v2_python_sparse | broker/execution_handler.py | JeromeMoreau/pyTrading2 | train | 0 |
ed48c783fbe2f6dad6e5fa15eaf7e71a08a55584 | [
"config_settings = {}\nif os.path.isfile(config_path):\n with open(config_path, 'r') as clam_config:\n yaml_config = yaml.load(clam_config)\n if yaml_config['ocav_ops_files']:\n config_settings['ocav_ops_files'] = yaml_config['ocav_ops_files']\n if yaml_config['ocav_s3_bucket']:\n... | <|body_start_0|>
config_settings = {}
if os.path.isfile(config_path):
with open(config_path, 'r') as clam_config:
yaml_config = yaml.load(clam_config)
if yaml_config['ocav_ops_files']:
config_settings['ocav_ops_files'] = yaml_config['ocav_o... | Class to upload clam config files and databases to an S3 bucket. | UpdateBucket | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateBucket:
"""Class to upload clam config files and databases to an S3 bucket."""
def get_config(config_path):
"""Open and read config data from the variables file."""
<|body_0|>
def upload_files(bucket, file_list, aws_creds_file, timestamp):
"""Use the provid... | stack_v2_sparse_classes_75kplus_train_004130 | 3,647 | permissive | [
{
"docstring": "Open and read config data from the variables file.",
"name": "get_config",
"signature": "def get_config(config_path)"
},
{
"docstring": "Use the provided credentials to upload files to the specified bucket. Raises: A ValueError if the specified bucket can not be found.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_013933 | Implement the Python class `UpdateBucket` described below.
Class description:
Class to upload clam config files and databases to an S3 bucket.
Method signatures and docstrings:
- def get_config(config_path): Open and read config data from the variables file.
- def upload_files(bucket, file_list, aws_creds_file, times... | Implement the Python class `UpdateBucket` described below.
Class description:
Class to upload clam config files and databases to an S3 bucket.
Method signatures and docstrings:
- def get_config(config_path): Open and read config data from the variables file.
- def upload_files(bucket, file_list, aws_creds_file, times... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class UpdateBucket:
"""Class to upload clam config files and databases to an S3 bucket."""
def get_config(config_path):
"""Open and read config data from the variables file."""
<|body_0|>
def upload_files(bucket, file_list, aws_creds_file, timestamp):
"""Use the provid... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateBucket:
"""Class to upload clam config files and databases to an S3 bucket."""
def get_config(config_path):
"""Open and read config data from the variables file."""
config_settings = {}
if os.path.isfile(config_path):
with open(config_path, 'r') as clam_config:
... | the_stack_v2_python_sparse | scripts/clam-update/push_clam_signatures.py | openshift/openshift-tools | train | 170 |
2790282b7dc23f93d24deb58022e094fd2c9cbfd | [
"super(DeployMachineAction, self).__init__(sitter)\nself.job = job\nself.name = '%s(%s, %s)' % (self.__class__.__name__, zone, job.name)\nself.stop = False\nself.zone = zone",
"if not self.job.deploy(self.zone):\n logger.error('%s: failed to deploy new machine' % self)\n return\nself.state.update_machine(se... | <|body_start_0|>
super(DeployMachineAction, self).__init__(sitter)
self.job = job
self.name = '%s(%s, %s)' % (self.__class__.__name__, zone, job.name)
self.stop = False
self.zone = zone
<|end_body_0|>
<|body_start_1|>
if not self.job.deploy(self.zone):
logger... | Deploy a master job to a new machine. | DeployMachineAction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployMachineAction:
"""Deploy a master job to a new machine."""
def __init__(self, sitter, zone, job):
"""Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job The job to deploy."""
<|body_0|>
def run(sel... | stack_v2_sparse_classes_75kplus_train_004131 | 15,057 | no_license | [
{
"docstring": "Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job The job to deploy.",
"name": "__init__",
"signature": "def __init__(self, sitter, zone, job)"
},
{
"docstring": "Run the action.",
"name": "run",
"signa... | 2 | null | Implement the Python class `DeployMachineAction` described below.
Class description:
Deploy a master job to a new machine.
Method signatures and docstrings:
- def __init__(self, sitter, zone, job): Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job ... | Implement the Python class `DeployMachineAction` described below.
Class description:
Deploy a master job to a new machine.
Method signatures and docstrings:
- def __init__(self, sitter, zone, job): Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job ... | 112c0459626a5e74367ff9fc512c04ea2226ea89 | <|skeleton|>
class DeployMachineAction:
"""Deploy a master job to a new machine."""
def __init__(self, sitter, zone, job):
"""Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job The job to deploy."""
<|body_0|>
def run(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeployMachineAction:
"""Deploy a master job to a new machine."""
def __init__(self, sitter, zone, job):
"""Initialize the action. @param sitter The cluster sitter object. @param zone The zone to deploy the tasks to. @param job The job to deploy."""
super(DeployMachineAction, self).__init_... | the_stack_v2_python_sparse | src/clustersitter/actions.py | ZachGoldberg/Cerebro | train | 4 |
2b33396f1c98803d3e79ba9a3b70b5831876f668 | [
"form = self.form_class()\ndata_category = queries.get_all_data_category(reverse=True)\npaginator = Paginator(data_category, 10)\npage_number = request.GET.get('page')\npage_obj = paginator.get_page(page_number)\nreturn render(request, 'data_manager_app/dataCategory.html', {'form': form, 'datas': page_obj})",
"ur... | <|body_start_0|>
form = self.form_class()
data_category = queries.get_all_data_category(reverse=True)
paginator = Paginator(data_category, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'data_manager_app/dataCat... | DataCategoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCategoryView:
def get(self, request):
"""get all data categories"""
<|body_0|>
def post(self, request):
"""add data category"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = self.form_class()
data_category = queries.get_all_data_ca... | stack_v2_sparse_classes_75kplus_train_004132 | 18,044 | no_license | [
{
"docstring": "get all data categories",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "add data category",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008594 | Implement the Python class `DataCategoryView` described below.
Class description:
Implement the DataCategoryView class.
Method signatures and docstrings:
- def get(self, request): get all data categories
- def post(self, request): add data category | Implement the Python class `DataCategoryView` described below.
Class description:
Implement the DataCategoryView class.
Method signatures and docstrings:
- def get(self, request): get all data categories
- def post(self, request): add data category
<|skeleton|>
class DataCategoryView:
def get(self, request):
... | 2dedee10bded628a0eaecacc4554b421cc6f0ddd | <|skeleton|>
class DataCategoryView:
def get(self, request):
"""get all data categories"""
<|body_0|>
def post(self, request):
"""add data category"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataCategoryView:
def get(self, request):
"""get all data categories"""
form = self.form_class()
data_category = queries.get_all_data_category(reverse=True)
paginator = Paginator(data_category, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_p... | the_stack_v2_python_sparse | data_model_manager_app/views/data_manager_views.py | SonThanhNguyen13/django_data_manager | train | 0 | |
3bb6316193371e75fe76a7becc79393c1ee79d8f | [
"super(TearDownBuilder, self).__init__()\nself.configfilename = configfilename\nself.storage = storage\nself.subdir = subdir\nself._configcopier = None\nself._logcopier = None\nself._teardown = None\nreturn",
"if self._configcopier is None:\n self._configcopier = copyfiles.CopyFiles((self.configfilename,), sel... | <|body_start_0|>
super(TearDownBuilder, self).__init__()
self.configfilename = configfilename
self.storage = storage
self.subdir = subdir
self._configcopier = None
self._logcopier = None
self._teardown = None
return
<|end_body_0|>
<|body_start_1|>
... | A basic tear-down builder that just copies log and config files. | TearDownBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TearDownBuilder:
"""A basic tear-down builder that just copies log and config files."""
def __init__(self, configfilename, storage, subdir='logs'):
""":param: - `configfilename`: the name of the config file to copy - `storage`: A storage object aimed at the data folder."""
<|... | stack_v2_sparse_classes_75kplus_train_004133 | 1,942 | permissive | [
{
"docstring": ":param: - `configfilename`: the name of the config file to copy - `storage`: A storage object aimed at the data folder.",
"name": "__init__",
"signature": "def __init__(self, configfilename, storage, subdir='logs')"
},
{
"docstring": ":return: A file copier aimed at the config fi... | 4 | null | Implement the Python class `TearDownBuilder` described below.
Class description:
A basic tear-down builder that just copies log and config files.
Method signatures and docstrings:
- def __init__(self, configfilename, storage, subdir='logs'): :param: - `configfilename`: the name of the config file to copy - `storage`:... | Implement the Python class `TearDownBuilder` described below.
Class description:
A basic tear-down builder that just copies log and config files.
Method signatures and docstrings:
- def __init__(self, configfilename, storage, subdir='logs'): :param: - `configfilename`: the name of the config file to copy - `storage`:... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class TearDownBuilder:
"""A basic tear-down builder that just copies log and config files."""
def __init__(self, configfilename, storage, subdir='logs'):
""":param: - `configfilename`: the name of the config file to copy - `storage`: A storage object aimed at the data folder."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TearDownBuilder:
"""A basic tear-down builder that just copies log and config files."""
def __init__(self, configfilename, storage, subdir='logs'):
""":param: - `configfilename`: the name of the config file to copy - `storage`: A storage object aimed at the data folder."""
super(TearDownB... | the_stack_v2_python_sparse | apetools/builders/subbuilders/teardownbuilder.py | russell-n/oldape | train | 0 |
fee9ebbf6d5f98f9d836a62e4b639a411861910e | [
"length = len(value)\nactual = ''\nfor x in range(0, length / 2):\n actual += value[length - 2 - 2 * x:length - 2 * x]\n x += 1\nintVal = Util.twosComp(actual)\nreturn intVal",
"firstVal = int(hex_value[:1], 16)\nif firstVal >= 8:\n bValue = bin(int(hex_value, 16))\n bValue = bValue[2:]\n newBinary... | <|body_start_0|>
length = len(value)
actual = ''
for x in range(0, length / 2):
actual += value[length - 2 - 2 * x:length - 2 * x]
x += 1
intVal = Util.twosComp(actual)
return intVal
<|end_body_0|>
<|body_start_1|>
firstVal = int(hex_value[:1], 16... | Util | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param val... | stack_v2_sparse_classes_75kplus_train_004134 | 2,436 | no_license | [
{
"docstring": "littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param value: :return:",
"name": "little_endian",... | 2 | stack_v2_sparse_classes_30k_train_048593 | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def little_endian(value): littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endi... | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def little_endian(value): littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endi... | e9edc06adbc3371c1453e0b23bdd098564f73d5e | <|skeleton|>
class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Util:
def little_endian(value):
"""littleEndian(value) receives: a parsed, hex data piece outputs: the decimal value of that data function: swaps byte by byte to convert little endian to big endian function: calls 2's compliment to convert to decimal returns: The integer value :param value: :return:""... | the_stack_v2_python_sparse | raspi-python/raspi/fc/util.py | raman-belsevr/labs | train | 0 | |
5f77c5318a4541c5e746d74d3fe1d3c2d656643a | [
"email_content, receivers_email = self.generate_report(task_id=task_id)\nlogger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))\nif receivers_email is not None and receivers_email.strip() != '':\n EmailUtils().send_mail_with_ssl(receivers_email, ... | <|body_start_0|>
email_content, receivers_email = self.generate_report(task_id=task_id)
logger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))
if receivers_email is not None and receivers_email.strip() != '':
EmailUti... | EmailObserver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
<|body_0|>
def generate_report(self, task_id):
"""生成邮件发送报告 :param cls: :param task_id: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email_content, receivers_email = self.gen... | stack_v2_sparse_classes_75kplus_train_004135 | 4,435 | permissive | [
{
"docstring": "发送邮件通知 :return:",
"name": "notify",
"signature": "def notify(self, task_id)"
},
{
"docstring": "生成邮件发送报告 :param cls: :param task_id: :return:",
"name": "generate_report",
"signature": "def generate_report(self, task_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021659 | Implement the Python class `EmailObserver` described below.
Class description:
Implement the EmailObserver class.
Method signatures and docstrings:
- def notify(self, task_id): 发送邮件通知 :return:
- def generate_report(self, task_id): 生成邮件发送报告 :param cls: :param task_id: :return: | Implement the Python class `EmailObserver` described below.
Class description:
Implement the EmailObserver class.
Method signatures and docstrings:
- def notify(self, task_id): 发送邮件通知 :return:
- def generate_report(self, task_id): 生成邮件发送报告 :param cls: :param task_id: :return:
<|skeleton|>
class EmailObserver:
d... | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | <|skeleton|>
class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
<|body_0|>
def generate_report(self, task_id):
"""生成邮件发送报告 :param cls: :param task_id: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailObserver:
def notify(self, task_id):
"""发送邮件通知 :return:"""
email_content, receivers_email = self.generate_report(task_id=task_id)
logger.info('task task_id:{} has been checked out, hunter will send result to email:{}'.format(task_id, receivers_email))
if receivers_email is... | the_stack_v2_python_sparse | HunterCelery/notice/email_observer.py | a1kaid/hunter | train | 0 | |
b234d8ae6f6e3e06a13d0b716613e1cebe997311 | [
"license_list = list()\nheaders = {'limit': str(page_size)}\nif active:\n headers['active'] = json.dumps(True)\nif all_pages:\n x_total_pages = 2\nelse:\n x_total_pages = page\nwhile page <= x_total_pages:\n headers['page'] = str(page)\n response = self.session.get(f'{self.api}/license?kind={kind.val... | <|body_start_0|>
license_list = list()
headers = {'limit': str(page_size)}
if active:
headers['active'] = json.dumps(True)
if all_pages:
x_total_pages = 2
else:
x_total_pages = page
while page <= x_total_pages:
headers['page... | Class dedicated to all "license" related endpoints | LicenseEndpoint | [
"MIT",
"GPL-1.0-or-later",
"GPL-1.0-only",
"LicenseRef-scancode-unknown-license-reference",
"JSON"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LicenseEndpoint:
"""Class dedicated to all "license" related endpoints"""
def list_licenses(self, active: bool=False, kind: LicenseType=LicenseType.ALL, page_size: int=100, page: int=1, all_pages: bool=False) -> Tuple[list[License], int]:
"""Get all license from the DB API Endpoint: ... | stack_v2_sparse_classes_75kplus_train_004136 | 7,363 | permissive | [
{
"docstring": "Get all license from the DB API Endpoint: GET /license :param active: list only active licenses (default: False) :param kind: list only licenses from type LicenseType (default: LicenseType.ALL) :param page_size: the maximum number of results per page (default: 100) :param page: the number of pag... | 4 | stack_v2_sparse_classes_30k_val_000426 | Implement the Python class `LicenseEndpoint` described below.
Class description:
Class dedicated to all "license" related endpoints
Method signatures and docstrings:
- def list_licenses(self, active: bool=False, kind: LicenseType=LicenseType.ALL, page_size: int=100, page: int=1, all_pages: bool=False) -> Tuple[list[L... | Implement the Python class `LicenseEndpoint` described below.
Class description:
Class dedicated to all "license" related endpoints
Method signatures and docstrings:
- def list_licenses(self, active: bool=False, kind: LicenseType=LicenseType.ALL, page_size: int=100, page: int=1, all_pages: bool=False) -> Tuple[list[L... | 16719d13fafd06bc9fdbeb5383ed0dc907ae5ef3 | <|skeleton|>
class LicenseEndpoint:
"""Class dedicated to all "license" related endpoints"""
def list_licenses(self, active: bool=False, kind: LicenseType=LicenseType.ALL, page_size: int=100, page: int=1, all_pages: bool=False) -> Tuple[list[License], int]:
"""Get all license from the DB API Endpoint: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LicenseEndpoint:
"""Class dedicated to all "license" related endpoints"""
def list_licenses(self, active: bool=False, kind: LicenseType=LicenseType.ALL, page_size: int=100, page: int=1, all_pages: bool=False) -> Tuple[list[License], int]:
"""Get all license from the DB API Endpoint: GET /license ... | the_stack_v2_python_sparse | fossology/license.py | fossology/fossology-python | train | 17 |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(DNN, self).__init__()\nself._dropout = dropout\nself.hidden_layers = [None for _ in range(10)]\nfor i in range(10):\n self.hidden_layers[i] = tf.keras.layers.Dense(100, activation='relu', use_bias=True, trainable=trainable, name='dense_{}'.format(i), kernel_initializer='he_normal')\nself.linear = tf.keras... | <|body_start_0|>
super(DNN, self).__init__()
self._dropout = dropout
self.hidden_layers = [None for _ in range(10)]
for i in range(10):
self.hidden_layers[i] = tf.keras.layers.Dense(100, activation='relu', use_bias=True, trainable=trainable, name='dense_{}'.format(i), kernel_... | Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer. | DNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameter... | stack_v2_sparse_classes_75kplus_train_004137 | 10,796 | permissive | [
{
"docstring": "Creates the DNN layers. Args: trainable: Whether the DNN parameters are trainable or not. dropout: Coefficient for dropout regularization.",
"name": "__init__",
"signature": "def __init__(self, trainable=True, dropout=0.15)"
},
{
"docstring": "Creates the output tensor given an i... | 2 | stack_v2_sparse_classes_30k_val_000659 | Implement the Python class `DNN` described below.
Class description:
Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer.
Method signatures and docstrings:
- def __init__(self, trainable=True, dropout=0.15): Creates t... | Implement the Python class `DNN` described below.
Class description:
Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer.
Method signatures and docstrings:
- def __init__(self, trainable=True, dropout=0.15): Creates t... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameters are trainab... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
4d3c99df3922cb7b43e3519b589fbfc8b92bb5c7 | [
"if self.step_type not in _STEP_TYPES:\n raise TypeError(f'Invalid step type {self.step_type}')\nmp_func = _STEP_TYPES[self.step_type]\naccessor = mp_func\nparams = self.params\nfunc_text = f'.{mp_func}({self._get_param_string()})'\nif self.step_type == 'pivot':\n _, func = _get_entity_and_pivot(self.entity, ... | <|body_start_0|>
if self.step_type not in _STEP_TYPES:
raise TypeError(f'Invalid step type {self.step_type}')
mp_func = _STEP_TYPES[self.step_type]
accessor = mp_func
params = self.params
func_text = f'.{mp_func}({self._get_param_string()})'
if self.step_type ... | Pivot pipeline step class. | PipelineStep | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters ... | stack_v2_sparse_classes_75kplus_train_004138 | 10,245 | permissive | [
{
"docstring": "Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters to be passed to the function text - the text representation of the accessor + params comment - optional com... | 2 | stack_v2_sparse_classes_30k_train_046871 | Implement the Python class `PipelineStep` described below.
Class description:
Pivot pipeline step class.
Method signatures and docstrings:
- def get_exec_step(self) -> PipelineExecStep: Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of th... | Implement the Python class `PipelineStep` described below.
Class description:
Pivot pipeline step class.
Method signatures and docstrings:
- def get_exec_step(self) -> PipelineExecStep: Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of th... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters to be passed ... | the_stack_v2_python_sparse | msticpy/datamodel/pivot_pipeline.py | RiskIQ/msticpy | train | 1 |
01895a4046eca661f203cbda16c54c73245d3930 | [
"self.sess = tf.Session(config=config)\nwith open(pbfile, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n self.sess.graph.as_default()\n tf.import_graph_def(graph_def, name='')\nself.sess.run(tf.global_variables_initializer())\nself.img = self.sess.graph.get_tensor_by_nam... | <|body_start_0|>
self.sess = tf.Session(config=config)
with open(pbfile, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
self.sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
self.sess.run(tf.global_variable... | Predictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
<|body_0|>
def __resize_image(self, image, short_edge_length=224, max_length=224):
"""resize image return: resized image"""
... | stack_v2_sparse_classes_75kplus_train_004139 | 1,721 | no_license | [
{
"docstring": "pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)",
"name": "__init__",
"signature": "def __init__(self, pbfile, config: tf.ConfigProto)"
},
{
"docstring": "resize image return: resized image",
"name": "__resize_image",
"signature": "def __resize_imag... | 3 | stack_v2_sparse_classes_30k_train_050749 | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, pbfile, config: tf.ConfigProto): pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)
- def __resize_image(self, image, short_edge_length=2... | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, pbfile, config: tf.ConfigProto): pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)
- def __resize_image(self, image, short_edge_length=2... | df392eabef563dcca47fc8389da079553a016650 | <|skeleton|>
class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
<|body_0|>
def __resize_image(self, image, short_edge_length=224, max_length=224):
"""resize image return: resized image"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
self.sess = tf.Session(config=config)
with open(pbfile, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.... | the_stack_v2_python_sparse | others/tf_1_15_0_materials/tf_1.15.0_workspace/tf_alexnet_test/tf_detect_pb.py | guoqiang0148666/person_caffe_mish | train | 0 | |
0117fb1d5c4b36387cd8969c751330e3ba00da98 | [
"self.min_sum = float('inf')\nself.subtree = TreeNode(None)\nself.helper(root)\nreturn self.subtree",
"if root is None:\n return 0\nsum = self.helper(root.left) + self.helper(root.right) + root.val\nif sum < self.min_sum:\n self.min_sum = sum\n self.subtree = root\nreturn sum"
] | <|body_start_0|>
self.min_sum = float('inf')
self.subtree = TreeNode(None)
self.helper(root)
return self.subtree
<|end_body_0|>
<|body_start_1|>
if root is None:
return 0
sum = self.helper(root.left) + self.helper(root.right) + root.val
if sum < self.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
<|b... | stack_v2_sparse_classes_75kplus_train_004140 | 1,786 | no_license | [
{
"docstring": "recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode",
"name": "minSubtree",
"signature": "def minSubtree(se... | 2 | stack_v2_sparse_classes_30k_train_032488 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubtree(self, root): recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum fo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubtree(self, root): recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum fo... | e1a4c1bc5d01b4e2ba51a5255deed6426557dcb0 | <|skeleton|>
class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
self.min_sum = fl... | the_stack_v2_python_sparse | src/minSumOfSubtree.py | xuetingandyang/leetcode | train | 3 | |
f51e1d097372a31ab33b82037a7d422a477cf4e6 | [
"device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)\nif device_class in (cover.CoverDeviceClass.GARAGE, cover.CoverDeviceClass.GATE):\n return [DisplayCategory.GARAGE_DOOR]\nif device_class == cover.CoverDeviceClass.DOOR:\n return [DisplayCategory.DOOR]\nif device_class in (cover.CoverDeviceClass.BL... | <|body_start_0|>
device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)
if device_class in (cover.CoverDeviceClass.GARAGE, cover.CoverDeviceClass.GATE):
return [DisplayCategory.GARAGE_DOOR]
if device_class == cover.CoverDeviceClass.DOOR:
return [DisplayCategory.DOOR... | Class to represent Cover capabilities. | CoverCapabilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoverCapabilities:
"""Class to represent Cover capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yield the support... | stack_v2_sparse_classes_75kplus_train_004141 | 35,310 | permissive | [
{
"docstring": "Return the display categories for this entity.",
"name": "default_display_categories",
"signature": "def default_display_categories(self) -> list[str]"
},
{
"docstring": "Yield the supported interfaces.",
"name": "interfaces",
"signature": "def interfaces(self) -> Generat... | 2 | stack_v2_sparse_classes_30k_train_029225 | Implement the Python class `CoverCapabilities` described below.
Class description:
Class to represent Cover capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str]: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapability, None, Non... | Implement the Python class `CoverCapabilities` described below.
Class description:
Class to represent Cover capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str]: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapability, None, Non... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class CoverCapabilities:
"""Class to represent Cover capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yield the support... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoverCapabilities:
"""Class to represent Cover capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)
if device_class in (cover.CoverDeviceClass.GARAGE, c... | the_stack_v2_python_sparse | homeassistant/components/alexa/entities.py | home-assistant/core | train | 35,501 |
9647767a21a6531ca37756e6771176083bea6573 | [
"zcmd = 'getVolume'\nzresp = None\ntry:\n zresp = aegir.zmq.prmessage(zcmd, None)\nexcept Exception as e:\n return ({'status': 'error', 'errors': [str(e)]}, 422)\nif 'status' not in zresp:\n return ({'status': 'error', 'errors': ['Malformed zmq message']}, 422)\nif zresp['status'] == 'error':\n return (... | <|body_start_0|>
zcmd = 'getVolume'
zresp = None
try:
zresp = aegir.zmq.prmessage(zcmd, None)
except Exception as e:
return ({'status': 'error', 'errors': [str(e)]}, 422)
if 'status' not in zresp:
return ({'status': 'error', 'errors': ['Malform... | This class allows the manipulation of the current Process' volume | BrewStateVolume | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrewStateVolume:
"""This class allows the manipulation of the current Process' volume"""
def get(self):
"""Retrieves and returns the current volume set"""
<|body_0|>
def post(self):
"""Sets a new volume"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004142 | 12,948 | permissive | [
{
"docstring": "Retrieves and returns the current volume set",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Sets a new volume",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048680 | Implement the Python class `BrewStateVolume` described below.
Class description:
This class allows the manipulation of the current Process' volume
Method signatures and docstrings:
- def get(self): Retrieves and returns the current volume set
- def post(self): Sets a new volume | Implement the Python class `BrewStateVolume` described below.
Class description:
This class allows the manipulation of the current Process' volume
Method signatures and docstrings:
- def get(self): Retrieves and returns the current volume set
- def post(self): Sets a new volume
<|skeleton|>
class BrewStateVolume:
... | 1275ca41bfe4a56347eb2531211df4c70933fb96 | <|skeleton|>
class BrewStateVolume:
"""This class allows the manipulation of the current Process' volume"""
def get(self):
"""Retrieves and returns the current volume set"""
<|body_0|>
def post(self):
"""Sets a new volume"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BrewStateVolume:
"""This class allows the manipulation of the current Process' volume"""
def get(self):
"""Retrieves and returns the current volume set"""
zcmd = 'getVolume'
zresp = None
try:
zresp = aegir.zmq.prmessage(zcmd, None)
except Exception as e... | the_stack_v2_python_sparse | aegir-api/lib/aegir/api/brewd.py | gczuczy/aegir | train | 0 |
ed1c7646e7c7881a3c1e54106d10b3a80bc28d18 | [
"sogouhao_search_consume = 0\ntry:\n for line in data:\n item = line[7].split(',')\n if len(item) >= 5:\n if item[5] == '108':\n sogouhao_search_consume += int(line[0])\nexcept IndexError as err:\n logging.error(err)\n sogouhao_search_consume = 0\nsogouhao_channel_co... | <|body_start_0|>
sogouhao_search_consume = 0
try:
for line in data:
item = line[7].split(',')
if len(item) >= 5:
if item[5] == '108':
sogouhao_search_consume += int(line[0])
except IndexError as err:
... | MonitorWSSogouHaoConsume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
<|body_0|>
def sogouhao_channel_back(cls, data):
"""搜狗号回流消耗"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sogouhao_search_consume = 0
try:
for lin... | stack_v2_sparse_classes_75kplus_train_004143 | 1,706 | no_license | [
{
"docstring": "搜狗号详情页消耗",
"name": "sogouhao_channel_search",
"signature": "def sogouhao_channel_search(cls, data)"
},
{
"docstring": "搜狗号回流消耗",
"name": "sogouhao_channel_back",
"signature": "def sogouhao_channel_back(cls, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047213 | Implement the Python class `MonitorWSSogouHaoConsume` described below.
Class description:
Implement the MonitorWSSogouHaoConsume class.
Method signatures and docstrings:
- def sogouhao_channel_search(cls, data): 搜狗号详情页消耗
- def sogouhao_channel_back(cls, data): 搜狗号回流消耗 | Implement the Python class `MonitorWSSogouHaoConsume` described below.
Class description:
Implement the MonitorWSSogouHaoConsume class.
Method signatures and docstrings:
- def sogouhao_channel_search(cls, data): 搜狗号详情页消耗
- def sogouhao_channel_back(cls, data): 搜狗号回流消耗
<|skeleton|>
class MonitorWSSogouHaoConsume:
... | a35ffc9fc869ac8cadb121c71daa0c977898f8d8 | <|skeleton|>
class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
<|body_0|>
def sogouhao_channel_back(cls, data):
"""搜狗号回流消耗"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
sogouhao_search_consume = 0
try:
for line in data:
item = line[7].split(',')
if len(item) >= 5:
if item[5] == '108':
... | the_stack_v2_python_sparse | monitor_consume/monitor_consume_sogouhao.py | talentrobinho/prometheus_monitor_script | train | 0 | |
946dd0055a89a64d57fe95ec40e98ae033b7be1c | [
"self.sequence = sequence\nself.init_rate = init_rate\nMRNA.MRNA.__init__(self, index=index, length=len(self.sequence), geneID=geneID, ribosomes=ribosomes)",
"if self.ribosomes:\n last_pos = max(self.ribosomes.keys())\n stopcodons = ['uga', 'uaa', 'uag']\n current_codon = self.sequence[last_pos:last_pos ... | <|body_start_0|>
self.sequence = sequence
self.init_rate = init_rate
MRNA.MRNA.__init__(self, index=index, length=len(self.sequence), geneID=geneID, ribosomes=ribosomes)
<|end_body_0|>
<|body_start_1|>
if self.ribosomes:
last_pos = max(self.ribosomes.keys())
stop... | mRNA_spec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mRNA_spec:
def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07):
"""initializes one mRNA molecule"""
<|body_0|>
def termination_condition(self):
"""returns True iff a ribosome hits a stop codon on the mRNA"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_004144 | 1,690 | no_license | [
{
"docstring": "initializes one mRNA molecule",
"name": "__init__",
"signature": "def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07)"
},
{
"docstring": "returns True iff a ribosome hits a stop codon on the mRNA",
"name": "termination_condition",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_032703 | Implement the Python class `mRNA_spec` described below.
Class description:
Implement the mRNA_spec class.
Method signatures and docstrings:
- def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07): initializes one mRNA molecule
- def termination_condition(self): returns True iff a ribosome hits ... | Implement the Python class `mRNA_spec` described below.
Class description:
Implement the mRNA_spec class.
Method signatures and docstrings:
- def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07): initializes one mRNA molecule
- def termination_condition(self): returns True iff a ribosome hits ... | 5068f1b980c5b4f76c750a45ebd456c315ac2d68 | <|skeleton|>
class mRNA_spec:
def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07):
"""initializes one mRNA molecule"""
<|body_0|>
def termination_condition(self):
"""returns True iff a ribosome hits a stop codon on the mRNA"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class mRNA_spec:
def __init__(self, index, sequence, geneID, ribosomes={}, init_rate=8.2e-07):
"""initializes one mRNA molecule"""
self.sequence = sequence
self.init_rate = init_rate
MRNA.MRNA.__init__(self, index=index, length=len(self.sequence), geneID=geneID, ribosomes=ribosomes)
... | the_stack_v2_python_sparse | translation/MRNA_specific.py | gittenberg/TRSL | train | 2 | |
9eee53666080595bf3d5754cff63751a2dc52e4d | [
"self.input_arr = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]\nself.output = 4\nreturn (self.input_arr, self.output)",
"input_arr, output = self.setUp()\noutput_method = minNumberOfJumps(input_arr)\nself.assertEqual(output, output_method)"
] | <|body_start_0|>
self.input_arr = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]
self.output = 4
return (self.input_arr, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, output = self.setUp()
output_method = minNumberOfJumps(input_arr)
self.assertEqual(output, output_method)
<... | Class with unittests for MinNumberOfJumps.py | test_MinNumberOfJumps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_MinNumberOfJumps:
"""Class with unittests for MinNumberOfJumps.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.input_... | stack_v2_sparse_classes_75kplus_train_004145 | 863 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if method works properly.",
"name": "test_user_input",
"signature": "def test_user_input(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024268 | Implement the Python class `test_MinNumberOfJumps` described below.
Class description:
Class with unittests for MinNumberOfJumps.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. | Implement the Python class `test_MinNumberOfJumps` described below.
Class description:
Class with unittests for MinNumberOfJumps.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly.
<|skeleton|>
class test_MinNumberOfJumps:
"""Class ... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_MinNumberOfJumps:
"""Class with unittests for MinNumberOfJumps.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_MinNumberOfJumps:
"""Class with unittests for MinNumberOfJumps.py"""
def setUp(self):
"""Sets up input."""
self.input_arr = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]
self.output = 4
return (self.input_arr, self.output)
def test_user_input(self):
"""Checks if meth... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/MinNumberOfJumps/test_MinNumberOfJumps.py | JakubKazimierski/PythonPortfolio | train | 9 |
2c77c09a7cea3a4946857fb628f336efd231c516 | [
"temp_file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)\nlogger.info('Successfully created a temporary file: %s', temp_file.name)\nreturn temp_file",
"try:\n os.unlink(file_path)\n logger.info('Successfully deleted the file: %s', file_path)\nexcept Exception as e:\n stack_trace = traceback.for... | <|body_start_0|>
temp_file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
logger.info('Successfully created a temporary file: %s', temp_file.name)
return temp_file
<|end_body_0|>
<|body_start_1|>
try:
os.unlink(file_path)
logger.info('Successfully delete... | A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system. | FileHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHelper:
"""A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system."""
def create_file(self):
"""Creates a named temporary file on local file system :rtype: str :return: Returns a file pa... | stack_v2_sparse_classes_75kplus_train_004146 | 1,158 | permissive | [
{
"docstring": "Creates a named temporary file on local file system :rtype: str :return: Returns a file path of temporary file",
"name": "create_file",
"signature": "def create_file(self)"
},
{
"docstring": "Deletes a file located on local file system :param file_path A file path for the file be... | 2 | stack_v2_sparse_classes_30k_train_046020 | Implement the Python class `FileHelper` described below.
Class description:
A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system.
Method signatures and docstrings:
- def create_file(self): Creates a named temporary file on... | Implement the Python class `FileHelper` described below.
Class description:
A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system.
Method signatures and docstrings:
- def create_file(self): Creates a named temporary file on... | 6983bb3032e526d58c322aaaf526dea95efdd167 | <|skeleton|>
class FileHelper:
"""A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system."""
def create_file(self):
"""Creates a named temporary file on local file system :rtype: str :return: Returns a file pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileHelper:
"""A helper class to work with local file system. The class methods offer methods to create a temporary files and delete the files on local file system."""
def create_file(self):
"""Creates a named temporary file on local file system :rtype: str :return: Returns a file path of tempora... | the_stack_v2_python_sparse | cosmos-db-migration-utility/src/migrator-app/helpers/file_helper.py | awslabs/amazon-documentdb-tools | train | 106 |
9b4722a7a44c872e1bcbed5105093aa574ac098e | [
"if np.any(periods < 0.01):\n raise ValueError('The periods must be greater or equal to 0.01s')\nif np.any(periods > 10):\n raise ValueError('The periods must be less or equal to 10s')\nnper = np.size(periods)\nrgi1 = RegularGridInterpolator((Tlist, Tlist), B1, method='linear')\nrgi2 = RegularGridInterpolator... | <|body_start_0|>
if np.any(periods < 0.01):
raise ValueError('The periods must be greater or equal to 0.01s')
if np.any(periods > 10):
raise ValueError('The periods must be less or equal to 10s')
nper = np.size(periods)
rgi1 = RegularGridInterpolator((Tlist, Tlist... | Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The function is strictly empirical, fitted over the range the range 0.01s <= t1, t2 <=... | LothBaker2013 | [
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"Python-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LothBaker2013:
"""Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The function is strictly empirical, fitted ov... | stack_v2_sparse_classes_75kplus_train_004147 | 6,916 | permissive | [
{
"docstring": "Create an instance of LB13. Args: periods (numpy.array): An array of periods that will be requested from the function. Values must be [0.01 -> 10.0], and must be sorted from smallest to largest. Returns: An instance of :class:`LothBaker2013`.",
"name": "__init__",
"signature": "def __ini... | 2 | null | Implement the Python class `LothBaker2013` described below.
Class description:
Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The fu... | Implement the Python class `LothBaker2013` described below.
Class description:
Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The fu... | 8094736e43cc8043044344116b064917d5560c5a | <|skeleton|>
class LothBaker2013:
"""Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The function is strictly empirical, fitted ov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LothBaker2013:
"""Created by Christophe Loth, 12/18/2012 Pythonized and vectorized by C. Bruce Worden, 3/15/2017 Updated with the erratum tables by C. Bruce Worden, 1/13/2021 Compute the spatial correlation of epsilons for the NGA ground motion models The function is strictly empirical, fitted over the range ... | the_stack_v2_python_sparse | shakelib/correlation/loth_baker_2013.py | GeoscienceAustralia/shakemap | train | 1 |
c5e91212ee3446b1bb55a8d3b29e33a3c58870e0 | [
"n = len(matrix)\nmatrix.reverse()\nprint(matrix)\nfor i in range(n):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])",
"print(matrix)\nN = len(matrix[0])\nfor x in range(0, int(N / 2)):\n for y in range(x, N - x - 1):\n temp = matrix[N - 1 - y][x]\n mat... | <|body_start_0|>
n = len(matrix)
matrix.reverse()
print(matrix)
for i in range(n):
for j in range(i):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
<|end_body_0|>
<|body_start_1|>
print(matrix)
N = len(matrix[0])
for x in r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_75kplus_train_004148 | 1,860 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 3 | stack_v2_sparse_classes_30k_train_029495 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List[... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
n = len(matrix)
matrix.reverse()
print(matrix)
for i in range(n):
for j in range(i):
matrix[i][j], ma... | the_stack_v2_python_sparse | PythonCode/src/0048_Rotate_Image.py | oneyuan/CodeforFun | train | 0 | |
829dd54892233d00e5c6af248b0fb5dd266110d3 | [
"filename = file_check.check_file(filename)\nkey = clazz._check_key(key)\nclazz.check_file_is_readable(filename)\nreturn linux_attr.has_key(filename, key)",
"filename = file_check.check_file(filename)\nkey = clazz._check_key(key)\nclazz.check_file_is_readable(filename)\nif not linux_attr.has_key(filename, key):\n... | <|body_start_0|>
filename = file_check.check_file(filename)
key = clazz._check_key(key)
clazz.check_file_is_readable(filename)
return linux_attr.has_key(filename, key)
<|end_body_0|>
<|body_start_1|>
filename = file_check.check_file(filename)
key = clazz._check_key(key)
... | _file_attributes_linux_attr_exe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
<|body_0|>
def get_bytes(clazz, filename, key):
"""Return the attribute value with key for filename."""
<|body_1|>
def set_bytes... | stack_v2_sparse_classes_75kplus_train_004149 | 2,330 | permissive | [
{
"docstring": "Return True if filename has an attributed with key.",
"name": "has_key",
"signature": "def has_key(clazz, filename, key)"
},
{
"docstring": "Return the attribute value with key for filename.",
"name": "get_bytes",
"signature": "def get_bytes(clazz, filename, key)"
},
... | 6 | stack_v2_sparse_classes_30k_train_034436 | Implement the Python class `_file_attributes_linux_attr_exe` described below.
Class description:
Implement the _file_attributes_linux_attr_exe class.
Method signatures and docstrings:
- def has_key(clazz, filename, key): Return True if filename has an attributed with key.
- def get_bytes(clazz, filename, key): Return... | Implement the Python class `_file_attributes_linux_attr_exe` described below.
Class description:
Implement the _file_attributes_linux_attr_exe class.
Method signatures and docstrings:
- def has_key(clazz, filename, key): Return True if filename has an attributed with key.
- def get_bytes(clazz, filename, key): Return... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
<|body_0|>
def get_bytes(clazz, filename, key):
"""Return the attribute value with key for filename."""
<|body_1|>
def set_bytes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _file_attributes_linux_attr_exe:
def has_key(clazz, filename, key):
"""Return True if filename has an attributed with key."""
filename = file_check.check_file(filename)
key = clazz._check_key(key)
clazz.check_file_is_readable(filename)
return linux_attr.has_key(filename... | the_stack_v2_python_sparse | lib/bes/fs/_detail/_file_attributes_linux_attr_exe.py | reconstruir/bes | train | 0 | |
fffedbd77503ae1f4297cd1388244a9b221949ab | [
"''' e.g. cause can be an exception or a string like \"file not found\"'''\n'cause can also have a xju_xn_readable_repr() method, in which case that'\n'will be used by xju_xn_readable_repr() below'\nself.cause = (cause, FileAndLine())\nself.context: List[Tuple[str, FileAndLine]] = []\npass",
"result = ''\nx = ''.... | <|body_start_0|>
''' e.g. cause can be an exception or a string like "file not found"'''
'cause can also have a xju_xn_readable_repr() method, in which case that'
'will be used by xju_xn_readable_repr() below'
self.cause = (cause, FileAndLine())
self.context: List[Tuple[str, File... | Capture cause and context. | Xn | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xn:
"""Capture cause and context."""
def __init__(self, cause: object) -> None:
"""cause is convertable to a string using str"""
<|body_0|>
def __str__(self) -> str:
"""programmer friendly format, each context and cause includes file and line, and intermediate st... | stack_v2_sparse_classes_75kplus_train_004150 | 7,232 | permissive | [
{
"docstring": "cause is convertable to a string using str",
"name": "__init__",
"signature": "def __init__(self, cause: object) -> None"
},
{
"docstring": "programmer friendly format, each context and cause includes file and line, and intermediate stack entries are included - see unit test belo... | 3 | stack_v2_sparse_classes_30k_train_017524 | Implement the Python class `Xn` described below.
Class description:
Capture cause and context.
Method signatures and docstrings:
- def __init__(self, cause: object) -> None: cause is convertable to a string using str
- def __str__(self) -> str: programmer friendly format, each context and cause includes file and line... | Implement the Python class `Xn` described below.
Class description:
Capture cause and context.
Method signatures and docstrings:
- def __init__(self, cause: object) -> None: cause is convertable to a string using str
- def __str__(self) -> str: programmer friendly format, each context and cause includes file and line... | 6ec484080222f27a33070fa3b65593645f94a575 | <|skeleton|>
class Xn:
"""Capture cause and context."""
def __init__(self, cause: object) -> None:
"""cause is convertable to a string using str"""
<|body_0|>
def __str__(self) -> str:
"""programmer friendly format, each context and cause includes file and line, and intermediate st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Xn:
"""Capture cause and context."""
def __init__(self, cause: object) -> None:
"""cause is convertable to a string using str"""
''' e.g. cause can be an exception or a string like "file not found"'''
'cause can also have a xju_xn_readable_repr() method, in which case that'
... | the_stack_v2_python_sparse | xju/xn.py | urnest/urnest | train | 1 |
be17f33a385e475578da2b69cab32d95a53e2098 | [
"def is_valid(idx, preorder):\n \"\"\"\"\"\"\n if preorder[idx] == Solution.NONE:\n return idx + 1\n else:\n after_left = is_valid(idx + 1, preorder)\n return is_valid(after_left, preorder)\nnodes = preorder.split(',')\ntry:\n return is_valid(0, nodes) == len(nodes)\nexcept IndexErr... | <|body_start_0|>
def is_valid(idx, preorder):
""""""
if preorder[idx] == Solution.NONE:
return idx + 1
else:
after_left = is_valid(idx + 1, preorder)
return is_valid(after_left, preorder)
nodes = preorder.split(',')
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidSerializationRec(self, preorder):
""":type preorder: str :rtype: bool"""
<|body_0|>
def isValidSerialization(self, preorder):
"""For a valid bianry tree, when you introduce a node, another two empty node is introduced, as empty left/right child, ... | stack_v2_sparse_classes_75kplus_train_004151 | 2,736 | no_license | [
{
"docstring": ":type preorder: str :rtype: bool",
"name": "isValidSerializationRec",
"signature": "def isValidSerializationRec(self, preorder)"
},
{
"docstring": "For a valid bianry tree, when you introduce a node, another two empty node is introduced, as empty left/right child, as well. That m... | 2 | stack_v2_sparse_classes_30k_train_030200 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSerializationRec(self, preorder): :type preorder: str :rtype: bool
- def isValidSerialization(self, preorder): For a valid bianry tree, when you introduce a node, anot... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSerializationRec(self, preorder): :type preorder: str :rtype: bool
- def isValidSerialization(self, preorder): For a valid bianry tree, when you introduce a node, anot... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def isValidSerializationRec(self, preorder):
""":type preorder: str :rtype: bool"""
<|body_0|>
def isValidSerialization(self, preorder):
"""For a valid bianry tree, when you introduce a node, another two empty node is introduced, as empty left/right child, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidSerializationRec(self, preorder):
""":type preorder: str :rtype: bool"""
def is_valid(idx, preorder):
""""""
if preorder[idx] == Solution.NONE:
return idx + 1
else:
after_left = is_valid(idx + 1, preorder)... | the_stack_v2_python_sparse | tree/leetcode_Verify_Preorder_Serialization_Of_A_Binary_Tree.py | monkeylyf/interviewjam | train | 59 | |
77b746b9e4c9476baeae6f71916a67c7136f0346 | [
"self.collection_summary = collection_summary\nself.collection_parent = collection_parent\nself.collection_item = collection_item",
"if dictionary is None:\n return None\ncollection_summary = awsecommerceservice.models.collection_summary.CollectionSummary.from_dictionary(dictionary.get('CollectionSummary')) if... | <|body_start_0|>
self.collection_summary = collection_summary
self.collection_parent = collection_parent
self.collection_item = collection_item
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
collection_summary = awsecommerceservice.models.collecti... | Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type description here. | Collection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type desc... | stack_v2_sparse_classes_75kplus_train_004152 | 2,741 | permissive | [
{
"docstring": "Constructor for the Collection class",
"name": "__init__",
"signature": "def __init__(self, collection_summary=None, collection_parent=None, collection_item=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary r... | 2 | stack_v2_sparse_classes_30k_train_025427 | Implement the Python class `Collection` described below.
Class description:
Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (l... | Implement the Python class `Collection` described below.
Class description:
Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (l... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type desc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type description here.... | the_stack_v2_python_sparse | awsecommerceservice/models/collection.py | nidaizamir/Test-PY | train | 0 |
3c3d9defc1454116d79fab1dda78c6a1bed68156 | [
"super().__init__()\nself.snr_dB = snr\nself.powers = powers",
"data, label, pos, file_name = sample\nsnr = 10.0 ** (self.snr_dB / 10.0)\nif self.powers is None:\n signal_power = data.flatten().var()\nelse:\n signal_power = self.powers[file_name]\nnoise_power = signal_power / snr\nnoise = np.random.randn(*d... | <|body_start_0|>
super().__init__()
self.snr_dB = snr
self.powers = powers
<|end_body_0|>
<|body_start_1|>
data, label, pos, file_name = sample
snr = 10.0 ** (self.snr_dB / 10.0)
if self.powers is None:
signal_power = data.flatten().var()
else:
... | Adds noise corresponding to a certain SNR ratio. | SNRTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SNRTransform:
"""Adds noise corresponding to a certain SNR ratio."""
def __init__(self, snr, powers: dict=None):
"""snr: desired SNR in dB"""
<|body_0|>
def __call__(self, sample):
"""x: np.ndarray: Signal to add noise to. Can be of any shape."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_004153 | 4,182 | no_license | [
{
"docstring": "snr: desired SNR in dB",
"name": "__init__",
"signature": "def __init__(self, snr, powers: dict=None)"
},
{
"docstring": "x: np.ndarray: Signal to add noise to. Can be of any shape.",
"name": "__call__",
"signature": "def __call__(self, sample)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001694 | Implement the Python class `SNRTransform` described below.
Class description:
Adds noise corresponding to a certain SNR ratio.
Method signatures and docstrings:
- def __init__(self, snr, powers: dict=None): snr: desired SNR in dB
- def __call__(self, sample): x: np.ndarray: Signal to add noise to. Can be of any shape... | Implement the Python class `SNRTransform` described below.
Class description:
Adds noise corresponding to a certain SNR ratio.
Method signatures and docstrings:
- def __init__(self, snr, powers: dict=None): snr: desired SNR in dB
- def __call__(self, sample): x: np.ndarray: Signal to add noise to. Can be of any shape... | 10fbe43b95c7dc474102c20fe74910ade51a5ae3 | <|skeleton|>
class SNRTransform:
"""Adds noise corresponding to a certain SNR ratio."""
def __init__(self, snr, powers: dict=None):
"""snr: desired SNR in dB"""
<|body_0|>
def __call__(self, sample):
"""x: np.ndarray: Signal to add noise to. Can be of any shape."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SNRTransform:
"""Adds noise corresponding to a certain SNR ratio."""
def __init__(self, snr, powers: dict=None):
"""snr: desired SNR in dB"""
super().__init__()
self.snr_dB = snr
self.powers = powers
def __call__(self, sample):
"""x: np.ndarray: Signal to add ... | the_stack_v2_python_sparse | transforms.py | zacholade/MRF-Project | train | 3 |
bbde5b9745d37f7bd9b24894b7f5d827f4312a85 | [
"from .valid_polls import ValidPoll\nif not hasattr(self, '_poll'):\n self._poll = None\nif self._poll is None:\n self._poll = ValidPoll.get(id=self.payload['poll_id'])\nreturn self._poll",
"if not hasattr(self, '_target_cs'):\n self._target_cs = None\nself._target_cs = self._target_cs or ChallengeSet.ge... | <|body_start_0|>
from .valid_polls import ValidPoll
if not hasattr(self, '_poll'):
self._poll = None
if self._poll is None:
self._poll = ValidPoll.get(id=self.payload['poll_id'])
return self._poll
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_tar... | This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field. | CBTesterJob | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBTesterJob:
"""This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field."""
def poll(self):
"""Get the poll that needs to be tested. :return: ValidPoll corr... | stack_v2_sparse_classes_75kplus_train_004154 | 17,092 | permissive | [
{
"docstring": "Get the poll that needs to be tested. :return: ValidPoll corresponding to this job.",
"name": "poll",
"signature": "def poll(self)"
},
{
"docstring": "Get the target CS to which this tester job belongs to. :return: ChallengeSet object",
"name": "target_cs",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_042029 | Implement the Python class `CBTesterJob` described below.
Class description:
This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field.
Method signatures and docstrings:
- def poll(self): Get ... | Implement the Python class `CBTesterJob` described below.
Class description:
This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field.
Method signatures and docstrings:
- def poll(self): Get ... | 7d6bcbd94ab5ab521c29309fe3c47a0f6005a5d3 | <|skeleton|>
class CBTesterJob:
"""This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field."""
def poll(self):
"""Get the poll that needs to be tested. :return: ValidPoll corr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CBTesterJob:
"""This represents a job for cb_tester. cb_tester requires a cs, patch_type and a poll as an input. Here, we receive the poll id, cs id and patch_type as a strings in the `payload` field."""
def poll(self):
"""Get the poll that needs to be tested. :return: ValidPoll corresponding to ... | the_stack_v2_python_sparse | farnsworth/models/job.py | nnamon/farnsworth | train | 0 |
4fb097419740566f4a32e5f3a1d862b02058fde9 | [
"self.INCREMENTAL_GROUP = 'incremental_tables'\nself.TRUNCATE_GROUP = 'truncate_tables'\nself.INCREMENTAL_COLUMN_TYPES = ['timestamp', 'date', 'datetime']",
"tables_data = {}\nlogger = injector.get('logger')\nfor table in tables_information['tables']:\n logger.debug('Generating configuration for table {table}'... | <|body_start_0|>
self.INCREMENTAL_GROUP = 'incremental_tables'
self.TRUNCATE_GROUP = 'truncate_tables'
self.INCREMENTAL_COLUMN_TYPES = ['timestamp', 'date', 'datetime']
<|end_body_0|>
<|body_start_1|>
tables_data = {}
logger = injector.get('logger')
for table in tables_i... | Generate the tables configuration | TablesConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TablesConfiguration:
"""Generate the tables configuration"""
def __init__(self):
"""Initialize the class"""
<|body_0|>
def generate_configuration(self, tables_information, injector):
"""Generate the basic configuration given all the tables information :param tabl... | stack_v2_sparse_classes_75kplus_train_004155 | 1,621 | permissive | [
{
"docstring": "Initialize the class",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generate the basic configuration given all the tables information :param tables_information: dict :param injector: Injector :return: dict",
"name": "generate_configuration",
"s... | 2 | stack_v2_sparse_classes_30k_train_005142 | Implement the Python class `TablesConfiguration` described below.
Class description:
Generate the tables configuration
Method signatures and docstrings:
- def __init__(self): Initialize the class
- def generate_configuration(self, tables_information, injector): Generate the basic configuration given all the tables in... | Implement the Python class `TablesConfiguration` described below.
Class description:
Generate the tables configuration
Method signatures and docstrings:
- def __init__(self): Initialize the class
- def generate_configuration(self, tables_information, injector): Generate the basic configuration given all the tables in... | d0e52277daff523eda63f5d3137b5a990413923d | <|skeleton|>
class TablesConfiguration:
"""Generate the tables configuration"""
def __init__(self):
"""Initialize the class"""
<|body_0|>
def generate_configuration(self, tables_information, injector):
"""Generate the basic configuration given all the tables information :param tabl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TablesConfiguration:
"""Generate the tables configuration"""
def __init__(self):
"""Initialize the class"""
self.INCREMENTAL_GROUP = 'incremental_tables'
self.TRUNCATE_GROUP = 'truncate_tables'
self.INCREMENTAL_COLUMN_TYPES = ['timestamp', 'date', 'datetime']
def gene... | the_stack_v2_python_sparse | src/slippinj/cli/scripts/tables_configuration/tables_configuration.py | cupid4/slippin-jimmy | train | 0 |
65d88785f79bd16f39bfc2dad2f2d76f92978334 | [
"super(PointerNet, self).__init__()\nself.embedding_dim = embedding_dim\nself.bidir = bidir\nself.encoder = Encoder(embedding_dim, hidden_dim, lstm_layers, dropout, bidir)\nself.decoder = Decoder(embedding_dim, hidden_dim)\nself.decoder_input0 = Parameter(torch.FloatTensor(embedding_dim), requires_grad=True)\nnn.in... | <|body_start_0|>
super(PointerNet, self).__init__()
self.embedding_dim = embedding_dim
self.bidir = bidir
self.encoder = Encoder(embedding_dim, hidden_dim, lstm_layers, dropout, bidir)
self.decoder = Decoder(embedding_dim, hidden_dim)
self.decoder_input0 = Parameter(torch... | Pointer-Net | PointerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointerNet:
"""Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, lstm_layers, dropout, bidir=False):
"""Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidden units :param int lstm_layers: Number of layers for LST... | stack_v2_sparse_classes_75kplus_train_004156 | 12,775 | no_license | [
{
"docstring": "Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidden units :param int lstm_layers: Number of layers for LSTMs :param float dropout: Float between 0-1 :param bool bidir: Bidirectional",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_006729 | Implement the Python class `PointerNet` described below.
Class description:
Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, lstm_layers, dropout, bidir=False): Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidd... | Implement the Python class `PointerNet` described below.
Class description:
Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, lstm_layers, dropout, bidir=False): Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidd... | 86a480b9196053cee9a3287e023dd12a13bb5df8 | <|skeleton|>
class PointerNet:
"""Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, lstm_layers, dropout, bidir=False):
"""Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidden units :param int lstm_layers: Number of layers for LST... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointerNet:
"""Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, lstm_layers, dropout, bidir=False):
"""Initiate Pointer-Net :param int embedding_dim: Number of embbeding channels :param int hidden_dim: Encoders hidden units :param int lstm_layers: Number of layers for LSTMs :param flo... | the_stack_v2_python_sparse | PointerNet.py | EleanorHYW/Rerank | train | 0 |
1cfce9e0c5e5f69a1e1a659548de04ba80ba7bcd | [
"super().__init__()\nself.data = data\nself.noise_map = noise_map",
"xvalues = np.arange(self.data.shape[0])\nmodel_data = instance.model_data_1d_via_xvalues_from(xvalues=xvalues)\nresidual_map = self.data - model_data\nchi_squared_map = (residual_map / self.noise_map) ** 2.0\nchi_squared = sum(chi_squared_map)\n... | <|body_start_0|>
super().__init__()
self.data = data
self.noise_map = noise_map
<|end_body_0|>
<|body_start_1|>
xvalues = np.arange(self.data.shape[0])
model_data = instance.model_data_1d_via_xvalues_from(xvalues=xvalues)
residual_map = self.data - model_data
chi... | Analysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analysis:
def __init__(self, data: np.ndarray, noise_map: np.ndarray):
"""Standard Analysis class example used throughout PyAutoFit examples."""
<|body_0|>
def log_likelihood_function(self, instance) -> float:
"""Standard log likelihood function used throughout PyAut... | stack_v2_sparse_classes_75kplus_train_004157 | 20,890 | no_license | [
{
"docstring": "Standard Analysis class example used throughout PyAutoFit examples.",
"name": "__init__",
"signature": "def __init__(self, data: np.ndarray, noise_map: np.ndarray)"
},
{
"docstring": "Standard log likelihood function used throughout PyAutoFit examples.",
"name": "log_likeliho... | 4 | stack_v2_sparse_classes_30k_test_002739 | Implement the Python class `Analysis` described below.
Class description:
Implement the Analysis class.
Method signatures and docstrings:
- def __init__(self, data: np.ndarray, noise_map: np.ndarray): Standard Analysis class example used throughout PyAutoFit examples.
- def log_likelihood_function(self, instance) -> ... | Implement the Python class `Analysis` described below.
Class description:
Implement the Analysis class.
Method signatures and docstrings:
- def __init__(self, data: np.ndarray, noise_map: np.ndarray): Standard Analysis class example used throughout PyAutoFit examples.
- def log_likelihood_function(self, instance) -> ... | ac76dfef4643189a130ce18d23070bb81272a93c | <|skeleton|>
class Analysis:
def __init__(self, data: np.ndarray, noise_map: np.ndarray):
"""Standard Analysis class example used throughout PyAutoFit examples."""
<|body_0|>
def log_likelihood_function(self, instance) -> float:
"""Standard log likelihood function used throughout PyAut... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Analysis:
def __init__(self, data: np.ndarray, noise_map: np.ndarray):
"""Standard Analysis class example used throughout PyAutoFit examples."""
super().__init__()
self.data = data
self.noise_map = noise_map
def log_likelihood_function(self, instance) -> float:
"""... | the_stack_v2_python_sparse | scripts/cookbooks/database.py | Jammy2211/autofit_workspace | train | 6 | |
71b1c35f975605741dce944f7b662ab9660fa935 | [
"super(EmailBackend, self).__init__(**kwargs)\nself.api_key = api_key if api_key is not None else getattr(settings, 'POSTMARK_API_KEY', None)\nif self.api_key is None:\n raise ImproperlyConfigured('POSTMARK API key must be set in Django settings file or passed to backend constructor.')\nself.default_sender = get... | <|body_start_0|>
super(EmailBackend, self).__init__(**kwargs)
self.api_key = api_key if api_key is not None else getattr(settings, 'POSTMARK_API_KEY', None)
if self.api_key is None:
raise ImproperlyConfigured('POSTMARK API key must be set in Django settings file or passed to backend ... | EmailBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailBackend:
def __init__(self, api_key=None, default_sender=None, **kwargs):
"""Initialize the backend."""
<|body_0|>
def send_messages(self, email_messages):
"""Sends one or more EmailMessage objects and returns the number of email messages sent."""
<|body... | stack_v2_sparse_classes_75kplus_train_004158 | 39,873 | no_license | [
{
"docstring": "Initialize the backend.",
"name": "__init__",
"signature": "def __init__(self, api_key=None, default_sender=None, **kwargs)"
},
{
"docstring": "Sends one or more EmailMessage objects and returns the number of email messages sent.",
"name": "send_messages",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_033249 | Implement the Python class `EmailBackend` described below.
Class description:
Implement the EmailBackend class.
Method signatures and docstrings:
- def __init__(self, api_key=None, default_sender=None, **kwargs): Initialize the backend.
- def send_messages(self, email_messages): Sends one or more EmailMessage objects... | Implement the Python class `EmailBackend` described below.
Class description:
Implement the EmailBackend class.
Method signatures and docstrings:
- def __init__(self, api_key=None, default_sender=None, **kwargs): Initialize the backend.
- def send_messages(self, email_messages): Sends one or more EmailMessage objects... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class EmailBackend:
def __init__(self, api_key=None, default_sender=None, **kwargs):
"""Initialize the backend."""
<|body_0|>
def send_messages(self, email_messages):
"""Sends one or more EmailMessage objects and returns the number of email messages sent."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailBackend:
def __init__(self, api_key=None, default_sender=None, **kwargs):
"""Initialize the backend."""
super(EmailBackend, self).__init__(**kwargs)
self.api_key = api_key if api_key is not None else getattr(settings, 'POSTMARK_API_KEY', None)
if self.api_key is None:
... | the_stack_v2_python_sparse | repoData/themartorana-python-postmark/allPythonContent.py | aCoffeeYin/pyreco | train | 0 | |
29ff9fa4dcb930c7f08f205ff35455dcaa30b137 | [
"argparser = kwargs.get('argparser', '')\ntrack = kwargs.get('track', '')\nif not (track and argparser and argparser.osd):\n return\nartist = track.split(' - ')[0]\nalbum_art = AlbumArt()\nicon = album_art.get(artist)\nif sys.version_info.major == 2:\n track = track.encode('utf-8')\nif platform.system() == 'D... | <|body_start_0|>
argparser = kwargs.get('argparser', '')
track = kwargs.get('track', '')
if not (track and argparser and argparser.osd):
return
artist = track.split(' - ')[0]
album_art = AlbumArt()
icon = album_art.get(artist)
if sys.version_info.major... | OSD notification (osx + growl / Linux GI) | OSDNotification | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
<|body_0|>
def linux_notify(cls, message, icon):
"""Linux OSD using GI"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004159 | 3,240 | permissive | [
{
"docstring": "Notification dispatcher that calls platform specific method",
"name": "notify",
"signature": "def notify(cls, *args, **kwargs)"
},
{
"docstring": "Linux OSD using GI",
"name": "linux_notify",
"signature": "def linux_notify(cls, message, icon)"
},
{
"docstring": "O... | 3 | stack_v2_sparse_classes_30k_test_000306 | Implement the Python class `OSDNotification` described below.
Class description:
OSD notification (osx + growl / Linux GI)
Method signatures and docstrings:
- def notify(cls, *args, **kwargs): Notification dispatcher that calls platform specific method
- def linux_notify(cls, message, icon): Linux OSD using GI
- def ... | Implement the Python class `OSDNotification` described below.
Class description:
OSD notification (osx + growl / Linux GI)
Method signatures and docstrings:
- def notify(cls, *args, **kwargs): Notification dispatcher that calls platform specific method
- def linux_notify(cls, message, icon): Linux OSD using GI
- def ... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
<|body_0|>
def linux_notify(cls, message, icon):
"""Linux OSD using GI"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
argparser = kwargs.get('argparser', '')
track = kwargs.get('track', '')
if not (track and argparser and argp... | the_stack_v2_python_sparse | voiceplay/player/hooks/osd.py | tb0hdan/voiceplay | train | 4 |
434dc0c4410f3899b9f3bd4b6a016f9850bcf9db | [
"response = self.client.get(reverse('rango:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'There are no categories present.')\nself.assertQuerysetEqual(response.context['categories'], [])",
"add_cat('test', 1, 1)\nadd_cat('temp', 1, 1)\nadd_cat('tmp', 1, 1)\nadd_cat('tmp test... | <|body_start_0|>
response = self.client.get(reverse('rango:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'There are no categories present.')
self.assertQuerysetEqual(response.context['categories'], [])
<|end_body_0|>
<|body_start_1|>
add_cat(... | IndexViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
... | stack_v2_sparse_classes_75kplus_train_004160 | 2,266 | no_license | [
{
"docstring": "If no questions exist,an appropriate message should be displayed.",
"name": "test_index_view_with_no_categories",
"signature": "def test_index_view_with_no_categories(self)"
},
{
"docstring": "If no questions exist,an appropriate message should be displayed.",
"name": "test_i... | 2 | stack_v2_sparse_classes_30k_train_018584 | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_categories(self): If no questions exist,an appropriate message should be displayed.
- def test_index_view_with_categories(self): If no que... | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_categories(self): If no questions exist,an appropriate message should be displayed.
- def test_index_view_with_categories(self): If no que... | 9e3d117d17025b3b587c5a80638cb8b3de754195 | <|skeleton|>
class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
response = self.client.get(reverse('rango:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'There are no categ... | the_stack_v2_python_sparse | Django-Projects/tango_with_django_project/rango/tests.py | breezy1812/MyCodes | train | 0 | |
c91c47f02781ce34df59f4f89d573d2afcce92a5 | [
"resp = requests.get(verify_url.format('json', cred[0], cred[1], 'TestApp', test_number))\nassert resp.status_code == 200\nassert resp.headers['Content-Type'] == 'application/json'\nassert resp.json()['status'] == '0'\nassert len(resp.json()['request_id']) <= 32\nrequest_id = resp.json()['request_id']\ntime.sleep(1... | <|body_start_0|>
resp = requests.get(verify_url.format('json', cred[0], cred[1], 'TestApp', test_number))
assert resp.status_code == 200
assert resp.headers['Content-Type'] == 'application/json'
assert resp.json()['status'] == '0'
assert len(resp.json()['request_id']) <= 32
... | This class contains only JSON format API testcases. | TestVerifyApiJson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVerifyApiJson:
"""This class contains only JSON format API testcases."""
def test_cancel_of_default_verify_request(self, cred):
"""Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19, After 30 sec. passed should be successful, Next cancel ... | stack_v2_sparse_classes_75kplus_train_004161 | 5,082 | no_license | [
{
"docstring": "Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19, After 30 sec. passed should be successful, Next cancel request should fail with status code 6.",
"name": "test_cancel_of_default_verify_request",
"signature": "def test_cancel_of_default_verify_... | 3 | stack_v2_sparse_classes_30k_train_020497 | Implement the Python class `TestVerifyApiJson` described below.
Class description:
This class contains only JSON format API testcases.
Method signatures and docstrings:
- def test_cancel_of_default_verify_request(self, cred): Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19... | Implement the Python class `TestVerifyApiJson` described below.
Class description:
This class contains only JSON format API testcases.
Method signatures and docstrings:
- def test_cancel_of_default_verify_request(self, cred): Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19... | a51f99c9595cf3b7910a262006a6584f4929eb70 | <|skeleton|>
class TestVerifyApiJson:
"""This class contains only JSON format API testcases."""
def test_cancel_of_default_verify_request(self, cred):
"""Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19, After 30 sec. passed should be successful, Next cancel ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestVerifyApiJson:
"""This class contains only JSON format API testcases."""
def test_cancel_of_default_verify_request(self, cred):
"""Test Verify Cancel request full cycle. Before 30 sec. passed should fail with status code 19, After 30 sec. passed should be successful, Next cancel request shoul... | the_stack_v2_python_sparse | nexmo_verify_control_api_testing.py | alx-fokin/api-testing-example | train | 0 |
0a30c72ce0612212202e8093a083871b1df348e8 | [
"dic = {}\nfor i in nums:\n dic[i] = dic.get(i, 1) + 1\nl = [(item, dic[item]) for item in dic]\nl.sort(key=lambda l: l[1], reverse=True)\nres = []\nfor i in range(k):\n res.append(l[i][0])\nreturn res",
"import heapq\ndic = {}\nfor i in nums:\n dic[i] = dic.get(i, 1) + 1\ntopK = heapq.nlargest(k, dic, k... | <|body_start_0|>
dic = {}
for i in nums:
dic[i] = dic.get(i, 1) + 1
l = [(item, dic[item]) for item in dic]
l.sort(key=lambda l: l[1], reverse=True)
res = []
for i in range(k):
res.append(l[i][0])
return res
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004162 | 1,713 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent1",
"signature": "def topKFrequent1(self, nums, k)"... | 2 | stack_v2_sparse_classes_30k_train_039295 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent1(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent1(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|... | cb6d5e9c3b8e02af904df5a615bf88f12d6fe77e | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
dic = {}
for i in nums:
dic[i] = dic.get(i, 1) + 1
l = [(item, dic[item]) for item in dic]
l.sort(key=lambda l: l[1], reverse=True)
res = []
... | the_stack_v2_python_sparse | 前K个高频元素 .py | daxiangpanda/lintCode | train | 0 | |
072f29e87aa5cf7f45957749a498119bee0c181c | [
"if not head or not head.next:\n return None\nslow = fast = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n break\nif slow != fast:\n return None\np = head\nwhile p != slow:\n p = p.next\n slow = slow.next\nreturn p",
"nodes = set()\nnode... | <|body_start_0|>
if not head or not head.next:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if slow != fast:
return None
p = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_75kplus_train_004163 | 997 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle1",
"signature": "def detectCycle1(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def de... | e2fecd266bfced6208694b19a2d81182b13dacd6 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
... | the_stack_v2_python_sparse | detectCycle.py | HuipengXu/leetcode | train | 0 | |
8916a8559bd46162a5a802c5ccf3bce761eb0727 | [
"LOGGER.info('Reading events')\nLOGGER.debug(f\"get events parameters: namespace={namespace}, name={name}, label_selector={label_selector}, field_selector='{field_selector}', resource_version={resource_version}, timeout={timeout}\")\nevent_listener = dyn_client.resources.get(api_version=cls.api_version, kind=cls.__... | <|body_start_0|>
LOGGER.info('Reading events')
LOGGER.debug(f"get events parameters: namespace={namespace}, name={name}, label_selector={label_selector}, field_selector='{field_selector}', resource_version={resource_version}, timeout={timeout}")
event_listener = dyn_client.resources.get(api_vers... | Allow read and remove K8s events. | Event | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
"""Allow read and remove K8s events."""
def get(cls, dyn_client, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""get - retrieves K8s events. :param dyn_client: K8s client; mandatory :param namespace: event namespace... | stack_v2_sparse_classes_75kplus_train_004164 | 3,991 | permissive | [
{
"docstring": "get - retrieves K8s events. :param dyn_client: K8s client; mandatory :param namespace: event namespace; optional :param name: event name; optional :param label_selector: filter events by labels; comma separated string of key=value; optional :param field_selector: filter events by event fields; c... | 2 | stack_v2_sparse_classes_30k_train_044288 | Implement the Python class `Event` described below.
Class description:
Allow read and remove K8s events.
Method signatures and docstrings:
- def get(cls, dyn_client, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None): get - retrieves K8s events. :param dyn_client... | Implement the Python class `Event` described below.
Class description:
Allow read and remove K8s events.
Method signatures and docstrings:
- def get(cls, dyn_client, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None): get - retrieves K8s events. :param dyn_client... | 01aa3234fc6333868222736d8f42e27943edb47a | <|skeleton|>
class Event:
"""Allow read and remove K8s events."""
def get(cls, dyn_client, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""get - retrieves K8s events. :param dyn_client: K8s client; mandatory :param namespace: event namespace... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Event:
"""Allow read and remove K8s events."""
def get(cls, dyn_client, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""get - retrieves K8s events. :param dyn_client: K8s client; mandatory :param namespace: event namespace; optional :p... | the_stack_v2_python_sparse | ocp_resources/event.py | ibesso-rh/openshift-python-wrapper | train | 0 |
926921f65421199debff8f5465ea38e83d722fb0 | [
"new_stmts = []\nfor stmt in body:\n stmts = self.visit(stmt)\n if isinstance(stmts, list):\n new_stmts.extend(stmts)\n else:\n new_stmts.append(stmts)\nreturn new_stmts",
"for func in recognized_idiom_variants:\n ret_tuple = func(node.test)\n if ret_tuple[0]:\n node.test = rec... | <|body_start_0|>
new_stmts = []
for stmt in body:
stmts = self.visit(stmt)
if isinstance(stmts, list):
new_stmts.extend(stmts)
else:
new_stmts.append(stmts)
return new_stmts
<|end_body_0|>
<|body_start_1|>
for func in r... | This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. This means that we have set a canonical form for each idiom and all the possible variants a... | IdiomConversionVisitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdiomConversionVisitor:
"""This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. This means that we have set a canonical f... | stack_v2_sparse_classes_75kplus_train_004165 | 32,554 | no_license | [
{
"docstring": "Visit the if body, applying the idiom on Ifs that are inside If bodies. :param body: :return:",
"name": "__visit_instruction_body",
"signature": "def __visit_instruction_body(self, body)"
},
{
"docstring": "Check if conditions to search for recognized idiom patterns. :param node:... | 2 | stack_v2_sparse_classes_30k_test_002423 | Implement the Python class `IdiomConversionVisitor` described below.
Class description:
This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. Th... | Implement the Python class `IdiomConversionVisitor` described below.
Class description:
This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. Th... | be66ae846c82ac40ba7b48f9880d6e3990681a5b | <|skeleton|>
class IdiomConversionVisitor:
"""This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. This means that we have set a canonical f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdiomConversionVisitor:
"""This transformer ensures that all the idiom variants that are recognized by stypy are transformed to its base equivalent form, in order to process them accordingly without spawning repeated code for each recognized code pattern. This means that we have set a canonical form for each ... | the_stack_v2_python_sparse | stypy/visitor/type_inference/desugaring/idiom_conversion_visitor.py | ComputationalReflection/stypy | train | 2 |
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea | [
"incl = ['a', 'b']\nexcl = ['b', 'c']\nfcn = da.lwc.search._get_dual_regex_indicator_fcn(incl, excl)\nassert fcn('a')\nassert not fcn('b')\nassert not fcn('c')\nassert not fcn('d')",
"incl = ['a', 'b']\nfcn = da.lwc.search._get_dual_regex_indicator_fcn(incl, excl=None)\nassert fcn('a')\nassert fcn('b')\nassert no... | <|body_start_0|>
incl = ['a', 'b']
excl = ['b', 'c']
fcn = da.lwc.search._get_dual_regex_indicator_fcn(incl, excl)
assert fcn('a')
assert not fcn('b')
assert not fcn('c')
assert not fcn('d')
<|end_body_0|>
<|body_start_1|>
incl = ['a', 'b']
fcn = ... | Specify the _get_dual_regex_indicator_fcn. | Specify_GetDualRegexIndicatorFcn | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Specify_GetDualRegexIndicatorFcn:
"""Specify the _get_dual_regex_indicator_fcn."""
def it_detects_items_in_include_list_but_not_those_in_exclude_list(self):
"""Test that items in include list return true unless in the exclude list."""
<|body_0|>
def it_nothing_is_exclude... | stack_v2_sparse_classes_75kplus_train_004166 | 29,518 | permissive | [
{
"docstring": "Test that items in include list return true unless in the exclude list.",
"name": "it_detects_items_in_include_list_but_not_those_in_exclude_list",
"signature": "def it_detects_items_in_include_list_but_not_those_in_exclude_list(self)"
},
{
"docstring": "Test that no include item... | 4 | stack_v2_sparse_classes_30k_train_037813 | Implement the Python class `Specify_GetDualRegexIndicatorFcn` described below.
Class description:
Specify the _get_dual_regex_indicator_fcn.
Method signatures and docstrings:
- def it_detects_items_in_include_list_but_not_those_in_exclude_list(self): Test that items in include list return true unless in the exclude l... | Implement the Python class `Specify_GetDualRegexIndicatorFcn` described below.
Class description:
Specify the _get_dual_regex_indicator_fcn.
Method signatures and docstrings:
- def it_detects_items_in_include_list_but_not_those_in_exclude_list(self): Test that items in include list return true unless in the exclude l... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class Specify_GetDualRegexIndicatorFcn:
"""Specify the _get_dual_regex_indicator_fcn."""
def it_detects_items_in_include_list_but_not_those_in_exclude_list(self):
"""Test that items in include list return true unless in the exclude list."""
<|body_0|>
def it_nothing_is_exclude... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Specify_GetDualRegexIndicatorFcn:
"""Specify the _get_dual_regex_indicator_fcn."""
def it_detects_items_in_include_list_but_not_those_in_exclude_list(self):
"""Test that items in include list return true unless in the exclude list."""
incl = ['a', 'b']
excl = ['b', 'c']
fc... | the_stack_v2_python_sparse | a3_src/h70_internal/da/lwc/spec/spec_search.py | wtpayne/hiai | train | 5 |
2b7873da2ea0e48bea2061664f11b22da0e56aec | [
"self.k = k\nself.heap = []\nfor each in nums:\n self.add(each)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelif self.heap[0] < val:\n heapq.heappop(self.heap)\n heapq.heappush(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = []
for each in nums:
self.add(each)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif self.heap[0] < val:
heapq.heappop(self.heap)
heapq.heappush... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = []
for each in nums... | stack_v2_sparse_classes_75kplus_train_004167 | 1,046 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000974 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = []
for each in nums:
self.add(each)
def add(self, val):
""":type val: int :rtype: int"""
if len(self.heap) < self.k:
heapq.heapp... | the_stack_v2_python_sparse | KthLargest.py | NeilWangziyu/Leetcode_py | train | 2 | |
ee959121d9abcb30c3ce0f32fff83f0a5a7ee203 | [
"self.alpha = lr\nself.epochs = epochs\nself.use_cuda = torch.cuda.is_available()\nself.tensor = torch.cuda.FloatTensor if self.use_cuda else torch.FloatTensor\nself.model = _LogisticRegressionModel(input_dim, output_dim)\nif self.use_cuda:\n self.model.cuda()",
"X_train = self.tensor(X_train).requires_grad_(T... | <|body_start_0|>
self.alpha = lr
self.epochs = epochs
self.use_cuda = torch.cuda.is_available()
self.tensor = torch.cuda.FloatTensor if self.use_cuda else torch.FloatTensor
self.model = _LogisticRegressionModel(input_dim, output_dim)
if self.use_cuda:
self.mod... | LogisticRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegression:
def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100):
"""Initialises Logistic Regression classifier with initializing alpha(learning rate), number of epochs."""
<|body_0|>
def train(self, X_train, y_train):
"""Train Logistic Regre... | stack_v2_sparse_classes_75kplus_train_004168 | 2,608 | no_license | [
{
"docstring": "Initialises Logistic Regression classifier with initializing alpha(learning rate), number of epochs.",
"name": "__init__",
"signature": "def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100)"
},
{
"docstring": "Train Logistic Regression classifier using function f... | 3 | stack_v2_sparse_classes_30k_train_012787 | Implement the Python class `LogisticRegression` described below.
Class description:
Implement the LogisticRegression class.
Method signatures and docstrings:
- def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100): Initialises Logistic Regression classifier with initializing alpha(learning rate), numb... | Implement the Python class `LogisticRegression` described below.
Class description:
Implement the LogisticRegression class.
Method signatures and docstrings:
- def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100): Initialises Logistic Regression classifier with initializing alpha(learning rate), numb... | 102de6a0f278d3ee6c366bbe4ab19e1f265b3b2f | <|skeleton|>
class LogisticRegression:
def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100):
"""Initialises Logistic Regression classifier with initializing alpha(learning rate), number of epochs."""
<|body_0|>
def train(self, X_train, y_train):
"""Train Logistic Regre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogisticRegression:
def __init__(self, input_dim=3072, output_dim=10, lr=0.5, epochs=100):
"""Initialises Logistic Regression classifier with initializing alpha(learning rate), number of epochs."""
self.alpha = lr
self.epochs = epochs
self.use_cuda = torch.cuda.is_available()
... | the_stack_v2_python_sparse | Assignment 1/models/LogisticRegression.py | zyz9066/Deep-Learning | train | 0 | |
38a8b53b275e59ce2d07d724b2c66855aad43d81 | [
"def rec(node):\n if node == root:\n return\n b, e, v = (pos - node.words, pos, node.end)\n while rst and b < rst[-1][1]:\n rst.pop(-1)\n rst.append((b, e, v))\nrec(node.first)",
"fails = node.get_fails()\nfor fail in reversed(fails):\n if fail != root:\n rst.append((pos - fail... | <|body_start_0|>
def rec(node):
if node == root:
return
b, e, v = (pos - node.words, pos, node.end)
while rst and b < rst[-1][1]:
rst.pop(-1)
rst.append((b, e, v))
rec(node.first)
<|end_body_0|>
<|body_start_1|>
fai... | 匹配结果的记录模式 | mode_t | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mode_t:
"""匹配结果的记录模式"""
def last(rst, pos, node, root):
"""后项最大匹配,记录最后出现的有效结果"""
<|body_0|>
def all(rst, pos, node, root):
"""记录原文字符pos处匹配的节点node的全部可能值"""
<|body_1|>
def cross(rst, pos, node, root):
"""交叉保留,丢弃重叠包含的匹配"""
<|body_2|>
<|... | stack_v2_sparse_classes_75kplus_train_004169 | 13,459 | no_license | [
{
"docstring": "后项最大匹配,记录最后出现的有效结果",
"name": "last",
"signature": "def last(rst, pos, node, root)"
},
{
"docstring": "记录原文字符pos处匹配的节点node的全部可能值",
"name": "all",
"signature": "def all(rst, pos, node, root)"
},
{
"docstring": "交叉保留,丢弃重叠包含的匹配",
"name": "cross",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_034616 | Implement the Python class `mode_t` described below.
Class description:
匹配结果的记录模式
Method signatures and docstrings:
- def last(rst, pos, node, root): 后项最大匹配,记录最后出现的有效结果
- def all(rst, pos, node, root): 记录原文字符pos处匹配的节点node的全部可能值
- def cross(rst, pos, node, root): 交叉保留,丢弃重叠包含的匹配 | Implement the Python class `mode_t` described below.
Class description:
匹配结果的记录模式
Method signatures and docstrings:
- def last(rst, pos, node, root): 后项最大匹配,记录最后出现的有效结果
- def all(rst, pos, node, root): 记录原文字符pos处匹配的节点node的全部可能值
- def cross(rst, pos, node, root): 交叉保留,丢弃重叠包含的匹配
<|skeleton|>
class mode_t:
"""匹配结果的... | ac8076428dbf4608fa0ec77eccbcd03751092e42 | <|skeleton|>
class mode_t:
"""匹配结果的记录模式"""
def last(rst, pos, node, root):
"""后项最大匹配,记录最后出现的有效结果"""
<|body_0|>
def all(rst, pos, node, root):
"""记录原文字符pos处匹配的节点node的全部可能值"""
<|body_1|>
def cross(rst, pos, node, root):
"""交叉保留,丢弃重叠包含的匹配"""
<|body_2|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class mode_t:
"""匹配结果的记录模式"""
def last(rst, pos, node, root):
"""后项最大匹配,记录最后出现的有效结果"""
def rec(node):
if node == root:
return
b, e, v = (pos - node.words, pos, node.end)
while rst and b < rst[-1][1]:
rst.pop(-1)
rst... | the_stack_v2_python_sparse | py/match_ac.py | hxrain/scutil | train | 3 |
bfdf7f9ffdc4a01783735ded467031573021c18e | [
"db_is_rel_to_cwd = kwargs.pop('db_is_rel_to_cwd', DEFAULT_DB_IS_REL_TO_CWD)\ndb_rel_dir = kwargs.pop('db_rel_dir', DEFAULT_DB_REL_DIR)\nif db_is_rel_to_cwd:\n db_dir = os.path.join(os.getcwd(), db_rel_dir)\nelse:\n db_dir = os.path.join(os.path.dirname(__file__), db_rel_dir)\nif not os.path.isdir(db_dir):\n ... | <|body_start_0|>
db_is_rel_to_cwd = kwargs.pop('db_is_rel_to_cwd', DEFAULT_DB_IS_REL_TO_CWD)
db_rel_dir = kwargs.pop('db_rel_dir', DEFAULT_DB_REL_DIR)
if db_is_rel_to_cwd:
db_dir = os.path.join(os.getcwd(), db_rel_dir)
else:
db_dir = os.path.join(os.path.dirname(_... | This class defines a strategy for the agent. | Strategy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
<|body_0|>
def collect_from_data_source(self) -> Dict[str, str]:
"""Build the data... | stack_v2_sparse_classes_75kplus_train_004170 | 2,847 | permissive | [
{
"docstring": "Initialize the strategy of the agent. :param kwargs: keyword arguments",
"name": "__init__",
"signature": "def __init__(self, **kwargs: Any) -> None"
},
{
"docstring": "Build the data payload. :return: the data",
"name": "collect_from_data_source",
"signature": "def colle... | 3 | null | Implement the Python class `Strategy` described below.
Class description:
This class defines a strategy for the agent.
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: Initialize the strategy of the agent. :param kwargs: keyword arguments
- def collect_from_data_source(self) -> Dict[str,... | Implement the Python class `Strategy` described below.
Class description:
This class defines a strategy for the agent.
Method signatures and docstrings:
- def __init__(self, **kwargs: Any) -> None: Initialize the strategy of the agent. :param kwargs: keyword arguments
- def collect_from_data_source(self) -> Dict[str,... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
<|body_0|>
def collect_from_data_source(self) -> Dict[str, str]:
"""Build the data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Strategy:
"""This class defines a strategy for the agent."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the strategy of the agent. :param kwargs: keyword arguments"""
db_is_rel_to_cwd = kwargs.pop('db_is_rel_to_cwd', DEFAULT_DB_IS_REL_TO_CWD)
db_rel_dir = kwargs.pop(... | the_stack_v2_python_sparse | packages/fetchai/skills/carpark_detection/strategy.py | fetchai/agents-aea | train | 192 |
7f35b79e5dec898a9ab8676a4779a55799b20ce1 | [
"import tempfile\ndata = '1 Null 15.0 aaa\\n Null 10.2 7.0 bb\\n 1 Null 7.0 cc\\n 26 10.44 1.0 Null'\nself.tfile = tempfile.NamedTemporaryFile()\nself.tfile.write(data)\nself.tfile.flush()\nself.tdata = asciifunction.open(self.tfile.name)",
"import numpy\nfrom numpy import ma\nnumpy_col = self.tdata[0].t... | <|body_start_0|>
import tempfile
data = '1 Null 15.0 aaa\n Null 10.2 7.0 bb\n 1 Null 7.0 cc\n 26 10.44 1.0 Null'
self.tfile = tempfile.NamedTemporaryFile()
self.tfile.write(data)
self.tfile.flush()
self.tdata = asciifunction.open(self.tfile.name)
<|end_body_0|>
... | A test class for the conversion to numpy | Test_AsciiNumpyNone | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_AsciiNumpyNone:
"""A test class for the conversion to numpy"""
def setUp(self):
"""Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file reference to the temporary file is returned for further use of i... | stack_v2_sparse_classes_75kplus_train_004171 | 7,675 | permissive | [
{
"docstring": "Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file reference to the temporary file is returned for further use of it.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the bas... | 3 | null | Implement the Python class `Test_AsciiNumpyNone` described below.
Class description:
A test class for the conversion to numpy
Method signatures and docstrings:
- def setUp(self): Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file referen... | Implement the Python class `Test_AsciiNumpyNone` described below.
Class description:
A test class for the conversion to numpy
Method signatures and docstrings:
- def setUp(self): Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file referen... | 043c173fd5497c18c2b1bfe8bcff65180bca3996 | <|skeleton|>
class Test_AsciiNumpyNone:
"""A test class for the conversion to numpy"""
def setUp(self):
"""Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file reference to the temporary file is returned for further use of i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_AsciiNumpyNone:
"""A test class for the conversion to numpy"""
def setUp(self):
"""Store a string into a temporary file The method creates a named temporary file and writes a string given on input into it. The file reference to the temporary file is returned for further use of it."""
... | the_stack_v2_python_sparse | stsdas/pkg/analysis/slitless/axe/axe_asciidata/asciidata_numtest.py | spacetelescope/stsdas_stripped | train | 1 |
584177dca817881156c740650306bde4ebe57790 | [
"if skos is None:\n skos = 'maps/marc21toFRBRExpression.rdf'\nif expression is None:\n self.entity = Expression()\nelse:\n self.entity = expression\nMARCSKOSMapper.__init__(self, redis_marc_key, redis_server, skos)",
"descriptions = self.skos.findall('{%s}Description' % ns.RDF)\nprint('..processing Expre... | <|body_start_0|>
if skos is None:
skos = 'maps/marc21toFRBRExpression.rdf'
if expression is None:
self.entity = Expression()
else:
self.entity = expression
MARCSKOSMapper.__init__(self, redis_marc_key, redis_server, skos)
<|end_body_0|>
<|body_start_1... | The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record | MARCtoExpressionMap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MARCtoExpressionMap:
"""The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record"""
def __init__(self, redis_marc_key, redis_server, skos=None, expression=None):
""":param redis_marc_key: Redis MARC R... | stack_v2_sparse_classes_75kplus_train_004172 | 10,193 | permissive | [
{
"docstring": ":param redis_marc_key: Redis MARC Record Key :param redis_server: Redis server :param skos: Optional SKOS Mapping file :param expression: Optional passed in FRBR Expression",
"name": "__init__",
"signature": "def __init__(self, redis_marc_key, redis_server, skos=None, expression=None)"
... | 2 | stack_v2_sparse_classes_30k_train_004853 | Implement the Python class `MARCtoExpressionMap` described below.
Class description:
The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record
Method signatures and docstrings:
- def __init__(self, redis_marc_key, redis_server, skos=No... | Implement the Python class `MARCtoExpressionMap` described below.
Class description:
The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record
Method signatures and docstrings:
- def __init__(self, redis_marc_key, redis_server, skos=No... | c11441311034fdda4b9c1d0a9bd152fdea32d94b | <|skeleton|>
class MARCtoExpressionMap:
"""The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record"""
def __init__(self, redis_marc_key, redis_server, skos=None, expression=None):
""":param redis_marc_key: Redis MARC R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MARCtoExpressionMap:
"""The :class:`MARCtoExpressionMap` class takes a SKOS file and creates a FRBR :class:`Expression` instances based on values of a MARC21 record"""
def __init__(self, redis_marc_key, redis_server, skos=None, expression=None):
""":param redis_marc_key: Redis MARC Record Key :pa... | the_stack_v2_python_sparse | parsers/marc2frbr_rda.py | jermnelson/FRBR-Redis-Datastore | train | 4 |
fd6a25be8769a87cba91ef545ca2d0b044f5070c | [
"workout_plan = get_object_or_404(WorkoutPlan, pk=plan_id)\ncheck_workout_plan_owner(workout_plan, request.user)\nform = self.form_class(initial={'day': date, 'plan_id': plan_id})\nctx = {'form': form, 'plan_id': workout_plan.id, 'date': date, 'month_number': month_number}\nreturn render(request, self.template_name... | <|body_start_0|>
workout_plan = get_object_or_404(WorkoutPlan, pk=plan_id)
check_workout_plan_owner(workout_plan, request.user)
form = self.form_class(initial={'day': date, 'plan_id': plan_id})
ctx = {'form': form, 'plan_id': workout_plan.id, 'date': date, 'month_number': month_number}
... | The class that creates a new training. | TrainingAdd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingAdd:
"""The class that creates a new training."""
def get(self, request, plan_id, month_number=None, date=None):
"""Display the form for creating a new training. :param request: request object :param plan_id: id of a workout plan to which a new training is to be added :type p... | stack_v2_sparse_classes_75kplus_train_004173 | 34,014 | no_license | [
{
"docstring": "Display the form for creating a new training. :param request: request object :param plan_id: id of a workout plan to which a new training is to be added :type plan_id: str :param month_number: month number according to workout plan numbering :type month_number: str :param date: date of training,... | 2 | null | Implement the Python class `TrainingAdd` described below.
Class description:
The class that creates a new training.
Method signatures and docstrings:
- def get(self, request, plan_id, month_number=None, date=None): Display the form for creating a new training. :param request: request object :param plan_id: id of a wo... | Implement the Python class `TrainingAdd` described below.
Class description:
The class that creates a new training.
Method signatures and docstrings:
- def get(self, request, plan_id, month_number=None, date=None): Display the form for creating a new training. :param request: request object :param plan_id: id of a wo... | b6100d4082c197bc7b40bac27a9b8f07f8efcd84 | <|skeleton|>
class TrainingAdd:
"""The class that creates a new training."""
def get(self, request, plan_id, month_number=None, date=None):
"""Display the form for creating a new training. :param request: request object :param plan_id: id of a workout plan to which a new training is to be added :type p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainingAdd:
"""The class that creates a new training."""
def get(self, request, plan_id, month_number=None, date=None):
"""Display the form for creating a new training. :param request: request object :param plan_id: id of a workout plan to which a new training is to be added :type plan_id: str :... | the_stack_v2_python_sparse | RunScheduleApp/views.py | Gribek/RunSchedules | train | 0 |
6eb2e44e13df2d5088802f2452a1763ae33183da | [
"self._params['room_type'] = room_type\nself.step('../data/hotel_detail.yaml')\nreturn HotelScheduled(self._mini)",
"self._params['room_code'] = room_code\nresult = self.step('../data/hotel_detail.yaml')\nreturn result"
] | <|body_start_0|>
self._params['room_type'] = room_type
self.step('../data/hotel_detail.yaml')
return HotelScheduled(self._mini)
<|end_body_0|>
<|body_start_1|>
self._params['room_code'] = room_code
result = self.step('../data/hotel_detail.yaml')
return result
<|end_body_... | 酒店列表页 | HotelDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HotelDetail:
"""酒店列表页"""
def goto_hotel_scheduled(self, room_type):
"""跳转到酒店预订页 :return:"""
<|body_0|>
def get_root_status(self, room_code):
"""获取当前房型的房态"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._params['room_type'] = room_type
... | stack_v2_sparse_classes_75kplus_train_004174 | 625 | no_license | [
{
"docstring": "跳转到酒店预订页 :return:",
"name": "goto_hotel_scheduled",
"signature": "def goto_hotel_scheduled(self, room_type)"
},
{
"docstring": "获取当前房型的房态",
"name": "get_root_status",
"signature": "def get_root_status(self, room_code)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002485 | Implement the Python class `HotelDetail` described below.
Class description:
酒店列表页
Method signatures and docstrings:
- def goto_hotel_scheduled(self, room_type): 跳转到酒店预订页 :return:
- def get_root_status(self, room_code): 获取当前房型的房态 | Implement the Python class `HotelDetail` described below.
Class description:
酒店列表页
Method signatures and docstrings:
- def goto_hotel_scheduled(self, room_type): 跳转到酒店预订页 :return:
- def get_root_status(self, room_code): 获取当前房型的房态
<|skeleton|>
class HotelDetail:
"""酒店列表页"""
def goto_hotel_scheduled(self, roo... | fc996ce4bb60223842114989e45c87d0aff488bb | <|skeleton|>
class HotelDetail:
"""酒店列表页"""
def goto_hotel_scheduled(self, room_type):
"""跳转到酒店预订页 :return:"""
<|body_0|>
def get_root_status(self, room_code):
"""获取当前房型的房态"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HotelDetail:
"""酒店列表页"""
def goto_hotel_scheduled(self, room_type):
"""跳转到酒店预订页 :return:"""
self._params['room_type'] = room_type
self.step('../data/hotel_detail.yaml')
return HotelScheduled(self._mini)
def get_root_status(self, room_code):
"""获取当前房型的房态"""
... | the_stack_v2_python_sparse | pages/hoteldetail.py | seselinfeng/m3_mp_test | train | 0 |
8ad2b477a8d1b6e149eef60643d9e8047d6b93a9 | [
"self.chart = chart\nself.pretty = pretty\nif isinstance(outfile, file) or hasattr(outfile, 'write'):\n self.outfile = outfile\nelif not outfile:\n self.outfile = sys.stdout\nelif outfile[-5:] == '.svgz':\n self.outfile = gzip.open(outfile, 'wb')\nelse:\n self.outfile = open(outfile, 'w')",
"if self.p... | <|body_start_0|>
self.chart = chart
self.pretty = pretty
if isinstance(outfile, file) or hasattr(outfile, 'write'):
self.outfile = outfile
elif not outfile:
self.outfile = sys.stdout
elif outfile[-5:] == '.svgz':
self.outfile = gzip.open(outfil... | Outputs a chart to the given file or standard output. | SVGOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVGOutput:
"""Outputs a chart to the given file or standard output."""
def __init__(self, chart=None, outfile=None, pretty=False):
"""@param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. Defaults to sys.stdout @param pretty: Enables pretty-printe... | stack_v2_sparse_classes_75kplus_train_004175 | 1,150 | permissive | [
{
"docstring": "@param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. Defaults to sys.stdout @param pretty: Enables pretty-printed XML. This option will use the minidom module and may degrade performance significantly. @type pretty: Boolean",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_031888 | Implement the Python class `SVGOutput` described below.
Class description:
Outputs a chart to the given file or standard output.
Method signatures and docstrings:
- def __init__(self, chart=None, outfile=None, pretty=False): @param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. De... | Implement the Python class `SVGOutput` described below.
Class description:
Outputs a chart to the given file or standard output.
Method signatures and docstrings:
- def __init__(self, chart=None, outfile=None, pretty=False): @param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. De... | ff440f55f38d64658fcad3c60ded5236b1c0a401 | <|skeleton|>
class SVGOutput:
"""Outputs a chart to the given file or standard output."""
def __init__(self, chart=None, outfile=None, pretty=False):
"""@param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. Defaults to sys.stdout @param pretty: Enables pretty-printe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SVGOutput:
"""Outputs a chart to the given file or standard output."""
def __init__(self, chart=None, outfile=None, pretty=False):
"""@param chart: The chart to print. @type chart: Shape @param outfile: The file to print to. Defaults to sys.stdout @param pretty: Enables pretty-printed XML. This o... | the_stack_v2_python_sparse | lib/output/SVGOutput.py | agold/svgchart | train | 1 |
9e29cb93c5c0377ee1aa43c33b7a7b4e53a51616 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')\ncollection = list(repo['jkmoy_mfflynn.crime'].find())\ntotal = len(collection)\ndata = [(doc['DAY_OF_WEEK'], 1) for doc in collection if doc['DAY_OF_WEEK'].strip != '']\... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')
collection = list(repo['jkmoy_mfflynn.crime'].find())
total = len(collection)
data = [(doc['DAY_OF_WEEK']... | dotw | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dotw:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happenin... | stack_v2_sparse_classes_75kplus_train_004176 | 3,857 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_027560 | Implement the Python class `dotw` described below.
Class description:
Implement the dotw class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Crea... | Implement the Python class `dotw` described below.
Class description:
Implement the dotw class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Crea... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class dotw:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happenin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dotw:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jkmoy_mfflynn', 'jkmoy_mfflynn')
colle... | the_stack_v2_python_sparse | jkmoy_mfflynn/dotw.py | maximega/course-2019-spr-proj | train | 2 | |
2a344cde064c4f6dc55cc8913569fddb19537382 | [
"self.color = color\nif fill is None:\n fill = color\nself.fill = fill\nself.length = length\nif width is None:\n width = length / 2\nself.width = width\nself.rotation = rotation",
"table_str = f'Ball2dTable:{self.color}'\ntable_str += f' length:{self.length} x {self.width} ft'\nreturn table_str"
] | <|body_start_0|>
self.color = color
if fill is None:
fill = color
self.fill = fill
self.length = length
if width is None:
width = length / 2
self.width = width
self.rotation = rotation
<|end_body_0|>
<|body_start_1|>
table_str = f'... | Ball2dTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length... | stack_v2_sparse_classes_75kplus_train_004177 | 1,423 | no_license | [
{
"docstring": "Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length/2 :rotation: length orientation in degrees default: No rotation",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_030212 | Implement the Python class `Ball2dTable` described below.
Class description:
Implement the Ball2dTable class.
Method signatures and docstrings:
- def __init__(self, color='green', fill=None, length=9, width=None, rotation=None): Define/Setup Tables's attributes :color: table's color default: green :fill: table fill c... | Implement the Python class `Ball2dTable` described below.
Class description:
Implement the Ball2dTable class.
Method signatures and docstrings:
- def __init__(self, color='green', fill=None, length=9, width=None, rotation=None): Define/Setup Tables's attributes :color: table's color default: green :fill: table fill c... | bedc16eb5f6db0ad3b313355df6d51b5161c3835 | <|skeleton|>
class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length/2 :rotation: ... | the_stack_v2_python_sparse | exercises/classes/ball_classes/ball_2d_table.py | raysmith619/Introduction-To-Programming | train | 3 | |
91bc824fbc850b3a8d04607956fc21673b175379 | [
"self.entity_description = description\nself.dht_client = dht_client\nself.temperature_offset = temperature_offset\nself.humidity_offset = humidity_offset\nself._attr_name = f'{name} {description.name}'",
"self.dht_client.update()\ntemperature_offset = self.temperature_offset\nhumidity_offset = self.humidity_offs... | <|body_start_0|>
self.entity_description = description
self.dht_client = dht_client
self.temperature_offset = temperature_offset
self.humidity_offset = humidity_offset
self._attr_name = f'{name} {description.name}'
<|end_body_0|>
<|body_start_1|>
self.dht_client.update()... | Implementation of the DHT sensor. | DHTSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from the DHT and u... | stack_v2_sparse_classes_75kplus_train_004178 | 5,733 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription)"
},
{
"docstring": "Get the latest data from the DHT and updates the states.",
"name": "update",
"sig... | 2 | stack_v2_sparse_classes_30k_train_044069 | Implement the Python class `DHTSensor` described below.
Class description:
Implementation of the DHT sensor.
Method signatures and docstrings:
- def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription): Initialize the sensor.
- def update(self): Get the latest da... | Implement the Python class `DHTSensor` described below.
Class description:
Implementation of the DHT sensor.
Method signatures and docstrings:
- def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription): Initialize the sensor.
- def update(self): Get the latest da... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from the DHT and u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
self.entity_description = description
self.dht_client = dht_client
self.temperat... | the_stack_v2_python_sparse | homeassistant/components/dht/sensor.py | AlexxIT/home-assistant | train | 9 |
a5a642817da1c334a050a930b50d8b8d067952e5 | [
"size = len(prices)\nif size == 0:\n return 0\nminValue = prices[0]\nascMax = [0] * size\ndesMax = [0] * (size + 1)\nfor i in range(len(prices)):\n minValue = min(minValue, prices[i])\n ascMax[i] = max(ascMax[i - 1], prices[i] - minValue)\nj = size - 1\nmaxValue = prices[size - 1]\nwhile j >= 0:\n maxVa... | <|body_start_0|>
size = len(prices)
if size == 0:
return 0
minValue = prices[0]
ascMax = [0] * size
desMax = [0] * (size + 1)
for i in range(len(prices)):
minValue = min(minValue, prices[i])
ascMax[i] = max(ascMax[i - 1], prices[i] - mi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(prices)
if size == 0:... | stack_v2_sparse_classes_75kplus_train_004179 | 1,745 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048415 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | 85ceaf8f3da0efd66b4394ef16669ea673218265 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
size = len(prices)
if size == 0:
return 0
minValue = prices[0]
ascMax = [0] * size
desMax = [0] * (size + 1)
for i in range(len(prices)):
minValue = ... | the_stack_v2_python_sparse | LeetCode/动态规划/123. 买卖股票的最佳时机3.py | alexkie007/offer | train | 2 | |
a248462386adc932b7f01f1d346593b1a21b98a5 | [
"self.dic = [0] * 26\nself.next = [None] * 26\nself.end = False",
"if word:\n index = ord(word[0]) - ord('a')\n if not self.dic[index]:\n self.dic[index] = 1\n if len(word) > 1:\n if self.next[index] is None:\n self.next[index] = WordDictionary()\n self.next[index].addWord... | <|body_start_0|>
self.dic = [0] * 26
self.next = [None] * 26
self.end = False
<|end_body_0|>
<|body_start_1|>
if word:
index = ord(word[0]) - ord('a')
if not self.dic[index]:
self.dic[index] = 1
if len(word) > 1:
if sel... | WordDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_75kplus_train_004180 | 3,055 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a word into the data structure. :type word: str :rtype: void",
"name": "addWord",
"signature": "def addWord(self, word)"
},
{
"docstring": "Returns... | 3 | stack_v2_sparse_classes_30k_val_000076 | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | 4599634f31d78a0372cf0ff6fb7935d054d5ecb5 | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
self.dic = [0] * 26
self.next = [None] * 26
self.end = False
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
if word:
... | the_stack_v2_python_sparse | leetcode_python/201-300/211.py | jhgdike/leetCode | train | 3 | |
2ed7da6db7dd50e13f474478914e92296f290894 | [
"d = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H'}\nif xint in d:\n return d[xint]\nelse:\n raise ValueError('Нет ключа для полученного xint {}'.format(xint))",
"d = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h... | <|body_start_0|>
d = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H'}
if xint in d:
return d[xint]
else:
raise ValueError('Нет ключа для полученного xint {}'.format(xint))
<|end_body_0|>
<|body_start_1|>
d = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4... | Класс со всякой фигней | UtilClass | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilClass:
"""Класс со всякой фигней"""
def xint2char(xint):
"""Конвертирование числа в букву"""
<|body_0|>
def char2xint(char):
"""Конвертирование буквы в число"""
<|body_1|>
def checkxy_value(part):
"""Проверка на корректные на координаты x... | stack_v2_sparse_classes_75kplus_train_004181 | 1,947 | permissive | [
{
"docstring": "Конвертирование числа в букву",
"name": "xint2char",
"signature": "def xint2char(xint)"
},
{
"docstring": "Конвертирование буквы в число",
"name": "char2xint",
"signature": "def char2xint(char)"
},
{
"docstring": "Проверка на корректные на координаты xy",
"nam... | 4 | stack_v2_sparse_classes_30k_train_035695 | Implement the Python class `UtilClass` described below.
Class description:
Класс со всякой фигней
Method signatures and docstrings:
- def xint2char(xint): Конвертирование числа в букву
- def char2xint(char): Конвертирование буквы в число
- def checkxy_value(part): Проверка на корректные на координаты xy
- def getfail... | Implement the Python class `UtilClass` described below.
Class description:
Класс со всякой фигней
Method signatures and docstrings:
- def xint2char(xint): Конвертирование числа в букву
- def char2xint(char): Конвертирование буквы в число
- def checkxy_value(part): Проверка на корректные на координаты xy
- def getfail... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class UtilClass:
"""Класс со всякой фигней"""
def xint2char(xint):
"""Конвертирование числа в букву"""
<|body_0|>
def char2xint(char):
"""Конвертирование буквы в число"""
<|body_1|>
def checkxy_value(part):
"""Проверка на корректные на координаты x... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilClass:
"""Класс со всякой фигней"""
def xint2char(xint):
"""Конвертирование числа в букву"""
d = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H'}
if xint in d:
return d[xint]
else:
raise ValueError('Нет ключа для полученного xint... | the_stack_v2_python_sparse | Course_I/Алгоритмы Python/Part2/семинары/pract5/защита/util_module.py | GeorgiyDemo/FA | train | 46 |
472652560a4eaf215409592e1738cfbf3a5d1f7e | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | EventServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
<|body_0|>
def GetAll(self, request, context):
"""GetA... | stack_v2_sparse_classes_75kplus_train_004182 | 9,593 | permissive | [
{
"docstring": "GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified).",
"name": "GetOne",
"signature": "def GetOne(self, request, context)"
},
{
"docstring": "GetAll returns all entities for this model... | 3 | stack_v2_sparse_classes_30k_train_000686 | Implement the Python class `EventServiceServicer` described below.
Class description:
Implement the EventServiceServicer class.
Method signatures and docstrings:
- def GetOne(self, request, context): GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated... | Implement the Python class `EventServiceServicer` described below.
Class description:
Implement the EventServiceServicer class.
Method signatures and docstrings:
- def GetOne(self, request, context): GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated... | d93b5f66a00b1e3710257d607d62f9d43736304e | <|skeleton|>
class EventServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
<|body_0|>
def GetAll(self, request, context):
"""GetA... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Meth... | the_stack_v2_python_sparse | CVP_API/Snapshot_Utils/getSnapshots_Resource_API/cloudvision-python/arista/event/v1/services/gen_pb2_grpc.py | Hugh-Adams/Example_Scripts | train | 4 | |
446d61fafbe72b2941c16679b08a387dd1feb642 | [
"reasons = Reasons()\nmask = ~reflections.get_flags(reflections.flags.integrated, all=False)\nreasons.add_reason('not integrated by any method', mask.count(True))\nif 'd' in reflections:\n d_mask = reflections['d'] <= 0.0\n reasons.add_reason('bad d-value', d_mask.count(True))\n mask = mask | d_mask\nrefle... | <|body_start_0|>
reasons = Reasons()
mask = ~reflections.get_flags(reflections.flags.integrated, all=False)
reasons.add_reason('not integrated by any method', mask.count(True))
if 'd' in reflections:
d_mask = reflections['d'] <= 0.0
reasons.add_reason('bad d-value... | Base class for Scaler Factories | ScalerFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalerFactory:
"""Base class for Scaler Factories"""
def filter_bad_reflections(cls, reflections):
"""Initial filter to select integrated reflections."""
<|body_0|>
def ensure_experiment_identifier(cls, params, experiment, reflection_table):
"""Check for consiste... | stack_v2_sparse_classes_75kplus_train_004183 | 12,591 | permissive | [
{
"docstring": "Initial filter to select integrated reflections.",
"name": "filter_bad_reflections",
"signature": "def filter_bad_reflections(cls, reflections)"
},
{
"docstring": "Check for consistent experiment identifier, and if not set then set it using scaled_id.",
"name": "ensure_experi... | 2 | null | Implement the Python class `ScalerFactory` described below.
Class description:
Base class for Scaler Factories
Method signatures and docstrings:
- def filter_bad_reflections(cls, reflections): Initial filter to select integrated reflections.
- def ensure_experiment_identifier(cls, params, experiment, reflection_table... | Implement the Python class `ScalerFactory` described below.
Class description:
Base class for Scaler Factories
Method signatures and docstrings:
- def filter_bad_reflections(cls, reflections): Initial filter to select integrated reflections.
- def ensure_experiment_identifier(cls, params, experiment, reflection_table... | acb12b9ece8cde7e6d6f3796aa41e624ca2358c4 | <|skeleton|>
class ScalerFactory:
"""Base class for Scaler Factories"""
def filter_bad_reflections(cls, reflections):
"""Initial filter to select integrated reflections."""
<|body_0|>
def ensure_experiment_identifier(cls, params, experiment, reflection_table):
"""Check for consiste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScalerFactory:
"""Base class for Scaler Factories"""
def filter_bad_reflections(cls, reflections):
"""Initial filter to select integrated reflections."""
reasons = Reasons()
mask = ~reflections.get_flags(reflections.flags.integrated, all=False)
reasons.add_reason('not inte... | the_stack_v2_python_sparse | algorithms/scaling/scaler_factory.py | hattne/dials | train | 0 |
cacbfeffa01d655eb190b43a5256dd00df08ad1e | [
"if target == nums[0]:\n return 0\nif target >= nums[0]:\n for i, v in enumerate(nums):\n print(i, v)\n if v == target:\n return i\nif target <= nums[0]:\n for i, v in enumerate(reversed(nums)):\n if v == target:\n return len(nums) - i\nreturn -1",
"first, last ... | <|body_start_0|>
if target == nums[0]:
return 0
if target >= nums[0]:
for i, v in enumerate(nums):
print(i, v)
if v == target:
return i
if target <= nums[0]:
for i, v in enumerate(reversed(nums)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if... | stack_v2_sparse_classes_75kplus_train_004184 | 1,271 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search2",
"signature": "def search2(self, nums, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search2(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search2(self, nums, target): :type nums: List[int] :type target: int :rtype: int
<|skel... | f234bd7b62cb7bc2150faa764bf05a9095e19192 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
if target == nums[0]:
return 0
if target >= nums[0]:
for i, v in enumerate(nums):
print(i, v)
if v == target:
... | the_stack_v2_python_sparse | alg/search_in_rotated_sorted_array.py | nyannko/leetcode-python | train | 0 | |
0e9e5169ee4e720ad90a2073d4ebb3519218a30d | [
"df = diesel_prices\nself.start_year = int(df.index[0])\nself.projected_prices = df * diesel_price_scaler + adder\nself.projected_prices.index.name = 'year'",
"prices = self.projected_prices.ix[start_year:end_year]\nif prices.index[-1] < end_year:\n values = [float(prices.ix[prices.index[-1]]) for i in range(e... | <|body_start_0|>
df = diesel_prices
self.start_year = int(df.index[0])
self.projected_prices = df * diesel_price_scaler + adder
self.projected_prices.index.name = 'year'
<|end_body_0|>
<|body_start_1|>
prices = self.projected_prices.ix[start_year:end_year]
if prices.inde... | This class Projects diesel fuel prices | DieselProjections | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DieselProjections:
"""This class Projects diesel fuel prices"""
def __init__(self, diesel_prices, diesel_price_scaler=1.0, adder=0):
"""create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Hot_Springs) diesel_prices_community.csv exists in the data... | stack_v2_sparse_classes_75kplus_train_004185 | 2,772 | permissive | [
{
"docstring": "create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Hot_Springs) diesel_prices_community.csv exists in the data_dir, must have a single data row Post: self.projected_prices will contain the projected prices, and the start year is configred based off of it",
... | 2 | stack_v2_sparse_classes_30k_train_030592 | Implement the Python class `DieselProjections` described below.
Class description:
This class Projects diesel fuel prices
Method signatures and docstrings:
- def __init__(self, diesel_prices, diesel_price_scaler=1.0, adder=0): create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Ho... | Implement the Python class `DieselProjections` described below.
Class description:
This class Projects diesel fuel prices
Method signatures and docstrings:
- def __init__(self, diesel_prices, diesel_price_scaler=1.0, adder=0): create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Ho... | 96fed0137152985ce280ea37e0affec131e3087f | <|skeleton|>
class DieselProjections:
"""This class Projects diesel fuel prices"""
def __init__(self, diesel_prices, diesel_price_scaler=1.0, adder=0):
"""create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Hot_Springs) diesel_prices_community.csv exists in the data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DieselProjections:
"""This class Projects diesel fuel prices"""
def __init__(self, diesel_prices, diesel_price_scaler=1.0, adder=0):
"""create the projected values Pre: comminity is a valid community string (ie. Adak, Manley_Hot_Springs) diesel_prices_community.csv exists in the data_dir, must ha... | the_stack_v2_python_sparse | aaem/diesel_prices.py | acep-uaf/alaska_affordable_energy_model | train | 0 |
694c6325561a13082dcd8001feb878d7dfc5cd6c | [
"if user_id is None or type(user_id) != str:\n return None\nid = uuid.uuid4()\nid = str(id)\nSessionAuth.user_id_by_session_id[id] = user_id\nreturn id",
"if session_id is None or type(session_id) != str:\n return None\nvalue = SessionAuth.user_id_by_session_id.get(session_id)\nreturn value",
"cookie_valu... | <|body_start_0|>
if user_id is None or type(user_id) != str:
return None
id = uuid.uuid4()
id = str(id)
SessionAuth.user_id_by_session_id[id] = user_id
return id
<|end_body_0|>
<|body_start_1|>
if session_id is None or type(session_id) != str:
ret... | SessionAuth subclass | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""User id method"""
<|body_1|>
def current_user(self, r... | stack_v2_sparse_classes_75kplus_train_004186 | 1,634 | no_license | [
{
"docstring": "Create session method",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "User id method",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, session_id: str=None) -> str"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_027727 | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth subclass
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create session method
- def user_id_for_session_id(self, session_id: str=None) -> str: User id method
- def current_user(self, reque... | Implement the Python class `SessionAuth` described below.
Class description:
SessionAuth subclass
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create session method
- def user_id_for_session_id(self, session_id: str=None) -> str: User id method
- def current_user(self, reque... | 014fc078421a2daca65322c51b367a936fa8e20a | <|skeleton|>
class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""User id method"""
<|body_1|>
def current_user(self, r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionAuth:
"""SessionAuth subclass"""
def create_session(self, user_id: str=None) -> str:
"""Create session method"""
if user_id is None or type(user_id) != str:
return None
id = uuid.uuid4()
id = str(id)
SessionAuth.user_id_by_session_id[id] = user_i... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | Nicolanz/holbertonschool-web_back_end | train | 0 |
6535292392b3f3a85c99c8c3b3d32c61fff71253 | [
"super().__init__(always_apply, p)\nself.n_max_holes = n_max_holes\nself.max_h_size = np.max((max_h_size, 5))\nself.max_w_size = np.max((max_w_size, 5))\nself.filled_value = filled_value\nself.n_zero_channels = n_zero_channels\nself.is_filled_last_channels = is_filled_last_channels",
"assert x.ndim == 3, 'Error: ... | <|body_start_0|>
super().__init__(always_apply, p)
self.n_max_holes = n_max_holes
self.max_h_size = np.max((max_h_size, 5))
self.max_w_size = np.max((max_w_size, 5))
self.filled_value = filled_value
self.n_zero_channels = n_zero_channels
self.is_filled_last_channe... | This data augmentation randomly cutout a few small holes in the spectrogram. Tested. | RandomCutoutHoleNp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomCutoutHoleNp:
"""This data augmentation randomly cutout a few small holes in the spectrogram. Tested."""
def __init__(self, always_apply: bool=False, p: float=0.5, n_max_holes: int=8, max_h_size: int=8, max_w_size: int=8, filled_value: float=None, n_zero_channels: int=None, is_filled_l... | stack_v2_sparse_classes_75kplus_train_004187 | 27,418 | permissive | [
{
"docstring": ":param always_apply: If True, always apply transform. :param p: If always_apply is false, p is the probability to apply transform. :param n_max_holes: Maximum number of holes to cutout. :param max_h_size: Maximum time frames of the cutout holes. :param max_w_size: Maximum freq bands of the cutou... | 2 | stack_v2_sparse_classes_30k_train_036140 | Implement the Python class `RandomCutoutHoleNp` described below.
Class description:
This data augmentation randomly cutout a few small holes in the spectrogram. Tested.
Method signatures and docstrings:
- def __init__(self, always_apply: bool=False, p: float=0.5, n_max_holes: int=8, max_h_size: int=8, max_w_size: int... | Implement the Python class `RandomCutoutHoleNp` described below.
Class description:
This data augmentation randomly cutout a few small holes in the spectrogram. Tested.
Method signatures and docstrings:
- def __init__(self, always_apply: bool=False, p: float=0.5, n_max_holes: int=8, max_h_size: int=8, max_w_size: int... | a6f631b0ccc3d652d0035a873ff1dbae92c833de | <|skeleton|>
class RandomCutoutHoleNp:
"""This data augmentation randomly cutout a few small holes in the spectrogram. Tested."""
def __init__(self, always_apply: bool=False, p: float=0.5, n_max_holes: int=8, max_h_size: int=8, max_w_size: int=8, filled_value: float=None, n_zero_channels: int=None, is_filled_l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomCutoutHoleNp:
"""This data augmentation randomly cutout a few small holes in the spectrogram. Tested."""
def __init__(self, always_apply: bool=False, p: float=0.5, n_max_holes: int=8, max_h_size: int=8, max_w_size: int=8, filled_value: float=None, n_zero_channels: int=None, is_filled_last_channels:... | the_stack_v2_python_sparse | utilities/transforms.py | achyun/SALSA | train | 0 |
c34409f6e9d68a6aba35fcaa3374f94bb01d1df8 | [
"self.hex_layout = hex_layout\nself.number_layout = number_layout\nself.robber_hex = robber_hex",
"soclog_line = soclog_line.strip()\nmsg_match = SOCBOARDLAYOUT_MATCH.search(soclog_line)\nif msg_match is not None:\n hex_layout = [int(x) for x in msg_match.group('hex_layout').split(' ')]\n number_layout = [i... | <|body_start_0|>
self.hex_layout = hex_layout
self.number_layout = number_layout
self.robber_hex = robber_hex
<|end_body_0|>
<|body_start_1|>
soclog_line = soclog_line.strip()
msg_match = SOCBOARDLAYOUT_MATCH.search(soclog_line)
if msg_match is not None:
hex_... | Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of 19 number tokens. robber_hex : str Initial position of the robber, hexadecima... | CatanBoard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatanBoard:
"""Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of 19 number tokens. robber_hex : str Init... | stack_v2_sparse_classes_75kplus_train_004188 | 3,916 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self, hex_layout, number_layout, robber_hex)"
},
{
"docstring": "Parse a SOCBoardLayout message from a line in the soclog.",
"name": "from_soclog_line",
"signature": "def from_soclog_line(cls, soclog_line)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001150 | Implement the Python class `CatanBoard` described below.
Class description:
Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of ... | Implement the Python class `CatanBoard` described below.
Class description:
Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of ... | ec36fac93d26101ba1014db5540483a182472918 | <|skeleton|>
class CatanBoard:
"""Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of 19 number tokens. robber_hex : str Init... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CatanBoard:
"""Board itself. Parameters ---------- hex_layout : sequence of int General layout of the board, as a sequence of 37 terrain tiles for land, port, water. number_layout : sequence of int Production on the land hexes of the board, as a sequence of 19 number tokens. robber_hex : str Initial position ... | the_stack_v2_python_sparse | intake/catan_board.py | Tapojit/irit-stac | train | 0 |
3c54577a58ae0980ae7e50bba98f4e78f9be434d | [
"query, session = context[:2]\ncondition = True\nif 's' in query:\n condition = Plugin.name.matches(query.s) | Plugin.description.matches(query.s)\nplugins = session.query(Plugin, condition)\nreturn cv.create_json('success', cv.dictize(plugins))",
"request, session = context[:2]\nzip_file = ZipFile(BytesIO(req... | <|body_start_0|>
query, session = context[:2]
condition = True
if 's' in query:
condition = Plugin.name.matches(query.s) | Plugin.description.matches(query.s)
plugins = session.query(Plugin, condition)
return cv.create_json('success', cv.dictize(plugins))
<|end_body_0... | PluginCollectionEndpoint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginCollectionEndpoint:
def on_get(self, context):
"""Retrieve a list of plugins."""
<|body_0|>
def on_post(self, context):
"""Upload a plugin."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query, session = context[:2]
condition = True
... | stack_v2_sparse_classes_75kplus_train_004189 | 1,550 | permissive | [
{
"docstring": "Retrieve a list of plugins.",
"name": "on_get",
"signature": "def on_get(self, context)"
},
{
"docstring": "Upload a plugin.",
"name": "on_post",
"signature": "def on_post(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020838 | Implement the Python class `PluginCollectionEndpoint` described below.
Class description:
Implement the PluginCollectionEndpoint class.
Method signatures and docstrings:
- def on_get(self, context): Retrieve a list of plugins.
- def on_post(self, context): Upload a plugin. | Implement the Python class `PluginCollectionEndpoint` described below.
Class description:
Implement the PluginCollectionEndpoint class.
Method signatures and docstrings:
- def on_get(self, context): Retrieve a list of plugins.
- def on_post(self, context): Upload a plugin.
<|skeleton|>
class PluginCollectionEndpoint... | 20fd6a3cc42af5f2cde73e3b100d3edeb4e50c01 | <|skeleton|>
class PluginCollectionEndpoint:
def on_get(self, context):
"""Retrieve a list of plugins."""
<|body_0|>
def on_post(self, context):
"""Upload a plugin."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PluginCollectionEndpoint:
def on_get(self, context):
"""Retrieve a list of plugins."""
query, session = context[:2]
condition = True
if 's' in query:
condition = Plugin.name.matches(query.s) | Plugin.description.matches(query.s)
plugins = session.query(Plugi... | the_stack_v2_python_sparse | cvpl-homepage/homepage/api.py | robinsax/canvas-plugin-multirepo | train | 0 | |
4d35dab17a15dc6a604c260eabb41efa65ff4b51 | [
"x = tf.random.uniform((5, 3, 4), dtype=tf.dtypes.float32)\nparams = {'output_min': (0.0, 1.4, 10.0), 'output_max': (1.0, 1.5, 16.0)}\nvalues = itertools.product(*params.values())\nparams = [dict(zip(params.keys(), v)) for v in values]\nfor p in params:\n with self.subTest(**p):\n if p['output_min'] >= p[... | <|body_start_0|>
x = tf.random.uniform((5, 3, 4), dtype=tf.dtypes.float32)
params = {'output_min': (0.0, 1.4, 10.0), 'output_max': (1.0, 1.5, 16.0)}
values = itertools.product(*params.values())
params = [dict(zip(params.keys(), v)) for v in values]
for p in params:
wi... | Tests for function `scale_by_min_max`. | ScaleMinmaxTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaleMinmaxTest:
"""Tests for function `scale_by_min_max`."""
def test_scale_by_min_max(self):
"""Test function `scale_by_min_max`."""
<|body_0|>
def test_scale_by_min_max_complex(self):
"""Test function `scale_by_min_max` with complex numbers."""
<|body_... | stack_v2_sparse_classes_75kplus_train_004190 | 12,649 | permissive | [
{
"docstring": "Test function `scale_by_min_max`.",
"name": "test_scale_by_min_max",
"signature": "def test_scale_by_min_max(self)"
},
{
"docstring": "Test function `scale_by_min_max` with complex numbers.",
"name": "test_scale_by_min_max_complex",
"signature": "def test_scale_by_min_max... | 2 | null | Implement the Python class `ScaleMinmaxTest` described below.
Class description:
Tests for function `scale_by_min_max`.
Method signatures and docstrings:
- def test_scale_by_min_max(self): Test function `scale_by_min_max`.
- def test_scale_by_min_max_complex(self): Test function `scale_by_min_max` with complex number... | Implement the Python class `ScaleMinmaxTest` described below.
Class description:
Tests for function `scale_by_min_max`.
Method signatures and docstrings:
- def test_scale_by_min_max(self): Test function `scale_by_min_max`.
- def test_scale_by_min_max_complex(self): Test function `scale_by_min_max` with complex number... | cfd8930ee5281e7f6dceb17c4a5acaf625fd3243 | <|skeleton|>
class ScaleMinmaxTest:
"""Tests for function `scale_by_min_max`."""
def test_scale_by_min_max(self):
"""Test function `scale_by_min_max`."""
<|body_0|>
def test_scale_by_min_max_complex(self):
"""Test function `scale_by_min_max` with complex numbers."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaleMinmaxTest:
"""Tests for function `scale_by_min_max`."""
def test_scale_by_min_max(self):
"""Test function `scale_by_min_max`."""
x = tf.random.uniform((5, 3, 4), dtype=tf.dtypes.float32)
params = {'output_min': (0.0, 1.4, 10.0), 'output_max': (1.0, 1.5, 16.0)}
values... | the_stack_v2_python_sparse | tensorflow_mri/python/ops/math_ops_test.py | mrphys/tensorflow-mri | train | 29 |
4a458856ca21c359d129a4b6419385611ff6d306 | [
"w_shape = (in_features, out_features)\nself.params = defaultdict(float)\nself.grads = defaultdict(float)\nself.params['weights'] = np.random.normal(0, 0.0001, w_shape)\nself.params['bias'] = np.zeros(out_features)\nself.grads['weights'] = np.zeros(w_shape)\nself.grads['bias'] = np.zeros(out_features)",
"self.x =... | <|body_start_0|>
w_shape = (in_features, out_features)
self.params = defaultdict(float)
self.grads = defaultdict(float)
self.params['weights'] = np.random.normal(0, 0.0001, w_shape)
self.params['bias'] = np.zeros(out_features)
self.grads['weights'] = np.zeros(w_shape)
... | Linear module. Applies a linear transformation to the input data. | LinearModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_75kplus_train_004191 | 10,154 | no_license | [
{
"docstring": "Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. Initialize biases self.params['bias'] with 0. Also, initialize ... | 3 | null | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | 19f4974c64cb69d47a2d133eb3797cc809e30769 | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.par... | the_stack_v2_python_sparse | assignment_1/1_mlp_cnn/code/modules.py | antreashp/DL_2020 | train | 0 |
ccfdb3766221be7651206160508e0f4a3d438217 | [
"self.panning_func = panning_func\nself.n_rows = n_rows\nself.panning_positions = self.generate_panning_positions_even(n_rows)\nself.panning_positions_results = np.apply_along_axis(panning_func, 1, self.panning_positions)",
"elevations = np.linspace(-90, 90, num=n_rows, endpoint=True)\npositions = []\nfor el in e... | <|body_start_0|>
self.panning_func = panning_func
self.n_rows = n_rows
self.panning_positions = self.generate_panning_positions_even(n_rows)
self.panning_positions_results = np.apply_along_axis(panning_func, 1, self.panning_positions)
<|end_body_0|>
<|body_start_1|>
elevations =... | A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function. | SpreadingPanner | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpreadingPanner:
"""A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function."""
def __init__(self, panning_func, n_rows):
"""Args: panner: panner used to find panning values of virtual sources n_rows (int): number of row... | stack_v2_sparse_classes_75kplus_train_004192 | 10,012 | permissive | [
{
"docstring": "Args: panner: panner used to find panning values of virtual sources n_rows (int): number of rows rows to place on sphere, e.g. 37 for 5 degree spacing",
"name": "__init__",
"signature": "def __init__(self, panning_func, n_rows)"
},
{
"docstring": "Generate points spread evenly on... | 3 | stack_v2_sparse_classes_30k_train_004245 | Implement the Python class `SpreadingPanner` described below.
Class description:
A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function.
Method signatures and docstrings:
- def __init__(self, panning_func, n_rows): Args: panner: panner used to find pann... | Implement the Python class `SpreadingPanner` described below.
Class description:
A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function.
Method signatures and docstrings:
- def __init__(self, panning_func, n_rows): Args: panner: panner used to find pann... | ef2189021203101eab323e1eccdd2527b32a5024 | <|skeleton|>
class SpreadingPanner:
"""A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function."""
def __init__(self, panning_func, n_rows):
"""Args: panner: panner used to find panning values of virtual sources n_rows (int): number of row... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpreadingPanner:
"""A wrapper around another panner that pans using a uniform spread of points around the sphere given a weighting function."""
def __init__(self, panning_func, n_rows):
"""Args: panner: panner used to find panning values of virtual sources n_rows (int): number of rows rows to pla... | the_stack_v2_python_sparse | ear/core/objectbased/extent.py | ebu/ebu_adm_renderer | train | 61 |
e839588baaa6080276f1fa7d57b8092f7acb5730 | [
"if cls._cai_to_api_dict is None:\n with open(os.path.join(os.path.dirname(__file__), 'cai_to_api_properties.json')) as f:\n cls._cai_to_api_dict = json.load(f)\nreturn cls._cai_to_api_dict",
"if isinstance(cai_properties, list):\n for item in cai_properties:\n cls._apply_cai_to_api(item, cai_... | <|body_start_0|>
if cls._cai_to_api_dict is None:
with open(os.path.join(os.path.dirname(__file__), 'cai_to_api_properties.json')) as f:
cls._cai_to_api_dict = json.load(f)
return cls._cai_to_api_dict
<|end_body_0|>
<|body_start_1|>
if isinstance(cai_properties, list... | Convert CAI properties names to API properties. | CAIToAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CAIToAPI:
"""Convert CAI properties names to API properties."""
def _get_cai_to_api_properties(cls):
"""Get the dict containing current mappings."""
<|body_0|>
def _apply_cai_to_api(cls, cai_properties, cai_to_api):
"""Recursively map CAI to API properties. Args:... | stack_v2_sparse_classes_75kplus_train_004193 | 3,452 | permissive | [
{
"docstring": "Get the dict containing current mappings.",
"name": "_get_cai_to_api_properties",
"signature": "def _get_cai_to_api_properties(cls)"
},
{
"docstring": "Recursively map CAI to API properties. Args: cai_properties: dict of cai properties at current level of recursion. cai_to_api: d... | 3 | null | Implement the Python class `CAIToAPI` described below.
Class description:
Convert CAI properties names to API properties.
Method signatures and docstrings:
- def _get_cai_to_api_properties(cls): Get the dict containing current mappings.
- def _apply_cai_to_api(cls, cai_properties, cai_to_api): Recursively map CAI to ... | Implement the Python class `CAIToAPI` described below.
Class description:
Convert CAI properties names to API properties.
Method signatures and docstrings:
- def _get_cai_to_api_properties(cls): Get the dict containing current mappings.
- def _apply_cai_to_api(cls, cai_properties, cai_to_api): Recursively map CAI to ... | d7bc3b194159ffdb149c9507890bb1fbae7a8d88 | <|skeleton|>
class CAIToAPI:
"""Convert CAI properties names to API properties."""
def _get_cai_to_api_properties(cls):
"""Get the dict containing current mappings."""
<|body_0|>
def _apply_cai_to_api(cls, cai_properties, cai_to_api):
"""Recursively map CAI to API properties. Args:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CAIToAPI:
"""Convert CAI properties names to API properties."""
def _get_cai_to_api_properties(cls):
"""Get the dict containing current mappings."""
if cls._cai_to_api_dict is None:
with open(os.path.join(os.path.dirname(__file__), 'cai_to_api_properties.json')) as f:
... | the_stack_v2_python_sparse | tools/asset-inventory/asset_inventory/cai_to_api.py | MCRen88/professional-services | train | 1 |
9114cf43474c93569c6cf8a41b6809c979fc0696 | [
"self.card_holder_name = card_holder_name\nself.account_number = account_number\nself.cvv = cvv\nself.expiration_month = expiration_month\nself.expiration_year = expiration_year\nself.billing_address = billing_address",
"if dictionary is None:\n return None\ncard_holder_name = dictionary.get('cardHolderName')\... | <|body_start_0|>
self.card_holder_name = card_holder_name
self.account_number = account_number
self.cvv = cvv
self.expiration_month = expiration_month
self.expiration_year = expiration_year
self.billing_address = billing_address
<|end_body_0|>
<|body_start_1|>
if... | Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type description here. billing_address (Addr... | Card | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type descrip... | stack_v2_sparse_classes_75kplus_train_004194 | 2,891 | permissive | [
{
"docstring": "Constructor for the Card class",
"name": "__init__",
"signature": "def __init__(self, card_holder_name=None, account_number=None, cvv=None, expiration_month=None, expiration_year=None, billing_address=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | stack_v2_sparse_classes_30k_train_054549 | Implement the Python class `Card` described below.
Class description:
Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expir... | Implement the Python class `Card` described below.
Class description:
Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expir... | e1ca52116aabfcdb2f36c24ebd866cf00bb5c6c9 | <|skeleton|>
class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type descrip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type description here. bi... | the_stack_v2_python_sparse | plastiqpublicapi/models/card.py | jeffkynaston/sdk-spike-python-apimatic | train | 0 |
5da65b84d756cd1be7cdd1a5bae308c5942554d0 | [
"builder = treelite.ModelBuilder(num_feature=sklearn_model.n_features_in_, average_tree_output=True, threshold_type='float64', leaf_output_type='float64')\nfor i in range(sklearn_model.n_estimators):\n builder.append(cls.process_tree(sklearn_model.estimators_[i].tree_, sklearn_model))\nreturn builder.commit()",
... | <|body_start_0|>
builder = treelite.ModelBuilder(num_feature=sklearn_model.n_features_in_, average_tree_output=True, threshold_type='float64', leaf_output_type='float64')
for i in range(sklearn_model.n_estimators):
builder.append(cls.process_tree(sklearn_model.estimators_[i].tree_, sklearn_m... | Mixin class to implement the converter for RandomForestClassifier (binary classifier) | SKLRFClassifierMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SKLRFClassifierMixin:
"""Mixin class to implement the converter for RandomForestClassifier (binary classifier)"""
def process_model(cls, sklearn_model):
"""Process a RandomForestClassifier (binary classifier) to convert it into a Treelite model"""
<|body_0|>
def process_... | stack_v2_sparse_classes_75kplus_train_004195 | 1,512 | permissive | [
{
"docstring": "Process a RandomForestClassifier (binary classifier) to convert it into a Treelite model",
"name": "process_model",
"signature": "def process_model(cls, sklearn_model)"
},
{
"docstring": "Process a test node with a given node ID",
"name": "process_leaf_node",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_025239 | Implement the Python class `SKLRFClassifierMixin` described below.
Class description:
Mixin class to implement the converter for RandomForestClassifier (binary classifier)
Method signatures and docstrings:
- def process_model(cls, sklearn_model): Process a RandomForestClassifier (binary classifier) to convert it into... | Implement the Python class `SKLRFClassifierMixin` described below.
Class description:
Mixin class to implement the converter for RandomForestClassifier (binary classifier)
Method signatures and docstrings:
- def process_model(cls, sklearn_model): Process a RandomForestClassifier (binary classifier) to convert it into... | 50a8db523a0d5b1859476995999b8aed394af7a4 | <|skeleton|>
class SKLRFClassifierMixin:
"""Mixin class to implement the converter for RandomForestClassifier (binary classifier)"""
def process_model(cls, sklearn_model):
"""Process a RandomForestClassifier (binary classifier) to convert it into a Treelite model"""
<|body_0|>
def process_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SKLRFClassifierMixin:
"""Mixin class to implement the converter for RandomForestClassifier (binary classifier)"""
def process_model(cls, sklearn_model):
"""Process a RandomForestClassifier (binary classifier) to convert it into a Treelite model"""
builder = treelite.ModelBuilder(num_featu... | the_stack_v2_python_sparse | python/treelite/sklearn/rf_classifier.py | dmlc/treelite | train | 700 |
9bb2900b028b756c54ffcdb2692e445423027849 | [
"try:\n arr1 = np.asanyarray(arr1)\n arr2 = np.asanyarray(arr2)\nexcept ValueError:\n try:\n for v1, v2 in zip_longest(arr1, arr2):\n self.assertAllClose(v1, v2, rtol, atol, msg)\n except TypeError:\n if msg is None:\n msg = ''\n else:\n msg += '; '\... | <|body_start_0|>
try:
arr1 = np.asanyarray(arr1)
arr2 = np.asanyarray(arr2)
except ValueError:
try:
for v1, v2 in zip_longest(arr1, arr2):
self.assertAllClose(v1, v2, rtol, atol, msg)
except TypeError:
if... | extends the basic TestCase class with some convenience functions | TestBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBase:
"""extends the basic TestCase class with some convenience functions"""
def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None):
"""compares all the entries of the arrays a and b"""
<|body_0|>
def assertDictAllClose(self, a, b, rtol=1e-05, atol=1e... | stack_v2_sparse_classes_75kplus_train_004196 | 6,334 | permissive | [
{
"docstring": "compares all the entries of the arrays a and b",
"name": "assertAllClose",
"signature": "def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None)"
},
{
"docstring": "compares all the entries of the dictionaries a and b",
"name": "assertDictAllClose",
"signat... | 2 | stack_v2_sparse_classes_30k_train_053135 | Implement the Python class `TestBase` described below.
Class description:
extends the basic TestCase class with some convenience functions
Method signatures and docstrings:
- def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None): compares all the entries of the arrays a and b
- def assertDictAllClose... | Implement the Python class `TestBase` described below.
Class description:
extends the basic TestCase class with some convenience functions
Method signatures and docstrings:
- def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None): compares all the entries of the arrays a and b
- def assertDictAllClose... | 2afae32df4fe9609c792a3b608cad79833f4178f | <|skeleton|>
class TestBase:
"""extends the basic TestCase class with some convenience functions"""
def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None):
"""compares all the entries of the arrays a and b"""
<|body_0|>
def assertDictAllClose(self, a, b, rtol=1e-05, atol=1e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBase:
"""extends the basic TestCase class with some convenience functions"""
def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None):
"""compares all the entries of the arrays a and b"""
try:
arr1 = np.asanyarray(arr1)
arr2 = np.asanyarray(arr2)
... | the_stack_v2_python_sparse | utils/testing.py | david-zwicker/py-utils | train | 0 |
c515ecf03d1a7b6d83f1e926eee054937be4b3b9 | [
"from copy import deepcopy\nboard = deepcopy(matrix)\nif not matrix:\n return\nn = len(matrix)\nfor i in range(n):\n for j in range(n):\n matrix[i][j] = board[n - 1 - j][i]",
"for i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nfor ... | <|body_start_0|>
from copy import deepcopy
board = deepcopy(matrix)
if not matrix:
return
n = len(matrix)
for i in range(n):
for j in range(n):
matrix[i][j] = board[n - 1 - j][i]
<|end_body_0|>
<|body_start_1|>
for i in range(len(m... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_75kplus_train_004197 | 2,115 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.",
"name": "_rotate",
"signature": "def _rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _rotate(self, matrix): :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _rotate(self, matrix): :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead."""
from copy import deepcopy
board = deepcopy(matrix)
if not matrix:
return
n = len(matrix)
for i in range(n):
... | the_stack_v2_python_sparse | 48.rotate-image.py | windard/leeeeee | train | 0 | |
2109ec0f9a6635ec2f83d05135abbb1dea8c061e | [
"print('SysDict.init_builtin_dicts')\nfrom itsm.service.models import DictData\nfor builtin_dict in BUILTIN_SYSDICT_LIST:\n obj, created = self.get_or_create(defaults={'is_builtin': True, 'name': builtin_dict['name'], 'updated_by': 'system', 'creator': 'system', 'is_show': builtin_dict['is_show']}, **{'key': bui... | <|body_start_0|>
print('SysDict.init_builtin_dicts')
from itsm.service.models import DictData
for builtin_dict in BUILTIN_SYSDICT_LIST:
obj, created = self.get_or_create(defaults={'is_builtin': True, 'name': builtin_dict['name'], 'updated_by': 'system', 'creator': 'system', 'is_show'... | Datadict管理器 | SysDictManager | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SysDictManager:
"""Datadict管理器"""
def init_builtin_dicts(self, *args, **kwargs):
"""初始化内置数据字典:可重入"""
<|body_0|>
def init_change_type_from_property(self):
"""迁移变更类型到数据字典:CHANGE_TYPE"""
<|body_1|>
def init_event_type_from_property(self):
"""迁移事... | stack_v2_sparse_classes_75kplus_train_004198 | 22,611 | permissive | [
{
"docstring": "初始化内置数据字典:可重入",
"name": "init_builtin_dicts",
"signature": "def init_builtin_dicts(self, *args, **kwargs)"
},
{
"docstring": "迁移变更类型到数据字典:CHANGE_TYPE",
"name": "init_change_type_from_property",
"signature": "def init_change_type_from_property(self)"
},
{
"docstrin... | 3 | null | Implement the Python class `SysDictManager` described below.
Class description:
Datadict管理器
Method signatures and docstrings:
- def init_builtin_dicts(self, *args, **kwargs): 初始化内置数据字典:可重入
- def init_change_type_from_property(self): 迁移变更类型到数据字典:CHANGE_TYPE
- def init_event_type_from_property(self): 迁移事件类型到数据字典:CHANGE... | Implement the Python class `SysDictManager` described below.
Class description:
Datadict管理器
Method signatures and docstrings:
- def init_builtin_dicts(self, *args, **kwargs): 初始化内置数据字典:可重入
- def init_change_type_from_property(self): 迁移变更类型到数据字典:CHANGE_TYPE
- def init_event_type_from_property(self): 迁移事件类型到数据字典:CHANGE... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class SysDictManager:
"""Datadict管理器"""
def init_builtin_dicts(self, *args, **kwargs):
"""初始化内置数据字典:可重入"""
<|body_0|>
def init_change_type_from_property(self):
"""迁移变更类型到数据字典:CHANGE_TYPE"""
<|body_1|>
def init_event_type_from_property(self):
"""迁移事... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SysDictManager:
"""Datadict管理器"""
def init_builtin_dicts(self, *args, **kwargs):
"""初始化内置数据字典:可重入"""
print('SysDict.init_builtin_dicts')
from itsm.service.models import DictData
for builtin_dict in BUILTIN_SYSDICT_LIST:
obj, created = self.get_or_create(default... | the_stack_v2_python_sparse | itsm/service/managers.py | TencentBlueKing/bk-itsm | train | 100 |
a4704e7c68fc14882c59a66a444b6bf88b988269 | [
"assert icon_style in IconFactory._convert_styles\nself._view = view\nself._icon_style = icon_style\nself._icon_factory = icon_factory\nself._name = name\nself._debug = debug",
"region, color = value\nicon_path = self._icon_factory.get_icon_path(self._icon_style, color)\nregion_key = GutterIconsColorHighlighter.r... | <|body_start_0|>
assert icon_style in IconFactory._convert_styles
self._view = view
self._icon_style = icon_style
self._icon_factory = icon_factory
self._name = name
self._debug = debug
<|end_body_0|>
<|body_start_1|>
region, color = value
icon_path = sel... | A color highlighter that uses gutter icons to highlight colors. | GutterIconsColorHighlighter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_75kplus_train_004199 | 7,583 | no_license | [
{
"docstring": "Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_factory - the icon factory to create icons with. - name - the name of the color highlighter. - debug - whether to enable debug mode.",
"name": "__init__",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_004689 | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | 83d469af3fc11d1aedb5193976ef84c59b595d6c | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_facto... | the_stack_v2_python_sparse | .config/sublime-text-2/Packages/Color Highlighter/gutter_icons_color_highlighter.py | Wallkerock/X-setup | train | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.