blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
e66b5edf7e64a9edcebe7126be3999a2a283beee
[ "assert isinstance(output_size, (int, tuple, list))\nif isinstance(output_size, int):\n output_size = (output_size, output_size)\nself.output_size = output_size", "h, w = image.shape[:2]\ntarget_h, target_w = (self.output_size[0], self.output_size[1])\n(new_h, new_w), (left, right, top, bottom) = get_rescale_s...
<|body_start_0|> assert isinstance(output_size, (int, tuple, list)) if isinstance(output_size, int): output_size = (output_size, output_size) self.output_size = output_size <|end_body_0|> <|body_start_1|> h, w = image.shape[:2] target_h, target_w = (self.output_size[...
Rescale
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rescale: def __init__(self, output_size: typing.Union[int, tuple, list]): """将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸""" <|body_0|> def __call__(self, image: np.ndarray) -> np.ndarray: """对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, ...
stack_v2_sparse_classes_36k_train_014100
1,407
no_license
[ { "docstring": "将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸", "name": "__init__", "signature": "def __init__(self, output_size: typing.Union[int, tuple, list])" }, { "docstring": "对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, (h, w, 3) :return: 等比例伸缩后的图像, (h, w, 3)"...
2
stack_v2_sparse_classes_30k_train_004533
Implement the Python class `Rescale` described below. Class description: Implement the Rescale class. Method signatures and docstrings: - def __init__(self, output_size: typing.Union[int, tuple, list]): 将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸 - def __call__(self, image: np.ndarray) -> np.ndarray: 对cv...
Implement the Python class `Rescale` described below. Class description: Implement the Rescale class. Method signatures and docstrings: - def __init__(self, output_size: typing.Union[int, tuple, list]): 将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸 - def __call__(self, image: np.ndarray) -> np.ndarray: 对cv...
13030bd157a499b80d1860b8b654a66224eaf475
<|skeleton|> class Rescale: def __init__(self, output_size: typing.Union[int, tuple, list]): """将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸""" <|body_0|> def __call__(self, image: np.ndarray) -> np.ndarray: """对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rescale: def __init__(self, output_size: typing.Union[int, tuple, list]): """将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸""" assert isinstance(output_size, (int, tuple, list)) if isinstance(output_size, int): output_size = (output_size, output_size) self...
the_stack_v2_python_sparse
dataloader/enhancement/rescale.py
zheng-yuwei/PyTorch-Image-Classification
train
63
f8e4ba210ee3d6b9cbb0285a22979754e8cb58b9
[ "assert isinstance(nameRef, str), 'Invalid reference name %s' % nameRef\nassert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\nassert isinstance(invoker.doEncodePath, IDo), 'Invalid path encode %s' % invoker.doEncodePath\nself.nameRef = nameRef\nself.invoker = invoker", "assert isinstance(specifica...
<|body_start_0|> assert isinstance(nameRef, str), 'Invalid reference name %s' % nameRef assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker assert isinstance(invoker.doEncodePath, IDo), 'Invalid path encode %s' % invoker.doEncodePath self.nameRef = nameRef self.in...
Implementation for a @see: ISpecifier for paths.
AttributeModelPath
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttributeModelPath: """Implementation for a @see: ISpecifier for paths.""" def __init__(self, nameRef, invoker): """Construct the paths attributes.""" <|body_0|> def populate(self, obj, specifications, support): """@see: IAttributes.populate""" <|body_1|>...
stack_v2_sparse_classes_36k_train_014101
4,233
no_license
[ { "docstring": "Construct the paths attributes.", "name": "__init__", "signature": "def __init__(self, nameRef, invoker)" }, { "docstring": "@see: IAttributes.populate", "name": "populate", "signature": "def populate(self, obj, specifications, support)" } ]
2
null
Implement the Python class `AttributeModelPath` described below. Class description: Implementation for a @see: ISpecifier for paths. Method signatures and docstrings: - def __init__(self, nameRef, invoker): Construct the paths attributes. - def populate(self, obj, specifications, support): @see: IAttributes.populate
Implement the Python class `AttributeModelPath` described below. Class description: Implementation for a @see: ISpecifier for paths. Method signatures and docstrings: - def __init__(self, nameRef, invoker): Construct the paths attributes. - def populate(self, obj, specifications, support): @see: IAttributes.populate ...
e0b3466b34d31548996d57be4a9dac134d904380
<|skeleton|> class AttributeModelPath: """Implementation for a @see: ISpecifier for paths.""" def __init__(self, nameRef, invoker): """Construct the paths attributes.""" <|body_0|> def populate(self, obj, specifications, support): """@see: IAttributes.populate""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttributeModelPath: """Implementation for a @see: ISpecifier for paths.""" def __init__(self, nameRef, invoker): """Construct the paths attributes.""" assert isinstance(nameRef, str), 'Invalid reference name %s' % nameRef assert isinstance(invoker, Invoker), 'Invalid invoker %s' %...
the_stack_v2_python_sparse
components/ally-core-http/ally/core/http/impl/processor/encoder/model_path.py
cristidomsa/Ally-Py
train
0
24dafe0425b70530685d818c0bd49632c5d3a8aa
[ "file_metadata = {'name': file_ext}\nfolder_list = service.files().list(q=\"mimeType = 'application/vnd.google-apps.folder'\", fields='files(id,name)').execute()\nfor folder in folder_list.get('files'):\n print('folder title: %s' % str(folder))\n if folder['name'] == self.main_upload_dir:\n folder_id =...
<|body_start_0|> file_metadata = {'name': file_ext} folder_list = service.files().list(q="mimeType = 'application/vnd.google-apps.folder'", fields='files(id,name)').execute() for folder in folder_list.get('files'): print('folder title: %s' % str(folder)) if folder['name']...
This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally
ImageUtils
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageUtils: """This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally""" def uploadImage(self, file, file_ext): """This function uploads th...
stack_v2_sparse_classes_36k_train_014102
5,208
no_license
[ { "docstring": "This function uploads the image with given file extension to google drive and create an individual url which can be used to retrieve uniquely. :param file: Input Image path which needs to be uplaoded :type file: str :param file_ext: Input Image extension to upload :type file_ext: str :return: re...
2
stack_v2_sparse_classes_30k_train_013374
Implement the Python class `ImageUtils` described below. Class description: This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally Method signatures and docstrings: - def up...
Implement the Python class `ImageUtils` described below. Class description: This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally Method signatures and docstrings: - def up...
84f729b79ac8b135789ef59a332253df4aaf7878
<|skeleton|> class ImageUtils: """This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally""" def uploadImage(self, file, file_ext): """This function uploads th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageUtils: """This Class contains the function for image downlaod (downloadImage) and image upload (uploadImage) All the images are stored to /spiders/temp folder in the local and deleted after uplaoding generally""" def uploadImage(self, file, file_ext): """This function uploads the image with ...
the_stack_v2_python_sparse
revit/imageUtils.py
aghilkp91/productScrapper
train
1
41e6260b57448ad08a207a1993e53a94d9002d75
[ "self.queue = []\nself.cap = size\nself.sum = 0", "queue = self.queue\nqueue.append(val)\nself.sum += val\nif len(queue) > self.cap:\n self.sum -= queue.pop(0)\nreturn self.sum / float(len(queue))" ]
<|body_start_0|> self.queue = [] self.cap = size self.sum = 0 <|end_body_0|> <|body_start_1|> queue = self.queue queue.append(val) self.sum += val if len(queue) > self.cap: self.sum -= queue.pop(0) return self.sum / float(len(queue)) <|end_bod...
87%.
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: """87%.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.queue = [] ...
stack_v2_sparse_classes_36k_train_014103
1,648
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_007299
Implement the Python class `MovingAverage` described below. Class description: 87%. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: 87%. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: """87%.""" def __init__...
d634941087bc51869f43c0d8044db09b7bdbaf58
<|skeleton|> class MovingAverage: """87%.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: """87%.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" self.queue = [] self.cap = size self.sum = 0 def next(self, val): """:type val: int :rtype: float""" queue = self.queue queue.append(...
the_stack_v2_python_sparse
346_Moving_Average_from_Data_Stream.py
susunini/leetcode
train
1
0d7435c9c3f78fea8212d02288beb662458c31ff
[ "events = get_list_or_404(Event)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(events, request)\n serializer = EventSerializer(results, many=True)\n...
<|body_start_0|> events = get_list_or_404(Event) if request.GET.get('pagination'): pagination = request.GET.get('pagination') if pagination == 'true': paginator = AdministratorPagination() results = paginator.paginate_queryset(events, request) ...
EventList
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventList: def get(self, request, format=None): """List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string paramType: query""" <|body_0|> def post(self, request, format=None): """Create new...
stack_v2_sparse_classes_36k_train_014104
30,608
permissive
[ { "docstring": "List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string paramType: query", "name": "get", "signature": "def get(self, request, format=None)" }, { "docstring": "Create new event --- serializer: administr...
2
stack_v2_sparse_classes_30k_train_000869
Implement the Python class `EventList` described below. Class description: Implement the EventList class. Method signatures and docstrings: - def get(self, request, format=None): List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string param...
Implement the Python class `EventList` described below. Class description: Implement the EventList class. Method signatures and docstrings: - def get(self, request, format=None): List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string param...
73728463badb3bfd4413aa0f7aeb44a9606fdfea
<|skeleton|> class EventList: def get(self, request, format=None): """List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string paramType: query""" <|body_0|> def post(self, request, format=None): """Create new...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventList: def get(self, request, format=None): """List all events --- serializer: administrator.serializers.EventSerializer parameters: - name: pagination required: false type: string paramType: query""" events = get_list_or_404(Event) if request.GET.get('pagination'): pag...
the_stack_v2_python_sparse
administrator/views.py
belatrix/BackendAllStars
train
5
b118f558b174ec499dc5d820ac8aaffe6520cc55
[ "self.exploration_vs_exploitation = exploration_vs_exploitation\nself.decomposition_funcs = decomposition_funcs\nself.preprocessors = preprocessors\nself.nbits = nbits\nself.seed = seed\nself.estimators = [SGDRegressor(penalty='elasticnet') for _ in range(n_estimators)]", "coefs = [est.coef_ for est in self.estim...
<|body_start_0|> self.exploration_vs_exploitation = exploration_vs_exploitation self.decomposition_funcs = decomposition_funcs self.preprocessors = preprocessors self.nbits = nbits self.seed = seed self.estimators = [SGDRegressor(penalty='elasticnet') for _ in range(n_est...
ScoreEstimator.
GraphLinearScoreEstimator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphLinearScoreEstimator: """ScoreEstimator.""" def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1): """init.""" <|body_0|> def predict_gradient(self, graphs): """predict_gradient.""...
stack_v2_sparse_classes_36k_train_014105
21,013
permissive
[ { "docstring": "init.", "name": "__init__", "signature": "def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1)" }, { "docstring": "predict_gradient.", "name": "predict_gradient", "signature": "def predict_grad...
2
stack_v2_sparse_classes_30k_train_015083
Implement the Python class `GraphLinearScoreEstimator` described below. Class description: ScoreEstimator. Method signatures and docstrings: - def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1): init. - def predict_gradient(self, graphs)...
Implement the Python class `GraphLinearScoreEstimator` described below. Class description: ScoreEstimator. Method signatures and docstrings: - def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1): init. - def predict_gradient(self, graphs)...
d89e88183cce1ff24dca9333c09fa11597a45c7a
<|skeleton|> class GraphLinearScoreEstimator: """ScoreEstimator.""" def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1): """init.""" <|body_0|> def predict_gradient(self, graphs): """predict_gradient.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphLinearScoreEstimator: """ScoreEstimator.""" def __init__(self, n_estimators=100, exploration_vs_exploitation=0, decomposition_funcs=None, preprocessors=None, nbits=14, seed=1): """init.""" self.exploration_vs_exploitation = exploration_vs_exploitation self.decomposition_funcs...
the_stack_v2_python_sparse
ego/optimization/score_estimator.py
smautner/EGO
train
0
b02a7c9404615481db2f8b5f10b31b537ee45e33
[ "if config is None:\n self.parser = spectraHeaderParser()\nelse:\n self.parser = spectraHeaderParser(config)\nself.xsdt = xsdTraverse(xsdDir)", "tree = etree.parse(xmlDir)\nheaderNodes = tree.findall('.//headers')\nfor headerNode in headerNodes:\n node = headerNode.getparent().getparent()\n xpath = tr...
<|body_start_0|> if config is None: self.parser = spectraHeaderParser() else: self.parser = spectraHeaderParser(config) self.xsdt = xsdTraverse(xsdDir) <|end_body_0|> <|body_start_1|> tree = etree.parse(xmlDir) headerNodes = tree.findall('.//headers') ...
spectraHeaderParserForXML
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class spectraHeaderParserForXML: def __init__(self, xsdDir, config=None): """:param xsdDir: path to the xsd schema file :type xsdDir: str""" <|body_0|> def runOnXML(self, xmlDir, createCopy=False): """Parse an xml file into an lxml.etree object, finds elements for spectra ...
stack_v2_sparse_classes_36k_train_014106
4,183
no_license
[ { "docstring": ":param xsdDir: path to the xsd schema file :type xsdDir: str", "name": "__init__", "signature": "def __init__(self, xsdDir, config=None)" }, { "docstring": "Parse an xml file into an lxml.etree object, finds elements for spectra data, reads the xpath and header information, calls...
2
stack_v2_sparse_classes_30k_train_005420
Implement the Python class `spectraHeaderParserForXML` described below. Class description: Implement the spectraHeaderParserForXML class. Method signatures and docstrings: - def __init__(self, xsdDir, config=None): :param xsdDir: path to the xsd schema file :type xsdDir: str - def runOnXML(self, xmlDir, createCopy=Fa...
Implement the Python class `spectraHeaderParserForXML` described below. Class description: Implement the spectraHeaderParserForXML class. Method signatures and docstrings: - def __init__(self, xsdDir, config=None): :param xsdDir: path to the xsd schema file :type xsdDir: str - def runOnXML(self, xmlDir, createCopy=Fa...
1c5808640914c45bbbbe2601f2a06f8ca52953dd
<|skeleton|> class spectraHeaderParserForXML: def __init__(self, xsdDir, config=None): """:param xsdDir: path to the xsd schema file :type xsdDir: str""" <|body_0|> def runOnXML(self, xmlDir, createCopy=False): """Parse an xml file into an lxml.etree object, finds elements for spectra ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class spectraHeaderParserForXML: def __init__(self, xsdDir, config=None): """:param xsdDir: path to the xsd schema file :type xsdDir: str""" if config is None: self.parser = spectraHeaderParser() else: self.parser = spectraHeaderParser(config) self.xsdt = xsdT...
the_stack_v2_python_sparse
src/jobs/XMLCONV/code_src/spectraHeaderParserForXML.py
Duke-MatSci/nanomine
train
15
a3baa22307cf1f2b3fe36efffea78c0dc62ea697
[ "assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.RidgeRegressionModel(_py2java(sc, self._coeff), self.intercept)\njava_model.save(sc._jsc.sc(), path)", "assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.RidgeRegressionModel.load(sc._jsc.sc(), pat...
<|body_start_0|> assert sc._jvm is not None java_model = sc._jvm.org.apache.spark.mllib.regression.RidgeRegressionModel(_py2java(sc, self._coeff), self.intercept) java_model.save(sc._jsc.sc(), path) <|end_body_0|> <|body_start_1|> assert sc._jvm is not None java_model = sc._jvm....
A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, [1.0]), ... LabeledPoint...
RidgeRegressionModel
[ "BSD-3-Clause", "CC0-1.0", "CDDL-1.1", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "EPL-2.0", "CDDL-1.0", "MIT", "LGPL-2.0-or-later", "Python-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown",...
stack_v2_sparse_python_classes_v1
<|skeleton|> class RidgeRegressionModel: """A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0])...
stack_v2_sparse_classes_36k_train_014107
36,577
permissive
[ { "docstring": "Save a RidgeRegressionMode.", "name": "save", "signature": "def save(self, sc: SparkContext, path: str) -> None" }, { "docstring": "Load a RidgeRegressionMode.", "name": "load", "signature": "def load(cls, sc: SparkContext, path: str) -> 'RidgeRegressionModel'" } ]
2
null
Implement the Python class `RidgeRegressionModel` described below. Class description: A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>...
Implement the Python class `RidgeRegressionModel` described below. Class description: A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>...
60d8fc49bec5dae1b8cf39a0670cb640b430f520
<|skeleton|> class RidgeRegressionModel: """A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0])...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RidgeRegressionModel: """A linear regression model derived from a least-squares fit with an l_2 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... Labeled...
the_stack_v2_python_sparse
python/pyspark/mllib/regression.py
apache/spark
train
39,983
595ec60b2bb03b434ba50714ec0217bade080bba
[ "try:\n comment_id = ObjectId(comment_id)\n comment = Comment.objects.get(pk=comment_id)\nexcept InvalidId as e:\n return ErrorResponse(e.message)\nexcept:\n return ErrorResponse(\"Comment doesn't exists\")\nif config.DEBUG:\n print('comment id : {0}'.format(comment_id))\nresults = dict()\nresults['c...
<|body_start_0|> try: comment_id = ObjectId(comment_id) comment = Comment.objects.get(pk=comment_id) except InvalidId as e: return ErrorResponse(e.message) except: return ErrorResponse("Comment doesn't exists") if config.DEBUG: ...
CommentResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentResource: def get(self, comment_id): """GET handler for the request /comments/{id} Return all details for the comment {id}""" <|body_0|> def delete(self, comment_id): """DELETE handler for the request /comments/{id} Delete the comment {id}""" <|body_1|...
stack_v2_sparse_classes_36k_train_014108
4,940
no_license
[ { "docstring": "GET handler for the request /comments/{id} Return all details for the comment {id}", "name": "get", "signature": "def get(self, comment_id)" }, { "docstring": "DELETE handler for the request /comments/{id} Delete the comment {id}", "name": "delete", "signature": "def dele...
2
stack_v2_sparse_classes_30k_train_008850
Implement the Python class `CommentResource` described below. Class description: Implement the CommentResource class. Method signatures and docstrings: - def get(self, comment_id): GET handler for the request /comments/{id} Return all details for the comment {id} - def delete(self, comment_id): DELETE handler for the...
Implement the Python class `CommentResource` described below. Class description: Implement the CommentResource class. Method signatures and docstrings: - def get(self, comment_id): GET handler for the request /comments/{id} Return all details for the comment {id} - def delete(self, comment_id): DELETE handler for the...
eff4a90312885495ccb3ecec5c78a94fc058feca
<|skeleton|> class CommentResource: def get(self, comment_id): """GET handler for the request /comments/{id} Return all details for the comment {id}""" <|body_0|> def delete(self, comment_id): """DELETE handler for the request /comments/{id} Delete the comment {id}""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentResource: def get(self, comment_id): """GET handler for the request /comments/{id} Return all details for the comment {id}""" try: comment_id = ObjectId(comment_id) comment = Comment.objects.get(pk=comment_id) except InvalidId as e: return Err...
the_stack_v2_python_sparse
wingo/resources/comments.py
dridk/wingo-server
train
0
d0a54b39fed77226579e8a12690d2c2a161cdf6d
[ "if dict_type == self.STOP_WORDS:\n f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8')\nelse:\n f = codecs.open(self.COMPONENT_FILE, 'r', 'utf-8')\nif f:\n content = f.read()\n content = content.replace('\\r\\n', ' ')\n kw_list = content.split(' ')\n try:\n kw_list.remove('')\n except Va...
<|body_start_0|> if dict_type == self.STOP_WORDS: f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8') else: f = codecs.open(self.COMPONENT_FILE, 'r', 'utf-8') if f: content = f.read() content = content.replace('\r\n', ' ') kw_list = cont...
更新词库
UpdateKw
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateKw: """更新词库""" def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): """从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库""" <|body_0|> def read_kw(self, kw_tb='kw_search'): """从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的...
stack_v2_sparse_classes_36k_train_014109
5,771
no_license
[ { "docstring": "从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库", "name": "update_dict", "signature": "def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS)" }, { "docstring": "从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的时候,从kw表中读取,否则从kw_search表中读取", "nam...
2
stack_v2_sparse_classes_30k_train_002259
Implement the Python class `UpdateKw` described below. Class description: 更新词库 Method signatures and docstrings: - def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): 从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库 - def read_kw(self, kw_tb='kw_search'): 从kw表或者kw_search表中读...
Implement the Python class `UpdateKw` described below. Class description: 更新词库 Method signatures and docstrings: - def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): 从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库 - def read_kw(self, kw_tb='kw_search'): 从kw表或者kw_search表中读...
0288830d0b5d48e6037ae852ec69aa94dcfa9cf3
<|skeleton|> class UpdateKw: """更新词库""" def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): """从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库""" <|body_0|> def read_kw(self, kw_tb='kw_search'): """从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateKw: """更新词库""" def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): """从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库""" if dict_type == self.STOP_WORDS: f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8') else: ...
the_stack_v2_python_sparse
jieba/kwtb.py
jeawy/comment
train
0
e4b91303ab3dffd8ed7f37cb61d125e50448b183
[ "self.input_dim = input_dim\nself.output_dim = output_dim\nself.act_func = act_func\nself.name_W = name_W\nself.name_b = name_b\nself.W = tf.Variable(rng.uniform(low=-0.08, high=0.08, size=(input_dim, output_dim)).astype('float32'), name=name_W)\nself.b = tf.Variable(rng.uniform(low=-0.08, high=0.08, size=output_di...
<|body_start_0|> self.input_dim = input_dim self.output_dim = output_dim self.act_func = act_func self.name_W = name_W self.name_b = name_b self.W = tf.Variable(rng.uniform(low=-0.08, high=0.08, size=(input_dim, output_dim)).astype('float32'), name=name_W) self.b ...
Drop layer class NOTE: This is not implemented. DO NOT USE this class.
Drop
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Drop: """Drop layer class NOTE: This is not implemented. DO NOT USE this class.""" def __init__(self, input_dim, output_dim, act_func, name_W, name_b): """:param input_dim : int, input dimension :param output_dim : int, output dimension :param act_func : function, actimation function...
stack_v2_sparse_classes_36k_train_014110
2,750
permissive
[ { "docstring": ":param input_dim : int, input dimension :param output_dim : int, output dimension :param act_func : function, actimation function :param name_W : str, weight name :param name_b : str, bias name", "name": "__init__", "signature": "def __init__(self, input_dim, output_dim, act_func, name_W...
2
stack_v2_sparse_classes_30k_train_006650
Implement the Python class `Drop` described below. Class description: Drop layer class NOTE: This is not implemented. DO NOT USE this class. Method signatures and docstrings: - def __init__(self, input_dim, output_dim, act_func, name_W, name_b): :param input_dim : int, input dimension :param output_dim : int, output ...
Implement the Python class `Drop` described below. Class description: Drop layer class NOTE: This is not implemented. DO NOT USE this class. Method signatures and docstrings: - def __init__(self, input_dim, output_dim, act_func, name_W, name_b): :param input_dim : int, input dimension :param output_dim : int, output ...
ad8e050cd754e5a1c73ed5df3bc223a1f6dc4148
<|skeleton|> class Drop: """Drop layer class NOTE: This is not implemented. DO NOT USE this class.""" def __init__(self, input_dim, output_dim, act_func, name_W, name_b): """:param input_dim : int, input dimension :param output_dim : int, output dimension :param act_func : function, actimation function...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Drop: """Drop layer class NOTE: This is not implemented. DO NOT USE this class.""" def __init__(self, input_dim, output_dim, act_func, name_W, name_b): """:param input_dim : int, input dimension :param output_dim : int, output dimension :param act_func : function, actimation function :param name_...
the_stack_v2_python_sparse
neuralnet/fine-tuning_transfer-learning/src/modeldev/d_layer.py
hsmtknj/machine-learning
train
0
0c4a8665bf265700b784fc92ff6fb8562580d2d4
[ "self.cur_sum = 0\nself.queue = collections.deque()\nself.size = size", "self.cur_sum += val\nself.queue.append(val)\nif len(self.queue) > self.size:\n self.cur_sum -= self.queue.popleft()\nreturn self.cur_sum / len(self.queue)" ]
<|body_start_0|> self.cur_sum = 0 self.queue = collections.deque() self.size = size <|end_body_0|> <|body_start_1|> self.cur_sum += val self.queue.append(val) if len(self.queue) > self.size: self.cur_sum -= self.queue.popleft() return self.cur_sum / l...
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: """Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type va...
stack_v2_sparse_classes_36k_train_014111
683
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
null
Implement the Python class `MovingAverage` described below. Class description: Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next...
Implement the Python class `MovingAverage` described below. Class description: Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next...
2536744423ee9dc7da30e739eb0bca521c216f00
<|skeleton|> class MovingAverage: """Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type va...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: """Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.""" def __init__(self, size): """Initialize your data structure here. :type size: int""" self.cur_sum = 0 self.queue = collections.deque() sel...
the_stack_v2_python_sparse
Design/346_Moving_average_from_data_stream.py
Rishabhh/LeetCode-Solutions
train
0
fb32b1668a8b5f0ca3ee202a5d6e87a0f2119108
[ "truck_capacity = 0\nfor vehicle_type in ModeOfTransport.get_scheduled_vehicles():\n number_of_containers_delivered_to_terminal_by_vehicle_type = inbound_capacity_of_vehicles[vehicle_type]\n mode_of_transport_distribution_of_vehicle_type = ModeOfTransportDistributionRepository().get_distribution()[vehicle_typ...
<|body_start_0|> truck_capacity = 0 for vehicle_type in ModeOfTransport.get_scheduled_vehicles(): number_of_containers_delivered_to_terminal_by_vehicle_type = inbound_capacity_of_vehicles[vehicle_type] mode_of_transport_distribution_of_vehicle_type = ModeOfTransportDistributionRe...
InboundAndOutboundVehicleCapacityCalculatorService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InboundAndOutboundVehicleCapacityCalculatorService: def get_truck_capacity_for_export_containers(inbound_capacity_of_vehicles: Dict[ModeOfTransport, float]) -> float: """Get the capacity in TEU which is transported by truck. Currently, during the generation process each import container ...
stack_v2_sparse_classes_36k_train_014112
8,656
permissive
[ { "docstring": "Get the capacity in TEU which is transported by truck. Currently, during the generation process each import container is picked up by one truck and for each import container, in the next step one export container is created. Thus, this method accounts for both import and export.", "name": "g...
3
null
Implement the Python class `InboundAndOutboundVehicleCapacityCalculatorService` described below. Class description: Implement the InboundAndOutboundVehicleCapacityCalculatorService class. Method signatures and docstrings: - def get_truck_capacity_for_export_containers(inbound_capacity_of_vehicles: Dict[ModeOfTranspor...
Implement the Python class `InboundAndOutboundVehicleCapacityCalculatorService` described below. Class description: Implement the InboundAndOutboundVehicleCapacityCalculatorService class. Method signatures and docstrings: - def get_truck_capacity_for_export_containers(inbound_capacity_of_vehicles: Dict[ModeOfTranspor...
f348838d1fd235c586384e067beaba8f630bc572
<|skeleton|> class InboundAndOutboundVehicleCapacityCalculatorService: def get_truck_capacity_for_export_containers(inbound_capacity_of_vehicles: Dict[ModeOfTransport, float]) -> float: """Get the capacity in TEU which is transported by truck. Currently, during the generation process each import container ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InboundAndOutboundVehicleCapacityCalculatorService: def get_truck_capacity_for_export_containers(inbound_capacity_of_vehicles: Dict[ModeOfTransport, float]) -> float: """Get the capacity in TEU which is transported by truck. Currently, during the generation process each import container is picked up b...
the_stack_v2_python_sparse
conflowgen/application/services/inbound_and_outbound_vehicle_capacity_calculator_service.py
1kastner/conflowgen
train
10
8105971ae453db6f1c5db9f213d74794841d9f51
[ "self.dataset = dataset\nself.k = k\nself.num = len(dataset)\nself.distance_func = distance_func\nself.mean_func = mean_func\nself.centroids = [None] * k\nself.group = np.array([0] * self.num)\nself.in_class_distance = 10000000000.0", "if method == 'k-means++':\n self.k_means_plus_init()\nelif method == 'k-mea...
<|body_start_0|> self.dataset = dataset self.k = k self.num = len(dataset) self.distance_func = distance_func self.mean_func = mean_func self.centroids = [None] * k self.group = np.array([0] * self.num) self.in_class_distance = 10000000000.0 <|end_body_0|>...
k-means算法
KMeans
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KMeans: """k-means算法""" def __init__(self, dataset, k, distance_func, mean_func): """k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数""" <|body_0|> def cluster(self, iter_total, loss_delta_thresh=1e-13, method='k-me...
stack_v2_sparse_classes_36k_train_014113
3,905
permissive
[ { "docstring": "k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数", "name": "__init__", "signature": "def __init__(self, dataset, k, distance_func, mean_func)" }, { "docstring": "初始化聚类中心 :param iter_total: 迭代计算聚类中心次数 :param loss_delta_thresh...
3
stack_v2_sparse_classes_30k_train_020894
Implement the Python class `KMeans` described below. Class description: k-means算法 Method signatures and docstrings: - def __init__(self, dataset, k, distance_func, mean_func): k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数 - def cluster(self, iter_total, loss_...
Implement the Python class `KMeans` described below. Class description: k-means算法 Method signatures and docstrings: - def __init__(self, dataset, k, distance_func, mean_func): k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数 - def cluster(self, iter_total, loss_...
8f2d722e4067aef0c8a9cc29f76d958c0f97fb9f
<|skeleton|> class KMeans: """k-means算法""" def __init__(self, dataset, k, distance_func, mean_func): """k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数""" <|body_0|> def cluster(self, iter_total, loss_delta_thresh=1e-13, method='k-me...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KMeans: """k-means算法""" def __init__(self, dataset, k, distance_func, mean_func): """k-means算法数据初始化 :param dataset:待聚类数据 :param k:中心点数量 :param distance_func: 距离计算函数 :param mean_func: 均值计算函数""" self.dataset = dataset self.k = k self.num = len(dataset) self.distance_...
the_stack_v2_python_sparse
utils/anchors/kmeans.py
zheng-yuwei/YOLOv3-tensorflow
train
5
329dc640538ece254f24bf1df4ba3ce6eb26349c
[ "distance, p1, p2 = (sys.maxint, -1, -1)\nfor i in range(len(words)):\n if words[i] == word1:\n p1 = i\n if words[i] == word2:\n if word1 == word2:\n p1 = p2\n p2 = i\n if p1 != -1 and p2 != -1:\n distance = min(distance, abs(p1 - p2))\nreturn distance", "if not wor...
<|body_start_0|> distance, p1, p2 = (sys.maxint, -1, -1) for i in range(len(words)): if words[i] == word1: p1 = i if words[i] == word2: if word1 == word2: p1 = p2 p2 = i if p1 != -1 and p2 != -1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def shortestWordDistanceBetter(self, words, word1, word2): """:type words: List[str] :type word1: str :type word2: str :rtype: int""" <|body_0|> def shortestWordDistance(self, words, word1, word2): """:type words: List[str] :type word1: str :type word2: str...
stack_v2_sparse_classes_36k_train_014114
1,574
no_license
[ { "docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int", "name": "shortestWordDistanceBetter", "signature": "def shortestWordDistanceBetter(self, words, word1, word2)" }, { "docstring": ":type words: List[str] :type word1: str :type word2: str :rtype: int", "nam...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestWordDistanceBetter(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int - def shortestWordDistance(self, words, word1, wor...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def shortestWordDistanceBetter(self, words, word1, word2): :type words: List[str] :type word1: str :type word2: str :rtype: int - def shortestWordDistance(self, words, word1, wor...
26e2a812d86b4c09b2917d983df76d3ece69b074
<|skeleton|> class Solution: def shortestWordDistanceBetter(self, words, word1, word2): """:type words: List[str] :type word1: str :type word2: str :rtype: int""" <|body_0|> def shortestWordDistance(self, words, word1, word2): """:type words: List[str] :type word1: str :type word2: str...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def shortestWordDistanceBetter(self, words, word1, word2): """:type words: List[str] :type word1: str :type word2: str :rtype: int""" distance, p1, p2 = (sys.maxint, -1, -1) for i in range(len(words)): if words[i] == word1: p1 = i if wo...
the_stack_v2_python_sparse
HashTable/ShortestWordDistance.py
YusiZhang/leetcode-python
train
1
14aca97ebde202990241251b24c982d52a548fc4
[ "self.is_training = is_training\nself.data_tools = Data()\nself.words_len = self.data_tools.words_len\nself.build_model()\nself.init_sess(tf.train.latest_checkpoint('model/tfmodel'))", "self.graph = tf.Graph()\ncell_fn = tf.nn.rnn_cell.BasicRNNCell()\nn_layer = 2\nhidden_size = 128\nwith self.graph.as_default():\...
<|body_start_0|> self.is_training = is_training self.data_tools = Data() self.words_len = self.data_tools.words_len self.build_model() self.init_sess(tf.train.latest_checkpoint('model/tfmodel')) <|end_body_0|> <|body_start_1|> self.graph = tf.Graph() cell_fn = tf...
分词模型中使用双向RNN模型进行处理
Model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """分词模型中使用双向RNN模型进行处理""" def __init__(self, is_training=True): """初始化类""" <|body_0|> def build_model(self): """构建计算图""" <|body_1|> def init_sess(self, restore=None): """初始化会话""" <|body_2|> def train(self): """训练函数"...
stack_v2_sparse_classes_36k_train_014115
8,430
no_license
[ { "docstring": "初始化类", "name": "__init__", "signature": "def __init__(self, is_training=True)" }, { "docstring": "构建计算图", "name": "build_model", "signature": "def build_model(self)" }, { "docstring": "初始化会话", "name": "init_sess", "signature": "def init_sess(self, restore=...
5
stack_v2_sparse_classes_30k_train_020069
Implement the Python class `Model` described below. Class description: 分词模型中使用双向RNN模型进行处理 Method signatures and docstrings: - def __init__(self, is_training=True): 初始化类 - def build_model(self): 构建计算图 - def init_sess(self, restore=None): 初始化会话 - def train(self): 训练函数 - def predict(self, txt): 预测函数 sess, 通过将sess设置为实例变量...
Implement the Python class `Model` described below. Class description: 分词模型中使用双向RNN模型进行处理 Method signatures and docstrings: - def __init__(self, is_training=True): 初始化类 - def build_model(self): 构建计算图 - def init_sess(self, restore=None): 初始化会话 - def train(self): 训练函数 - def predict(self, txt): 预测函数 sess, 通过将sess设置为实例变量...
28247627eab50613c1a5bf67f70e979a0a9eecb2
<|skeleton|> class Model: """分词模型中使用双向RNN模型进行处理""" def __init__(self, is_training=True): """初始化类""" <|body_0|> def build_model(self): """构建计算图""" <|body_1|> def init_sess(self, restore=None): """初始化会话""" <|body_2|> def train(self): """训练函数"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Model: """分词模型中使用双向RNN模型进行处理""" def __init__(self, is_training=True): """初始化类""" self.is_training = is_training self.data_tools = Data() self.words_len = self.data_tools.words_len self.build_model() self.init_sess(tf.train.latest_checkpoint('model/tfmodel')...
the_stack_v2_python_sparse
b2_rnn/text_rnn/12_text_segment_log_device.py
Gilbert-Gb-Li/Artificial-Intelligence
train
0
c67758c8c1b703c11caf0955d82095fcaa4273bb
[ "def foder(root, left):\n if not root:\n return\n left.append(str(root.val))\n foder(root.left, left)\n foder(root.right, left)\n\ndef inorder(root, mid):\n if not root:\n return\n inorder(root.left, mid)\n mid.append(str(root.val))\n inorder(root.right, mid)\nleft = []\nmid = ...
<|body_start_0|> def foder(root, left): if not root: return left.append(str(root.val)) foder(root.left, left) foder(root.right, left) def inorder(root, mid): if not root: return inorder(root.left, mi...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_014116
4,836
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
690adf05774a1c500d6c9160223dab7bcc38ccc1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def foder(root, left): if not root: return left.append(str(root.val)) foder(root.left, left) foder(root.right, left) ...
the_stack_v2_python_sparse
297. Serialize and Deserialize Binary Tree.py
supersj/LeetCode
train
2
a3e920255d5f799064803e7f1d1f43869648e130
[ "if not nums:\n return None\nspring = nums\nself.count = [None] * len(spring)\nself.count[0] = spring[0]\nfor k in range(1, len(spring)):\n self.count[k] = self.count[k - 1] + spring[k]", "if i == 0:\n return self.count[j]\nelse:\n return self.count[j] - self.count[i - 1]" ]
<|body_start_0|> if not nums: return None spring = nums self.count = [None] * len(spring) self.count[0] = spring[0] for k in range(1, len(spring)): self.count[k] = self.count[k - 1] + spring[k] <|end_body_0|> <|body_start_1|> if i == 0: ...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return None spring = nums ...
stack_v2_sparse_classes_36k_train_014117
882
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, i, j)" } ]
2
stack_v2_sparse_classes_30k_train_013110
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int <|skeleton|> class NumArray: def __init__(self, nums): ...
769d89efc97e43b85b8b36d80dfb75f2fcf173fc
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumArray: def __init__(self, nums): """:type nums: List[int]""" if not nums: return None spring = nums self.count = [None] * len(spring) self.count[0] = spring[0] for k in range(1, len(spring)): self.count[k] = self.count[k - 1] + spring[...
the_stack_v2_python_sparse
303_range_sum_query_immutable.py
Rainphix/LeetCode
train
0
41c1af81bdde394de10b6e9022d457c877dab05f
[ "self.samplers = []\nfor balancerPar in samplers:\n balancerPar[1]['randState'] = 0\n if self.randomUnderSampling == balancerPar[0]:\n self.samplers.append(RandomUnderSampling(**balancerPar[1]))\n elif self.randomOverSampling == balancerPar[0]:\n self.samplers.append(RandomOverSampling(**bala...
<|body_start_0|> self.samplers = [] for balancerPar in samplers: balancerPar[1]['randState'] = 0 if self.randomUnderSampling == balancerPar[0]: self.samplers.append(RandomUnderSampling(**balancerPar[1])) elif self.randomOverSampling == balancerPar[0]: ...
Třída pro vyvažování nevyvážených dat.
Balancing
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Balancing: """Třída pro vyvažování nevyvážených dat.""" def __init__(self, samplers): """Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny. Metodu reprezentuje (název metody, parametry) :raise Ba...
stack_v2_sparse_classes_36k_train_014118
6,657
no_license
[ { "docstring": "Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny. Metodu reprezentuje (název metody, parametry) :raise BalancingInvalidBalancingMethod: Při nevalidním názvu balancovací metody.", "name": "__init__", ...
2
stack_v2_sparse_classes_30k_test_000442
Implement the Python class `Balancing` described below. Class description: Třída pro vyvažování nevyvážených dat. Method signatures and docstrings: - def __init__(self, samplers): Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny...
Implement the Python class `Balancing` described below. Class description: Třída pro vyvažování nevyvážených dat. Method signatures and docstrings: - def __init__(self, samplers): Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny...
4e5395875d60ed3b138922d1100f6a4e05ac60e7
<|skeleton|> class Balancing: """Třída pro vyvažování nevyvážených dat.""" def __init__(self, samplers): """Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny. Metodu reprezentuje (název metody, parametry) :raise Ba...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Balancing: """Třída pro vyvažování nevyvážených dat.""" def __init__(self, samplers): """Nastavení metod pro vyvažování. :param samplers: list -- Obsahující metody vyvažování. Budou použity v pořadí v jakém jsou v listu uvedeny. Metodu reprezentuje (název metody, parametry) :raise BalancingInvali...
the_stack_v2_python_sparse
CPKclassifierPack/balancing/Balancing.py
KNOT-FIT-BUT/CPKclassifier
train
1
2289e727b6a0d1ed455c00bc1473dedac23a6eee
[ "if data is None:\n if n <= 0:\n raise ValueError('n must be a positive value')\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n self.n = int(n)\n self.p = float(p)\nelse:\n if not isinstance(data, list):\n raise TypeError('data must be a li...
<|body_start_0|> if data is None: if n <= 0: raise ValueError('n must be a positive value') if p <= 0 or p >= 1: raise ValueError('p must be greater than 0 and less than 1') self.n = int(n) self.p = float(p) else: ...
class Binomial
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" <|body_0|> def pmf(self, k): """calculates mass function""" <|body_1|> def cdf(self, k): """calculate CDF function""" <|body_2|> def fact...
stack_v2_sparse_classes_36k_train_014119
1,641
no_license
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "calculates mass function", "name": "pmf", "signature": "def pmf(self, k)" }, { "docstring": "calculate CDF function", "name": "cdf", "signature": ...
4
stack_v2_sparse_classes_30k_train_015045
Implement the Python class `Binomial` described below. Class description: class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): constructor - def pmf(self, k): calculates mass function - def cdf(self, k): calculate CDF function - def factorial(self, x): calculate factorial x
Implement the Python class `Binomial` described below. Class description: class Binomial Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): constructor - def pmf(self, k): calculates mass function - def cdf(self, k): calculate CDF function - def factorial(self, x): calculate factorial x <...
ff1af62484620b599cc3813068770db03b37036d
<|skeleton|> class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" <|body_0|> def pmf(self, k): """calculates mass function""" <|body_1|> def cdf(self, k): """calculate CDF function""" <|body_2|> def fact...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binomial: """class Binomial""" def __init__(self, data=None, n=1, p=0.5): """constructor""" if data is None: if n <= 0: raise ValueError('n must be a positive value') if p <= 0 or p >= 1: raise ValueError('p must be greater than 0 an...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
paurbano/holbertonschool-machine_learning
train
0
5bd03de74ff65b1a2028820b43b512869fc12818
[ "self.net = net\nself.optim = optim\nself.best_loss = 1000000000.0\nsetattr(self.optim, 'net', self.net)", "assert X.shape[0] == y.shape[0], '\\n 특징과 목푯값은 행의 수가 같아야 하는데,\\n 특징은 {0}행, 목푯값은 {1}행이다\\n '.format(X.shape[0], y.shape[0])\nN = X.shape[0]\nfor ii in range(0, N, size):\n X_batch, y_...
<|body_start_0|> self.net = net self.optim = optim self.best_loss = 1000000000.0 setattr(self.optim, 'net', self.net) <|end_body_0|> <|body_start_1|> assert X.shape[0] == y.shape[0], '\n 특징과 목푯값은 행의 수가 같아야 하는데,\n 특징은 {0}행, 목푯값은 {1}행이다\n '.format(X.shape[0], ...
신경망 모델을 학습시키는 역할을 수행함
Trainer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trainer: """신경망 모델을 학습시키는 역할을 수행함""" def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None: """학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것""" <|body_0|> def generate_batches(self, X: ndarray, y: ndarray, size: int=...
stack_v2_sparse_classes_36k_train_014120
4,073
permissive
[ { "docstring": "학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것", "name": "__init__", "signature": "def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None" }, { "docstring": "배치 생성", "name": "generate_batches", "signature": "def generat...
3
stack_v2_sparse_classes_30k_train_004974
Implement the Python class `Trainer` described below. Class description: 신경망 모델을 학습시키는 역할을 수행함 Method signatures and docstrings: - def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None: 학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것 - def generate_batches(self, X:...
Implement the Python class `Trainer` described below. Class description: 신경망 모델을 학습시키는 역할을 수행함 Method signatures and docstrings: - def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None: 학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것 - def generate_batches(self, X:...
07b559b95f8f658303ee53114107ae35940a6080
<|skeleton|> class Trainer: """신경망 모델을 학습시키는 역할을 수행함""" def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None: """학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것""" <|body_0|> def generate_batches(self, X: ndarray, y: ndarray, size: int=...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trainer: """신경망 모델을 학습시키는 역할을 수행함""" def __init__(self, net: NeuralNetwork, optim: Optimizer) -> None: """학습을 수행하려면 NeuralNetwork, Optimizer 객체가 필요함 Optimizer 객체의 인스턴스 변수로 NeuralNetwork 객체를 전달할 것""" self.net = net self.optim = optim self.best_loss = 1000000000.0 se...
the_stack_v2_python_sparse
2.Model Implementation/0. DNN/jskim_DNN/train.py
jskim0406/Study
train
0
e40f5025c78cf16e3e0fae8e3f3c588fc5fe2a36
[ "self.active_sessions = active_sessions\nself.file_path = file_path\nself.view_id = view_id\nself.view_name = view_name", "if dictionary is None:\n return None\nactive_sessions = None\nif dictionary.get('activeSessions') != None:\n active_sessions = list()\n for structure in dictionary.get('activeSession...
<|body_start_0|> self.active_sessions = active_sessions self.file_path = file_path self.view_id = view_id self.view_name = view_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None active_sessions = None if dictionary.get('activeSes...
Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the view. view_id (long|int): Specifies the id of...
SmbActiveFilePath
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the ...
stack_v2_sparse_classes_36k_train_014121
2,539
permissive
[ { "docstring": "Constructor for the SmbActiveFilePath class", "name": "__init__", "signature": "def __init__(self, active_sessions=None, file_path=None, view_id=None, view_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona...
2
stack_v2_sparse_classes_30k_train_008964
Implement the Python class `SmbActiveFilePath` described below. Class description: Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (...
Implement the Python class `SmbActiveFilePath` described below. Class description: Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmbActiveFilePath: """Implementation of the 'SmbActiveFilePath' model. Specifies a file path in an SMB view that has active sessions and opens. Attributes: active_sessions (list of SmbActiveSession): Specifies the sessions where the file is open. file_path (string): Specifies the filepath in the view. view_id...
the_stack_v2_python_sparse
cohesity_management_sdk/models/smb_active_file_path.py
cohesity/management-sdk-python
train
24
34b3b8818b0f343761bd8dcfc506f73b31a2615e
[ "if not channelType in cls._proxyMap:\n cls._proxyMap[channelType] = {}\ncls._proxyMap[channelType][proxy.name] = proxy", "if not channelType in cls._proxyMap:\n return None\nif not name in cls._proxyMap[channelType]:\n return None\nreturn cls._proxyMap[channelType][name]" ]
<|body_start_0|> if not channelType in cls._proxyMap: cls._proxyMap[channelType] = {} cls._proxyMap[channelType][proxy.name] = proxy <|end_body_0|> <|body_start_1|> if not channelType in cls._proxyMap: return None if not name in cls._proxyMap[channelType]: ...
ProxyManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProxyManager: def addProxy(cls, channelType, proxy): """:type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy""" <|body_0|> def getProxy(cls, channelType, name): """:type channelType: int :type name: str :rtype: gamit.rmi.rmicore.RmiProxy""" <|body_1...
stack_v2_sparse_classes_36k_train_014122
939
no_license
[ { "docstring": ":type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy", "name": "addProxy", "signature": "def addProxy(cls, channelType, proxy)" }, { "docstring": ":type channelType: int :type name: str :rtype: gamit.rmi.rmicore.RmiProxy", "name": "getProxy", "signature": "def g...
2
stack_v2_sparse_classes_30k_train_018009
Implement the Python class `ProxyManager` described below. Class description: Implement the ProxyManager class. Method signatures and docstrings: - def addProxy(cls, channelType, proxy): :type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy - def getProxy(cls, channelType, name): :type channelType: int :type...
Implement the Python class `ProxyManager` described below. Class description: Implement the ProxyManager class. Method signatures and docstrings: - def addProxy(cls, channelType, proxy): :type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy - def getProxy(cls, channelType, name): :type channelType: int :type...
47811e2cfe67c3c0de4c4be7394dd30e48732799
<|skeleton|> class ProxyManager: def addProxy(cls, channelType, proxy): """:type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy""" <|body_0|> def getProxy(cls, channelType, name): """:type channelType: int :type name: str :rtype: gamit.rmi.rmicore.RmiProxy""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProxyManager: def addProxy(cls, channelType, proxy): """:type channelType: int :type proxy: gamit.rmi.rmicore.RmiProxy""" if not channelType in cls._proxyMap: cls._proxyMap[channelType] = {} cls._proxyMap[channelType][proxy.name] = proxy def getProxy(cls, channelType, ...
the_stack_v2_python_sparse
python/gamit/rmi/proxymanager.py
bropony/gamit
train
0
2f100a8f47a6ef7bec868f944c9126b5b7ece87c
[ "assert len(phases) == len(components), 'phases and components should be of same length'\nself.phases = phases\nself.components = components\nself.t_pres = t_pres\nself.t_posts = t_posts\nself.fmin = fmin\nself.fmax = fmax\nself.zerophase = zerophase\nself.dt = dt\nself.tstars = tstars\nself.sigmas = sigmas\nself.b...
<|body_start_0|> assert len(phases) == len(components), 'phases and components should be of same length' self.phases = phases self.components = components self.t_pres = t_pres self.t_posts = t_posts self.fmin = fmin self.fmax = fmax self.zerophase = zeroph...
This class does source (SRC) and structure (STR) inversion
SRC_STR
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SRC_STR: """This class does source (SRC) and structure (STR) inversion""" def __init__(self, binary_file_path: str, prior_dat_filepath: str, save_folder: str, phases: [str], components: [str], t_pres: [float], t_posts: [float], vpvs: bool, depth: bool, dt: [float], sigmas: [float], tstars: [...
stack_v2_sparse_classes_36k_train_014123
22,015
permissive
[ { "docstring": "If vpvs and depth are both True (depth and vpvs are both inverted) :param binary_path: path to reflectivity code binary file :param prior_dat_filepath: path to your initial (prior) crfl.dat file :param save_folder: save folder :param phases: phases to be windowed :param components: on which comp...
3
stack_v2_sparse_classes_30k_val_000668
Implement the Python class `SRC_STR` described below. Class description: This class does source (SRC) and structure (STR) inversion Method signatures and docstrings: - def __init__(self, binary_file_path: str, prior_dat_filepath: str, save_folder: str, phases: [str], components: [str], t_pres: [float], t_posts: [floa...
Implement the Python class `SRC_STR` described below. Class description: This class does source (SRC) and structure (STR) inversion Method signatures and docstrings: - def __init__(self, binary_file_path: str, prior_dat_filepath: str, save_folder: str, phases: [str], components: [str], t_pres: [float], t_posts: [floa...
2632214f7df9caaa53d33432193ba0602470d21a
<|skeleton|> class SRC_STR: """This class does source (SRC) and structure (STR) inversion""" def __init__(self, binary_file_path: str, prior_dat_filepath: str, save_folder: str, phases: [str], components: [str], t_pres: [float], t_posts: [float], vpvs: bool, depth: bool, dt: [float], sigmas: [float], tstars: [...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SRC_STR: """This class does source (SRC) and structure (STR) inversion""" def __init__(self, binary_file_path: str, prior_dat_filepath: str, save_folder: str, phases: [str], components: [str], t_pres: [float], t_posts: [float], vpvs: bool, depth: bool, dt: [float], sigmas: [float], tstars: [float]=None, ...
the_stack_v2_python_sparse
SS_MTI/Gradient.py
nienkebrinkman/SS_MTI
train
0
3c90999adc021f228935beaf5c4e594acacdf7b0
[ "result = super(RedirectableAdmin, self).add_view(request, *args, **kwargs)\nref = request.META.get('HTTP_REFERER', '')\nif ref.find('?') != -1:\n request.session['filtered'] = ref\nif request.POST.has_key('_save'):\n \"\\n We only kick into action if we've saved and if\\n there is a ses...
<|body_start_0|> result = super(RedirectableAdmin, self).add_view(request, *args, **kwargs) ref = request.META.get('HTTP_REFERER', '') if ref.find('?') != -1: request.session['filtered'] = ref if request.POST.has_key('_save'): "\n We only kick into acti...
The redirectable admin, that correctly redirects after a filter has been choosen
RedirectableAdmin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedirectableAdmin: """The redirectable admin, that correctly redirects after a filter has been choosen""" def add_view(self, request, *args, **kwargs): """Used to redirect users back to their filtered list of locations if there were any""" <|body_0|> def change_view(self...
stack_v2_sparse_classes_36k_train_014124
15,009
permissive
[ { "docstring": "Used to redirect users back to their filtered list of locations if there were any", "name": "add_view", "signature": "def add_view(self, request, *args, **kwargs)" }, { "docstring": "Save the referer of the page to return to the filtered change_list after saving the page", "n...
2
null
Implement the Python class `RedirectableAdmin` described below. Class description: The redirectable admin, that correctly redirects after a filter has been choosen Method signatures and docstrings: - def add_view(self, request, *args, **kwargs): Used to redirect users back to their filtered list of locations if there...
Implement the Python class `RedirectableAdmin` described below. Class description: The redirectable admin, that correctly redirects after a filter has been choosen Method signatures and docstrings: - def add_view(self, request, *args, **kwargs): Used to redirect users back to their filtered list of locations if there...
d134624da9d36c4ba0bea2df8a21698df196bdf6
<|skeleton|> class RedirectableAdmin: """The redirectable admin, that correctly redirects after a filter has been choosen""" def add_view(self, request, *args, **kwargs): """Used to redirect users back to their filtered list of locations if there were any""" <|body_0|> def change_view(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedirectableAdmin: """The redirectable admin, that correctly redirects after a filter has been choosen""" def add_view(self, request, *args, **kwargs): """Used to redirect users back to their filtered list of locations if there were any""" result = super(RedirectableAdmin, self).add_view(...
the_stack_v2_python_sparse
civil/library/admin.py
christopinka/django-civil
train
3
ba5b3c14286eae33b13698809693a4f00da4be8a
[ "new_project = AdviserProject.objects.create(**validated_data)\nplayers = self.initial_data.get('players', [])\nPlayer.send_project(players, new_project)\nreturn new_project", "instance.name = validated_data.get('name', instance.name)\ninstance.description = validated_data.get('description', instance.description)...
<|body_start_0|> new_project = AdviserProject.objects.create(**validated_data) players = self.initial_data.get('players', []) Player.send_project(players, new_project) return new_project <|end_body_0|> <|body_start_1|> instance.name = validated_data.get('name', instance.name) ...
Serializer for AdviserProject
AdviserProjectSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdviserProjectSerializer: """Serializer for AdviserProject""" def create(self, validated_data): """Create and return a new "AdviserProject" instance, given the validated data. Also send created AdviserProject to selected players""" <|body_0|> def update(self, instance, v...
stack_v2_sparse_classes_36k_train_014125
1,471
no_license
[ { "docstring": "Create and return a new \"AdviserProject\" instance, given the validated data. Also send created AdviserProject to selected players", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Update and return an existing \"AdviserProject\" instance, gi...
2
stack_v2_sparse_classes_30k_train_004908
Implement the Python class `AdviserProjectSerializer` described below. Class description: Serializer for AdviserProject Method signatures and docstrings: - def create(self, validated_data): Create and return a new "AdviserProject" instance, given the validated data. Also send created AdviserProject to selected player...
Implement the Python class `AdviserProjectSerializer` described below. Class description: Serializer for AdviserProject Method signatures and docstrings: - def create(self, validated_data): Create and return a new "AdviserProject" instance, given the validated data. Also send created AdviserProject to selected player...
46bbe0fb30ce151e398034720939fb4fecea9ac5
<|skeleton|> class AdviserProjectSerializer: """Serializer for AdviserProject""" def create(self, validated_data): """Create and return a new "AdviserProject" instance, given the validated data. Also send created AdviserProject to selected players""" <|body_0|> def update(self, instance, v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdviserProjectSerializer: """Serializer for AdviserProject""" def create(self, validated_data): """Create and return a new "AdviserProject" instance, given the validated data. Also send created AdviserProject to selected players""" new_project = AdviserProject.objects.create(**validated_d...
the_stack_v2_python_sparse
itaplay/itaplay/projects/serializers.py
TarasStankovskyi/itaplay
train
0
fdb9af6308e60b7f913135329713a002b28acc66
[ "elem = deepcopy(elem)\nyld = elem.find('./YIELD')\nif yld is not None:\n yld.tag = 'YLD'\nreturn super(MFINFO, MFINFO).groom(elem)", "elem = deepcopy(elem)\nyld = elem.find('./YLD')\nif yld is not None:\n yld.tag = 'YIELD'\nreturn super(MFINFO, MFINFO).ungroom(elem)" ]
<|body_start_0|> elem = deepcopy(elem) yld = elem.find('./YIELD') if yld is not None: yld.tag = 'YLD' return super(MFINFO, MFINFO).groom(elem) <|end_body_0|> <|body_start_1|> elem = deepcopy(elem) yld = elem.find('./YLD') if yld is not None: ...
OFX section 13.8.5.3
MFINFO
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MFINFO: """OFX section 13.8.5.3""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" <|body_0|> def ungroom(elem): """Rename YLD back to YIELD""" <|body_1|> <|end_skeleton|> <|body_start_0|> elem = deepcopy...
stack_v2_sparse_classes_36k_train_014126
6,031
no_license
[ { "docstring": "Rename all Elements tagged YIELD (reserved Python keyword) to YLD", "name": "groom", "signature": "def groom(elem)" }, { "docstring": "Rename YLD back to YIELD", "name": "ungroom", "signature": "def ungroom(elem)" } ]
2
stack_v2_sparse_classes_30k_train_004118
Implement the Python class `MFINFO` described below. Class description: OFX section 13.8.5.3 Method signatures and docstrings: - def groom(elem): Rename all Elements tagged YIELD (reserved Python keyword) to YLD - def ungroom(elem): Rename YLD back to YIELD
Implement the Python class `MFINFO` described below. Class description: OFX section 13.8.5.3 Method signatures and docstrings: - def groom(elem): Rename all Elements tagged YIELD (reserved Python keyword) to YLD - def ungroom(elem): Rename YLD back to YIELD <|skeleton|> class MFINFO: """OFX section 13.8.5.3""" ...
67e688ea6510853657736c3804969d029c672c5c
<|skeleton|> class MFINFO: """OFX section 13.8.5.3""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" <|body_0|> def ungroom(elem): """Rename YLD back to YIELD""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MFINFO: """OFX section 13.8.5.3""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" elem = deepcopy(elem) yld = elem.find('./YIELD') if yld is not None: yld.tag = 'YLD' return super(MFINFO, MFINFO).groom(elem) ...
the_stack_v2_python_sparse
env/lib/python3.6/site-packages/ofxtools/models/invest/securities.py
yetaai/batchaccounting
train
0
5911c7d5ddecf2fb3a4b7f37e4bcd3fa3716c19f
[ "self.frequency = frequency\nself.octaves = octaves\nself.mountain_thresh = mountain_thresh\nself.minimum_elevation = minimum_elevation\nself.seed_modifier = seed_modifier", "modded_seed = self._get_modified_seed_val(seed_val, self.seed_modifier)\nfor y in range(0, mmap.get_map_height()):\n for x in range(0, m...
<|body_start_0|> self.frequency = frequency self.octaves = octaves self.mountain_thresh = mountain_thresh self.minimum_elevation = minimum_elevation self.seed_modifier = seed_modifier <|end_body_0|> <|body_start_1|> modded_seed = self._get_modified_seed_val(seed_val, sel...
A simplex noise-based mountain setter. This is very rudimentary.
SimplexMountainModifier
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimplexMountainModifier: """A simplex noise-based mountain setter. This is very rudimentary.""" def __init__(self, frequency=40.0, octaves=3, mountain_thresh=0.2, minimum_elevation=6, seed_modifier=None): """:keyword float frequency: Adjusts the frequency of the simplex noise. Higher...
stack_v2_sparse_classes_36k_train_014127
2,309
permissive
[ { "docstring": ":keyword float frequency: Adjusts the frequency of the simplex noise. Higher values will lead to larger individual mountainous patches. Smaller values will cause smaller clusters to be scattered all over the map. :keyword int octaves: The number of noise passes to make on each hex. Additional pa...
2
stack_v2_sparse_classes_30k_val_000194
Implement the Python class `SimplexMountainModifier` described below. Class description: A simplex noise-based mountain setter. This is very rudimentary. Method signatures and docstrings: - def __init__(self, frequency=40.0, octaves=3, mountain_thresh=0.2, minimum_elevation=6, seed_modifier=None): :keyword float freq...
Implement the Python class `SimplexMountainModifier` described below. Class description: A simplex noise-based mountain setter. This is very rudimentary. Method signatures and docstrings: - def __init__(self, frequency=40.0, octaves=3, mountain_thresh=0.2, minimum_elevation=6, seed_modifier=None): :keyword float freq...
001d35dbaef1f89e9b441fe63c7182cb1f3cda40
<|skeleton|> class SimplexMountainModifier: """A simplex noise-based mountain setter. This is very rudimentary.""" def __init__(self, frequency=40.0, octaves=3, mountain_thresh=0.2, minimum_elevation=6, seed_modifier=None): """:keyword float frequency: Adjusts the frequency of the simplex noise. Higher...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimplexMountainModifier: """A simplex noise-based mountain setter. This is very rudimentary.""" def __init__(self, frequency=40.0, octaves=3, mountain_thresh=0.2, minimum_elevation=6, seed_modifier=None): """:keyword float frequency: Adjusts the frequency of the simplex noise. Higher values will ...
the_stack_v2_python_sparse
btmux_maplib/map_generator/modifiers/mountains.py
gtaylor/btmux_maplib
train
0
052213def3eabc7014cc5a2ede6c288536d0d6c6
[ "with session_scope() as session:\n word_factor = session.query(WordFactor).filter_by(word_id=word_id).first()\n OF_objs = word_factor.OF_matrix\n OF_matrix = [(OF_i.number, OF_i.OF) for OF_i in OF_objs]\nreturn OF_matrix", "with session_scope() as session:\n word_factor = session.query(WordFactor).fi...
<|body_start_0|> with session_scope() as session: word_factor = session.query(WordFactor).filter_by(word_id=word_id).first() OF_objs = word_factor.OF_matrix OF_matrix = [(OF_i.number, OF_i.OF) for OF_i in OF_objs] return OF_matrix <|end_body_0|> <|body_start_1|> ...
WordFactor Store
WordFactorStore
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFactorStore: """WordFactor Store""" def get_OF_matrix(self, word_id): """Return historical optimum factor matrix of the word""" <|body_0|> def get_EF(self, word_id): """Return word's EF""" <|body_1|> def set_EF(self, word_id, EF, session=None): ...
stack_v2_sparse_classes_36k_train_014128
8,639
permissive
[ { "docstring": "Return historical optimum factor matrix of the word", "name": "get_OF_matrix", "signature": "def get_OF_matrix(self, word_id)" }, { "docstring": "Return word's EF", "name": "get_EF", "signature": "def get_EF(self, word_id)" }, { "docstring": "Set EF for word", ...
6
stack_v2_sparse_classes_30k_train_003588
Implement the Python class `WordFactorStore` described below. Class description: WordFactor Store Method signatures and docstrings: - def get_OF_matrix(self, word_id): Return historical optimum factor matrix of the word - def get_EF(self, word_id): Return word's EF - def set_EF(self, word_id, EF, session=None): Set E...
Implement the Python class `WordFactorStore` described below. Class description: WordFactor Store Method signatures and docstrings: - def get_OF_matrix(self, word_id): Return historical optimum factor matrix of the word - def get_EF(self, word_id): Return word's EF - def set_EF(self, word_id, EF, session=None): Set E...
dca9d9d7629ad943708aff91f3d4876a4b095ee4
<|skeleton|> class WordFactorStore: """WordFactor Store""" def get_OF_matrix(self, word_id): """Return historical optimum factor matrix of the word""" <|body_0|> def get_EF(self, word_id): """Return word's EF""" <|body_1|> def set_EF(self, word_id, EF, session=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordFactorStore: """WordFactor Store""" def get_OF_matrix(self, word_id): """Return historical optimum factor matrix of the word""" with session_scope() as session: word_factor = session.query(WordFactor).filter_by(word_id=word_id).first() OF_objs = word_factor.OF_...
the_stack_v2_python_sparse
rwords/store.py
Endlex-net/Rwords
train
5
e4aa19031cda0e419a773a12d03ad717e8a33f1a
[ "super(Set_arrivals, self).__init__(time, 'Set_arrivals')\nself.timestep = timestep\nself.nodes = nodes\nself.case = case", "for n in self.nodes:\n for i in range(n.max_k):\n if bernoulli_arrival(self.case['arrivals'][i]):\n t = Task(self.time + self.timestep, task_type=self.case['task_type']...
<|body_start_0|> super(Set_arrivals, self).__init__(time, 'Set_arrivals') self.timestep = timestep self.nodes = nodes self.case = case <|end_body_0|> <|body_start_1|> for n in self.nodes: for i in range(n.max_k): if bernoulli_arrival(self.case['arriva...
Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] - a list of fog nodes to which tasks will arrive at their buffers case: case_str...
Set_arrivals
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Set_arrivals: """Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] - a list of fog nodes to which tasks wil...
stack_v2_sparse_classes_36k_train_014129
2,500
no_license
[ { "docstring": "Parameters: time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] - a list of fog nodes to which tasks will arrive at their buffers case: case_struct - a structure defined in sim_env.configs settling slices charac...
2
stack_v2_sparse_classes_30k_train_021053
Implement the Python class `Set_arrivals` described below. Class description: Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] -...
Implement the Python class `Set_arrivals` described below. Class description: Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] -...
a16291d34269a206f98a663fa7dacf48292e1aa8
<|skeleton|> class Set_arrivals: """Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] - a list of fog nodes to which tasks wil...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Set_arrivals: """Set_arrivals calculates which nodes and slices are recieving a task this timestep. Attributes: (super) time: float - the current simulation time timestep: float - the timestep taken until the next arrival calculation nodes: List[Fog_nodes] - a list of fog nodes to which tasks will arrive at t...
the_stack_v2_python_sparse
sim_env/events/set_arrivals.py
luisferreira32/fog-computing-orchestration
train
1
fd603bb71353611ebb3c52086591316ab594f730
[ "date = getattr(model_instance, self.attname)\nif date is not None:\n if type(date) is str and re.match('\\\\d{4}-\\\\d{2}-\\\\d{2}', date):\n year = int(date[:4])\n month = int(date[5:7])\n day = int(date[8:])\n setattr(model_instance, self.attname, create_utc_time(year, month, day))...
<|body_start_0|> date = getattr(model_instance, self.attname) if date is not None: if type(date) is str and re.match('\\d{4}-\\d{2}-\\d{2}', date): year = int(date[:4]) month = int(date[5:7]) day = int(date[8:]) setattr(model_in...
PSTDateTimeField
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PSTDateTimeField: def pre_save(self, model_instance, add): """Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone""" <|body_0|> def from_db_value(self, value, expression, connection): """Converts the value from the DB from UTC t...
stack_v2_sparse_classes_36k_train_014130
1,612
no_license
[ { "docstring": "Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone", "name": "pre_save", "signature": "def pre_save(self, model_instance, add)" }, { "docstring": "Converts the value from the DB from UTC time to PST time before returning to calling code", ...
2
null
Implement the Python class `PSTDateTimeField` described below. Class description: Implement the PSTDateTimeField class. Method signatures and docstrings: - def pre_save(self, model_instance, add): Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone - def from_db_value(self, valu...
Implement the Python class `PSTDateTimeField` described below. Class description: Implement the PSTDateTimeField class. Method signatures and docstrings: - def pre_save(self, model_instance, add): Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone - def from_db_value(self, valu...
5152787e8db3b1c4a73362e8f06a117f5fadc817
<|skeleton|> class PSTDateTimeField: def pre_save(self, model_instance, add): """Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone""" <|body_0|> def from_db_value(self, value, expression, connection): """Converts the value from the DB from UTC t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PSTDateTimeField: def pre_save(self, model_instance, add): """Makes sure to convert the date to UTC time before saving if its in Canada/Pacific timezone""" date = getattr(model_instance, self.attname) if date is not None: if type(date) is str and re.match('\\d{4}-\\d{2}-\\d...
the_stack_v2_python_sparse
csss-site/src/csss/PSTDateTimeField.py
CSSS/csss-site
train
9
902524621404174757d97f6c2e538abf1be3d376
[ "user = self.request.user\nif user.is_staff:\n return self.queryset\nif user.company:\n return self.queryset.filter(company=user.company)\nreturn self.queryset.none()", "filtered_qs = self.filter_queryset(self.get_queryset())\nw_alerts_qs = Distillery.objects.have_alerts(filtered_qs)\npage = self.paginate_q...
<|body_start_0|> user = self.request.user if user.is_staff: return self.queryset if user.company: return self.queryset.filter(company=user.company) return self.queryset.none() <|end_body_0|> <|body_start_1|> filtered_qs = self.filter_queryset(self.get_que...
REST API views for Distilleries.
DistilleryViewSet
[ "MIT", "LicenseRef-scancode-proprietary-license", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DistilleryViewSet: """REST API views for Distilleries.""" def get_queryset(self): """Returns a queryset of |Distilleries| associated with a company.""" <|body_0|> def have_alerts(self, request, *args, **kwargs): """Get |Distilleries| that are associated with |Ale...
stack_v2_sparse_classes_36k_train_014131
3,287
permissive
[ { "docstring": "Returns a queryset of |Distilleries| associated with a company.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Get |Distilleries| that are associated with |Alerts|. Parameters ---------- request : :class:`rest_framework.request.Request` A Djang...
2
null
Implement the Python class `DistilleryViewSet` described below. Class description: REST API views for Distilleries. Method signatures and docstrings: - def get_queryset(self): Returns a queryset of |Distilleries| associated with a company. - def have_alerts(self, request, *args, **kwargs): Get |Distilleries| that are...
Implement the Python class `DistilleryViewSet` described below. Class description: REST API views for Distilleries. Method signatures and docstrings: - def get_queryset(self): Returns a queryset of |Distilleries| associated with a company. - def have_alerts(self, request, *args, **kwargs): Get |Distilleries| that are...
a379a134c0c5af14df4ed2afa066c1626506b754
<|skeleton|> class DistilleryViewSet: """REST API views for Distilleries.""" def get_queryset(self): """Returns a queryset of |Distilleries| associated with a company.""" <|body_0|> def have_alerts(self, request, *args, **kwargs): """Get |Distilleries| that are associated with |Ale...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DistilleryViewSet: """REST API views for Distilleries.""" def get_queryset(self): """Returns a queryset of |Distilleries| associated with a company.""" user = self.request.user if user.is_staff: return self.queryset if user.company: return self.quer...
the_stack_v2_python_sparse
Incident-Response/Tools/cyphon/cyphon/distilleries/views.py
foss2cyber/Incident-Playbook
train
1
5b62c474c7a3113c037069c9b2ceb49a5fd9eca5
[ "if type(data) is not np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = data.shape\nif n < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1).reshape(d, 1)\nX = data - self.mean\nself.cov = np.matmul(X, X.T) / (n - ...
<|body_start_0|> if type(data) is not np.ndarray or len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') d, n = data.shape if n < 2: raise ValueError('data must contain multiple data points') self.mean = np.mean(data, axis=1).reshape(d, 1) ...
Class multinormal
MultiNormal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiNormal: """Class multinormal""" def __init__(self, data): """Class constructor""" <|body_0|> def pdf(self, x): """Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose P...
stack_v2_sparse_classes_36k_train_014132
1,495
no_license
[ { "docstring": "Class constructor", "name": "__init__", "signature": "def __init__(self, data)" }, { "docstring": "Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose PDF should be calculated. Returns:", ...
2
null
Implement the Python class `MultiNormal` described below. Class description: Class multinormal Method signatures and docstrings: - def __init__(self, data): Class constructor - def pdf(self, x): Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing t...
Implement the Python class `MultiNormal` described below. Class description: Class multinormal Method signatures and docstrings: - def __init__(self, data): Class constructor - def pdf(self, x): Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing t...
5aff923277cfe9f2b5324a773e4e5c3cac810a0c
<|skeleton|> class MultiNormal: """Class multinormal""" def __init__(self, data): """Class constructor""" <|body_0|> def pdf(self, x): """Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose P...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiNormal: """Class multinormal""" def __init__(self, data): """Class constructor""" if type(data) is not np.ndarray or len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') d, n = data.shape if n < 2: raise ValueError('data mus...
the_stack_v2_python_sparse
math/0x06-multivariate_prob/multinormal.py
cmmolanos1/holbertonschool-machine_learning
train
1
03a2bd7294afdf4da42d5d37ab1399610e0f6283
[ "self.test_invoice_file = 'test_invoice.csv'\nself.test_furniture_list = ['Elisa Miles', 'LR04', 'Leather Sofa', '25']\nself.test_single_list = ['Susan Wong', 'LR04', 'Leather Sofa', '25']", "open(self.test_invoice_file, 'w').close()\ninventory.add_furniture(self.test_invoice_file, 'Elisa Miles', 'LR04', 'Leather...
<|body_start_0|> self.test_invoice_file = 'test_invoice.csv' self.test_furniture_list = ['Elisa Miles', 'LR04', 'Leather Sofa', '25'] self.test_single_list = ['Susan Wong', 'LR04', 'Leather Sofa', '25'] <|end_body_0|> <|body_start_1|> open(self.test_invoice_file, 'w').close() in...
Class for testing inventory module.
InventoryTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InventoryTest: """Class for testing inventory module.""" def setUp(self): """Establish class data structures.""" <|body_0|> def test_add_furniture(self): """Test add_furniture function.""" <|body_1|> def test_single_customer(self): """Test si...
stack_v2_sparse_classes_36k_train_014133
1,442
no_license
[ { "docstring": "Establish class data structures.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test add_furniture function.", "name": "test_add_furniture", "signature": "def test_add_furniture(self)" }, { "docstring": "Test single_customer function.", "...
3
null
Implement the Python class `InventoryTest` described below. Class description: Class for testing inventory module. Method signatures and docstrings: - def setUp(self): Establish class data structures. - def test_add_furniture(self): Test add_furniture function. - def test_single_customer(self): Test single_customer f...
Implement the Python class `InventoryTest` described below. Class description: Class for testing inventory module. Method signatures and docstrings: - def setUp(self): Establish class data structures. - def test_add_furniture(self): Test add_furniture function. - def test_single_customer(self): Test single_customer f...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class InventoryTest: """Class for testing inventory module.""" def setUp(self): """Establish class data structures.""" <|body_0|> def test_add_furniture(self): """Test add_furniture function.""" <|body_1|> def test_single_customer(self): """Test si...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InventoryTest: """Class for testing inventory module.""" def setUp(self): """Establish class data structures.""" self.test_invoice_file = 'test_invoice.csv' self.test_furniture_list = ['Elisa Miles', 'LR04', 'Leather Sofa', '25'] self.test_single_list = ['Susan Wong', 'LR0...
the_stack_v2_python_sparse
students/al_headstrong/lesson08/assignment/test_inventory.py
JavaRod/SP_Python220B_2019
train
1
b6d751bee3e871bce59453d32b8c4bb19b1aa645
[ "self.parser = reqparse.RequestParser()\nself.parser.add_argument('token')\nsuper(Error, self).__init__()", "args = self.parser.parse_args()\ntoken = args['token']\ndata = me.getError()\nl = [o.__dict__ for o in data]\nreturn {'result_code': 'success', 'data': l}" ]
<|body_start_0|> self.parser = reqparse.RequestParser() self.parser.add_argument('token') super(Error, self).__init__() <|end_body_0|> <|body_start_1|> args = self.parser.parse_args() token = args['token'] data = me.getError() l = [o.__dict__ for o in data] ...
错误
Error
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Error: """错误""" def __init__(self): """初始化""" <|body_0|> def get(self): """查询""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.parser = reqparse.RequestParser() self.parser.add_argument('token') super(Error, self).__init__() ...
stack_v2_sparse_classes_36k_train_014134
24,002
permissive
[ { "docstring": "初始化", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "查询", "name": "get", "signature": "def get(self)" } ]
2
stack_v2_sparse_classes_30k_train_012211
Implement the Python class `Error` described below. Class description: 错误 Method signatures and docstrings: - def __init__(self): 初始化 - def get(self): 查询
Implement the Python class `Error` described below. Class description: 错误 Method signatures and docstrings: - def __init__(self): 初始化 - def get(self): 查询 <|skeleton|> class Error: """错误""" def __init__(self): """初始化""" <|body_0|> def get(self): """查询""" <|body_1|> <|end...
c316649161086da2543d39bf0455d0f793cdd08f
<|skeleton|> class Error: """错误""" def __init__(self): """初始化""" <|body_0|> def get(self): """查询""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Error: """错误""" def __init__(self): """初始化""" self.parser = reqparse.RequestParser() self.parser.add_argument('token') super(Error, self).__init__() def get(self): """查询""" args = self.parser.parse_args() token = args['token'] data = me...
the_stack_v2_python_sparse
WebTrader/webServer.py
webclinic017/riskBacktestingPlatform
train
0
761287b7c4900163c3d869c3a7c6a8b37429ada7
[ "super().__init__(coordinator, description, user)\nentry_id = coordinator.config_entry.entry_id\nself._attr_unique_id = f'{entry_id}_{user.user_id}_{description.key}'", "if self.coordinator.activity:\n for session in self.coordinator.activity.sessions:\n if self.user and session.user_id == self.user.use...
<|body_start_0|> super().__init__(coordinator, description, user) entry_id = coordinator.config_entry.entry_id self._attr_unique_id = f'{entry_id}_{user.user_id}_{description.key}' <|end_body_0|> <|body_start_1|> if self.coordinator.activity: for session in self.coordinator....
Representation of a Tautulli session sensor.
TautulliSessionSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TautulliSessionSensor: """Representation of a Tautulli session sensor.""" def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None: """Initialize the Tautulli entity.""" <|body_0|> def native_value(se...
stack_v2_sparse_classes_36k_train_014135
10,227
permissive
[ { "docstring": "Initialize the Tautulli entity.", "name": "__init__", "signature": "def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None" }, { "docstring": "Return the state of the sensor.", "name": "native_value", ...
2
null
Implement the Python class `TautulliSessionSensor` described below. Class description: Representation of a Tautulli session sensor. Method signatures and docstrings: - def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None: Initialize the Tautul...
Implement the Python class `TautulliSessionSensor` described below. Class description: Representation of a Tautulli session sensor. Method signatures and docstrings: - def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None: Initialize the Tautul...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class TautulliSessionSensor: """Representation of a Tautulli session sensor.""" def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None: """Initialize the Tautulli entity.""" <|body_0|> def native_value(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TautulliSessionSensor: """Representation of a Tautulli session sensor.""" def __init__(self, coordinator: TautulliDataUpdateCoordinator, description: EntityDescription, user: PyTautulliApiUser) -> None: """Initialize the Tautulli entity.""" super().__init__(coordinator, description, user)...
the_stack_v2_python_sparse
homeassistant/components/tautulli/sensor.py
home-assistant/core
train
35,501
39c40f6306e92855a045c0841c63d574ffe680c0
[ "binning = '1,1' if hdu is None else self.get_meta_value(self.get_headarr(hdu), 'binning')\ndetector_dict = dict(binning=binning, det=1, dataext=1, specaxis=0, specflip=False, spatflip=False, platescale=0.2, darkcurr=0.0, saturation=65535.0, nonlinear=0.76, mincounts=-10000000000.0, numamplifiers=1, gain=np.atleast...
<|body_start_0|> binning = '1,1' if hdu is None else self.get_meta_value(self.get_headarr(hdu), 'binning') detector_dict = dict(binning=binning, det=1, dataext=1, specaxis=0, specflip=False, spatflip=False, platescale=0.2, darkcurr=0.0, saturation=65535.0, nonlinear=0.76, mincounts=-10000000000.0, numam...
Child to handle WHT/ISIS blue specific code
WHTISISBlueSpectrograph
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WHTISISBlueSpectrograph: """Child to handle WHT/ISIS blue specific code""" def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with t...
stack_v2_sparse_classes_36k_train_014136
16,230
permissive
[ { "docstring": "Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of interest. If not provided, frame-dependent parameters are set to a default. Returns: :class:`~pypeit.images.detector_...
4
stack_v2_sparse_classes_30k_train_007133
Implement the Python class `WHTISISBlueSpectrograph` described below. Class description: Child to handle WHT/ISIS blue specific code Method signatures and docstrings: - def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astrop...
Implement the Python class `WHTISISBlueSpectrograph` described below. Class description: Child to handle WHT/ISIS blue specific code Method signatures and docstrings: - def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astrop...
0d2e2196afc6904050b1af4d572f5c643bb07e38
<|skeleton|> class WHTISISBlueSpectrograph: """Child to handle WHT/ISIS blue specific code""" def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WHTISISBlueSpectrograph: """Child to handle WHT/ISIS blue specific code""" def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image ...
the_stack_v2_python_sparse
pypeit/spectrographs/wht_isis.py
pypeit/PypeIt
train
136
1e44ec960166040dbb1041490f9aef53115f8e89
[ "name = 'cityscapes'\ndataset_builder = tfds.builder(name, try_gcs=try_gcs, data_dir=data_dir)\nif is_training is None:\n is_training = split in ['train', tfds.Split.TRAIN]\nnew_split = base.get_validation_percent_split(dataset_builder, validation_percent, split, test_split=tfds.Split.VALIDATION)\nsuper().__init...
<|body_start_0|> name = 'cityscapes' dataset_builder = tfds.builder(name, try_gcs=try_gcs, data_dir=data_dir) if is_training is None: is_training = split in ['train', tfds.Split.TRAIN] new_split = base.get_validation_percent_split(dataset_builder, validation_percent, split, t...
Cityscapes dataset builder class.
CityscapesDataset
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CityscapesDataset: """Cityscapes dataset builder class.""" def __init__(self, split: str, validation_percent: float=0.0, shuffle_buffer_size: Optional[int]=1, num_parallel_parser_calls: int=1, try_gcs: bool=False, download_data: bool=False, data_dir: Optional[str]=None, is_training: Optional...
stack_v2_sparse_classes_36k_train_014137
5,098
permissive
[ { "docstring": "Create an Cityscapes tf.data.Dataset builder. Args: split: a dataset split, either a custom tfds.Split or one of the tfds.Split enums [TRAIN, VALIDAITON, TEST] or their lowercase string names. validation_percent: the percent of the training set to use as a validation set. shuffle_buffer_size: th...
2
null
Implement the Python class `CityscapesDataset` described below. Class description: Cityscapes dataset builder class. Method signatures and docstrings: - def __init__(self, split: str, validation_percent: float=0.0, shuffle_buffer_size: Optional[int]=1, num_parallel_parser_calls: int=1, try_gcs: bool=False, download_d...
Implement the Python class `CityscapesDataset` described below. Class description: Cityscapes dataset builder class. Method signatures and docstrings: - def __init__(self, split: str, validation_percent: float=0.0, shuffle_buffer_size: Optional[int]=1, num_parallel_parser_calls: int=1, try_gcs: bool=False, download_d...
f5f6f50f82bd441339c9d9efbef3f09e72c5fef6
<|skeleton|> class CityscapesDataset: """Cityscapes dataset builder class.""" def __init__(self, split: str, validation_percent: float=0.0, shuffle_buffer_size: Optional[int]=1, num_parallel_parser_calls: int=1, try_gcs: bool=False, download_data: bool=False, data_dir: Optional[str]=None, is_training: Optional...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CityscapesDataset: """Cityscapes dataset builder class.""" def __init__(self, split: str, validation_percent: float=0.0, shuffle_buffer_size: Optional[int]=1, num_parallel_parser_calls: int=1, try_gcs: bool=False, download_data: bool=False, data_dir: Optional[str]=None, is_training: Optional[bool]=None, ...
the_stack_v2_python_sparse
uncertainty_baselines/datasets/cityscapes.py
google/uncertainty-baselines
train
1,235
395969d589050ee2eac1fa07e864d1a185f0273e
[ "if file_name:\n with open(file_name, encoding='utf-8') as f:\n self.content = f.read()\nelif content:\n self.content = content\nelse:\n raise ValueError('Either file_name or content must be provided(file_name is prioritized)')", "results = re.findall('\\\\w*,\\\\w*', self.content)\nto_return: Lis...
<|body_start_0|> if file_name: with open(file_name, encoding='utf-8') as f: self.content = f.read() elif content: self.content = content else: raise ValueError('Either file_name or content must be provided(file_name is prioritized)') <|end_body...
The class that models the parser for the words file
WordFileParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFileParser: """The class that models the parser for the words file""" def __init__(self, *, file_name: str=None, content: str=None) -> None: """The constructor, either a file_name or a content must be provided If both are provided, file_name is used If none are provided, ValueErr...
stack_v2_sparse_classes_36k_train_014138
4,456
permissive
[ { "docstring": "The constructor, either a file_name or a content must be provided If both are provided, file_name is used If none are provided, ValueError is raised", "name": "__init__", "signature": "def __init__(self, *, file_name: str=None, content: str=None) -> None" }, { "docstring": "Parse...
2
stack_v2_sparse_classes_30k_train_021211
Implement the Python class `WordFileParser` described below. Class description: The class that models the parser for the words file Method signatures and docstrings: - def __init__(self, *, file_name: str=None, content: str=None) -> None: The constructor, either a file_name or a content must be provided If both are p...
Implement the Python class `WordFileParser` described below. Class description: The class that models the parser for the words file Method signatures and docstrings: - def __init__(self, *, file_name: str=None, content: str=None) -> None: The constructor, either a file_name or a content must be provided If both are p...
700900d8b9ddf7aa198d79c10e77f40fcd813bea
<|skeleton|> class WordFileParser: """The class that models the parser for the words file""" def __init__(self, *, file_name: str=None, content: str=None) -> None: """The constructor, either a file_name or a content must be provided If both are provided, file_name is used If none are provided, ValueErr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordFileParser: """The class that models the parser for the words file""" def __init__(self, *, file_name: str=None, content: str=None) -> None: """The constructor, either a file_name or a content must be provided If both are provided, file_name is used If none are provided, ValueError is raised"...
the_stack_v2_python_sparse
pyautomata/core/parser.py
aiwaverse/pyautomata-git
train
2
ae9d18ff5cd47707b62de44018aee927236d476b
[ "self._vehicle = vehicle\nself._world = self._vehicle.get_world()\nself._long_controller = PIDLongitudinalController(self._vehicle, **args_longitudinal)\nself._later_controller = PIDLateralController(self._vehicle, **args_lateral)", "throttle = self._long_controller.run_step(target_speed)\nsteering, adjusted_wayp...
<|body_start_0|> self._vehicle = vehicle self._world = self._vehicle.get_world() self._long_controller = PIDLongitudinalController(self._vehicle, **args_longitudinal) self._later_controller = PIDLateralController(self._vehicle, **args_lateral) <|end_body_0|> <|body_start_1|> thr...
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
VehiclePIDController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VehiclePIDController: """VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side""" def __init__(self, vehicle, args_lateral={'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}, args_longitudinal={'K_P': 1.0, 'K_D...
stack_v2_sparse_classes_36k_train_014139
13,383
no_license
[ { "docstring": ":param vehicle: actor to apply to local planner logic onto :param args_lateral: dictionary of arguments to set the lateral PID controller using the following semantics: K_P -- Proportional term K_D -- Differential term K_I -- Integral term :param args_longitudinal: dictionary of arguments to set...
4
stack_v2_sparse_classes_30k_train_014123
Implement the Python class `VehiclePIDController` described below. Class description: VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side Method signatures and docstrings: - def __init__(self, vehicle, args_lateral={'K_P...
Implement the Python class `VehiclePIDController` described below. Class description: VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side Method signatures and docstrings: - def __init__(self, vehicle, args_lateral={'K_P...
da35bfec7d40708e4f76d08f54e04587bef1dd8b
<|skeleton|> class VehiclePIDController: """VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side""" def __init__(self, vehicle, args_lateral={'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}, args_longitudinal={'K_P': 1.0, 'K_D...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VehiclePIDController: """VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side""" def __init__(self, vehicle, args_lateral={'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}, args_longitudinal={'K_P': 1.0, 'K_D': 0.0, 'K_I'...
the_stack_v2_python_sparse
drive_interfaces/carla/comercial_cars/Navigation/controller.py
gy20073/CIL_modular
train
2
9f44765518ce70b7b0adc98269f254e02d652436
[ "try:\n group_type = TeamType.objects.get(pk=pk)\nexcept ObjectDoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\nif request.user.has_perm(VIEW_TEAMTYPE):\n serializer = TeamTypeDetailsSerializer(group_type)\n return Response(serializer.data)\nreturn Response(status=status.HTTP_401_UNAUT...
<|body_start_0|> try: group_type = TeamType.objects.get(pk=pk) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.user.has_perm(VIEW_TEAMTYPE): serializer = TeamTypeDetailsSerializer(group_type) return Response(...
# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type with the data on the request or if the data i...
TeamTypesDetail
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeamTypesDetail: """# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type wi...
stack_v2_sparse_classes_36k_train_014140
6,650
permissive
[ { "docstring": "docstring.", "name": "get", "signature": "def get(self, request, pk)" }, { "docstring": "docstrings.", "name": "put", "signature": "def put(self, request, pk)" }, { "docstring": "docstrings.", "name": "delete", "signature": "def delete(self, request, pk)" ...
3
stack_v2_sparse_classes_30k_train_006645
Implement the Python class `TeamTypesDetail` described below. Class description: # Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data...
Implement the Python class `TeamTypesDetail` described below. Class description: # Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data...
56511ebac83a5dc1fb8768a98bc675e88530a447
<|skeleton|> class TeamTypesDetail: """# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type wi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TeamTypesDetail: """# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type with the data o...
the_stack_v2_python_sparse
usersmanagement/views/views_teamtypes.py
Open-CMMS/openCMMS_backend
train
4
cb8c240fef428d40429751f39de3929a5f320d1b
[ "flag = 1\ncount = 0\nwhile flag <= n:\n if flag & n:\n count += 1\n flag <<= 1\nreturn count", "bits = 0\nwhile n:\n bits += 1\n n = n - 1 & n\nreturn bits" ]
<|body_start_0|> flag = 1 count = 0 while flag <= n: if flag & n: count += 1 flag <<= 1 return count <|end_body_0|> <|body_start_1|> bits = 0 while n: bits += 1 n = n - 1 & n return bits <|end_body_1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" <|body_0|> def hamming_weight(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> flag = 1 count = 0 while flag <= n: ...
stack_v2_sparse_classes_36k_train_014141
2,783
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "hammingWeight", "signature": "def hammingWeight(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "hamming_weight", "signature": "def hamming_weight(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_000990
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hammingWeight(self, n): :type n: int :rtype: int - def hamming_weight(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hammingWeight(self, n): :type n: int :rtype: int - def hamming_weight(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def hammingWeight(self, n): ...
47911c354145d9867774aeb3358de20e55cf89ad
<|skeleton|> class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" <|body_0|> def hamming_weight(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hammingWeight(self, n): """:type n: int :rtype: int""" flag = 1 count = 0 while flag <= n: if flag & n: count += 1 flag <<= 1 return count def hamming_weight(self, n): """:type n: int :rtype: int""" ...
the_stack_v2_python_sparse
rsc/1_easy/offer_15.py
VincentGaoHJ/Sword-For-Offer
train
1
e457b140a10b558983129b901b5b7bef5594ae9a
[ "encoding = []\nfor s in strs:\n len_s = str(len(s))\n encoding.append(len_s)\n encoding.append('*')\n encoding.append(s)\nreturn ''.join(encoding)", "decoding = []\ni = 0\nwhile i < len(s):\n j = s.find('*', i)\n len_substring = int(s[i:j])\n decoding.append(s[j + 1:j + 1 + len_substring])\n...
<|body_start_0|> encoding = [] for s in strs: len_s = str(len(s)) encoding.append(len_s) encoding.append('*') encoding.append(s) return ''.join(encoding) <|end_body_0|> <|body_start_1|> decoding = [] i = 0 while i < len(s):...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_014142
1,708
no_license
[ { "docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str", "name": "encode", "signature": "def encode(self, strs)" }, { "docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]", "name": "decode", "signature": "def ...
2
stack_v2_sparse_classes_30k_train_008682
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
05e0beff0047f0ad399d0b46d625bb8d3459814e
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" encoding = [] for s in strs: len_s = str(len(s)) encoding.append(len_s) encoding.append('*') encoding.append(s) r...
the_stack_v2_python_sparse
python_1_to_1000/271_Encode_and_Decode_Strings.py
jakehoare/leetcode
train
58
e8e82ed44fe0b6deecfdbed962d7491ff233da95
[ "super().__init__(question, test_dict)\nself.preamble = compile(test_dict.get('preamble', ''), '%s.preamble' % self.path, 'exec')\nself.test = compile(test_dict['test'], '%s.test' % self.path, 'eval')\nself.success = test_dict['success']\nself.failure = test_dict['failure']", "bindings = dict(module_dict)\nexec(s...
<|body_start_0|> super().__init__(question, test_dict) self.preamble = compile(test_dict.get('preamble', ''), '%s.preamble' % self.path, 'exec') self.test = compile(test_dict['test'], '%s.test' % self.path, 'eval') self.success = test_dict['success'] self.failure = test_dict['fai...
Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.
EvalTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EvalTest: """Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.""" def __init__(self, question, test_dict): """Create test from question and test dictionary.""" ...
stack_v2_sparse_classes_36k_train_014143
6,372
no_license
[ { "docstring": "Create test from question and test dictionary.", "name": "__init__", "signature": "def __init__(self, question, test_dict)" }, { "docstring": "Evaluate the code.", "name": "eval_code", "signature": "def eval_code(self, module_dict)" }, { "docstring": "Run the test...
4
stack_v2_sparse_classes_30k_train_020850
Implement the Python class `EvalTest` described below. Class description: Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's. Method signatures and docstrings: - def __init__(self, question, test_d...
Implement the Python class `EvalTest` described below. Class description: Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's. Method signatures and docstrings: - def __init__(self, question, test_d...
9612a1ff8748d9d58cc929a937a6001e8f0a2494
<|skeleton|> class EvalTest: """Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.""" def __init__(self, question, test_dict): """Create test from question and test dictionary.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EvalTest: """Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.""" def __init__(self, question, test_dict): """Create test from question and test dictionary.""" super(...
the_stack_v2_python_sparse
Lab_2/test_classes.py
liamcannon/CSI-275
train
0
f352fa80db460ea3dbed7405e7f6cad9bbb12c58
[ "from scoop.editorial.models import Excerpt\nidentifier = self.value\ntry:\n excerpt = Excerpt.objects.get(name=identifier)\nexcept Excerpt.DoesNotExist:\n excerpt = None\nreturn {'excerpt': excerpt}", "base = super(ExcerptInline, self).get_template_name()[0]\npath = 'editorial/%s' % base\nreturn path" ]
<|body_start_0|> from scoop.editorial.models import Excerpt identifier = self.value try: excerpt = Excerpt.objects.get(name=identifier) except Excerpt.DoesNotExist: excerpt = None return {'excerpt': excerpt} <|end_body_0|> <|body_start_1|> base = ...
Inline d'extrait
ExcerptInline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExcerptInline: """Inline d'extrait""" def get_context(self): """Renvoyer le contexte d'affichage du template""" <|body_0|> def get_template_name(self): """Renvoyer le chemin du template d'affichage""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_014144
875
no_license
[ { "docstring": "Renvoyer le contexte d'affichage du template", "name": "get_context", "signature": "def get_context(self)" }, { "docstring": "Renvoyer le chemin du template d'affichage", "name": "get_template_name", "signature": "def get_template_name(self)" } ]
2
stack_v2_sparse_classes_30k_train_002480
Implement the Python class `ExcerptInline` described below. Class description: Inline d'extrait Method signatures and docstrings: - def get_context(self): Renvoyer le contexte d'affichage du template - def get_template_name(self): Renvoyer le chemin du template d'affichage
Implement the Python class `ExcerptInline` described below. Class description: Inline d'extrait Method signatures and docstrings: - def get_context(self): Renvoyer le contexte d'affichage du template - def get_template_name(self): Renvoyer le chemin du template d'affichage <|skeleton|> class ExcerptInline: """In...
8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7
<|skeleton|> class ExcerptInline: """Inline d'extrait""" def get_context(self): """Renvoyer le contexte d'affichage du template""" <|body_0|> def get_template_name(self): """Renvoyer le chemin du template d'affichage""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExcerptInline: """Inline d'extrait""" def get_context(self): """Renvoyer le contexte d'affichage du template""" from scoop.editorial.models import Excerpt identifier = self.value try: excerpt = Excerpt.objects.get(name=identifier) except Excerpt.DoesNot...
the_stack_v2_python_sparse
scoop/editorial/util/inlines.py
artscoop/scoop
train
0
4a568831581b53f29c13b0bfcba6db435b34bc84
[ "try:\n story = story_fetchers.get_story_from_model(story_model)\n story.validate()\n assert topic_id_to_topic is not None\n corresponding_topic = topic_id_to_topic[story.corresponding_topic_id]\n story_services.validate_prerequisite_skills_in_story_contents(corresponding_topic.get_all_skill_ids(), s...
<|body_start_0|> try: story = story_fetchers.get_story_from_model(story_model) story.validate() assert topic_id_to_topic is not None corresponding_topic = topic_id_to_topic[story.corresponding_topic_id] story_services.validate_prerequisite_skills_in_st...
Transform that gets all Story models, performs migration and filters any error results.
MigrateStoryModels
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MigrateStoryModels: """Transform that gets all Story models, performs migration and filters any error results.""" def _migrate_story(story_id: str, story_model: story_models.StoryModel, topic_id_to_topic: Optional[Dict[str, topic_domain.Topic]]=None) -> result.Result[Tuple[str, story_domain....
stack_v2_sparse_classes_36k_train_014145
14,753
permissive
[ { "docstring": "Migrates story and transform story model into story object. Args: story_id: str. The id of the story. story_model: StoryModel. The story model to migrate. topic_id_to_topic: dict(str, Topic). The mapping from topic ID to topic. Returns: Result((str, Story), (str, Exception)). Result containing t...
3
null
Implement the Python class `MigrateStoryModels` described below. Class description: Transform that gets all Story models, performs migration and filters any error results. Method signatures and docstrings: - def _migrate_story(story_id: str, story_model: story_models.StoryModel, topic_id_to_topic: Optional[Dict[str, ...
Implement the Python class `MigrateStoryModels` described below. Class description: Transform that gets all Story models, performs migration and filters any error results. Method signatures and docstrings: - def _migrate_story(story_id: str, story_model: story_models.StoryModel, topic_id_to_topic: Optional[Dict[str, ...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class MigrateStoryModels: """Transform that gets all Story models, performs migration and filters any error results.""" def _migrate_story(story_id: str, story_model: story_models.StoryModel, topic_id_to_topic: Optional[Dict[str, topic_domain.Topic]]=None) -> result.Result[Tuple[str, story_domain....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MigrateStoryModels: """Transform that gets all Story models, performs migration and filters any error results.""" def _migrate_story(story_id: str, story_model: story_models.StoryModel, topic_id_to_topic: Optional[Dict[str, topic_domain.Topic]]=None) -> result.Result[Tuple[str, story_domain.Story], Tuple...
the_stack_v2_python_sparse
core/jobs/batch_jobs/story_migration_jobs.py
oppia/oppia
train
6,172
a7ec8e287bbe3a0124fcf174a801e0296dbe337d
[ "self.auxiliary_load = params['aux']\nself.site_load = params['site']\nself.system_load = params['system']\nself.deferral_load = params['deferral']\nself.no_export = params['no_export']\nself.no_import = params['no_import']\nself.default_growth = params['default_growth']\nself.deferral_growth = params['deferral_gro...
<|body_start_0|> self.auxiliary_load = params['aux'] self.site_load = params['site'] self.system_load = params['system'] self.deferral_load = params['deferral'] self.no_export = params['no_export'] self.no_import = params['no_import'] self.default_growth = params[...
This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI.
POI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class POI: """This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI.""" def __init__(self, params): """Initialize Args: params (Dict): the dictionary of user inputs""" ...
stack_v2_sparse_classes_36k_train_014146
3,190
no_license
[ { "docstring": "Initialize Args: params (Dict): the dictionary of user inputs", "name": "__init__", "signature": "def __init__(self, params)" }, { "docstring": "Builds the master constraint list for the subset of timeseries data being optimized. Args: variables (Dict): Dictionary of variables be...
2
null
Implement the Python class `POI` described below. Class description: This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI. Method signatures and docstrings: - def __init__(self, params): Initialize ...
Implement the Python class `POI` described below. Class description: This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI. Method signatures and docstrings: - def __init__(self, params): Initialize ...
eb490d94baac2c287a77f1b403ce7337cf51aaf4
<|skeleton|> class POI: """This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI.""" def __init__(self, params): """Initialize Args: params (Dict): the dictionary of user inputs""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class POI: """This class holds the load data for the case described by the user defined model parameter. It will also impose any constraints that should be opposed at the microgrid's POI.""" def __init__(self, params): """Initialize Args: params (Dict): the dictionary of user inputs""" self.aux...
the_stack_v2_python_sparse
storagevet_dervet/Technology/POI.py
pajalevi/StorageVET
train
0
557d6e74e0faeb90155f57f9302edd20b5fa33e8
[ "response = requests.get(cls.COURSE_URL + '-')\ncourses = response.json()['course']\nfor course in courses:\n course_code = course['code'].upper()\n if course_code in skip:\n continue\n response = requests.get(cls.COURSE_URL + course_code)\n course_info = response.json()['course']\n yield {'co...
<|body_start_0|> response = requests.get(cls.COURSE_URL + '-') courses = response.json()['course'] for course in courses: course_code = course['code'].upper() if course_code in skip: continue response = requests.get(cls.COURSE_URL + course_code...
Class for interacting with the NTNU-IME API.
IMEAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IMEAPI: """Class for interacting with the NTNU-IME API.""" def all_courses(cls, skip: Set[str]): """Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded.""" <|body_0|> def course_homepage(course): """Retrieve...
stack_v2_sparse_classes_36k_train_014147
2,132
permissive
[ { "docstring": "Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded.", "name": "all_courses", "signature": "def all_courses(cls, skip: Set[str])" }, { "docstring": "Retrieve course homepage if present in Course API response.", "name": "...
2
stack_v2_sparse_classes_30k_train_016446
Implement the Python class `IMEAPI` described below. Class description: Class for interacting with the NTNU-IME API. Method signatures and docstrings: - def all_courses(cls, skip: Set[str]): Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded. - def course_homep...
Implement the Python class `IMEAPI` described below. Class description: Class for interacting with the NTNU-IME API. Method signatures and docstrings: - def all_courses(cls, skip: Set[str]): Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded. - def course_homep...
5743b1d4c3fefa66fcaa4d283436d2a3f0490604
<|skeleton|> class IMEAPI: """Class for interacting with the NTNU-IME API.""" def all_courses(cls, skip: Set[str]): """Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded.""" <|body_0|> def course_homepage(course): """Retrieve...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IMEAPI: """Class for interacting with the NTNU-IME API.""" def all_courses(cls, skip: Set[str]): """Yield all courses available from the IME API. :param skip: List of course codes which should not be yielded.""" response = requests.get(cls.COURSE_URL + '-') courses = response.json...
the_stack_v2_python_sparse
semesterpage/management/commands/populate_courses.py
JakobGM/WikiLinks
train
7
943ae4f90e786925f62c91f4fbb72cf710aa5e0c
[ "exe = which.which('xcode-select')\nif not exe:\n return False\ncmd = [exe, '--print-path']\nrv = execute.execute(cmd, raise_error=False)\nif rv.exit_code != 0:\n if verbose:\n print('not installed')\n return False\nprint('installed')\nreturn True", "installed = clazz.installed(False)\nclazz._log....
<|body_start_0|> exe = which.which('xcode-select') if not exe: return False cmd = [exe, '--print-path'] rv = execute.execute(cmd, raise_error=False) if rv.exit_code != 0: if verbose: print('not installed') return False p...
Class to deal with the command_line_tools executable.
command_line_tools
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class command_line_tools: """Class to deal with the command_line_tools executable.""" def installed(clazz, verbose=False): """Return True of command line tools are installed.""" <|body_0|> def install(clazz, verbose): """Install the command line tools.""" <|bod...
stack_v2_sparse_classes_36k_train_014148
1,991
permissive
[ { "docstring": "Return True of command line tools are installed.", "name": "installed", "signature": "def installed(clazz, verbose=False)" }, { "docstring": "Install the command line tools.", "name": "install", "signature": "def install(clazz, verbose)" }, { "docstring": "Ensure ...
3
null
Implement the Python class `command_line_tools` described below. Class description: Class to deal with the command_line_tools executable. Method signatures and docstrings: - def installed(clazz, verbose=False): Return True of command line tools are installed. - def install(clazz, verbose): Install the command line to...
Implement the Python class `command_line_tools` described below. Class description: Class to deal with the command_line_tools executable. Method signatures and docstrings: - def installed(clazz, verbose=False): Return True of command line tools are installed. - def install(clazz, verbose): Install the command line to...
b9dd35b518848cea82e43d5016e425cc7dac32e5
<|skeleton|> class command_line_tools: """Class to deal with the command_line_tools executable.""" def installed(clazz, verbose=False): """Return True of command line tools are installed.""" <|body_0|> def install(clazz, verbose): """Install the command line tools.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class command_line_tools: """Class to deal with the command_line_tools executable.""" def installed(clazz, verbose=False): """Return True of command line tools are installed.""" exe = which.which('xcode-select') if not exe: return False cmd = [exe, '--print-path'] ...
the_stack_v2_python_sparse
lib/bes/macos/command_line_tools/command_line_tools.py
reconstruir/bes
train
0
b1dad7223fb13b611eaf8975b62f76a456234dc7
[ "data_schema = CONFIG_SCHEMA\nerrors = {}\nif user_input is not None:\n self._async_abort_entries_match(user_input)\n airzone = AirzoneLocalApi(aiohttp_client.async_get_clientsession(self.hass), ConnectionOptions(user_input[CONF_HOST], user_input[CONF_PORT], user_input.get(CONF_ID, DEFAULT_SYSTEM_ID)))\n t...
<|body_start_0|> data_schema = CONFIG_SCHEMA errors = {} if user_input is not None: self._async_abort_entries_match(user_input) airzone = AirzoneLocalApi(aiohttp_client.async_get_clientsession(self.hass), ConnectionOptions(user_input[CONF_HOST], user_input[CONF_PORT], use...
Handle config flow for an Airzone device.
ConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigFlow: """Handle config flow for an Airzone device.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResul...
stack_v2_sparse_classes_36k_train_014149
5,614
permissive
[ { "docstring": "Handle the initial step.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult" }, { "docstring": "Handle DHCP discovery.", "name": "async_step_dhcp", "signature": "async def async_step_dhcp(self, ...
3
null
Implement the Python class `ConfigFlow` described below. Class description: Handle config flow for an Airzone device. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def async_step_dhcp(self, discovery_info: dh...
Implement the Python class `ConfigFlow` described below. Class description: Handle config flow for an Airzone device. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def async_step_dhcp(self, discovery_info: dh...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ConfigFlow: """Handle config flow for an Airzone device.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResul...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigFlow: """Handle config flow for an Airzone device.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" data_schema = CONFIG_SCHEMA errors = {} if user_input is not None: self._async_abor...
the_stack_v2_python_sparse
homeassistant/components/airzone/config_flow.py
home-assistant/core
train
35,501
600fb6e7f7b30b17903933e01785f6081a15ae99
[ "now = __dt__.now()\nnow = str(now)\nnow = '[@' + now + ']: '\nreturn now", "message = str(Log.timestamp()) + msg\nif print_msg is True:\n print(str(Log.timestamp()), msg)\nreturn message" ]
<|body_start_0|> now = __dt__.now() now = str(now) now = '[@' + now + ']: ' return now <|end_body_0|> <|body_start_1|> message = str(Log.timestamp()) + msg if print_msg is True: print(str(Log.timestamp()), msg) return message <|end_body_1|>
Log
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Log: def timestamp(self=None): """Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string describing the current time and date.""" <|body_0|> def msg(msg=None, print_ms...
stack_v2_sparse_classes_36k_train_014150
2,667
permissive
[ { "docstring": "Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string describing the current time and date.", "name": "timestamp", "signature": "def timestamp(self=None)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_004194
Implement the Python class `Log` described below. Class description: Implement the Log class. Method signatures and docstrings: - def timestamp(self=None): Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string...
Implement the Python class `Log` described below. Class description: Implement the Log class. Method signatures and docstrings: - def timestamp(self=None): Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string...
53a5dc2d1006ada20911f672daf2e3827296a4fd
<|skeleton|> class Log: def timestamp(self=None): """Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string describing the current time and date.""" <|body_0|> def msg(msg=None, print_ms...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Log: def timestamp(self=None): """Returns the current time and date with lots of precision. Args: self(NoneType): unused parameter that does absolutely nothing. (default None) Returns: str: string describing the current time and date.""" now = __dt__.now() now = str(now) now = ...
the_stack_v2_python_sparse
qbitkit/error/error.py
qbitkit/qbitkit
train
5
f9e231a8d6a8315ee596a70a78e9ea84ccccf93c
[ "link = Link(url='http://example.com')\nlink.save()\nself.assert_(link.slug, 'autoslug must be assigned when slug is undefined')", "link1 = Link(url='http://example.com')\nlink1.save()\nslug1 = link1.slug\nlink1.delete()\nlink2 = Link(url='http://example.net')\nlink2.save()\nslug2 = link2.slug\nself.assertNotEqua...
<|body_start_0|> link = Link(url='http://example.com') link.save() self.assert_(link.slug, 'autoslug must be assigned when slug is undefined') <|end_body_0|> <|body_start_1|> link1 = Link(url='http://example.com') link1.save() slug1 = link1.slug link1.delete() ...
LinkTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkTest: def test_autoslug(self): """If slug is undefined, will autoslug be assigned?""" <|body_0|> def test_autoslug_no_reassignment(self): """Create a link, delete it, create a new one. Make sure the IDs differ.""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_014151
4,985
permissive
[ { "docstring": "If slug is undefined, will autoslug be assigned?", "name": "test_autoslug", "signature": "def test_autoslug(self)" }, { "docstring": "Create a link, delete it, create a new one. Make sure the IDs differ.", "name": "test_autoslug_no_reassignment", "signature": "def test_au...
2
stack_v2_sparse_classes_30k_val_000805
Implement the Python class `LinkTest` described below. Class description: Implement the LinkTest class. Method signatures and docstrings: - def test_autoslug(self): If slug is undefined, will autoslug be assigned? - def test_autoslug_no_reassignment(self): Create a link, delete it, create a new one. Make sure the IDs...
Implement the Python class `LinkTest` described below. Class description: Implement the LinkTest class. Method signatures and docstrings: - def test_autoslug(self): If slug is undefined, will autoslug be assigned? - def test_autoslug_no_reassignment(self): Create a link, delete it, create a new one. Make sure the IDs...
96154ebd4015abd2827561ad8c218b4940e0e1a0
<|skeleton|> class LinkTest: def test_autoslug(self): """If slug is undefined, will autoslug be assigned?""" <|body_0|> def test_autoslug_no_reassignment(self): """Create a link, delete it, create a new one. Make sure the IDs differ.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinkTest: def test_autoslug(self): """If slug is undefined, will autoslug be assigned?""" link = Link(url='http://example.com') link.save() self.assert_(link.slug, 'autoslug must be assigned when slug is undefined') def test_autoslug_no_reassignment(self): """Creat...
the_stack_v2_python_sparse
apps/shortener/tests.py
fwenzel/millimeter
train
0
8a071d31064ba894c446a0212ab06d415af08d3d
[ "if not root:\n return []\nres = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]\nreturn res", "if len(data) == 0:\n return None\nroot = TreeNode(data[0])\nroot.left = self.deserialize(data[1])\nroot.right = self.deserialize(data[2])\nreturn root" ]
<|body_start_0|> if not root: return [] res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)] return res <|end_body_0|> <|body_start_1|> if len(data) == 0: return None root = TreeNode(data[0]) root.left = self.deserialize(d...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_014152
5,388
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_005897
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
f96a2273c6831a8035e1adacfa452f73c599ae16
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return [] res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)] return res def deserialize(self, data): """D...
the_stack_v2_python_sparse
Python/SerializeandDeserializeBinaryTree.py
here0009/LeetCode
train
1
63595358a0cadb80b9cb932b540e470864ea69d2
[ "self.zero = LinkedList(0)\nself.one = LinkedList(1)\nself.two = LinkedList(2)\nself.three = LinkedList(3)\nself.four = LinkedList(4)\nself.five = LinkedList(5)\nself.six = LinkedList(6)\nself.seven = LinkedList(7)\nself.eight = LinkedList(8)\nself.nine = LinkedList(9)\nself.zero.next = self.one\nself.one.next = se...
<|body_start_0|> self.zero = LinkedList(0) self.one = LinkedList(1) self.two = LinkedList(2) self.three = LinkedList(3) self.four = LinkedList(4) self.five = LinkedList(5) self.six = LinkedList(6) self.seven = LinkedList(7) self.eight = LinkedList(...
Class with unittests for RemoveKthNodeFromEnd.py
test_RemoveKthNodeFromEnd
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_RemoveKthNodeFromEnd: """Class with unittests for RemoveKthNodeFromEnd.py""" def SetUp(self): """Set Up input list.""" <|body_0|> def test_RemoveKthNodeFromEnd(self): """Checks if output is correct.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_014153
1,607
no_license
[ { "docstring": "Set Up input list.", "name": "SetUp", "signature": "def SetUp(self)" }, { "docstring": "Checks if output is correct.", "name": "test_RemoveKthNodeFromEnd", "signature": "def test_RemoveKthNodeFromEnd(self)" } ]
2
null
Implement the Python class `test_RemoveKthNodeFromEnd` described below. Class description: Class with unittests for RemoveKthNodeFromEnd.py Method signatures and docstrings: - def SetUp(self): Set Up input list. - def test_RemoveKthNodeFromEnd(self): Checks if output is correct.
Implement the Python class `test_RemoveKthNodeFromEnd` described below. Class description: Class with unittests for RemoveKthNodeFromEnd.py Method signatures and docstrings: - def SetUp(self): Set Up input list. - def test_RemoveKthNodeFromEnd(self): Checks if output is correct. <|skeleton|> class test_RemoveKthNode...
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
<|skeleton|> class test_RemoveKthNodeFromEnd: """Class with unittests for RemoveKthNodeFromEnd.py""" def SetUp(self): """Set Up input list.""" <|body_0|> def test_RemoveKthNodeFromEnd(self): """Checks if output is correct.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_RemoveKthNodeFromEnd: """Class with unittests for RemoveKthNodeFromEnd.py""" def SetUp(self): """Set Up input list.""" self.zero = LinkedList(0) self.one = LinkedList(1) self.two = LinkedList(2) self.three = LinkedList(3) self.four = LinkedList(4) ...
the_stack_v2_python_sparse
AlgoExpert_algorithms/Medium/RemoveKthNodeFromEnd/test_RemoveKthNodeFromEnd.py
JakubKazimierski/PythonPortfolio
train
9
d289e5547441ca375772b60e966cb0cf439913fb
[ "super().__init__()\nself.size = size\nself.trg_trg_att = MultiHeadedAttention(num_heads, size, dropout=dropout)\nself.src_trg_att = MultiHeadedAttention(num_heads, size, dropout=dropout)\nself.feed_forward = PositionwiseFeedForward(size, ff_size=ff_size, dropout=dropout, alpha=alpha, layer_norm=layer_norm, activat...
<|body_start_0|> super().__init__() self.size = size self.trg_trg_att = MultiHeadedAttention(num_heads, size, dropout=dropout) self.src_trg_att = MultiHeadedAttention(num_heads, size, dropout=dropout) self.feed_forward = PositionwiseFeedForward(size, ff_size=ff_size, dropout=drop...
Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward.
TransformerDecoderLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransformerDecoderLayer: """Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward.""" def __init__(self, size: int=0, ff_size: int=0, num_heads: int=0, dropout: float=0.1, alpha: float=1.0, layer_norm: str='post', activation: str='relu') -> None: "...
stack_v2_sparse_classes_36k_train_014154
13,169
permissive
[ { "docstring": "Represents a single Transformer decoder layer. It attends to the source representation and the previous decoder states. Note: don't change the name or the order of members! otherwise pretrained models cannot be loaded correctly. :param size: model dimensionality :param ff_size: size of the feed-...
2
stack_v2_sparse_classes_30k_train_012954
Implement the Python class `TransformerDecoderLayer` described below. Class description: Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward. Method signatures and docstrings: - def __init__(self, size: int=0, ff_size: int=0, num_heads: int=0, dropout: float=0.1, alpha: float=1.0...
Implement the Python class `TransformerDecoderLayer` described below. Class description: Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward. Method signatures and docstrings: - def __init__(self, size: int=0, ff_size: int=0, num_heads: int=0, dropout: float=0.1, alpha: float=1.0...
0968187ac0968007cabebed5e5cb6587c08dff78
<|skeleton|> class TransformerDecoderLayer: """Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward.""" def __init__(self, size: int=0, ff_size: int=0, num_heads: int=0, dropout: float=0.1, alpha: float=1.0, layer_norm: str='post', activation: str='relu') -> None: "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransformerDecoderLayer: """Transformer decoder layer. Consists of self-attention, source-attention, and feed-forward.""" def __init__(self, size: int=0, ff_size: int=0, num_heads: int=0, dropout: float=0.1, alpha: float=1.0, layer_norm: str='post', activation: str='relu') -> None: """Represents ...
the_stack_v2_python_sparse
joeynmt/transformer_layers.py
joeynmt/joeynmt
train
668
b60accf7b765aa9dfa7271ee9566a26305c02e9a
[ "self.name = name\nself.description = description\nself.amount_current = amount_current\nself.amount_ytd = amount_ytd\nself.mtype = mtype\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nname = dictionary.get('name')\ndescription = dictionary.get('description')\namou...
<|body_start_0|> self.name = name self.description = description self.amount_current = amount_current self.amount_ytd = amount_ytd self.mtype = mtype self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: ...
Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurrence starting at one. description (string): The deduction line’s deduction typ...
Deduction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Deduction: """Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurrence starting at one. description (string...
stack_v2_sparse_classes_36k_train_014155
2,999
permissive
[ { "docstring": "Constructor for the Deduction class", "name": "__init__", "signature": "def __init__(self, name=None, description=None, amount_current=None, amount_ytd=None, mtype=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictio...
2
null
Implement the Python class `Deduction` described below. Class description: Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurren...
Implement the Python class `Deduction` described below. Class description: Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurren...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class Deduction: """Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurrence starting at one. description (string...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Deduction: """Implementation of the 'Deduction' model. TODO: type model description here. Attributes: name (string): The normalized category of the deductions in the format [type][number]. The number is the will be the iterating number of the type’s occurrence starting at one. description (string): The deduct...
the_stack_v2_python_sparse
finicityapi/models/deduction.py
monarchmoney/finicity-python
train
0
aa7cee438a10c52c1b6cf24f42b980ce4fadee4a
[ "super(HeadStack, self).__init__(name='head_stack')\nself._bridge_heads = []\nfor head_param in params.bridge:\n head_name = head_param.name.lower()\n module_kwargs = head_param.as_dict()\n self._bridge_heads.append(head_modules['bridge'][head_name](**module_kwargs))", "outputs = {'bridge': {}}\nwith tf....
<|body_start_0|> super(HeadStack, self).__init__(name='head_stack') self._bridge_heads = [] for head_param in params.bridge: head_name = head_param.name.lower() module_kwargs = head_param.as_dict() self._bridge_heads.append(head_modules['bridge'][head_name](**...
Constructs a Head layer given the parameters and head type.
HeadStack
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeadStack: """Constructs a Head layer given the parameters and head type.""" def __init__(self, head_modules, params): """HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the model.""" <|body_0|> def call(self, inputs, t...
stack_v2_sparse_classes_36k_train_014156
3,138
permissive
[ { "docstring": "HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the model.", "name": "__init__", "signature": "def __init__(self, head_modules, params)" }, { "docstring": "Call the layer. Args: inputs: input tensors of different modalities. tra...
2
stack_v2_sparse_classes_30k_train_014206
Implement the Python class `HeadStack` described below. Class description: Constructs a Head layer given the parameters and head type. Method signatures and docstrings: - def __init__(self, head_modules, params): HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the m...
Implement the Python class `HeadStack` described below. Class description: Constructs a Head layer given the parameters and head type. Method signatures and docstrings: - def __init__(self, head_modules, params): HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the m...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class HeadStack: """Constructs a Head layer given the parameters and head type.""" def __init__(self, head_modules, params): """HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the model.""" <|body_0|> def call(self, inputs, t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HeadStack: """Constructs a Head layer given the parameters and head type.""" def __init__(self, head_modules, params): """HeadStack. Args: head_modules: a dictionary containing all head modules. params: Hyperparameters of the model.""" super(HeadStack, self).__init__(name='head_stack') ...
the_stack_v2_python_sparse
vatt/modeling/heads/factory.py
Jimmy-INL/google-research
train
1
926d3a73aacb66b53a1851730cb63376c0a60563
[ "res = []\nself.dfs(candidates, target, 0, [], res)\nreturn res", "if target < 0:\n return\nif target == 0:\n res.append(path)\n return\nfor i in range(index, len(nums)):\n self.dfs(nums, target - nums[i], i, path + [nums[i]], res)" ]
<|body_start_0|> res = [] self.dfs(candidates, target, 0, [], res) return res <|end_body_0|> <|body_start_1|> if target < 0: return if target == 0: res.append(path) return for i in range(index, len(nums)): self.dfs(nums, ta...
Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum.
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum.""" def combinationSum(self, candidates, target): """Given a set of candidate numbers (candidate...
stack_v2_sparse_classes_36k_train_014157
2,337
no_license
[ { "docstring": "Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including t...
2
stack_v2_sparse_classes_30k_train_014412
Implement the Python class `Solution` described below. Class description: Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum. Method signatures and docstrings: - def combinationSum(self, candida...
Implement the Python class `Solution` described below. Class description: Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum. Method signatures and docstrings: - def combinationSum(self, candida...
01fe893ba2e37c9bda79e3081c556698f0b6d2f0
<|skeleton|> class Solution: """Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum.""" def combinationSum(self, candidates, target): """Given a set of candidate numbers (candidate...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum. Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum.""" def combinationSum(self, candidates, target): """Given a set of candidate numbers (candidates) (without d...
the_stack_v2_python_sparse
LeetCode/39_combination_sum.py
KKosukeee/CodingQuestions
train
1
95d7cc0d06c6b9e7e6552d56d9e0d68d1f7c423a
[ "super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\nself.redshift_conn_id = redshift_conn_id\nself.aws_credentials_id = aws_credentials_id\nself.table = table\nself.s3_bucket = s3_bucket\nself.s3_key = s3_key\nself.region = region\nself.file_type = file_type\nself.json_format_file = json_format_file\ns...
<|body_start_0|> super(StageToRedshiftOperator, self).__init__(*args, **kwargs) self.redshift_conn_id = redshift_conn_id self.aws_credentials_id = aws_credentials_id self.table = table self.s3_bucket = s3_bucket self.s3_key = s3_key self.region = region se...
An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions.
StageToRedshiftOperator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StageToRedshiftOperator: """An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions.""" def __init__(self, red...
stack_v2_sparse_classes_36k_train_014158
5,277
no_license
[ { "docstring": "StageToRedshiftOperator Constructor to inialize the object. Parameters ---------- redshift_conn_id : str redshift connection id used by the Postgresql hook. aws_credentials_id : str AWS credential id used by Aws hooks. table : str The table to which we want to stage the data to. s3_bucket : str ...
2
stack_v2_sparse_classes_30k_train_007672
Implement the Python class `StageToRedshiftOperator` described below. Class description: An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and ...
Implement the Python class `StageToRedshiftOperator` described below. Class description: An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and ...
c061dbede550e18111de346e58dfb5f258e4c63f
<|skeleton|> class StageToRedshiftOperator: """An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions.""" def __init__(self, red...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StageToRedshiftOperator: """An airflow operator which stages s3 data to the redshift table. Attributes ---------- copy_sql : str A sql template used for staging the data from S3 path to the table. It requires table, path to s3, credentials, file_formats and regions.""" def __init__(self, redshift_conn_id...
the_stack_v2_python_sparse
Projects/project5-Data Pipelines with Airflow/plugins/operators/stage_redshift.py
MyDataDevOps/DataEngineeringNanoDegree
train
0
074a642b5b495a578ecd731904cc01556aedc788
[ "if robust:\n median = np.median(ser)\n std = np.percentile(ser, 75) - np.percentile(ser, 25)\n return (median, std)\nmean, std = (ser.mean(), ser.std())\nreturn (mean, std)", "_, mask = self.float2int(data[feature])\nser = self.fill(data, feature, **kwargs)\nfillv, origin = (ser[~mask], ser[mask])\nfig ...
<|body_start_0|> if robust: median = np.median(ser) std = np.percentile(ser, 75) - np.percentile(ser, 25) return (median, std) mean, std = (ser.mean(), ser.std()) return (mean, std) <|end_body_0|> <|body_start_1|> _, mask = self.float2int(data[feature...
填充数值特征的父类,用于填充非obejct类型
DistFillNum
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DistFillNum: """填充数值特征的父类,用于填充非obejct类型""" def get_info(self, ser, robust=False): """得到序列的均值、方差或者中位数和四分位差。""" <|body_0|> def plot_fill_num(self, data, feature, **kwargs): """可视化填充的缺失值分布和样本未确实的值的分布。""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_014159
16,602
no_license
[ { "docstring": "得到序列的均值、方差或者中位数和四分位差。", "name": "get_info", "signature": "def get_info(self, ser, robust=False)" }, { "docstring": "可视化填充的缺失值分布和样本未确实的值的分布。", "name": "plot_fill_num", "signature": "def plot_fill_num(self, data, feature, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_018974
Implement the Python class `DistFillNum` described below. Class description: 填充数值特征的父类,用于填充非obejct类型 Method signatures and docstrings: - def get_info(self, ser, robust=False): 得到序列的均值、方差或者中位数和四分位差。 - def plot_fill_num(self, data, feature, **kwargs): 可视化填充的缺失值分布和样本未确实的值的分布。
Implement the Python class `DistFillNum` described below. Class description: 填充数值特征的父类,用于填充非obejct类型 Method signatures and docstrings: - def get_info(self, ser, robust=False): 得到序列的均值、方差或者中位数和四分位差。 - def plot_fill_num(self, data, feature, **kwargs): 可视化填充的缺失值分布和样本未确实的值的分布。 <|skeleton|> class DistFillNum: """填充数值...
823184005a3a2ed70a32b37c0afc2066e6e8907a
<|skeleton|> class DistFillNum: """填充数值特征的父类,用于填充非obejct类型""" def get_info(self, ser, robust=False): """得到序列的均值、方差或者中位数和四分位差。""" <|body_0|> def plot_fill_num(self, data, feature, **kwargs): """可视化填充的缺失值分布和样本未确实的值的分布。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DistFillNum: """填充数值特征的父类,用于填充非obejct类型""" def get_info(self, ser, robust=False): """得到序列的均值、方差或者中位数和四分位差。""" if robust: median = np.median(ser) std = np.percentile(ser, 75) - np.percentile(ser, 25) return (median, std) mean, std = (ser.mean(), ...
the_stack_v2_python_sparse
WorkCode/Models/UserFunc/FillOut.py
johngolt/gitln
train
1
bec0cd42895282b1d22f8f3acba9a9d79acbbbb2
[ "data = super().get_context_data(**kwargs)\nif self.object.serialized:\n data['previous'] = self.object.get_next_serialized_item(reverse=True)\n data['next'] = self.object.get_next_serialized_item()\ndata['ownership_enabled'] = common.models.InvenTreeSetting.get_setting('STOCK_OWNERSHIP_CONTROL')\ndata['item_...
<|body_start_0|> data = super().get_context_data(**kwargs) if self.object.serialized: data['previous'] = self.object.get_next_serialized_item(reverse=True) data['next'] = self.object.get_next_serialized_item() data['ownership_enabled'] = common.models.InvenTreeSetting.get...
Detailed view of a single StockItem object.
StockItemDetail
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StockItemDetail: """Detailed view of a single StockItem object.""" def get_context_data(self, **kwargs): """Add information on the "next" and "previous" StockItem objects, based on the serial numbers.""" <|body_0|> def get(self, request, *args, **kwargs): """Chec...
stack_v2_sparse_classes_36k_train_014160
3,900
permissive
[ { "docstring": "Add information on the \"next\" and \"previous\" StockItem objects, based on the serial numbers.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Check if item exists else return to stock index.", "name": "get", "signatu...
2
null
Implement the Python class `StockItemDetail` described below. Class description: Detailed view of a single StockItem object. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add information on the "next" and "previous" StockItem objects, based on the serial numbers. - def get(self, request, *...
Implement the Python class `StockItemDetail` described below. Class description: Detailed view of a single StockItem object. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add information on the "next" and "previous" StockItem objects, based on the serial numbers. - def get(self, request, *...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class StockItemDetail: """Detailed view of a single StockItem object.""" def get_context_data(self, **kwargs): """Add information on the "next" and "previous" StockItem objects, based on the serial numbers.""" <|body_0|> def get(self, request, *args, **kwargs): """Chec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StockItemDetail: """Detailed view of a single StockItem object.""" def get_context_data(self, **kwargs): """Add information on the "next" and "previous" StockItem objects, based on the serial numbers.""" data = super().get_context_data(**kwargs) if self.object.serialized: ...
the_stack_v2_python_sparse
InvenTree/stock/views.py
inventree/InvenTree
train
3,077
5385b8ba54e3cf316ebd899565314ab28d0efb27
[ "print('\\nLoading Keras model...')\nself.model = load_model('./net_4conv_patience5.h5')\nprint('loaded\\n')\nstatus = 0\nic = None\nic = EasyIce.initialize(sys.argv)\nproperties = ic.getProperties()\nself.lock = threading.Lock()\ntry:\n obj = ic.propertyToProxy('Digitclassifier.Camera.Proxy')\n self.cam = Ca...
<|body_start_0|> print('\nLoading Keras model...') self.model = load_model('./net_4conv_patience5.h5') print('loaded\n') status = 0 ic = None ic = EasyIce.initialize(sys.argv) properties = ic.getProperties() self.lock = threading.Lock() try: ...
Camera
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Camera: def __init__(self): """Camera class gets images from live video and transform them in order to predict the digit in the image.""" <|body_0|> def getImage(self): """Gets the image from the webcam and returns the original image with a ROI draw over it and the t...
stack_v2_sparse_classes_36k_train_014161
4,345
no_license
[ { "docstring": "Camera class gets images from live video and transform them in order to predict the digit in the image.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Gets the image from the webcam and returns the original image with a ROI draw over it and the transfo...
5
stack_v2_sparse_classes_30k_train_018608
Implement the Python class `Camera` described below. Class description: Implement the Camera class. Method signatures and docstrings: - def __init__(self): Camera class gets images from live video and transform them in order to predict the digit in the image. - def getImage(self): Gets the image from the webcam and r...
Implement the Python class `Camera` described below. Class description: Implement the Camera class. Method signatures and docstrings: - def __init__(self): Camera class gets images from live video and transform them in order to predict the digit in the image. - def getImage(self): Gets the image from the webcam and r...
4512c094bedd05646eb8cd2d9d5aba474ccbcb3d
<|skeleton|> class Camera: def __init__(self): """Camera class gets images from live video and transform them in order to predict the digit in the image.""" <|body_0|> def getImage(self): """Gets the image from the webcam and returns the original image with a ROI draw over it and the t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Camera: def __init__(self): """Camera class gets images from live video and transform them in order to predict the digit in the image.""" print('\nLoading Keras model...') self.model = load_model('./net_4conv_patience5.h5') print('loaded\n') status = 0 ic = None...
the_stack_v2_python_sparse
2016-tfg-david-pascual-replicado/Camera/camera.py
RoboticsLabURJC/2017-tfm-alexandre-rodriguez
train
2
b26fb1defb170bfa210f568377e151630e91b286
[ "if cls.credentials is None:\n cls.credentials = service_account.Credentials.from_service_account_info(cls.service_account_info, scopes=cls.GCP_SA_SCOPES)\nrequest = google.auth.transport.requests.Request()\ncls.credentials.refresh(request)\ncurrent_app.logger.info('Call successful: obtained token.')\nreturn cls...
<|body_start_0|> if cls.credentials is None: cls.credentials = service_account.Credentials.from_service_account_info(cls.service_account_info, scopes=cls.GCP_SA_SCOPES) request = google.auth.transport.requests.Request() cls.credentials.refresh(request) current_app.logger.info...
Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls.
GoogleAuthService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleAuthService: """Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls.""" def get_token(cls): """Generate an OAuth access token with cloud storage access.""" <|body_0|> def get_report_api_...
stack_v2_sparse_classes_36k_train_014162
3,364
permissive
[ { "docstring": "Generate an OAuth access token with cloud storage access.", "name": "get_token", "signature": "def get_token(cls)" }, { "docstring": "Generate an OAuth access token with IAM configured auth mhr api container to report api container.", "name": "get_report_api_token", "sign...
3
null
Implement the Python class `GoogleAuthService` described below. Class description: Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls. Method signatures and docstrings: - def get_token(cls): Generate an OAuth access token with cloud stora...
Implement the Python class `GoogleAuthService` described below. Class description: Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls. Method signatures and docstrings: - def get_token(cls): Generate an OAuth access token with cloud stora...
af1a4458bb78c16ecca484514d4bd0d1d8c24b5d
<|skeleton|> class GoogleAuthService: """Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls.""" def get_token(cls): """Generate an OAuth access token with cloud storage access.""" <|body_0|> def get_report_api_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GoogleAuthService: """Google Auth Service implementation. Maintains a wrapper to get a service account access token and credentials for Google API calls.""" def get_token(cls): """Generate an OAuth access token with cloud storage access.""" if cls.credentials is None: cls.cred...
the_stack_v2_python_sparse
mhr_api/src/mhr_api/services/gcp_auth/auth_service.py
bcgov/ppr
train
4
55596d8d7b478dbec42c4046bcb78c8e6e34a5d8
[ "if self._started:\n raise RuntimeError('The profiler was already started. It cannot be done again.')\nself._frames[0] = inspect.currentframe()\nself._started = True\nself._copy_cache = False\nself._buffer.log_event(-1, -1, 100, 0, 0)", "if not self._started:\n raise RuntimeError('The profiler was not start...
<|body_start_0|> if self._started: raise RuntimeError('The profiler was already started. It cannot be done again.') self._frames[0] = inspect.currentframe() self._started = True self._copy_cache = False self._buffer.log_event(-1, -1, 100, 0, 0) <|end_body_0|> <|body_...
One class to measure time wasted by profiling.
EventProfilerDebug
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventProfilerDebug: """One class to measure time wasted by profiling.""" def start(self): """Starts the profiling without enabling it.""" <|body_0|> def stop(self): """Stops the unstarted profiling.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_014163
13,879
permissive
[ { "docstring": "Starts the profiling without enabling it.", "name": "start", "signature": "def start(self)" }, { "docstring": "Stops the unstarted profiling.", "name": "stop", "signature": "def stop(self)" } ]
2
stack_v2_sparse_classes_30k_train_006607
Implement the Python class `EventProfilerDebug` described below. Class description: One class to measure time wasted by profiling. Method signatures and docstrings: - def start(self): Starts the profiling without enabling it. - def stop(self): Stops the unstarted profiling.
Implement the Python class `EventProfilerDebug` described below. Class description: One class to measure time wasted by profiling. Method signatures and docstrings: - def start(self): Starts the profiling without enabling it. - def stop(self): Stops the unstarted profiling. <|skeleton|> class EventProfilerDebug: ...
9d52a497e72d2807e87a730b38db1843f3a098ed
<|skeleton|> class EventProfilerDebug: """One class to measure time wasted by profiling.""" def start(self): """Starts the profiling without enabling it.""" <|body_0|> def stop(self): """Stops the unstarted profiling.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventProfilerDebug: """One class to measure time wasted by profiling.""" def start(self): """Starts the profiling without enabling it.""" if self._started: raise RuntimeError('The profiler was already started. It cannot be done again.') self._frames[0] = inspect.curren...
the_stack_v2_python_sparse
cpyquickhelper/profiling/event_profiler.py
sdpython/cpyquickhelper
train
2
5284ea7f59cbc5feb22fecdf99f88f664a644450
[ "obj = form.save(commit=False)\nif obj.user_id is None:\n obj.user = request.user\nreturn super(OwnableAdmin, self).save_form(request, form, change)", "opts = self.model._meta\nmodel_name = ('%s.%s' % (opts.app_label, opts.object_name)).lower()\nmodels_all_editable = settings.OWNABLE_MODELS_ALL_EDITABLE\nmodel...
<|body_start_0|> obj = form.save(commit=False) if obj.user_id is None: obj.user = request.user return super(OwnableAdmin, self).save_form(request, form, change) <|end_body_0|> <|body_start_1|> opts = self.model._meta model_name = ('%s.%s' % (opts.app_label, opts.obje...
Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this will include the ``user`` field in the required fields for the admin change form w...
OwnableAdmin
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OwnableAdmin: """Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this will include the ``user`` field in the req...
stack_v2_sparse_classes_36k_train_014164
17,362
permissive
[ { "docstring": "Set the object's owner as the logged in user.", "name": "save_form", "signature": "def save_form(self, request, form, change)" }, { "docstring": "Filter the change list by currently logged in user if not a superuser. We also skip filtering if the model for this admin class has be...
2
stack_v2_sparse_classes_30k_train_021119
Implement the Python class `OwnableAdmin` described below. Class description: Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this wil...
Implement the Python class `OwnableAdmin` described below. Class description: Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this wil...
29203de1d111a6d94d576a89430b37edd24cef55
<|skeleton|> class OwnableAdmin: """Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this will include the ``user`` field in the req...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OwnableAdmin: """Admin class for models that subclass the abstract ``Ownable`` model. Handles limiting the change list to objects owned by the logged in user, as well as setting the owner of newly created objects to the logged in user. Remember that this will include the ``user`` field in the required fields ...
the_stack_v2_python_sparse
mezzanine/core/admin.py
fermorltd/mezzanine
train
6
0f021e1bd51522bcc09de1c9f48836b88a41b01b
[ "len1 = len(set(candies))\nif len1 > len(candies) / 2:\n return int(len(candies) / 2)\nelse:\n return len1", "sister_count = len(candies) // 2\nunique_candies = set(candies)\nreturn min(sister_count, len(unique_candies))" ]
<|body_start_0|> len1 = len(set(candies)) if len1 > len(candies) / 2: return int(len(candies) / 2) else: return len1 <|end_body_0|> <|body_start_1|> sister_count = len(candies) // 2 unique_candies = set(candies) return min(sister_count, len(unique...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def distributeCandies(self, candies): """:type candies: List[int] :rtype: int""" <|body_0|> def distributeCandies2(self, candies): """:type candies: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> len1 = len(set(candi...
stack_v2_sparse_classes_36k_train_014165
613
no_license
[ { "docstring": ":type candies: List[int] :rtype: int", "name": "distributeCandies", "signature": "def distributeCandies(self, candies)" }, { "docstring": ":type candies: List[int] :rtype: int", "name": "distributeCandies2", "signature": "def distributeCandies2(self, candies)" } ]
2
stack_v2_sparse_classes_30k_train_010878
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def distributeCandies(self, candies): :type candies: List[int] :rtype: int - def distributeCandies2(self, candies): :type candies: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def distributeCandies(self, candies): :type candies: List[int] :rtype: int - def distributeCandies2(self, candies): :type candies: List[int] :rtype: int <|skeleton|> class Solut...
f777f0224f188a787457c418fa3331c1e92d13e5
<|skeleton|> class Solution: def distributeCandies(self, candies): """:type candies: List[int] :rtype: int""" <|body_0|> def distributeCandies2(self, candies): """:type candies: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def distributeCandies(self, candies): """:type candies: List[int] :rtype: int""" len1 = len(set(candies)) if len1 > len(candies) / 2: return int(len(candies) / 2) else: return len1 def distributeCandies2(self, candies): """:type ca...
the_stack_v2_python_sparse
let575.py
fredfeng0326/LeetCode
train
3
4e5aaf07f9a99c88cddd7d8ef47b6689526a119b
[ "length = 0\nnode = head\nwhile node:\n length += 1\n node = node.next\ndummy = ListNode(0)\ndummy.next = head\ni = 0\nprev = dummy\nwhile i < length - n:\n i += 1\n prev = prev.next\nprev.next = prev.next.next\nreturn dummy.next", "dummy = ListNode(0)\ndummy.next = head\nfront = dummy\nback = dummy\n...
<|body_start_0|> length = 0 node = head while node: length += 1 node = node.next dummy = ListNode(0) dummy.next = head i = 0 prev = dummy while i < length - n: i += 1 prev = prev.next prev.next = prev...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: """1. 扫描两遍""" <|body_0|> def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: """KEY: 2. 双指针""" <|body_1|> <|end_skeleton|> <|body_start_0|> length = 0 no...
stack_v2_sparse_classes_36k_train_014166
2,002
no_license
[ { "docstring": "1. 扫描两遍", "name": "removeNthFromEnd_1", "signature": "def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode" }, { "docstring": "KEY: 2. 双指针", "name": "removeNthFromEnd", "signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: 1. 扫描两遍 - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: KEY: 2. 双指针
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: 1. 扫描两遍 - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: KEY: 2. 双指针 <|skeleton|> class Soluti...
4732fb80710a08a715c3e7080c394f5298b8326d
<|skeleton|> class Solution: def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: """1. 扫描两遍""" <|body_0|> def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: """KEY: 2. 双指针""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode: """1. 扫描两遍""" length = 0 node = head while node: length += 1 node = node.next dummy = ListNode(0) dummy.next = head i = 0 prev = dummy whi...
the_stack_v2_python_sparse
.leetcode/19.删除链表的倒数第n个节点.py
xiaoruijiang/algorithm
train
0
86818570e6aaacf6e897de3c50c140910a26e736
[ "self.config = self.trainer.config\nif vega.is_torch_backend():\n count_input = torch.FloatTensor(1, 3, 192, 192).cuda()\nelif vega.is_tf_backend():\n tf.reset_default_graph()\n count_input = tf.random_uniform([1, 192, 192, 3], dtype=tf.float32)\nflops_count, params_count = calc_model_flops_params(self.tra...
<|body_start_0|> self.config = self.trainer.config if vega.is_torch_backend(): count_input = torch.FloatTensor(1, 3, 192, 192).cuda() elif vega.is_tf_backend(): tf.reset_default_graph() count_input = tf.random_uniform([1, 192, 192, 3], dtype=tf.float32) ...
Construct the trainer of Adelaide-EA.
AdelaideEATrainerCallback
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdelaideEATrainerCallback: """Construct the trainer of Adelaide-EA.""" def before_train(self, logs=None): """Be called before the training process.""" <|body_0|> def after_epoch(self, epoch, logs=None): """Update gflops and kparams.""" <|body_1|> def...
stack_v2_sparse_classes_36k_train_014167
2,317
permissive
[ { "docstring": "Be called before the training process.", "name": "before_train", "signature": "def before_train(self, logs=None)" }, { "docstring": "Update gflops and kparams.", "name": "after_epoch", "signature": "def after_epoch(self, epoch, logs=None)" }, { "docstring": "Make ...
3
null
Implement the Python class `AdelaideEATrainerCallback` described below. Class description: Construct the trainer of Adelaide-EA. Method signatures and docstrings: - def before_train(self, logs=None): Be called before the training process. - def after_epoch(self, epoch, logs=None): Update gflops and kparams. - def mak...
Implement the Python class `AdelaideEATrainerCallback` described below. Class description: Construct the trainer of Adelaide-EA. Method signatures and docstrings: - def before_train(self, logs=None): Be called before the training process. - def after_epoch(self, epoch, logs=None): Update gflops and kparams. - def mak...
df51ed9c1d6dbde1deef63f2a037a369f8554406
<|skeleton|> class AdelaideEATrainerCallback: """Construct the trainer of Adelaide-EA.""" def before_train(self, logs=None): """Be called before the training process.""" <|body_0|> def after_epoch(self, epoch, logs=None): """Update gflops and kparams.""" <|body_1|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdelaideEATrainerCallback: """Construct the trainer of Adelaide-EA.""" def before_train(self, logs=None): """Be called before the training process.""" self.config = self.trainer.config if vega.is_torch_backend(): count_input = torch.FloatTensor(1, 3, 192, 192).cuda() ...
the_stack_v2_python_sparse
built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/algorithms/nas/adelaide_ea/adelaide_trainer_callback.py
Huawei-Ascend/modelzoo
train
1
d7784f46060d2636ff485544f671b0617ddf3fa3
[ "output = ''\nsummary = ''\nlogic = True\nfor bucket in list(result.keys()):\n summary += '\\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n Analyzing for Bucket {0}'.format(bucket)\n summary += '...
<|body_start_0|> output = '' summary = '' logic = True for bucket in list(result.keys()): summary += '\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' output += '\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' output += '\n...
Class containing methods to help analyze results for data analysis
DataAnalysisResultAnalyzer
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result This ...
stack_v2_sparse_classes_36k_train_014168
48,606
permissive
[ { "docstring": "Method to Generate & analyze result AND output the logical and analysis result This works on a bucket level only since we have already taken a union for all nodes", "name": "analyze_all_result", "signature": "def analyze_all_result(self, result, deletedItems=False, addedItems=False, upda...
3
null
Implement the Python class `DataAnalysisResultAnalyzer` described below. Class description: Class containing methods to help analyze results for data analysis Method signatures and docstrings: - def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz...
Implement the Python class `DataAnalysisResultAnalyzer` described below. Class description: Class containing methods to help analyze results for data analysis Method signatures and docstrings: - def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz...
9d8220a0925327bddf0e10887e22b57c5d6adb37
<|skeleton|> class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result This ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result This works on a bu...
the_stack_v2_python_sparse
lib/couchbase_helper/data_analysis_helper.py
couchbase/testrunner
train
18
c96b040eb2334c8b0acfd63708be915bdbd75589
[ "super(MergeCell, self).__init__()\ninp_1, inp_2 = inps\nself.op_1 = ctx_cell(op_names=op_names, config=ctx_config, inp=inp_1, repeats=repeats)\nself.op_2 = ctx_cell(op_names=op_names, config=ctx_config, inp=inp_2, repeats=repeats)\nself.agg = AggregateCell(size_1=inp_1, size_2=inp_2, agg_size=agg_size, concat=cell...
<|body_start_0|> super(MergeCell, self).__init__() inp_1, inp_2 = inps self.op_1 = ctx_cell(op_names=op_names, config=ctx_config, inp=inp_1, repeats=repeats) self.op_2 = ctx_cell(op_names=op_names, config=ctx_config, inp=inp_2, repeats=repeats) self.agg = AggregateCell(size_1=inp...
Pass two inputs through ContextualCell, and aggregate their results.
MergeCell
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MergeCell: """Pass two inputs through ContextualCell, and aggregate their results.""" def __init__(self, op_names, ctx_config, conn, inps, agg_size, ctx_cell, repeats=1, cell_concat=False): """Construct MergeCell class. :param op_names: list of operation indices :param ctx_config: li...
stack_v2_sparse_classes_36k_train_014169
8,338
permissive
[ { "docstring": "Construct MergeCell class. :param op_names: list of operation indices :param ctx_config: list of config numbers :param conn: list of two indices :param inps: channel of first and second input :param agg_size: number of aggregation channel :param ctx_cell: ctx module :param repeats: number of rep...
2
null
Implement the Python class `MergeCell` described below. Class description: Pass two inputs through ContextualCell, and aggregate their results. Method signatures and docstrings: - def __init__(self, op_names, ctx_config, conn, inps, agg_size, ctx_cell, repeats=1, cell_concat=False): Construct MergeCell class. :param ...
Implement the Python class `MergeCell` described below. Class description: Pass two inputs through ContextualCell, and aggregate their results. Method signatures and docstrings: - def __init__(self, op_names, ctx_config, conn, inps, agg_size, ctx_cell, repeats=1, cell_concat=False): Construct MergeCell class. :param ...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class MergeCell: """Pass two inputs through ContextualCell, and aggregate their results.""" def __init__(self, op_names, ctx_config, conn, inps, agg_size, ctx_cell, repeats=1, cell_concat=False): """Construct MergeCell class. :param op_names: list of operation indices :param ctx_config: li...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MergeCell: """Pass two inputs through ContextualCell, and aggregate their results.""" def __init__(self, op_names, ctx_config, conn, inps, agg_size, ctx_cell, repeats=1, cell_concat=False): """Construct MergeCell class. :param op_names: list of operation indices :param ctx_config: list of config ...
the_stack_v2_python_sparse
zeus/modules/blocks/micro_decoder.py
huawei-noah/xingtian
train
308
c791596abbd38c58500e87328052720b387ac850
[ "self.inventory = []\nself.name = 'Mysterious denizen'\nLog.info('new player created')", "result = self.get(thing_name) is not None\nLog.info('thing: %s, result: %s' % (thing_name, result))\nreturn result", "Log.info('thing: %s' % thing_name)\nfor thing in self.inventory:\n if thing.name == thing_name:\n ...
<|body_start_0|> self.inventory = [] self.name = 'Mysterious denizen' Log.info('new player created') <|end_body_0|> <|body_start_1|> result = self.get(thing_name) is not None Log.info('thing: %s, result: %s' % (thing_name, result)) return result <|end_body_1|> <|body_st...
models a player (user) in the game environment
Player
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Player: """models a player (user) in the game environment""" def __init__(self): """creates a new player""" <|body_0|> def has(self, thing_name): """checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :retur...
stack_v2_sparse_classes_36k_train_014170
39,311
no_license
[ { "docstring": "creates a new player", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :return: True if the item is present in the Player's inventory", "name":...
5
stack_v2_sparse_classes_30k_train_021012
Implement the Python class `Player` described below. Class description: models a player (user) in the game environment Method signatures and docstrings: - def __init__(self): creates a new player - def has(self, thing_name): checks if this Player has an item with a given name in their inventory :param thing_name: the...
Implement the Python class `Player` described below. Class description: models a player (user) in the game environment Method signatures and docstrings: - def __init__(self): creates a new player - def has(self, thing_name): checks if this Player has an item with a given name in their inventory :param thing_name: the...
ad9ac095c335fedba5ae294331e1846c036d560a
<|skeleton|> class Player: """models a player (user) in the game environment""" def __init__(self): """creates a new player""" <|body_0|> def has(self, thing_name): """checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :retur...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Player: """models a player (user) in the game environment""" def __init__(self): """creates a new player""" self.inventory = [] self.name = 'Mysterious denizen' Log.info('new player created') def has(self, thing_name): """checks if this Player has an item with...
the_stack_v2_python_sparse
lab/Lab12.py
csumb-serious-business/18-FallB-205-Lab11
train
0
3d94a69c9696ffff86a98363b8f75c4b8139ac47
[ "self._trigger = trigger\nself._echo = echo\nself._speed_of_sound = 33100 + 0.6 * temperature\nself._trigger.write(0)", "self._trigger.write(1)\nwait_us(10)\nself._trigger.write(0)\nwhile self._echo.read() == 0:\n pass\nstart = time.time()\nwhile self._echo.read() != 0:\n pass\nend = time.time()\nreturn (en...
<|body_start_0|> self._trigger = trigger self._echo = echo self._speed_of_sound = 33100 + 0.6 * temperature self._trigger.write(0) <|end_body_0|> <|body_start_1|> self._trigger.write(1) wait_us(10) self._trigger.write(0) while self._echo.read() == 0: ...
SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V echo from the sr04 to the Pi must be reduced to 3.3V, for instance by a tw...
sr04
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sr04: """SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V echo from the sr04 to the Pi must be reduc...
stack_v2_sparse_classes_36k_train_014171
1,750
permissive
[ { "docstring": "Create an sr04 interface object. Create an sr04 object from the trigger (output to sr04) and echo (input from sr04, via resistors) pins. The speed of sound is somewhat dependant on the temperature. By default a temperature of 20 degrees is assumed, but you can specify a different temperature.", ...
2
stack_v2_sparse_classes_30k_train_005444
Implement the Python class `sr04` described below. Class description: SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V ech...
Implement the Python class `sr04` described below. Class description: SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V ech...
f00f2acf23bc7160d0970be609b06ea4d824b76b
<|skeleton|> class sr04: """SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V echo from the sr04 to the Pi must be reduc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class sr04: """SR04 ultrasonic distance sensor interface. The HC-SR04 is an ultrasonic distance sensor. It runs at 5 Volt. The Pi runs at 3.3V. The trigger output to the sr04 is no problem, the sr04 will recognise the 3.3V from the Pi as a valid signal. The 5V echo from the sr04 to the Pi must be reduced to 3.3V, f...
the_stack_v2_python_sparse
hwpy_modules/sr04.py
wovo/hwpy
train
0
65e8caeb0cb2bb3afb521fdb7b85d00be851a109
[ "ret = 0\nlength_of_word = len(A[0])\nlength_of_A = len(A)\nis_sorted = [0] * (length_of_A - 1)\nfor j in range(length_of_word):\n is_sorted2 = is_sorted[:]\n for i in range(length_of_A - 1):\n if A[i][j] > A[i + 1][j] and is_sorted[i] == 0:\n ret += 1\n break\n is_sorted2[...
<|body_start_0|> ret = 0 length_of_word = len(A[0]) length_of_A = len(A) is_sorted = [0] * (length_of_A - 1) for j in range(length_of_word): is_sorted2 = is_sorted[:] for i in range(length_of_A - 1): if A[i][j] > A[i + 1][j] and is_sorted[i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minDeletionSize(self, A): """:type A: List[str] :rtype: int""" <|body_0|> def minDeletionSize2(self, A): """:type A: List[str] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ret = 0 length_of_word = len(A[0]) ...
stack_v2_sparse_classes_36k_train_014172
1,791
no_license
[ { "docstring": ":type A: List[str] :rtype: int", "name": "minDeletionSize", "signature": "def minDeletionSize(self, A)" }, { "docstring": ":type A: List[str] :rtype: int", "name": "minDeletionSize2", "signature": "def minDeletionSize2(self, A)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDeletionSize(self, A): :type A: List[str] :rtype: int - def minDeletionSize2(self, A): :type A: List[str] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minDeletionSize(self, A): :type A: List[str] :rtype: int - def minDeletionSize2(self, A): :type A: List[str] :rtype: int <|skeleton|> class Solution: def minDeletionSiz...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def minDeletionSize(self, A): """:type A: List[str] :rtype: int""" <|body_0|> def minDeletionSize2(self, A): """:type A: List[str] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minDeletionSize(self, A): """:type A: List[str] :rtype: int""" ret = 0 length_of_word = len(A[0]) length_of_A = len(A) is_sorted = [0] * (length_of_A - 1) for j in range(length_of_word): is_sorted2 = is_sorted[:] for i in ra...
the_stack_v2_python_sparse
python/leetcode/955_Delete_Columns_to_Make_Sorted_II.py
bobcaoge/my-code
train
0
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5
[ "args = entity_parser.parse_args()\npage = args['page']\nper_page = args['per_page']\nsort_order = args['order']\nif per_page > 100:\n per_page = 100\ndescending = sort_order == 'desc'\nstart = per_page * (page - 1)\nstop = start + per_page\nkwargs = {'start': start, 'stop': stop, 'descending': descending, 'sess...
<|body_start_0|> args = entity_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_order = args['order'] if per_page > 100: per_page = 100 descending = sort_order == 'desc' start = per_page * (page - 1) stop = start + per_p...
SeriesEpisodesAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeriesEpisodesAPI: def get(self, show_id, session): """Get episodes by show ID""" <|body_0|> def delete(self, show_id, session): """Deletes all episodes of a show""" <|body_1|> <|end_skeleton|> <|body_start_0|> args = entity_parser.parse_args() ...
stack_v2_sparse_classes_36k_train_014173
47,001
permissive
[ { "docstring": "Get episodes by show ID", "name": "get", "signature": "def get(self, show_id, session)" }, { "docstring": "Deletes all episodes of a show", "name": "delete", "signature": "def delete(self, show_id, session)" } ]
2
stack_v2_sparse_classes_30k_train_000581
Implement the Python class `SeriesEpisodesAPI` described below. Class description: Implement the SeriesEpisodesAPI class. Method signatures and docstrings: - def get(self, show_id, session): Get episodes by show ID - def delete(self, show_id, session): Deletes all episodes of a show
Implement the Python class `SeriesEpisodesAPI` described below. Class description: Implement the SeriesEpisodesAPI class. Method signatures and docstrings: - def get(self, show_id, session): Get episodes by show ID - def delete(self, show_id, session): Deletes all episodes of a show <|skeleton|> class SeriesEpisodes...
ea95ff60041beaea9aacbc2d93549e3a6b981dc5
<|skeleton|> class SeriesEpisodesAPI: def get(self, show_id, session): """Get episodes by show ID""" <|body_0|> def delete(self, show_id, session): """Deletes all episodes of a show""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeriesEpisodesAPI: def get(self, show_id, session): """Get episodes by show ID""" args = entity_parser.parse_args() page = args['page'] per_page = args['per_page'] sort_order = args['order'] if per_page > 100: per_page = 100 descending = sort...
the_stack_v2_python_sparse
flexget/components/series/api.py
BrutuZ/Flexget
train
1
87b88498fa0b5a40b4c94c5d8228b2e1d4793a49
[ "context = super().get_context_data()\n' dfirtrack api settings '\nif 'dfirtrack_api' in installed_apps:\n context['dfirtrack_api'] = True\nelse:\n context['dfirtrack_api'] = False\n\"\\n filter: provide initial form values according to config\\n for a better understanding of filter related cond...
<|body_start_0|> context = super().get_context_data() ' dfirtrack api settings ' if 'dfirtrack_api' in installed_apps: context['dfirtrack_api'] = True else: context['dfirtrack_api'] = False "\n filter: provide initial form values according to config...
SystemList
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SystemList: def get_context_data(self, **kwargs): """enrich context data""" <|body_0|> def form_valid(self, form): """save form data to config and call view again""" <|body_1|> <|end_skeleton|> <|body_start_0|> context = super().get_context_data() ...
stack_v2_sparse_classes_36k_train_014174
24,755
permissive
[ { "docstring": "enrich context data", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "save form data to config and call view again", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
stack_v2_sparse_classes_30k_test_000240
Implement the Python class `SystemList` described below. Class description: Implement the SystemList class. Method signatures and docstrings: - def get_context_data(self, **kwargs): enrich context data - def form_valid(self, form): save form data to config and call view again
Implement the Python class `SystemList` described below. Class description: Implement the SystemList class. Method signatures and docstrings: - def get_context_data(self, **kwargs): enrich context data - def form_valid(self, form): save form data to config and call view again <|skeleton|> class SystemList: def ...
58c9fd44d24a351f5b12440fa64f43ec2b861d4c
<|skeleton|> class SystemList: def get_context_data(self, **kwargs): """enrich context data""" <|body_0|> def form_valid(self, form): """save form data to config and call view again""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SystemList: def get_context_data(self, **kwargs): """enrich context data""" context = super().get_context_data() ' dfirtrack api settings ' if 'dfirtrack_api' in installed_apps: context['dfirtrack_api'] = True else: context['dfirtrack_api'] = Fal...
the_stack_v2_python_sparse
dfirtrack_main/views/system_views.py
TKCERT/dfirtrack
train
0
d675ffb926b6f8f2fb131440c062b5fa10eee2f4
[ "super().__init__()\nfull_list = [input_dim] + list(hidden_dims) + [z_dim]\nself.encoder = MLP(dim_list=full_list)\nfull_list.reverse()\nself.decoder = MLP(dim_list=full_list)\nself.noise = noise", "z = self.encoder(x)\nif self.noise > 0:\n z_decoder = z + self.noise * torch.randn_like(z)\nelse:\n z_decoder...
<|body_start_0|> super().__init__() full_list = [input_dim] + list(hidden_dims) + [z_dim] self.encoder = MLP(dim_list=full_list) full_list.reverse() self.decoder = MLP(dim_list=full_list) self.noise = noise <|end_body_0|> <|body_start_1|> z = self.encoder(x) ...
Vanilla Autoencoder torch module
AutoencoderModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoencoderModule: """Vanilla Autoencoder torch module""" def __init__(self, input_dim, hidden_dims, z_dim, noise=0): """Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions. Do not include dimensions of the input layer and the bo...
stack_v2_sparse_classes_36k_train_014175
10,936
no_license
[ { "docstring": "Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions. Do not include dimensions of the input layer and the bottleneck. See MLP for example. z_dim(int): Bottleneck dimension. noise(float): Variance of the gaussian noise applied to the latent s...
2
stack_v2_sparse_classes_30k_train_012672
Implement the Python class `AutoencoderModule` described below. Class description: Vanilla Autoencoder torch module Method signatures and docstrings: - def __init__(self, input_dim, hidden_dims, z_dim, noise=0): Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions...
Implement the Python class `AutoencoderModule` described below. Class description: Vanilla Autoencoder torch module Method signatures and docstrings: - def __init__(self, input_dim, hidden_dims, z_dim, noise=0): Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions...
9027b529eaa4cf0a38f25512141810f92db99639
<|skeleton|> class AutoencoderModule: """Vanilla Autoencoder torch module""" def __init__(self, input_dim, hidden_dims, z_dim, noise=0): """Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions. Do not include dimensions of the input layer and the bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutoencoderModule: """Vanilla Autoencoder torch module""" def __init__(self, input_dim, hidden_dims, z_dim, noise=0): """Init. Args: input_dim(int): Dimension of the input data. hidden_dims(List[int]): List of hidden dimensions. Do not include dimensions of the input layer and the bottleneck. See...
the_stack_v2_python_sparse
grae/models/torch_modules.py
jakerhodes/GRAE
train
0
917c32520057c54b8c26508d63f6751885636dce
[ "test = App4Pyro()\nresult = test.sendURI()\nself.assertTrue(result)", "test = App4Pyro()\ntest.sendURI()\nresult = test.getPayload()\nself.assertTrue(result)" ]
<|body_start_0|> test = App4Pyro() result = test.sendURI() self.assertTrue(result) <|end_body_0|> <|body_start_1|> test = App4Pyro() test.sendURI() result = test.getPayload() self.assertTrue(result) <|end_body_1|>
Test methods for Pyro ORB
App4PyroTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class App4PyroTest: """Test methods for Pyro ORB""" def test_sendURI(self): """Test method for sendURI Compares boolean value True to the actual boolean value""" <|body_0|> def test_getPayload(self): """Test method for getPayload Compares boolean value True to the actu...
stack_v2_sparse_classes_36k_train_014176
710
no_license
[ { "docstring": "Test method for sendURI Compares boolean value True to the actual boolean value", "name": "test_sendURI", "signature": "def test_sendURI(self)" }, { "docstring": "Test method for getPayload Compares boolean value True to the actual boolean value", "name": "test_getPayload", ...
2
stack_v2_sparse_classes_30k_train_011884
Implement the Python class `App4PyroTest` described below. Class description: Test methods for Pyro ORB Method signatures and docstrings: - def test_sendURI(self): Test method for sendURI Compares boolean value True to the actual boolean value - def test_getPayload(self): Test method for getPayload Compares boolean v...
Implement the Python class `App4PyroTest` described below. Class description: Test methods for Pyro ORB Method signatures and docstrings: - def test_sendURI(self): Test method for sendURI Compares boolean value True to the actual boolean value - def test_getPayload(self): Test method for getPayload Compares boolean v...
d2029629a3fbcacd1e0322d96d12adf636ab9d61
<|skeleton|> class App4PyroTest: """Test methods for Pyro ORB""" def test_sendURI(self): """Test method for sendURI Compares boolean value True to the actual boolean value""" <|body_0|> def test_getPayload(self): """Test method for getPayload Compares boolean value True to the actu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class App4PyroTest: """Test methods for Pyro ORB""" def test_sendURI(self): """Test method for sendURI Compares boolean value True to the actual boolean value""" test = App4Pyro() result = test.sendURI() self.assertTrue(result) def test_getPayload(self): """Test met...
the_stack_v2_python_sparse
IST411_Distributed_Object_Computing/Project_Diamond/App4/test_app4Pyro.py
riz5034/PSU
train
1
41cb7080d4173d34a825a03aa9120e40535d9f71
[ "self.trained = False\nself.rank = rank\nself.lbd = lbd\nself.verbose = verbose\nif random_state is not None:\n seed(random_state)", "dg = K.diag() if isinstance(K, Kinterface) else diag(K)\npi = dg / dg.sum()\nn = K.shape[0]\nlinxs = choice(xrange(n), size=self.rank, replace=True, p=pi)\nC = K[:, linxs]\nW = ...
<|body_start_0|> self.trained = False self.rank = rank self.lbd = lbd self.verbose = verbose if random_state is not None: seed(random_state) <|end_body_0|> <|body_start_1|> dg = K.diag() if isinstance(K, Kinterface) else diag(K) pi = dg / dg.sum() ...
:ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the active set and the full data set. :ivar G: (``numpy.ndarray``) Low-rank app...
Nystrom
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Nystrom: """:ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the active set and the full data set. :ivar ...
stack_v2_sparse_classes_36k_train_014177
6,490
permissive
[ { "docstring": ":param rank: (``int``) Maximal decomposition rank. :param lbd: (``float``) regularization parameter (to be used in Kernel Ridge Regression). :param verbose (``bool``) Set verbosity.", "name": "__init__", "signature": "def __init__(self, rank=10, random_state=None, lbd=0, verbose=False)" ...
4
stack_v2_sparse_classes_30k_train_012624
Implement the Python class `Nystrom` described below. Class description: :ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the a...
Implement the Python class `Nystrom` described below. Class description: :ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the a...
d9e7890aaa26cb3877e1a82114ab1e52df595d96
<|skeleton|> class Nystrom: """:ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the active set and the full data set. :ivar ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Nystrom: """:ivar K: (``Kinterface``) or (``numpy.ndarray``) the kernel matrix. :ivar active_set_: The selected avtive set of indices. :ivar K_SS_i: (``numpy.ndarray``) the inverse kernel of the active set. :ivar K_XS: (``numpy.ndarray``) the kernel of the active set and the full data set. :ivar G: (``numpy.n...
the_stack_v2_python_sparse
mklaren/projection/nystrom.py
tkemps/mklaren
train
0
6acf13a974d1b81971f8d2e64203fe94dfd7cde5
[ "self.log = log\nself.socket = socket\nself.request = request", "self.log.debug('Verifying install request')\nfor key in ['package']:\n if key not in self.request:\n raise InstallerError(f'ERROR:No {key} in request')", "pkg_path = self.request['package']\ntry:\n cmd = ['/usr/sbin/installer', '-verb...
<|body_start_0|> self.log = log self.socket = socket self.request = request <|end_body_0|> <|body_start_1|> self.log.debug('Verifying install request') for key in ['package']: if key not in self.request: raise InstallerError(f'ERROR:No {key} in reques...
Runs /usr/sbin/installer to install a package
Installer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Installer: """Runs /usr/sbin/installer to install a package""" def __init__(self, log, socket, request): """Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format.""" <|body_0|> def verify_request(self): ""...
stack_v2_sparse_classes_36k_train_014178
2,756
permissive
[ { "docstring": "Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format.", "name": "__init__", "signature": "def __init__(self, log, socket, request)" }, { "docstring": "Make sure copy request has everything we need", "name": "verify_re...
4
stack_v2_sparse_classes_30k_train_003493
Implement the Python class `Installer` described below. Class description: Runs /usr/sbin/installer to install a package Method signatures and docstrings: - def __init__(self, log, socket, request): Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format. - def ...
Implement the Python class `Installer` described below. Class description: Runs /usr/sbin/installer to install a package Method signatures and docstrings: - def __init__(self, log, socket, request): Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format. - def ...
126f90f7c6ea9c89c164b9dd575520bf97718e38
<|skeleton|> class Installer: """Runs /usr/sbin/installer to install a package""" def __init__(self, log, socket, request): """Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format.""" <|body_0|> def verify_request(self): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Installer: """Runs /usr/sbin/installer to install a package""" def __init__(self, log, socket, request): """Arguments: log A logger instance. socket The socket for the requesting object request A request in plist format.""" self.log = log self.socket = socket self.request ...
the_stack_v2_python_sparse
Code/autopkgserver/installer.py
autopkg/autopkg
train
1,059
e4cc7f263d1e2a103b065e68de700f19b2e0eb2c
[ "num = sum([n * pow(10, len(num) - i - 1) for i, n in enumerate(num)]) + k\nres = []\nwhile num:\n res = [num % 10] + res\n num = num // 10\nreturn res", "res = []\ni = len(num) - 1\ncarry = 0\nwhile k or i >= 0 or carry:\n n1 = num[i] if i >= 0 else 0\n n2 = k % 10 if k else 0\n n = n1 + n2 + carr...
<|body_start_0|> num = sum([n * pow(10, len(num) - i - 1) for i, n in enumerate(num)]) + k res = [] while num: res = [num % 10] + res num = num // 10 return res <|end_body_0|> <|body_start_1|> res = [] i = len(num) - 1 carry = 0 wh...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def addToArrayForm(self, num, k): """:type num: List[int] :type k: int :rtype: List[int]""" <|body_0|> def addToArrayForm(self, num, k): """:type num: List[int] :type k: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_014179
2,023
no_license
[ { "docstring": ":type num: List[int] :type k: int :rtype: List[int]", "name": "addToArrayForm", "signature": "def addToArrayForm(self, num, k)" }, { "docstring": ":type num: List[int] :type k: int :rtype: List[int]", "name": "addToArrayForm", "signature": "def addToArrayForm(self, num, k...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def addToArrayForm(self, num, k): :type num: List[int] :type k: int :rtype: List[int] - def addToArrayForm(self, num, k): :type num: 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 addToArrayForm(self, num, k): :type num: List[int] :type k: int :rtype: List[int] - def addToArrayForm(self, num, k): :type num: List[int] :type k: int :rtype: List[int] <|s...
860590239da0618c52967a55eda8d6bbe00bfa96
<|skeleton|> class Solution: def addToArrayForm(self, num, k): """:type num: List[int] :type k: int :rtype: List[int]""" <|body_0|> def addToArrayForm(self, num, k): """:type num: List[int] :type k: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def addToArrayForm(self, num, k): """:type num: List[int] :type k: int :rtype: List[int]""" num = sum([n * pow(10, len(num) - i - 1) for i, n in enumerate(num)]) + k res = [] while num: res = [num % 10] + res num = num // 10 return res ...
the_stack_v2_python_sparse
LeetCode/p0989/I/add-to-array-form-of-integer.py
Ynjxsjmh/PracticeMakesPerfect
train
0
44aa5ecc53b7637fb6b3caec17d746cc98e78562
[ "left, right = (1, n)\nwhile left <= right:\n mid = (left + right) // 2\n if not isBadVersion(mid - 1) and isBadVersion(mid):\n return mid\n if isBadVersion(mid):\n right = mid - 1\n else:\n left = mid + 1", "l = 1\nr = n\nwhile l < r:\n mid = (l + r) / 2\n if isBadVersion(m...
<|body_start_0|> left, right = (1, n) while left <= right: mid = (left + right) // 2 if not isBadVersion(mid - 1) and isBadVersion(mid): return mid if isBadVersion(mid): right = mid - 1 else: left = mid + 1 <...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def firstBadVersion(self, n): """:type n: int :rtype: int""" <|body_0|> def firstBadVersion2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> left, right = (1, n) while left <= right: ...
stack_v2_sparse_classes_36k_train_014180
962
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "firstBadVersion", "signature": "def firstBadVersion(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "firstBadVersion2", "signature": "def firstBadVersion2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_015261
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def firstBadVersion(self, n): :type n: int :rtype: int - def firstBadVersion2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def firstBadVersion(self, n): :type n: int :rtype: int - def firstBadVersion2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def firstBadVersion(self, n): ...
85128e7d26157b3c36eb43868269de42ea2fcb98
<|skeleton|> class Solution: def firstBadVersion(self, n): """:type n: int :rtype: int""" <|body_0|> def firstBadVersion2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def firstBadVersion(self, n): """:type n: int :rtype: int""" left, right = (1, n) while left <= right: mid = (left + right) // 2 if not isBadVersion(mid - 1) and isBadVersion(mid): return mid if isBadVersion(mid): ...
the_stack_v2_python_sparse
src/First Bad Version.py
jsdiuf/leetcode
train
1
52078b2df4a29be015a0176e613b0d5aa750bcb1
[ "res = super(purchase_order_line, self)._onchange_product_id()\nif self.product_id and self.product_id.purchase_pad_id:\n pad = self.product_id.purchase_pad_id\n list_line = []\n for line in pad.distribution_ids:\n vals = {'company_id': pad.company_id.id, 'type': line.type, 'value': line.value, 'acc...
<|body_start_0|> res = super(purchase_order_line, self)._onchange_product_id() if self.product_id and self.product_id.purchase_pad_id: pad = self.product_id.purchase_pad_id list_line = [] for line in pad.distribution_ids: vals = {'company_id': pad.comp...
purchase_order_line
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class purchase_order_line: def _onchange_product_id(self): """Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique""" <|body_0|> def create_purchase_order_line(self, purchase=False, product=None, values=None, first_qty=False, forced_qty=False, not_...
stack_v2_sparse_classes_36k_train_014181
4,289
no_license
[ { "docstring": "Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique", "name": "_onchange_product_id", "signature": "def _onchange_product_id(self)" }, { "docstring": "Surcharge de la méthode de création des lignes d'achat afin de prendre en compte la distributio...
2
null
Implement the Python class `purchase_order_line` described below. Class description: Implement the purchase_order_line class. Method signatures and docstrings: - def _onchange_product_id(self): Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique - def create_purchase_order_line(self,...
Implement the Python class `purchase_order_line` described below. Class description: Implement the purchase_order_line class. Method signatures and docstrings: - def _onchange_product_id(self): Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique - def create_purchase_order_line(self,...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class purchase_order_line: def _onchange_product_id(self): """Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique""" <|body_0|> def create_purchase_order_line(self, purchase=False, product=None, values=None, first_qty=False, forced_qty=False, not_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class purchase_order_line: def _onchange_product_id(self): """Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique""" res = super(purchase_order_line, self)._onchange_product_id() if self.product_id and self.product_id.purchase_pad_id: pad = self....
the_stack_v2_python_sparse
OpenPROD/openprod-addons/analytic_distribution/purchase.py
kazacube-mziouadi/ceci
train
0
3d2c1538dd30697dabbc21cbf9d9835334a7d8aa
[ "soup = bs(response.text, 'html.parser')\npage_div = soup.find('div', class_='col-md-2 col-xs-3 text-right')\nself.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a')[-1] else 0\nyield scrapy.Request(response.url, callback=self.parse_get_next_page)", "soup = bs(response.tex...
<|body_start_0|> soup = bs(response.text, 'html.parser') page_div = soup.find('div', class_='col-md-2 col-xs-3 text-right') self.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a')[-1] else 0 yield scrapy.Request(response.url, callback=self.parse_g...
dprSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class dprSpider: def parse(self, response): """:param response: :return: 最大页码数""" <|body_0|> def parse_get_next_page(self, response): """:param response: :return:一级目录链接""" <|body_1|> def get_news_detail(self, response): """:param response: x新闻正文respons...
stack_v2_sparse_classes_36k_train_014182
4,942
no_license
[ { "docstring": ":param response: :return: 最大页码数", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": ":param response: :return:一级目录链接", "name": "parse_get_next_page", "signature": "def parse_get_next_page(self, response)" }, { "docstring": ":param respons...
3
stack_v2_sparse_classes_30k_train_005093
Implement the Python class `dprSpider` described below. Class description: Implement the dprSpider class. Method signatures and docstrings: - def parse(self, response): :param response: :return: 最大页码数 - def parse_get_next_page(self, response): :param response: :return:一级目录链接 - def get_news_detail(self, response): :pa...
Implement the Python class `dprSpider` described below. Class description: Implement the dprSpider class. Method signatures and docstrings: - def parse(self, response): :param response: :return: 最大页码数 - def parse_get_next_page(self, response): :param response: :return:一级目录链接 - def get_news_detail(self, response): :pa...
1bcb03a48aff1ebca4e04a5c060be299ca9881d4
<|skeleton|> class dprSpider: def parse(self, response): """:param response: :return: 最大页码数""" <|body_0|> def parse_get_next_page(self, response): """:param response: :return:一级目录链接""" <|body_1|> def get_news_detail(self, response): """:param response: x新闻正文respons...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class dprSpider: def parse(self, response): """:param response: :return: 最大页码数""" soup = bs(response.text, 'html.parser') page_div = soup.find('div', class_='col-md-2 col-xs-3 text-right') self.max_page = int(page_div.select('a')[-1].get('href').split('/')[-1]) if page_div.select('a'...
the_stack_v2_python_sparse
crawler/v1/dprgoid.py
AMAtreus/dg_crawler_website
train
0
61c24e6a861cbd9e3f4b822619c6d42c9b293c2a
[ "max_sieve = 1000000\nif n > max_sieve:\n print('%d is too large to compute sieve' % d)\n sys.exit(-1)\nself.mx = n * n\nself.sieve(n)", "if n > self.mx:\n print('%d is too large to factor. Max size is %d' % (n, mx))\n return False\nsq = int(math.ceil(math.sqrt(n)))\nm = n\nf = []\nfor p in self.plist...
<|body_start_0|> max_sieve = 1000000 if n > max_sieve: print('%d is too large to compute sieve' % d) sys.exit(-1) self.mx = n * n self.sieve(n) <|end_body_0|> <|body_start_1|> if n > self.mx: print('%d is too large to factor. Max size is %d' %...
sieve
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sieve: def __init__(self, n=10000): """Computes the sieve""" <|body_0|> def factor(self, n): """Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_014183
3,579
no_license
[ { "docstring": "Computes the sieve", "name": "__init__", "signature": "def __init__(self, n=10000)" }, { "docstring": "Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p.", "name": "factor", "sign...
5
stack_v2_sparse_classes_30k_train_015311
Implement the Python class `sieve` described below. Class description: Implement the sieve class. Method signatures and docstrings: - def __init__(self, n=10000): Computes the sieve - def factor(self, n): Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime fact...
Implement the Python class `sieve` described below. Class description: Implement the sieve class. Method signatures and docstrings: - def __init__(self, n=10000): Computes the sieve - def factor(self, n): Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime fact...
a34f151d4ec4f1f6b90ad65afc8ef70e78adb28d
<|skeleton|> class sieve: def __init__(self, n=10000): """Computes the sieve""" <|body_0|> def factor(self, n): """Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class sieve: def __init__(self, n=10000): """Computes the sieve""" max_sieve = 1000000 if n > max_sieve: print('%d is too large to compute sieve' % d) sys.exit(-1) self.mx = n * n self.sieve(n) def factor(self, n): """Factors in into its p...
the_stack_v2_python_sparse
euler/utilities/primes.py
khmacdonald/Misc
train
0
c801dee5fcc3f8886deab4774e2d86cfb654f257
[ "super().__init__(CIFAR10Dataset.NAME, batch_size, batch_size_test, shuffle_buffer_size, seed)\nif self.get_test_len() % batch_size_test != 0:\n raise ValueError('Test data not evenly divisible by batch size: {} % {} != 0.'.format(self.get_test_len(), batch_size_test))", "data = super().preprocess(data)\nmean_...
<|body_start_0|> super().__init__(CIFAR10Dataset.NAME, batch_size, batch_size_test, shuffle_buffer_size, seed) if self.get_test_len() % batch_size_test != 0: raise ValueError('Test data not evenly divisible by batch size: {} % {} != 0.'.format(self.get_test_len(), batch_size_test)) <|end_bod...
CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name.
CIFAR10Dataset
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CIFAR10Dataset: """CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name.""" def __init__(self, batch_size, batch_size_test, shuffle_buffer_size=1024, seed=42): """CIFAR10 dataset. Args: batch_size: The batch size to use for the training datasets. batch_size_test: ...
stack_v2_sparse_classes_36k_train_014184
2,838
permissive
[ { "docstring": "CIFAR10 dataset. Args: batch_size: The batch size to use for the training datasets. batch_size_test: The batch size used for the test dataset. shuffle_buffer_size: The buffer size to use for dataset shuffling. seed: The random seed used to shuffle. Returns: Dataset: A dataset object. Raises: Val...
2
null
Implement the Python class `CIFAR10Dataset` described below. Class description: CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name. Method signatures and docstrings: - def __init__(self, batch_size, batch_size_test, shuffle_buffer_size=1024, seed=42): CIFAR10 dataset. Args: batch_size: The batch...
Implement the Python class `CIFAR10Dataset` described below. Class description: CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name. Method signatures and docstrings: - def __init__(self, batch_size, batch_size_test, shuffle_buffer_size=1024, seed=42): CIFAR10 dataset. Args: batch_size: The batch...
d39fc7d46505cb3196cb1edeb32ed0b6dd44c0f9
<|skeleton|> class CIFAR10Dataset: """CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name.""" def __init__(self, batch_size, batch_size_test, shuffle_buffer_size=1024, seed=42): """CIFAR10 dataset. Args: batch_size: The batch size to use for the training datasets. batch_size_test: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CIFAR10Dataset: """CIFAR10 dataset. Attributes: NAME: The Tensorflow Dataset's dataset name.""" def __init__(self, batch_size, batch_size_test, shuffle_buffer_size=1024, seed=42): """CIFAR10 dataset. Args: batch_size: The batch size to use for the training datasets. batch_size_test: The batch siz...
the_stack_v2_python_sparse
rigl/experimental/jax/datasets/cifar10.py
google-research/rigl
train
324
8dcbe90644bd46f5233699283584b8b8451d6d43
[ "shapes = list(map(var_shape, var_list))\ntotal_size = np.sum([int(np.prod(shape)) for shape in shapes])\nself.theta = theta = tf.placeholder(dtype, [total_size])\nstart = 0\nassigns = []\nfor shape, _var in zip(shapes, var_list):\n size = int(np.prod(shape))\n assigns.append(tf.assign(_var, tf.reshape(theta[...
<|body_start_0|> shapes = list(map(var_shape, var_list)) total_size = np.sum([int(np.prod(shape)) for shape in shapes]) self.theta = theta = tf.placeholder(dtype, [total_size]) start = 0 assigns = [] for shape, _var in zip(shapes, var_list): size = int(np.prod...
Set the parameters from a flat vector.
SetFromFlat
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SetFromFlat: """Set the parameters from a flat vector.""" def __init__(self, var_list, dtype=tf.float32, sess=None): """Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dtype : type the type for the placeholder sess : tf.Session ...
stack_v2_sparse_classes_36k_train_014185
28,004
permissive
[ { "docstring": "Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dtype : type the type for the placeholder sess : tf.Session the tensorflow session", "name": "__init__", "signature": "def __init__(self, var_list, dtype=tf.float32, sess=None)" }, ...
2
null
Implement the Python class `SetFromFlat` described below. Class description: Set the parameters from a flat vector. Method signatures and docstrings: - def __init__(self, var_list, dtype=tf.float32, sess=None): Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dty...
Implement the Python class `SetFromFlat` described below. Class description: Set the parameters from a flat vector. Method signatures and docstrings: - def __init__(self, var_list, dtype=tf.float32, sess=None): Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dty...
5c5522b096ddcf3124ff2fcbfb6eb7fa4fc0fb57
<|skeleton|> class SetFromFlat: """Set the parameters from a flat vector.""" def __init__(self, var_list, dtype=tf.float32, sess=None): """Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dtype : type the type for the placeholder sess : tf.Session ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SetFromFlat: """Set the parameters from a flat vector.""" def __init__(self, var_list, dtype=tf.float32, sess=None): """Set the parameters from a flat vector. Parameters ---------- var_list : list of tf.Tensor the variables dtype : type the type for the placeholder sess : tf.Session the tensorflo...
the_stack_v2_python_sparse
hbaselines/utils/tf_util.py
AboudyKreidieh/h-baselines
train
263
27446b7a109f296100c0a523f8a2cd544faa817e
[ "data = super(IntegerControl, self).parse(args)\nvalue = data[self.name]\nif value is not None:\n value = datetime.timedelta(value)\n data[self.name] = value\nreturn data", "result = super(IntegerControl, self).unparse(object)\nvalue = result[self.name]\nif value:\n value = value[:value.find(' ')]\n r...
<|body_start_0|> data = super(IntegerControl, self).parse(args) value = data[self.name] if value is not None: value = datetime.timedelta(value) data[self.name] = value return data <|end_body_0|> <|body_start_1|> result = super(IntegerControl, self).unpars...
Date/Time interval. This control accepts a number of days as its input.
IntervalControl
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IntervalControl: """Date/Time interval. This control accepts a number of days as its input.""" def parse(self, args): """Parse `args' to Python format.""" <|body_0|> def unparse(self, object): """Parse `object' to string format.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k_train_014186
12,353
permissive
[ { "docstring": "Parse `args' to Python format.", "name": "parse", "signature": "def parse(self, args)" }, { "docstring": "Parse `object' to string format.", "name": "unparse", "signature": "def unparse(self, object)" } ]
2
null
Implement the Python class `IntervalControl` described below. Class description: Date/Time interval. This control accepts a number of days as its input. Method signatures and docstrings: - def parse(self, args): Parse `args' to Python format. - def unparse(self, object): Parse `object' to string format.
Implement the Python class `IntervalControl` described below. Class description: Date/Time interval. This control accepts a number of days as its input. Method signatures and docstrings: - def parse(self, args): Parse `args' to Python format. - def unparse(self, object): Parse `object' to string format. <|skeleton|>...
3a533d3158860102866eaf603840691618f39f81
<|skeleton|> class IntervalControl: """Date/Time interval. This control accepts a number of days as its input.""" def parse(self, args): """Parse `args' to Python format.""" <|body_0|> def unparse(self, object): """Parse `object' to string format.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IntervalControl: """Date/Time interval. This control accepts a number of days as its input.""" def parse(self, args): """Parse `args' to Python format.""" data = super(IntegerControl, self).parse(args) value = data[self.name] if value is not None: value = datet...
the_stack_v2_python_sparse
draco2/form/control.py
geertj/draco2
train
0
6038afc0b08d4a18d6282a715d1c5684c3348869
[ "def decorator(subclass):\n cls.subclasses[dataset_type] = subclass\n return subclass\nreturn decorator", "if dataset_type not in cls.subclasses:\n logger.debug('Bad dataset type {}'.format(dataset_type))\n raise ValueError('Bad dataset type {}'.format(dataset_type))\nreturn cls.subclasses[dataset_typ...
<|body_start_0|> def decorator(subclass): cls.subclasses[dataset_type] = subclass return subclass return decorator <|end_body_0|> <|body_start_1|> if dataset_type not in cls.subclasses: logger.debug('Bad dataset type {}'.format(dataset_type)) rais...
Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific dataset (e.g. data download, pre-processing).
BaseDataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseDataset: """Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific dataset (e.g. data download, pre-processi...
stack_v2_sparse_classes_36k_train_014187
15,607
no_license
[ { "docstring": "Register dataset with the dataset manager. Registers the dataset identified by datset_type with the dataset manager. This allows the appropriate dataset to be created automatically when requested. :param dataset_type: Dataset name. :type dataset_type: string", "name": "register_subclass", ...
2
null
Implement the Python class `BaseDataset` described below. Class description: Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific da...
Implement the Python class `BaseDataset` described below. Class description: Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific da...
143ae8d1c518ef2771447dbf6dcb544e5e199f1e
<|skeleton|> class BaseDataset: """Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific dataset (e.g. data download, pre-processi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseDataset: """Base class for dataset configuration objects. Manages registration of dataset configurations and creation of dataset configuration objects. Dataset configurations provide the ability to generate config file sections related to the specific dataset (e.g. data download, pre-processing).""" ...
the_stack_v2_python_sparse
vampire/config_products/BaseDataset.py
asrofialkindi/vampire
train
1
095ad7bef982ef908aae6b22867f33205388c756
[ "self.episode_length = episode_length\nself.env_num = env_num\nself.gamma = gamma\nself.gae_lambda = gae_lambda\nself._use_popart = use_popart\nself.share_obs = np.zeros((self.episode_length + 1, self.env_num, share_obs_shape), dtype=np.float32)\nself.obs = np.zeros((self.episode_length + 1, self.env_num, obs_shape...
<|body_start_0|> self.episode_length = episode_length self.env_num = env_num self.gamma = gamma self.gae_lambda = gae_lambda self._use_popart = use_popart self.share_obs = np.zeros((self.episode_length + 1, self.env_num, share_obs_shape), dtype=np.float32) self.ob...
SeparatedReplayBuffer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeparatedReplayBuffer: def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): """ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length fo...
stack_v2_sparse_classes_36k_train_014188
6,900
permissive
[ { "docstring": "ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length for any episode env_num (int): Number of parallel envs to train gamma (float): discount factor for rewards gae_lambda (float): gae lambda parameter obs...
5
null
Implement the Python class `SeparatedReplayBuffer` described below. Class description: Implement the SeparatedReplayBuffer class. Method signatures and docstrings: - def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): ReplayBuffer for each agent Args: mod...
Implement the Python class `SeparatedReplayBuffer` described below. Class description: Implement the SeparatedReplayBuffer class. Method signatures and docstrings: - def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): ReplayBuffer for each agent Args: mod...
3bb5fe36d245f4d69bae0710dc1dc9d1a172f64d
<|skeleton|> class SeparatedReplayBuffer: def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): """ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length fo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeparatedReplayBuffer: def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): """ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length for any episode ...
the_stack_v2_python_sparse
benchmark/torch/mappo/mappo_buffer.py
PaddlePaddle/PARL
train
3,818
07015697a309763c9dd62e212fb8a48856c6a5bf
[ "if len(arr.shape) == 1:\n arr = np.expand_dims(arr, axis=0)\nif arr.shape[-1] != 599 and arr.shape[-1] != 603:\n raise RuntimeError('This is not an array valid with all classes defined!')\nelif arr.shape[-1] == 599:\n return arr[:, list(CATEGORIES_MAP.values())]\nelse:\n return arr[:, list(CATEGORIES_M...
<|body_start_0|> if len(arr.shape) == 1: arr = np.expand_dims(arr, axis=0) if arr.shape[-1] != 599 and arr.shape[-1] != 603: raise RuntimeError('This is not an array valid with all classes defined!') elif arr.shape[-1] == 599: return arr[:, list(CATEGORIES_MAP...
CategoryEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CategoryEncoder: def transform(arr: np.array) -> np.array: """Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array""" <|body_0|> def invert_transform(arr: np.array) -> np.array: """Returns all categories, tranfor...
stack_v2_sparse_classes_36k_train_014189
2,046
no_license
[ { "docstring": "Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array", "name": "transform", "signature": "def transform(arr: np.array) -> np.array" }, { "docstring": "Returns all categories, tranforming back from useful categories Args: arr:...
2
stack_v2_sparse_classes_30k_train_012993
Implement the Python class `CategoryEncoder` described below. Class description: Implement the CategoryEncoder class. Method signatures and docstrings: - def transform(arr: np.array) -> np.array: Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array - def invert_t...
Implement the Python class `CategoryEncoder` described below. Class description: Implement the CategoryEncoder class. Method signatures and docstrings: - def transform(arr: np.array) -> np.array: Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array - def invert_t...
af685a136a6303b56af857bf70011b222db46fe5
<|skeleton|> class CategoryEncoder: def transform(arr: np.array) -> np.array: """Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array""" <|body_0|> def invert_transform(arr: np.array) -> np.array: """Returns all categories, tranfor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CategoryEncoder: def transform(arr: np.array) -> np.array: """Return the useful categories, according to class exploration notebook Args: arr: np.array Returns: np.array""" if len(arr.shape) == 1: arr = np.expand_dims(arr, axis=0) if arr.shape[-1] != 599 and arr.shape[-1] !...
the_stack_v2_python_sparse
project/utils/category_encoder.py
BAlmeidaS/capstone-udacity-mle
train
1
84cbf9f0b28d1f2a3c30ccebb19e3ab0b429cacc
[ "total_issues = 0\nif os.path.isfile(logfile):\n with open(logfile) as open_file:\n stripped_line = list([line.rstrip() for line in open_file.readlines()])\n for line in stripped_line:\n line_found = re.search(log_message, line, re.IGNORECASE)\n if line_found:\n ...
<|body_start_0|> total_issues = 0 if os.path.isfile(logfile): with open(logfile) as open_file: stripped_line = list([line.rstrip() for line in open_file.readlines()]) for line in stripped_line: line_found = re.search(log_message, line, re.I...
Class to check for issues found in psad logs.
CheckStatus
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckStatus: """Class to check for issues found in psad logs.""" def check_psad(log_message, logfile): """Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.""" <|body_0|> def search_logfile(logfile): ...
stack_v2_sparse_classes_36k_train_014190
5,322
permissive
[ { "docstring": "Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.", "name": "check_psad", "signature": "def check_psad(log_message, logfile)" }, { "docstring": "Look for positive scan results.", "name": "search_logfile", ...
5
stack_v2_sparse_classes_30k_train_010230
Implement the Python class `CheckStatus` described below. Class description: Class to check for issues found in psad logs. Method signatures and docstrings: - def check_psad(log_message, logfile): Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found. ...
Implement the Python class `CheckStatus` described below. Class description: Class to check for issues found in psad logs. Method signatures and docstrings: - def check_psad(log_message, logfile): Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found. ...
e342f6659a4ef1a188ff403e2fc6b06ac6d119c7
<|skeleton|> class CheckStatus: """Class to check for issues found in psad logs.""" def check_psad(log_message, logfile): """Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.""" <|body_0|> def search_logfile(logfile): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckStatus: """Class to check for issues found in psad logs.""" def check_psad(log_message, logfile): """Check number of occurrences of issues in the specified logfile. Returns: An int representing the number of issues found.""" total_issues = 0 if os.path.isfile(logfile): ...
the_stack_v2_python_sparse
docker/oso-psad/src/scripts/check_psad.py
openshift/openshift-tools
train
170
f1cb71ed6a45a6a81068504dfb916292bcdfe8cf
[ "host = DEFAULT_HOST if host is None else host\nport = DEFAULT_PORT if port is None else port\nself._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself._current_list = list()\nself.is_alive = True\ntry:\n self._socket.connect((host, port))\n self._receiver = Thread(target=self._hear_message_from...
<|body_start_0|> host = DEFAULT_HOST if host is None else host port = DEFAULT_PORT if port is None else port self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._current_list = list() self.is_alive = True try: self._socket.connect((host, port...
Client
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Client: def __init__(self, host=None, port=None): """Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor""" <|body_0|> def _hear_message_from_server(self): """Esta funcion es la que q...
stack_v2_sparse_classes_36k_train_014191
2,503
no_license
[ { "docstring": "Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor", "name": "__init__", "signature": "def __init__(self, host=None, port=None)" }, { "docstring": "Esta funcion es la que queda en un thread auxil...
4
stack_v2_sparse_classes_30k_train_001443
Implement the Python class `Client` described below. Class description: Implement the Client class. Method signatures and docstrings: - def __init__(self, host=None, port=None): Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor - de...
Implement the Python class `Client` described below. Class description: Implement the Client class. Method signatures and docstrings: - def __init__(self, host=None, port=None): Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor - de...
1458756a37d927d8dd365ba21cef4490360f1985
<|skeleton|> class Client: def __init__(self, host=None, port=None): """Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor""" <|body_0|> def _hear_message_from_server(self): """Esta funcion es la que q...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Client: def __init__(self, host=None, port=None): """Esta clase representa a un cliente, el cual se conecta a un servidor en host:port. Ademas, puede enviar y recibir mensajes del servidor""" host = DEFAULT_HOST if host is None else host port = DEFAULT_PORT if port is None else port ...
the_stack_v2_python_sparse
Ayudantias/11 - Networking/Ejemplo - Envio de objetos/client.py
frhuerta/Syllabus
train
0
a1db7aadbeb658a757b76d8f33eaf5a3baab6ac2
[ "self.sequence = sequence\nself.sequence_length = len(sequence)\nself.mutations = mutations", "if maximum_number_of_mutations > self.sequence_length:\n logger.warning(f'resetting maximum number of mutations ({maximum_number_of_mutations}), since it is higher than sequence length: {self.sequence_length}')\n ...
<|body_start_0|> self.sequence = sequence self.sequence_length = len(sequence) self.mutations = mutations <|end_body_0|> <|body_start_1|> if maximum_number_of_mutations > self.sequence_length: logger.warning(f'resetting maximum number of mutations ({maximum_number_of_mutatio...
AASequence
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AASequence: def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: """Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_014192
17,866
permissive
[ { "docstring": "Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs.", "name": "__init__", "signature": "def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None" }, ...
2
null
Implement the Python class `AASequence` described below. Class description: Implement the AASequence class. Method signatures and docstrings: - def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: Initialize an AA sequence representation. Args: sequence: AA sequence. muta...
Implement the Python class `AASequence` described below. Class description: Implement the AASequence class. Method signatures and docstrings: - def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: Initialize an AA sequence representation. Args: sequence: AA sequence. muta...
0b69b7d5b261f2f9af3984793c1295b9b80cd01a
<|skeleton|> class AASequence: def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: """Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AASequence: def __init__(self, sequence: str, mutations: Mutations=Mutations(IUPAC_MUTATION_MAPPING)) -> None: """Initialize an AA sequence representation. Args: sequence: AA sequence. mutations: mutations definition. Defaults to uniform sampling of IUPAC AAs.""" self.sequence = sequence ...
the_stack_v2_python_sparse
src/gt4sd/frameworks/enzeptional/optimization.py
GT4SD/gt4sd-core
train
239
338a937c20c72f999bc886be1c995efe488476b5
[ "self.tagged = tagged or []\nself.copy = copy or []\nself.link = symlink or []\nself.tagged_hierarchy = None\nself._check_files()", "self.tagged = self._type_check_files(self.tagged, 'Tagged')\nself.copy = self._type_check_files(self.copy, 'Copyable')\nself.link = self._type_check_files(self.link, 'Symlink')\nsel...
<|body_start_0|> self.tagged = tagged or [] self.copy = copy or [] self.link = symlink or [] self.tagged_hierarchy = None self._check_files() <|end_body_0|> <|body_start_1|> self.tagged = self._type_check_files(self.tagged, 'Tagged') self.copy = self._type_check_...
EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be present within the generated model or node directory. Tagged files are the conf...
EntityFiles
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EntityFiles: """EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be present within the generated model or no...
stack_v2_sparse_classes_36k_train_014193
11,875
permissive
[ { "docstring": "Initialize an EntityFiles instance :param tagged: tagged files for model configuration :type tagged: list of str :param copy: files or directories to copy into model or node directories :type copy: list of str :param symlink: files to symlink into model or node directories :type symlink: list of...
4
null
Implement the Python class `EntityFiles` described below. Class description: EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be p...
Implement the Python class `EntityFiles` described below. Class description: EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be p...
f9e17f00ed1109fd09610111d54ac9cb82bccaa7
<|skeleton|> class EntityFiles: """EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be present within the generated model or no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EntityFiles: """EntityFiles are the files a user wishes to have available to models and nodes within SmartSim. Each entity has a method `entity.attach_generator_files()` that creates one of these objects such that at generation time, each file type will be present within the generated model or node directory....
the_stack_v2_python_sparse
smartsim/entity/files.py
CrayLabs/SmartSim
train
177
e6d8ae0eb196988cfedc077a0f0b1392b50acf7d
[ "is_negative = x < 0\nreversed_num = self.reverse_num(abs(x))\nif -reversed_num < -2 ** 31 or reversed_num > 2 ** 31 - 1:\n return 0\nreturn -reversed_num if is_negative else reversed_num", "reversed = 0\nwhile x > 0:\n reversed += x % 10\n x //= 10\n reversed *= 10\nreturn reversed // 10" ]
<|body_start_0|> is_negative = x < 0 reversed_num = self.reverse_num(abs(x)) if -reversed_num < -2 ** 31 or reversed_num > 2 ** 31 - 1: return 0 return -reversed_num if is_negative else reversed_num <|end_body_0|> <|body_start_1|> reversed = 0 while x > 0: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse(self, x): """(Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the given integer has zeros at the end, then the reversed integer should not have the leading zeroes...
stack_v2_sparse_classes_36k_train_014194
2,101
no_license
[ { "docstring": "(Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the given integer has zeros at the end, then the reversed integer should not have the leading zeroes. If the reversed integer is outside the 32...
2
stack_v2_sparse_classes_30k_train_006773
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): (Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x): (Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the...
6812253b90bdd5a35c6bfba8eac54da9be26d56c
<|skeleton|> class Solution: def reverse(self, x): """(Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the given integer has zeros at the end, then the reversed integer should not have the leading zeroes...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse(self, x): """(Solution, int) -> int Reverse the digits of a given integer. If the given integer is negative, then the reversed integer should be negative as well. If the given integer has zeros at the end, then the reversed integer should not have the leading zeroes. If the rever...
the_stack_v2_python_sparse
python2/reverseInt.py
yichuanma95/leetcode-solns
train
2
2efab58566853984d83853eb9ecc00bcf1771983
[ "self.dict = {}\nfor i in range(len(wordsDict)):\n if wordsDict[i] in self.dict:\n self.dict[wordsDict[i]].append(i)\n else:\n self.dict[wordsDict[i]] = [i]\nfor k in self.dict:\n self.dict[k].sort()\nself.mindist = {}", "if word1 + '_' + word2 in self.mindist:\n return self.mindist['wor...
<|body_start_0|> self.dict = {} for i in range(len(wordsDict)): if wordsDict[i] in self.dict: self.dict[wordsDict[i]].append(i) else: self.dict[wordsDict[i]] = [i] for k in self.dict: self.dict[k].sort() self.mindist = {...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, wordsDict): """:type wordsDict: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.dict = {} for i ...
stack_v2_sparse_classes_36k_train_014195
1,522
no_license
[ { "docstring": ":type wordsDict: List[str]", "name": "__init__", "signature": "def __init__(self, wordsDict)" }, { "docstring": ":type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortest(self, word1, word2)" } ]
2
stack_v2_sparse_classes_30k_train_016253
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, wordsDict): :type wordsDict: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, wordsDict): :type wordsDict: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int <|skeleton|> class WordDistan...
48b43999fb7e2ed82d922e1f64ac76f8fabe4baa
<|skeleton|> class WordDistance: def __init__(self, wordsDict): """:type wordsDict: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, wordsDict): """:type wordsDict: List[str]""" self.dict = {} for i in range(len(wordsDict)): if wordsDict[i] in self.dict: self.dict[wordsDict[i]].append(i) else: self.dict[wordsDict[i]] = [i] ...
the_stack_v2_python_sparse
244.py
saleed/LeetCode
train
2
296ce7a9b959bb0cc8cc6b75363359ec614be1d1
[ "if parent.type != ExternalObjectType.SERIES:\n raise InvalidRelation('part of', parent, self)\nself.series = parent", "try:\n if key == 'episode':\n self.episode = int(content)\n elif key == 'season':\n self.season = int(content)\n else:\n raise InvalidMetadata(ExternalObjectType...
<|body_start_0|> if parent.type != ExternalObjectType.SERIES: raise InvalidRelation('part of', parent, self) self.series = parent <|end_body_0|> <|body_start_1|> try: if key == 'episode': self.episode = int(content) elif key == 'season': ...
An episode of a TV series.
Episode
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Episode: """An episode of a TV series.""" def set_parent(self, parent): """Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.InvalidRelation when the parent's type isn't a :obj:`ExternalO...
stack_v2_sparse_classes_36k_train_014196
38,954
no_license
[ { "docstring": "Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.InvalidRelation when the parent's type isn't a :obj:`ExternalObjectType.SERIES`", "name": "set_parent", "signature": "def set_parent(self, pa...
2
stack_v2_sparse_classes_30k_train_012549
Implement the Python class `Episode` described below. Class description: An episode of a TV series. Method signatures and docstrings: - def set_parent(self, parent): Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.Inval...
Implement the Python class `Episode` described below. Class description: An episode of a TV series. Method signatures and docstrings: - def set_parent(self, parent): Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.Inval...
5f4493bedb36c29e80740676bbb179901272d91e
<|skeleton|> class Episode: """An episode of a TV series.""" def set_parent(self, parent): """Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.InvalidRelation when the parent's type isn't a :obj:`ExternalO...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Episode: """An episode of a TV series.""" def set_parent(self, parent): """Set the parent season. Parameters ---------- parent : ExternalObject the season that contains this :obj:`Episode` Raises ------ matcher.exceptions.InvalidRelation when the parent's type isn't a :obj:`ExternalObjectType.SER...
the_stack_v2_python_sparse
matcher/scheme/object.py
sandhose/obs-matcher
train
2
f25c2d70d1996a1d7c4af3a5f77a615ad0623115
[ "super().validate(data)\nhandle_invalid_fields(self, data)\nreturn data", "dh = DateHelper()\nif value >= materialized_view_month_start(dh).date() and value <= dh.today.date():\n return value\nerror = 'Parameter start_date must be from {} to {}'.format(dh.last_month_start.date(), dh.today.date())\nraise serial...
<|body_start_0|> super().validate(data) handle_invalid_fields(self, data) return data <|end_body_0|> <|body_start_1|> dh = DateHelper() if value >= materialized_view_month_start(dh).date() and value <= dh.today.date(): return value error = 'Parameter start_da...
Serializer for handling query parameters.
OrgQueryParamSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrgQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_014197
5,499
permissive
[ { "docstring": "Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Validate that the start_date is within the expec...
3
null
Implement the Python class `OrgQueryParamSerializer` described below. Class description: Serializer for handling query parameters. Method signatures and docstrings: - def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if...
Implement the Python class `OrgQueryParamSerializer` described below. Class description: Serializer for handling query parameters. Method signatures and docstrings: - def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if...
2979f03fbdd1c20c3abc365a963a1282b426f321
<|skeleton|> class OrgQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrgQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" super().validate(data) ha...
the_stack_v2_python_sparse
koku/api/organizations/serializers.py
luisfdez/koku
train
0
07dcaaa6ac0165186ec9c4df0bf7aa5e5f18500e
[ "super().__init__()\nnum_dim_conditioner = convert_none_to_zero(num_dim_conditioner)\nself.num_dim_data = num_dim_data\n\ndef round_up_to_even(number):\n return math.ceil(number / 2.0) * 2\nself.dim_coupling_in = round_up_to_even(num_dim_data / 2)\nself.dim_coupling_out = num_dim_data - self.dim_coupling_in\nsel...
<|body_start_0|> super().__init__() num_dim_conditioner = convert_none_to_zero(num_dim_conditioner) self.num_dim_data = num_dim_data def round_up_to_even(number): return math.ceil(number / 2.0) * 2 self.dim_coupling_in = round_up_to_even(num_dim_data / 2) sel...
Coupling
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Coupling: def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False): """TODO: add description""" <|body_0|> def forward(self, x, sldj, x_conditioner=None, in...
stack_v2_sparse_classes_36k_train_014198
42,653
no_license
[ { "docstring": "TODO: add description", "name": "__init__", "signature": "def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False)" }, { "docstring": "D dimension of the data, N...
2
stack_v2_sparse_classes_30k_train_019079
Implement the Python class `Coupling` described below. Class description: Implement the Coupling class. Method signatures and docstrings: - def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False): T...
Implement the Python class `Coupling` described below. Class description: Implement the Coupling class. Method signatures and docstrings: - def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False): T...
6d42c7641e9e060802b69c8c9a89aeb02c46c922
<|skeleton|> class Coupling: def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False): """TODO: add description""" <|body_0|> def forward(self, x, sldj, x_conditioner=None, in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Coupling: def __init__(self, num_dim_data, flow_type, rezero_flag, num_centers=None, num_bins=None, num_dim_conditioner=None, learnable_convex_weights=False, cap_householder_refl=False): """TODO: add description""" super().__init__() num_dim_conditioner = convert_none_to_zero(num_dim_c...
the_stack_v2_python_sparse
code/flow_models_backup_old_16_12_2020.py
P4ppenheimer/circle_slice_flow_and_variational_determinant_estimator
train
5
0bc98fe7a9549d9484b78732968681cdd35807d8
[ "if not matrix or not matrix[0]:\n return 0\nm, n = (len(matrix), len(matrix[0]))\ndp = [[0] * (n + 1) for _ in range(m + 1)]\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if matrix[i - 1][j - 1] == '1':\n dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])\nreturn ma...
<|body_start_0|> if not matrix or not matrix[0]: return 0 m, n = (len(matrix), len(matrix[0])) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if matrix[i - 1][j - 1] == '1': dp[i][...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maximalSquare(self, matrix): """dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return:""" <|body_0|> def maximalSquare2(self, matrix): """逻辑写复杂了。 dp[i][j]:i,j能构成的最大正方形边长 遍历矩阵 当[i][...
stack_v2_sparse_classes_36k_train_014199
2,223
no_license
[ { "docstring": "dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return:", "name": "maximalSquare", "signature": "def maximalSquare(self, matrix)" }, { "docstring": "逻辑写复杂了。 dp[i][j]:i,j能构成的最大正方形边长 遍历矩阵 当[i][j]是1的时候,看[i-k,j-k...
2
stack_v2_sparse_classes_30k_val_000545
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalSquare(self, matrix): dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return: - def maximalSqua...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalSquare(self, matrix): dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return: - def maximalSqua...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def maximalSquare(self, matrix): """dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return:""" <|body_0|> def maximalSquare2(self, matrix): """逻辑写复杂了。 dp[i][j]:i,j能构成的最大正方形边长 遍历矩阵 当[i][...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maximalSquare(self, matrix): """dp[i][j] i,j为正方形右下角能构成的最大正方形边长 状态转移方程: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) :param matrix: :return:""" if not matrix or not matrix[0]: return 0 m, n = (len(matrix), len(matrix[0])) dp = [[0] *...
the_stack_v2_python_sparse
221_最大正方形.py
lovehhf/LeetCode
train
0