blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
328bda4e6891fd1d1145b1320580ef8f119262b2 | [
"self.fig = plt.figure()\nsuper().__init__(self.fig)\nself.ax_main = self.fig.add_subplot()\nif hasattr(specmodel, 'spec'):\n if specmodel.spec is not None:\n specmodel._plot_specmodel(self.ax_main)\nself.ax_main.set_xlim(specmodel.xlim)\nself.ax_main.set_ylim(specmodel.ylim)\nself.draw()",
"self.ax_mai... | <|body_start_0|>
self.fig = plt.figure()
super().__init__(self.fig)
self.ax_main = self.fig.add_subplot()
if hasattr(specmodel, 'spec'):
if specmodel.spec is not None:
specmodel._plot_specmodel(self.ax_main)
self.ax_main.set_xlim(specmodel.xlim)
... | A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot | SpecModelCanvas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
de... | stack_v2_sparse_classes_75kplus_train_001400 | 1,655 | permissive | [
{
"docstring": "Initilization method for the SpecFitCanvas :param (SpecModel) specmodel: SpecModel object, which holds information on the astronomical spectrum and its fit.",
"name": "__init__",
"signature": "def __init__(self, specmodel)"
},
{
"docstring": "Plot the spectrum and the model :para... | 2 | stack_v2_sparse_classes_30k_test_001841 | Implement the Python class `SpecModelCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.ax... | Implement the Python class `SpecModelCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.ax... | a71c24f07a13546e662271349b1e83b31ac1720e | <|skeleton|>
class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
def __init__(se... | the_stack_v2_python_sparse | sculptor/specmodelcanvas.py | jtschindler/sculptor | train | 9 |
c8a063328ac99310ee9137b42308900ceb2feb14 | [
"if not inorder or not postorder or len(inorder) == 0:\n return None\n' last element of the post-order list is the current node\\n each iteration will reduce the length of post-order list by 1\\n\\n since elements are popped from the end of the list, create\\n right sub-tree foll... | <|body_start_0|>
if not inorder or not postorder or len(inorder) == 0:
return None
' last element of the post-order list is the current node\n each iteration will reduce the length of post-order list by 1\n\n since elements are popped from the end of the list, create\n ... | BinaryTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def buildFromPostInOrder(self, postorder: List[int], inorder: List[int]) -> TreeNode:
"""use post-order to fetch the nodes use in-order to build out the tree overall complexity of the algorithm : O(N^2) - searching for a value in in-order list : O(N) [line 35] - each recursiv... | stack_v2_sparse_classes_75kplus_train_001401 | 2,664 | permissive | [
{
"docstring": "use post-order to fetch the nodes use in-order to build out the tree overall complexity of the algorithm : O(N^2) - searching for a value in in-order list : O(N) [line 35] - each recursive call : O(N) [line 40 & 41]",
"name": "buildFromPostInOrder",
"signature": "def buildFromPostInOrder... | 2 | null | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def buildFromPostInOrder(self, postorder: List[int], inorder: List[int]) -> TreeNode: use post-order to fetch the nodes use in-order to build out the tree overall complexity ... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def buildFromPostInOrder(self, postorder: List[int], inorder: List[int]) -> TreeNode: use post-order to fetch the nodes use in-order to build out the tree overall complexity ... | 14356c6adb1946417482eaaf6f42dde4b8351d2f | <|skeleton|>
class BinaryTree:
def buildFromPostInOrder(self, postorder: List[int], inorder: List[int]) -> TreeNode:
"""use post-order to fetch the nodes use in-order to build out the tree overall complexity of the algorithm : O(N^2) - searching for a value in in-order list : O(N) [line 35] - each recursiv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryTree:
def buildFromPostInOrder(self, postorder: List[int], inorder: List[int]) -> TreeNode:
"""use post-order to fetch the nodes use in-order to build out the tree overall complexity of the algorithm : O(N^2) - searching for a value in in-order list : O(N) [line 35] - each recursive call : O(N) ... | the_stack_v2_python_sparse | binary_tree/m_create_from_post_in.py | dhrubach/python-code-recipes | train | 1 | |
39ac1e357e1364878d7a3f4a51a5cd4e4cd9a23e | [
"sLabel = self.sDefaultLabel\ndomnode = graph_node.node\nsXmlLabel = domnode.get(self.sLabelAttr)\nsXmlLabel = {'B': 'B', 'I': 'I', 'E': 'I', 'S': 'S', 'O': 'O'}[sXmlLabel]\ntry:\n sLabel = self.dXmlLabel2Label[sXmlLabel]\nexcept KeyError:\n try:\n self.checkIsIgnored(sXmlLabel)\n except:\n r... | <|body_start_0|>
sLabel = self.sDefaultLabel
domnode = graph_node.node
sXmlLabel = domnode.get(self.sLabelAttr)
sXmlLabel = {'B': 'B', 'I': 'I', 'E': 'I', 'S': 'S', 'O': 'O'}[sXmlLabel]
try:
sLabel = self.dXmlLabel2Label[sXmlLabel]
except KeyError:
... | Convert BIESO labeling to BIO | NodeType_BIESO_to_BISO_Shape | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeType_BIESO_to_BISO_Shape:
"""Convert BIESO labeling to BIO"""
def parseDocNodeLabel(self, graph_node, defaultCls=None):
"""Parse and set the graph node label and return its class index raise a ValueError if the label is missing while bOther was not True, or if the label is neithe... | stack_v2_sparse_classes_75kplus_train_001402 | 8,852 | permissive | [
{
"docstring": "Parse and set the graph node label and return its class index raise a ValueError if the label is missing while bOther was not True, or if the label is neither a valid one nor an ignored one",
"name": "parseDocNodeLabel",
"signature": "def parseDocNodeLabel(self, graph_node, defaultCls=No... | 2 | stack_v2_sparse_classes_30k_train_022091 | Implement the Python class `NodeType_BIESO_to_BISO_Shape` described below.
Class description:
Convert BIESO labeling to BIO
Method signatures and docstrings:
- def parseDocNodeLabel(self, graph_node, defaultCls=None): Parse and set the graph node label and return its class index raise a ValueError if the label is mis... | Implement the Python class `NodeType_BIESO_to_BISO_Shape` described below.
Class description:
Convert BIESO labeling to BIO
Method signatures and docstrings:
- def parseDocNodeLabel(self, graph_node, defaultCls=None): Parse and set the graph node label and return its class index raise a ValueError if the label is mis... | 9f2fed81672dc222ca52ee4329eac3126b500d21 | <|skeleton|>
class NodeType_BIESO_to_BISO_Shape:
"""Convert BIESO labeling to BIO"""
def parseDocNodeLabel(self, graph_node, defaultCls=None):
"""Parse and set the graph node label and return its class index raise a ValueError if the label is missing while bOther was not True, or if the label is neithe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeType_BIESO_to_BISO_Shape:
"""Convert BIESO labeling to BIO"""
def parseDocNodeLabel(self, graph_node, defaultCls=None):
"""Parse and set the graph node label and return its class index raise a ValueError if the label is missing while bOther was not True, or if the label is neither a valid one... | the_stack_v2_python_sparse | TranskribusDU/tasks/TablePrototypes/DU_ABPTableSkewed_txtBISO_sepSIO_line.py | Transkribus/TranskribusDU | train | 24 |
ce5ff41227402d99412c197b2dcfd4a113492449 | [
"super(FLAME, self).__init__(*args, **kwargs)\nself.keypoint_src = keypoint_src\nself.keypoint_dst = keypoint_dst\nself.keypoint_approximate = keypoint_approximate\nself.num_verts = self.get_num_verts()\nself.num_faces = self.get_num_faces()\nself.num_joints = get_keypoint_num(convention=self.keypoint_dst)",
"fla... | <|body_start_0|>
super(FLAME, self).__init__(*args, **kwargs)
self.keypoint_src = keypoint_src
self.keypoint_dst = keypoint_dst
self.keypoint_approximate = keypoint_approximate
self.num_verts = self.get_num_verts()
self.num_faces = self.get_num_faces()
self.num_jo... | Extension of the official FLAME implementation. | FLAME | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of ... | stack_v2_sparse_classes_75kplus_train_001403 | 6,673 | permissive | [
{
"docstring": "Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoints. This convention is used for keypoints obtained from joint regressors. Keypoints then undergo conversion into keypoint_dst convention. keypoint_dst: destination convention of keypoints. This conve... | 2 | stack_v2_sparse_classes_30k_val_003014 | Implement the Python class `FLAME` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments for ... | Implement the Python class `FLAME` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments for ... | 9431addec32f7fbeffa1786927a854c0ab79d9ea | <|skeleton|>
class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoints. Th... | the_stack_v2_python_sparse | mmhuman3d/models/body_models/flame.py | open-mmlab/mmhuman3d | train | 966 |
660b40e8076493c33b9cea79e78ce17768d6a882 | [
"if order is None:\n return TableWrapper.all(self, order=collate(Category.name, 'NOCASE'))\nelse:\n return TableWrapper.all(self, order=order)",
"db_record = None\nwith self.session() as session:\n db_record = session.query(self.table_class).filter_by(name=name).first()\nreturn db_record"
] | <|body_start_0|>
if order is None:
return TableWrapper.all(self, order=collate(Category.name, 'NOCASE'))
else:
return TableWrapper.all(self, order=order)
<|end_body_0|>
<|body_start_1|>
db_record = None
with self.session() as session:
db_record = sess... | Class to wrap interaction to the Categories table in the database | CategoriesWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoriesWrapper:
"""Class to wrap interaction to the Categories table in the database"""
def all(self, order=None):
"""Returns all transactions from the database"""
<|body_0|>
def findByName(self, name):
"""Return a Category with the given name"""
<|bod... | stack_v2_sparse_classes_75kplus_train_001404 | 849 | no_license | [
{
"docstring": "Returns all transactions from the database",
"name": "all",
"signature": "def all(self, order=None)"
},
{
"docstring": "Return a Category with the given name",
"name": "findByName",
"signature": "def findByName(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002047 | Implement the Python class `CategoriesWrapper` described below.
Class description:
Class to wrap interaction to the Categories table in the database
Method signatures and docstrings:
- def all(self, order=None): Returns all transactions from the database
- def findByName(self, name): Return a Category with the given ... | Implement the Python class `CategoriesWrapper` described below.
Class description:
Class to wrap interaction to the Categories table in the database
Method signatures and docstrings:
- def all(self, order=None): Returns all transactions from the database
- def findByName(self, name): Return a Category with the given ... | 57c909c8581bef3b66388038a1cf5edda426ecf9 | <|skeleton|>
class CategoriesWrapper:
"""Class to wrap interaction to the Categories table in the database"""
def all(self, order=None):
"""Returns all transactions from the database"""
<|body_0|>
def findByName(self, name):
"""Return a Category with the given name"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoriesWrapper:
"""Class to wrap interaction to the Categories table in the database"""
def all(self, order=None):
"""Returns all transactions from the database"""
if order is None:
return TableWrapper.all(self, order=collate(Category.name, 'NOCASE'))
else:
... | the_stack_v2_python_sparse | src/db/categories.py | cloew/PersonalAccountingSoftware | train | 0 |
79d69363fbe31734700c2d6a312fb3bd0246924c | [
"self.typology = 'SimpleFault'\nself.id = identifier\nself.name = name\nself.trt = trt\nself.geometry = geometry\nself.fault_trace = None\nself.upper_depth = upper_depth\nself.lower_depth = lower_depth\nself.mag_scale_rel = mag_scale_rel\nself.rupt_aspect_ratio = rupt_aspect_ratio\nself.mfd = mfd\nself.rake = rake\... | <|body_start_0|>
self.typology = 'SimpleFault'
self.id = identifier
self.name = name
self.trt = trt
self.geometry = geometry
self.fault_trace = None
self.upper_depth = upper_depth
self.lower_depth = lower_depth
self.mag_scale_rel = mag_scale_rel
... | New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.surface.simple_fault.SimpleFaultSource :param float dip: Dip of the fault surface :param f... | mtkSimpleFaultSource | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.surface.simple_fault.SimpleFaultSource :pa... | stack_v2_sparse_classes_75kplus_train_001405 | 10,020 | permissive | [
{
"docstring": "Instantiate class with just the basic attributes identifier and name",
"name": "__init__",
"signature": "def __init__(self, identifier, name, trt=None, geometry=None, dip=None, upper_depth=None, lower_depth=None, mag_scale_rel=None, rupt_aspect_ratio=None, mfd=None, rake=None)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_018897 | Implement the Python class `mtkSimpleFaultSource` described below.
Class description:
New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.sur... | Implement the Python class `mtkSimpleFaultSource` described below.
Class description:
New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.sur... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.surface.simple_fault.SimpleFaultSource :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: openquake.hazardlib.geo.surface.simple_fault.SimpleFaultSource :param float dip... | the_stack_v2_python_sparse | openquake/hmtk/sources/simple_fault_source.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
bff7b017dfa54596a7b68196d6fdf2e44896c215 | [
"context = super(SponsorshipLevelListView, self).get_context_data(**kwargs)\ncontext['num_sponsorshiplevels'] = context['sponsorshiplevels'].count()\ncontext['unapproved'] = False\nproject_slug = self.kwargs.get('project_slug', None)\ncontext['project_slug'] = project_slug\nif project_slug:\n context['the_projec... | <|body_start_0|>
context = super(SponsorshipLevelListView, self).get_context_data(**kwargs)
context['num_sponsorshiplevels'] = context['sponsorshiplevels'].count()
context['unapproved'] = False
project_slug = self.kwargs.get('project_slug', None)
context['project_slug'] = project... | List view for Sponsorship Level. | SponsorshipLevelListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the ... | stack_v2_sparse_classes_75kplus_train_001406 | 17,162 | no_license | [
{
"docstring": "Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rtype: dict",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
... | 2 | stack_v2_sparse_classes_30k_train_044076 | Implement the Python class `SponsorshipLevelListView` described below.
Class description:
List view for Sponsorship Level.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs:... | Implement the Python class `SponsorshipLevelListView` described below.
Class description:
List view for Sponsorship Level.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs:... | ca489c38fdfde29f75c9c1e7f4b4c55d78d91c79 | <|skeleton|>
class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rt... | the_stack_v2_python_sparse | django_project/changes/views/sponsorship_level.py | gitter-badger/projecta | train | 0 |
ab28329bfd7daadf808d5e3e8adcb44b821ae29a | [
"groundtruths = load_groundtruth(groundtruth_path, object_path)\nself.example_groundtruths = reverse_object_order(groundtruths)\nself.check_entity = check_entity\nself.iou_threshold = iou_threshold",
"if prediction.image_id != groundtruth.image_id:\n return False\nif self.check_entity and prediction.entity != ... | <|body_start_0|>
groundtruths = load_groundtruth(groundtruth_path, object_path)
self.example_groundtruths = reverse_object_order(groundtruths)
self.check_entity = check_entity
self.iou_threshold = iou_threshold
<|end_body_0|>
<|body_start_1|>
if prediction.image_id != groundtrut... | Evaluator for computing vrd metrics. | VRDEvaluator | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_... | stack_v2_sparse_classes_75kplus_train_001407 | 16,875 | permissive | [
{
"docstring": "Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_entity: if True, check the object entity when determining whether an object is detected. iou_threshold: the threshold for correctly detected objects.",
"name"... | 5 | stack_v2_sparse_classes_30k_train_023454 | Implement the Python class `VRDEvaluator` described below.
Class description:
Evaluator for computing vrd metrics.
Method signatures and docstrings:
- def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5): Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground tr... | Implement the Python class `VRDEvaluator` described below.
Class description:
Evaluator for computing vrd metrics.
Method signatures and docstrings:
- def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5): Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground tr... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_entity: if Tr... | the_stack_v2_python_sparse | visual_relationship/evaluation/evaluate_vrd_lib.py | Jimmy-INL/google-research | train | 1 |
a0e49acc8c730929c378924c601b41a8d7cf4485 | [
"super().__init__(detect_lines, detect_lines=detect_lines)\nself._negatives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glob(os.path.join(path, '**', 'negative-*.png'), recursive=True)]\nself._positives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glo... | <|body_start_0|>
super().__init__(detect_lines, detect_lines=detect_lines)
self._negatives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glob(os.path.join(path, '**', 'negative-*.png'), recursive=True)]
self._positives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAY... | Obtains edges for for further processing. | EdgeDetectionTemplateMatching | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
<|body_0|>
def filter(sel... | stack_v2_sparse_classes_75kplus_train_001408 | 2,342 | permissive | [
{
"docstring": "Initializes a new instance of the EdgeDetection class.",
"name": "__init__",
"signature": "def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False)"
},
{
"docstring": "Filters the specified image. :param img: The image to obtain mas... | 2 | stack_v2_sparse_classes_30k_test_001351 | Implement the Python class `EdgeDetectionTemplateMatching` described below.
Class description:
Obtains edges for for further processing.
Method signatures and docstrings:
- def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False): Initializes a new instance of the EdgeD... | Implement the Python class `EdgeDetectionTemplateMatching` described below.
Class description:
Obtains edges for for further processing.
Method signatures and docstrings:
- def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False): Initializes a new instance of the EdgeD... | 9692cf242f6d531fe37dca9ec462c632f1bcf832 | <|skeleton|>
class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
<|body_0|>
def filter(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
super().__init__(detect_lines, detect_lines... | the_stack_v2_python_sparse | pipeline/edges/EdgeDetectionTemplateMatching.py | sunsided/CarND-Advanced-Lane-Lines | train | 1 |
765b8253b24a828ec5bb794779e0f5ad74983783 | [
"try:\n show = series.show_by_id(show_id, session=session)\nexcept NoResultFound:\n return ({'status': 'error', 'message': 'Show with ID %s not found' % show_id}, 404)\nshow = get_series_details(show)\nreturn jsonify(show)",
"try:\n show = series.show_by_id(show_id, session=session)\nexcept NoResultFound... | <|body_start_0|>
try:
show = series.show_by_id(show_id, session=session)
except NoResultFound:
return ({'status': 'error', 'message': 'Show with ID %s not found' % show_id}, 404)
show = get_series_details(show)
return jsonify(show)
<|end_body_0|>
<|body_start_1|>... | SeriesShowAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_75kplus_train_001409 | 36,378 | permissive | [
{
"docstring": "Get show details by ID",
"name": "get",
"signature": "def get(self, show_id, session)"
},
{
"docstring": "Remove series from DB",
"name": "delete",
"signature": "def delete(self, show_id, session)"
},
{
"docstring": "Set the initial episode of an existing show",
... | 3 | null | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | 900bd353a70c5a41176eb505af68ed3fc65a796d | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
try:
show = series.show_by_id(show_id, session=session)
except NoResultFound:
return ({'status': 'error', 'message': 'Show with ID %s not found' % show_id}, 404)
show = get_seri... | the_stack_v2_python_sparse | flexget/plugins/api/series.py | ashumkin/Flexget | train | 1 | |
03099adea2c47f4756ec8b789dca398b0f3e9a4f | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | VIP车无在场严出 | TestNoPresenceVipStrictOutProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNoPresenceVipStrictOutProcess:
"""VIP车无在场严出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def te... | stack_v2_sparse_classes_75kplus_train_001410 | 2,801 | no_license | [
{
"docstring": "创建自定义月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "用自定义月票类型开通月票",
"name": "test_openMonthTicketBill",
"signature": "def test_openMonthTicketBill(self, userLogin, send_d... | 5 | stack_v2_sparse_classes_30k_train_024934 | Implement the Python class `TestNoPresenceVipStrictOutProcess` described below.
Class description:
VIP车无在场严出
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票
- def test_m... | Implement the Python class `TestNoPresenceVipStrictOutProcess` described below.
Class description:
VIP车无在场严出
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票
- def test_m... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestNoPresenceVipStrictOutProcess:
"""VIP车无在场严出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def te... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNoPresenceVipStrictOutProcess:
"""VIP车无在场严出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['valid... | the_stack_v2_python_sparse | test_suite/parkingManage/monthTicket/test_noPresenceVipStrictOutProcess.py | oyebino/pomp_api | train | 1 |
8372a77511ee6b728d2c0e6a91a8577916fc4324 | [
"self.log = logging.getLogger(__name__)\nself.name = name\nself.clouds = {}\nself.group_resources = group_resources\nself.group_yamls = group_yamls\nself.metadata = metadata\nself.config = Config('/etc/cloudscheduler/cloudscheduler.yaml', [])",
"self.config.db_open()\nfor cloud in self.group_resources:\n try:\... | <|body_start_0|>
self.log = logging.getLogger(__name__)
self.name = name
self.clouds = {}
self.group_resources = group_resources
self.group_yamls = group_yamls
self.metadata = metadata
self.config = Config('/etc/cloudscheduler/cloudscheduler.yaml', [])
<|end_body_... | CloudManager class for holding a groups resources and their group yaml | CloudManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resou... | stack_v2_sparse_classes_75kplus_train_001411 | 2,474 | permissive | [
{
"docstring": "Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param group_yamls: the group's yaml from the database.",
"name": "__init__",
"signature": "def __init__(self, name, group_resources, group_yamls, metadata)"
... | 2 | stack_v2_sparse_classes_30k_train_013076 | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls, metadata): Create a new CloudManager. :param name: The name of the group :para... | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls, metadata): Create a new CloudManager. :param name: The name of the group :para... | 65323a6a208484ab0412e54fbbeeeb9070f861bb | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param g... | the_stack_v2_python_sparse | cloudscheduler/cloudmanager.py | hep-gc/cloudscheduler | train | 5 |
6029ae44d34399aa8dfaf94a1b43b23884eafce7 | [
"group = Group.objects.get(id=pk)\ngroup_form = GroupInscriptionForm(instance=group)\naddress_form = AddressForm(instance=group.address)\nreturn render(request, 'group/group_modification.html', {'group_form': group_form, 'address_form': address_form})",
"group = Group.objects.get(id=pk)\nif request.method == 'POS... | <|body_start_0|>
group = Group.objects.get(id=pk)
group_form = GroupInscriptionForm(instance=group)
address_form = AddressForm(instance=group.address)
return render(request, 'group/group_modification.html', {'group_form': group_form, 'address_form': address_form})
<|end_body_0|>
<|body_... | Generic class-based view that permit to group member to modify a community (Group object) | GroupChangeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupChangeView:
"""Generic class-based view that permit to group member to modify a community (Group object)"""
def get(self, request, pk):
"""Method GET to print community informations"""
<|body_0|>
def post(self, request, pk):
"""Method POST to send datas inpu... | stack_v2_sparse_classes_75kplus_train_001412 | 7,810 | no_license | [
{
"docstring": "Method GET to print community informations",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "Method POST to send datas input by user and modify a User object (user account)",
"name": "post",
"signature": "def post(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023956 | Implement the Python class `GroupChangeView` described below.
Class description:
Generic class-based view that permit to group member to modify a community (Group object)
Method signatures and docstrings:
- def get(self, request, pk): Method GET to print community informations
- def post(self, request, pk): Method PO... | Implement the Python class `GroupChangeView` described below.
Class description:
Generic class-based view that permit to group member to modify a community (Group object)
Method signatures and docstrings:
- def get(self, request, pk): Method GET to print community informations
- def post(self, request, pk): Method PO... | cf0b982a6df2b8b4318d12d344ef0827394eedfd | <|skeleton|>
class GroupChangeView:
"""Generic class-based view that permit to group member to modify a community (Group object)"""
def get(self, request, pk):
"""Method GET to print community informations"""
<|body_0|>
def post(self, request, pk):
"""Method POST to send datas inpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupChangeView:
"""Generic class-based view that permit to group member to modify a community (Group object)"""
def get(self, request, pk):
"""Method GET to print community informations"""
group = Group.objects.get(id=pk)
group_form = GroupInscriptionForm(instance=group)
... | the_stack_v2_python_sparse | group/views.py | cleliofavoccia/Share | train | 0 |
64b46bd4a7bea407ade903ffea07f9604be1bffb | [
"super(PublishingDelayTimeMetric, self).__init__()\nself.logger = logging.getLogger(__name__)\nself.accumulated_tuple_delay_time = self.current_metric",
"self.processed_instances += 1\nlast_delay = self.accumulated_tuple_delay_time\ntuple_timestamp = record_pair.anonymized_record.timestamp\nself.accumulated_tuple... | <|body_start_0|>
super(PublishingDelayTimeMetric, self).__init__()
self.logger = logging.getLogger(__name__)
self.accumulated_tuple_delay_time = self.current_metric
<|end_body_0|>
<|body_start_1|>
self.processed_instances += 1
last_delay = self.accumulated_tuple_delay_time
... | Class implementing a publishing delay estimator, measuring the average delay of published tuples | PublishingDelayTimeMetric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
<|body_0|>
def update_estimation(self, time, record_pair, cluster=None):
... | stack_v2_sparse_classes_75kplus_train_001413 | 1,999 | no_license | [
{
"docstring": "Class constructor - initialization",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the publishing delay of current published tuple. :param time: Current time step in stream (last assigned tuple). :param record_pair: Pair of original instance and ... | 3 | stack_v2_sparse_classes_30k_train_039007 | Implement the Python class `PublishingDelayTimeMetric` described below.
Class description:
Class implementing a publishing delay estimator, measuring the average delay of published tuples
Method signatures and docstrings:
- def __init__(self): Class constructor - initialization
- def update_estimation(self, time, rec... | Implement the Python class `PublishingDelayTimeMetric` described below.
Class description:
Class implementing a publishing delay estimator, measuring the average delay of published tuples
Method signatures and docstrings:
- def __init__(self): Class constructor - initialization
- def update_estimation(self, time, rec... | b66862bd469bf078ca12bdb692e39675d40c96b8 | <|skeleton|>
class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
<|body_0|>
def update_estimation(self, time, record_pair, cluster=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
super(PublishingDelayTimeMetric, self).__init__()
self.logger = logging.getLogger(__name__... | the_stack_v2_python_sparse | PerformanceEstimators/ExecutionTimeMetric/PublishingDelayTimeMetric.py | Navypowder/MiDiPSA-for-non-stationary-streams | train | 0 |
734c7845ed1b204740ecca6a7ac45bd8047e5c7c | [
"assert check_argument_types()\nsuper().__init__()\nassert use_masking != use_weighted_masking or not use_masking\nself.use_masking = use_masking\nself.use_weighted_masking = use_weighted_masking\nreduction = 'none' if self.use_weighted_masking else 'mean'\nself.l1_criterion = nn.L1Loss(reduction=reduction)",
"if... | <|body_start_0|>
assert check_argument_types()
super().__init__()
assert use_masking != use_weighted_masking or not use_masking
self.use_masking = use_masking
self.use_weighted_masking = use_weighted_masking
reduction = 'none' if self.use_weighted_masking else 'mean'
... | Loss function module for Diffusion module on DiffSinger. | DiffusionLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiffusionLoss:
"""Loss function module for Diffusion module on DiffSinger."""
def __init__(self, use_masking: bool=True, use_weighted_masking: bool=False):
"""Initialize feed-forward Transformer loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss c... | stack_v2_sparse_classes_75kplus_train_001414 | 15,614 | permissive | [
{
"docstring": "Initialize feed-forward Transformer loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_masking (bool): Whether to weighted masking in loss calculation.",
"name": "__init__",
"signature": "def __init__(self, use_masking: bool=... | 2 | stack_v2_sparse_classes_30k_train_007030 | Implement the Python class `DiffusionLoss` described below.
Class description:
Loss function module for Diffusion module on DiffSinger.
Method signatures and docstrings:
- def __init__(self, use_masking: bool=True, use_weighted_masking: bool=False): Initialize feed-forward Transformer loss module. Args: use_masking (... | Implement the Python class `DiffusionLoss` described below.
Class description:
Loss function module for Diffusion module on DiffSinger.
Method signatures and docstrings:
- def __init__(self, use_masking: bool=True, use_weighted_masking: bool=False): Initialize feed-forward Transformer loss module. Args: use_masking (... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class DiffusionLoss:
"""Loss function module for Diffusion module on DiffSinger."""
def __init__(self, use_masking: bool=True, use_weighted_masking: bool=False):
"""Initialize feed-forward Transformer loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiffusionLoss:
"""Loss function module for Diffusion module on DiffSinger."""
def __init__(self, use_masking: bool=True, use_weighted_masking: bool=False):
"""Initialize feed-forward Transformer loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. u... | the_stack_v2_python_sparse | paddlespeech/t2s/models/diffsinger/diffsinger.py | anniyanvr/DeepSpeech-1 | train | 0 |
5629ad020469bb4f0749842a5e0a615cc8c15d4c | [
"Frame.__init__(self, master)\nself.pack()\nself.createArtistWidgets()",
"top_frame = Frame(self)\nself.labelInput = Label(top_frame, text='Artist Name')\nself.text_in = Entry(top_frame)\nself.labelResult = Label(top_frame, text='Result')\nself.labelInput.pack()\nself.text_in.pack()\nself.labelResult.pack()\ntop_... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.labelInput = Label(top_frame, text='Artist Name')
self.text_in = Entry(top_frame)
self.labelResult = Label(top_frame,... | Application main window class. | getArtist_UI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):... | stack_v2_sparse_classes_75kplus_train_001415 | 10,077 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createArtistWidgets",
"signature": "def createArtistWidgets(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_049637 | Implement the Python class `getArtist_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Han... | Implement the Python class `getArtist_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Han... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class getArtist_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
def createArtistWidgets(self):
"""Add all the widgets to ... | the_stack_v2_python_sparse | Mux_src/Fix_All_Music_Guis.py | rduvalwa5/Mux | train | 0 |
0d65ecbbb78339ad30ca9eaf86e5ca5e500f4017 | [
"if weights is None:\n self.weights = [0, 0, 0]\nelse:\n self.weights = weights[:]\nself.alpha = alpha",
"y_hat = self.weights[-1]\nfor ii in range(len(x_vector)):\n y_hat += self.weights[ii] * x_vector[ii]\nif y_hat >= 0:\n return 1.0\nelse:\n return -1.0",
"y_hat = self.classify(x_vector)\nif y... | <|body_start_0|>
if weights is None:
self.weights = [0, 0, 0]
else:
self.weights = weights[:]
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
y_hat = self.weights[-1]
for ii in range(len(x_vector)):
y_hat += self.weights[ii] * x_vector[ii]
... | Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier | BinaryPerceptron | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alp... | stack_v2_sparse_classes_75kplus_train_001416 | 4,625 | no_license | [
{
"docstring": "Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alpha: Learning rate",
"name": "__init__",
"signature": "def __init__(self, weights=None, alpha=0.5)"
},
{
"docstring": "Method that classifies a given data point into on... | 4 | stack_v2_sparse_classes_30k_train_048752 | Implement the Python class `BinaryPerceptron` described below.
Class description:
Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier
Method signatures and docstrings:
- def __init__(self, weights=None, alpha=0.5): Initialize the Binary Perceptron --- weights: Weight vec... | Implement the Python class `BinaryPerceptron` described below.
Class description:
Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier
Method signatures and docstrings:
- def __init__(self, weights=None, alpha=0.5): Initialize the Binary Perceptron --- weights: Weight vec... | 05620c2e7f2afe54027cdb3f6cb9eca52de377b5 | <|skeleton|>
class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryPerceptron:
"""Class representing the Binary Perceptron --- It is an algorithm that can learn a binary classifier"""
def __init__(self, weights=None, alpha=0.5):
"""Initialize the Binary Perceptron --- weights: Weight vector of the form [w_0, w_1, ..., w_{n-1}, bias_weight] alpha: Learning ... | the_stack_v2_python_sparse | A6/a6-starter-files/a6-starter-files/binary_perceptron.py | mccullohg/McCulloh-CSE-415 | train | 1 |
540bd8dae80f6a27dd5c6639fd112f8df9b7b8eb | [
"if 0 <= event_type < len(self._EVENT_TYPES):\n return self._EVENT_TYPES[event_type]\nreturn 'Unknown {0:d}'.format(event_type)",
"if 0 <= severity < len(self._SEVERITY):\n return self._SEVERITY[severity]\nreturn 'Unknown {0:d}'.format(severity)",
"if self.DATA_TYPE != event_data.data_type:\n raise err... | <|body_start_0|>
if 0 <= event_type < len(self._EVENT_TYPES):
return self._EVENT_TYPES[event_type]
return 'Unknown {0:d}'.format(event_type)
<|end_body_0|>
<|body_start_1|>
if 0 <= severity < len(self._SEVERITY):
return self._SEVERITY[severity]
return 'Unknown {0... | Formatter for a Windows EventLog (EVT) record event. | WinEVTFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinEVTFormatter:
"""Formatter for a Windows EventLog (EVT) record event."""
def GetEventTypeString(self, event_type):
"""Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_001417 | 3,961 | permissive | [
{
"docstring": "Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type.",
"name": "GetEventTypeString",
"signature": "def GetEventTypeString(self, event_type)"
},
{
"docstring": "Retrieves a string representation of th... | 3 | stack_v2_sparse_classes_30k_train_041977 | Implement the Python class `WinEVTFormatter` described below.
Class description:
Formatter for a Windows EventLog (EVT) record event.
Method signatures and docstrings:
- def GetEventTypeString(self, event_type): Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: des... | Implement the Python class `WinEVTFormatter` described below.
Class description:
Formatter for a Windows EventLog (EVT) record event.
Method signatures and docstrings:
- def GetEventTypeString(self, event_type): Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: des... | 9f8e05f21fa23793bfdade6af1d617e9dd092531 | <|skeleton|>
class WinEVTFormatter:
"""Formatter for a Windows EventLog (EVT) record event."""
def GetEventTypeString(self, event_type):
"""Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WinEVTFormatter:
"""Formatter for a Windows EventLog (EVT) record event."""
def GetEventTypeString(self, event_type):
"""Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type."""
if 0 <= event_type < len(self._... | the_stack_v2_python_sparse | plaso/formatters/winevt.py | joshlemon/plaso | train | 1 |
5f9dd74edaf1bd7e7a8605ccd8aa461770078303 | [
"ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)\nsuper(BarPlot, self).__init__(**kwargs)\nself.color = kwargs.get('color', 'b')\nself.strokeColor = kwargs.get('strokeColor', 'none')\nself.data = kwargs.get('data', [])\nself.isLog = kwargs.get('isLog', False)",
"if not self.xLimits or not len(self.xLimits) ... | <|body_start_0|>
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(BarPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.strokeColor = kwargs.get('strokeColor', 'none')
self.data = kwargs.get('data', [])
self.isLog = kwargs.get('isLog', Fa... | A class for... | BarPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of BarPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def _d... | stack_v2_sparse_classes_75kplus_train_001418 | 3,328 | no_license | [
{
"docstring": "Creates a new instance of BarPlot.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "shaveData doc...",
"name": "shaveDataToXLimits",
"signature": "def shaveDataToXLimits(self)"
},
{
"docstring": "_plot doc...",
"name": "_plo... | 4 | stack_v2_sparse_classes_30k_train_027350 | Implement the Python class `BarPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of BarPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemToV... | Implement the Python class `BarPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of BarPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemToV... | bcd0d80077c68cf4bb515d643e51f62dd6c4caaa | <|skeleton|>
class BarPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of BarPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def _d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BarPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of BarPlot."""
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(BarPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.strokeColor = kwargs.get('s... | the_stack_v2_python_sparse | src/cadence/analysis/shared/plotting/BarPlot.py | sernst/Cadence | train | 2 |
506e22432b46b906ca84796856578ca1d473f842 | [
"super().__init__()\nself.use_sigmoid = use_sigmoid\nmodel = [nn.Conv2d(input_nc, 64, 3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True)]\nmodel += [nn.Conv2d(64, 64, 3, stride=2, padding=1), norm_layer(64), nn.LeakyReLU(0.2, inplace=True)]\ninput_nc = 64\nfor i in range(n_layers_d):\n model += [nn.Conv2d(... | <|body_start_0|>
super().__init__()
self.use_sigmoid = use_sigmoid
model = [nn.Conv2d(input_nc, 64, 3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(64, 64, 3, stride=2, padding=1), norm_layer(64), nn.LeakyReLU(0.2, inplace=True)]
input_nc = 64
... | NoPatchDiscriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_... | stack_v2_sparse_classes_75kplus_train_001419 | 1,792 | permissive | [
{
"docstring": "Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_layers_d (int): the number of convolution blocks use_sigmoid (bool): sigmoid activation at the end",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_040674 | Implement the Python class `NoPatchDiscriminator` described below.
Class description:
Implement the NoPatchDiscriminator class.
Method signatures and docstrings:
- def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True): Construct a no patch gan discriminator... | Implement the Python class `NoPatchDiscriminator` described below.
Class description:
Implement the NoPatchDiscriminator class.
Method signatures and docstrings:
- def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True): Construct a no patch gan discriminator... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_layers_d (int)... | the_stack_v2_python_sparse | simulation/utils/machine_learning/cycle_gan/models/no_patch_discriminator.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 | |
5c0224b96d566d32d45f8ad0f85311dfed22b4d2 | [
"self.name = name\nself.max_tau = max_tau\nself.tau_integration = tau_integration\nself.temp = temp\nself.root = root\nself.dir_pattern = dir_pattern\nself.input_file = input_file",
"prep_results = sr.check_n_analyse(self.root, self.dir_pattern)\nprep_results.check_finished(sim.input_file)\nprep_results.check_sta... | <|body_start_0|>
self.name = name
self.max_tau = max_tau
self.tau_integration = tau_integration
self.temp = temp
self.root = root
self.dir_pattern = dir_pattern
self.input_file = input_file
<|end_body_0|>
<|body_start_1|>
prep_results = sr.check_n_analyse... | AnalysisGKPore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisGKPore:
def __init__(self, name, max_tau, tau_integration, temp, root, dir_pattern, input_file):
"""Args: name: Identifier of the simulation max_tau: maximum length of the correlation analysis in LJ time tau_integration: upper time limit of the correlation integration temp: syste... | stack_v2_sparse_classes_75kplus_train_001420 | 13,710 | no_license | [
{
"docstring": "Args: name: Identifier of the simulation max_tau: maximum length of the correlation analysis in LJ time tau_integration: upper time limit of the correlation integration temp: system temperature in Kelvin root: Where all the simulations folders are in dir_pattern: the pattern of the simulations f... | 2 | null | Implement the Python class `AnalysisGKPore` described below.
Class description:
Implement the AnalysisGKPore class.
Method signatures and docstrings:
- def __init__(self, name, max_tau, tau_integration, temp, root, dir_pattern, input_file): Args: name: Identifier of the simulation max_tau: maximum length of the corre... | Implement the Python class `AnalysisGKPore` described below.
Class description:
Implement the AnalysisGKPore class.
Method signatures and docstrings:
- def __init__(self, name, max_tau, tau_integration, temp, root, dir_pattern, input_file): Args: name: Identifier of the simulation max_tau: maximum length of the corre... | a86e72787059e511983cd047f3027aa10eba7090 | <|skeleton|>
class AnalysisGKPore:
def __init__(self, name, max_tau, tau_integration, temp, root, dir_pattern, input_file):
"""Args: name: Identifier of the simulation max_tau: maximum length of the correlation analysis in LJ time tau_integration: upper time limit of the correlation integration temp: syste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalysisGKPore:
def __init__(self, name, max_tau, tau_integration, temp, root, dir_pattern, input_file):
"""Args: name: Identifier of the simulation max_tau: maximum length of the correlation analysis in LJ time tau_integration: upper time limit of the correlation integration temp: system temperature ... | the_stack_v2_python_sparse | Lammps/Pore/EMD/GK_transport_mu_mu.py | sramirezh/Utilities | train | 4 | |
cd217c4e4854534439e9fb5bb00b41906940a83c | [
"raw_config = self.config.to_json()\nraw_config.type = self.config.type\nmap_dict = OptimMappingDict\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)\nself.optim_cls = ClassFactory.get_cls(ClassType.OPTIMIZER, self.map_config.type)",
"pa... | <|body_start_0|>
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = OptimMappingDict
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)
self.optim_cls = ClassFactory.get_cls(Cl... | Register and call Optimizer class. | Optimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer:
"""Register and call Optimizer class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self, model=None, distributed=False):
"""Call Optimizer class. :param model: model, used in torch case :param distributed: use distributed :return: o... | stack_v2_sparse_classes_75kplus_train_001421 | 3,996 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call Optimizer class. :param model: model, used in torch case :param distributed: use distributed :return: optimizer",
"name": "__call__",
"signature": "def __call__(self, model=None, d... | 3 | null | Implement the Python class `Optimizer` described below.
Class description:
Register and call Optimizer class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self, model=None, distributed=False): Call Optimizer class. :param model: model, used in torch case :param distributed: use d... | Implement the Python class `Optimizer` described below.
Class description:
Register and call Optimizer class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self, model=None, distributed=False): Call Optimizer class. :param model: model, used in torch case :param distributed: use d... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Optimizer:
"""Register and call Optimizer class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self, model=None, distributed=False):
"""Call Optimizer class. :param model: model, used in torch case :param distributed: use distributed :return: o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Optimizer:
"""Register and call Optimizer class."""
def __init__(self):
"""Initialize."""
raw_config = self.config.to_json()
raw_config.type = self.config.type
map_dict = OptimMappingDict
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.p... | the_stack_v2_python_sparse | zeus/trainer/modules/optimizer/optim.py | huawei-noah/xingtian | train | 308 |
b53e4603b387644eeccbed8a999ac75b4d1f426b | [
"assert da.getDim() == 1\nself.da = da\nself.factor = factor\nself.dx = dx\nself.prob = prob\nself.localX = da.createLocalVec()\nself.xs, self.xe = self.da.getRanges()[0]\nself.mx = self.da.getSizes()[0]\nself.row = PETSc.Mat.Stencil()\nself.col = PETSc.Mat.Stencil()",
"self.da.globalToLocal(X, self.localX)\nx = ... | <|body_start_0|>
assert da.getDim() == 1
self.da = da
self.factor = factor
self.dx = dx
self.prob = prob
self.localX = da.createLocalVec()
self.xs, self.xe = self.da.getRanges()[0]
self.mx = self.da.getSizes()[0]
self.row = PETSc.Mat.Stencil()
... | Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES | Fisher_full | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fisher_full:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor, dx):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"... | stack_v2_sparse_classes_75kplus_train_001422 | 16,584 | permissive | [
{
"docstring": "Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction",
"name": "__init__",
"signature": "def __init__(self, da, prob, factor, dx)"
},
{
"docstring": "Function to evaluate the residual for the Newton so... | 3 | stack_v2_sparse_classes_30k_train_006414 | Implement the Python class `Fisher_full` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor, dx): Initialization routine Args: da: DMDA object prob: problem instance factor:... | Implement the Python class `Fisher_full` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor, dx): Initialization routine Args: da: DMDA object prob: problem instance factor:... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class Fisher_full:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor, dx):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fisher_full:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor, dx):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd) dx: grid spacing in x direction"""
as... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/GeneralizedFisher_1D_PETSc.py | Parallel-in-Time/pySDC | train | 30 |
718a8d60b16760ec352731a29ee43b53d90b448c | [
"super().__init__()\nself.querystring = ''\nfor code in station_codes:\n if len(self.querystring) > 0:\n self.querystring += ' or '\n self.querystring += f'stationCode=={code}'",
"params = {'size': self.max_page_size, 'sort': 'displayLabel', 'page': page, 'query': self.querystring}\nurl = f'{self.bas... | <|body_start_0|>
super().__init__()
self.querystring = ''
for code in station_codes:
if len(self.querystring) > 0:
self.querystring += ' or '
self.querystring += f'stationCode=={code}'
<|end_body_0|>
<|body_start_1|>
params = {'size': self.max_pag... | Class for building a url and params to request a list of stations by code | BuildQueryByStationCode | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildQueryByStationCode:
"""Class for building a url and params to request a list of stations by code"""
def __init__(self, station_codes: List[int]):
"""Initialize object"""
<|body_0|>
def query(self, page) -> Tuple[str, dict]:
"""Return query url and params for... | stack_v2_sparse_classes_75kplus_train_001423 | 5,089 | permissive | [
{
"docstring": "Initialize object",
"name": "__init__",
"signature": "def __init__(self, station_codes: List[int])"
},
{
"docstring": "Return query url and params for a list of stations",
"name": "query",
"signature": "def query(self, page) -> Tuple[str, dict]"
}
] | 2 | stack_v2_sparse_classes_30k_train_053332 | Implement the Python class `BuildQueryByStationCode` described below.
Class description:
Class for building a url and params to request a list of stations by code
Method signatures and docstrings:
- def __init__(self, station_codes: List[int]): Initialize object
- def query(self, page) -> Tuple[str, dict]: Return que... | Implement the Python class `BuildQueryByStationCode` described below.
Class description:
Class for building a url and params to request a list of stations by code
Method signatures and docstrings:
- def __init__(self, station_codes: List[int]): Initialize object
- def query(self, page) -> Tuple[str, dict]: Return que... | 0ba707b0eddc280240964efa481988df92046e6a | <|skeleton|>
class BuildQueryByStationCode:
"""Class for building a url and params to request a list of stations by code"""
def __init__(self, station_codes: List[int]):
"""Initialize object"""
<|body_0|>
def query(self, page) -> Tuple[str, dict]:
"""Return query url and params for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildQueryByStationCode:
"""Class for building a url and params to request a list of stations by code"""
def __init__(self, station_codes: List[int]):
"""Initialize object"""
super().__init__()
self.querystring = ''
for code in station_codes:
if len(self.querys... | the_stack_v2_python_sparse | api/app/wildfire_one/query_builders.py | bcgov/wps | train | 35 |
fb28a3b29f9ef7db76c9994915428a098694080c | [
"if bundle.request.GET.get('pdf'):\n bundle.data['pdf'] = {'url': bundle.obj.pdf.generate_url()}\nreturn bundle",
"logger.debug('Creating the shipping manifest...')\nbundle.obj = Shipping()\nbundle = self.full_hydrate(bundle, **kwargs)\ntry:\n bundle.obj.acknowledgement = Ack.objects.get(pk=bundle.data['ack... | <|body_start_0|>
if bundle.request.GET.get('pdf'):
bundle.data['pdf'] = {'url': bundle.obj.pdf.generate_url()}
return bundle
<|end_body_0|>
<|body_start_1|>
logger.debug('Creating the shipping manifest...')
bundle.obj = Shipping()
bundle = self.full_hydrate(bundle, *... | ShippingResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShippingResource:
def dehydrate(self, bundle):
"""Implements a dehydrate method to prepare the data for the resource before it is returned to the client"""
<|body_0|>
def obj_create(self, bundle, **kwargs):
"""Implements the creation method for shipping"""
<|... | stack_v2_sparse_classes_75kplus_train_001424 | 4,014 | no_license | [
{
"docstring": "Implements a dehydrate method to prepare the data for the resource before it is returned to the client",
"name": "dehydrate",
"signature": "def dehydrate(self, bundle)"
},
{
"docstring": "Implements the creation method for shipping",
"name": "obj_create",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_test_002158 | Implement the Python class `ShippingResource` described below.
Class description:
Implement the ShippingResource class.
Method signatures and docstrings:
- def dehydrate(self, bundle): Implements a dehydrate method to prepare the data for the resource before it is returned to the client
- def obj_create(self, bundle,... | Implement the Python class `ShippingResource` described below.
Class description:
Implement the ShippingResource class.
Method signatures and docstrings:
- def dehydrate(self, bundle): Implements a dehydrate method to prepare the data for the resource before it is returned to the client
- def obj_create(self, bundle,... | bef520659a7316c861933f9609b6b9ca7d9f47ac | <|skeleton|>
class ShippingResource:
def dehydrate(self, bundle):
"""Implements a dehydrate method to prepare the data for the resource before it is returned to the client"""
<|body_0|>
def obj_create(self, bundle, **kwargs):
"""Implements the creation method for shipping"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShippingResource:
def dehydrate(self, bundle):
"""Implements a dehydrate method to prepare the data for the resource before it is returned to the client"""
if bundle.request.GET.get('pdf'):
bundle.data['pdf'] = {'url': bundle.obj.pdf.generate_url()}
return bundle
def o... | the_stack_v2_python_sparse | shipping/api.py | charliephairoj/backend | train | 0 | |
c3896d75a26b9d504e928316b30c420c7472c99a | [
"memory = '1,9,10,3,2,3,11,0,99,30,40,50'.split(',')\nmemory = [int(x) for x in memory]\ncur_instr = 0\n_ = interpreter.execute_instruction(memory, cur_instr)\nexpected_memory = '1,9,10,70,2,3,11,0,99,30,40,50'.split(',')\nexpected_memory = [int(x) for x in expected_memory]\nself.assertListEqual(memory, expected_me... | <|body_start_0|>
memory = '1,9,10,3,2,3,11,0,99,30,40,50'.split(',')
memory = [int(x) for x in memory]
cur_instr = 0
_ = interpreter.execute_instruction(memory, cur_instr)
expected_memory = '1,9,10,70,2,3,11,0,99,30,40,50'.split(',')
expected_memory = [int(x) for x in exp... | Class to test interpreter based on examples in Day 2 Part 1. | InterpreterPart1Test | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpreterPart1Test:
"""Class to test interpreter based on examples in Day 2 Part 1."""
def test_program1_command1(self):
"""Test the first command of the first program."""
<|body_0|>
def test_program1_command1_instr_step(self):
"""Test that first command gives ... | stack_v2_sparse_classes_75kplus_train_001425 | 2,702 | permissive | [
{
"docstring": "Test the first command of the first program.",
"name": "test_program1_command1",
"signature": "def test_program1_command1(self)"
},
{
"docstring": "Test that first command gives back instruction step 4.",
"name": "test_program1_command1_instr_step",
"signature": "def test... | 6 | null | Implement the Python class `InterpreterPart1Test` described below.
Class description:
Class to test interpreter based on examples in Day 2 Part 1.
Method signatures and docstrings:
- def test_program1_command1(self): Test the first command of the first program.
- def test_program1_command1_instr_step(self): Test that... | Implement the Python class `InterpreterPart1Test` described below.
Class description:
Class to test interpreter based on examples in Day 2 Part 1.
Method signatures and docstrings:
- def test_program1_command1(self): Test the first command of the first program.
- def test_program1_command1_instr_step(self): Test that... | 7ecb827745bd59e6ad249707bd976888006f935c | <|skeleton|>
class InterpreterPart1Test:
"""Class to test interpreter based on examples in Day 2 Part 1."""
def test_program1_command1(self):
"""Test the first command of the first program."""
<|body_0|>
def test_program1_command1_instr_step(self):
"""Test that first command gives ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpreterPart1Test:
"""Class to test interpreter based on examples in Day 2 Part 1."""
def test_program1_command1(self):
"""Test the first command of the first program."""
memory = '1,9,10,3,2,3,11,0,99,30,40,50'.split(',')
memory = [int(x) for x in memory]
cur_instr = 0... | the_stack_v2_python_sparse | 2019/02/test_interpreter.py | cheshyre/advent-of-code | train | 1 |
da25f9b138a3f9a70898200c055a91dd22c6d598 | [
"if other not in self.document:\n return False\nif len(value) != len(self.document[other]) - 1:\n self._error(field, \"Length of field %s doesn't match field %s's length.\" % (field, other))",
"if other not in self.document:\n return False\nn_sequences = len(self.document[other])\ncurrent_set = set([])\n... | <|body_start_0|>
if other not in self.document:
return False
if len(value) != len(self.document[other]) - 1:
self._error(field, "Length of field %s doesn't match field %s's length." % (field, other))
<|end_body_0|>
<|body_start_1|>
if other not in self.document:
... | Add functionalities which doesn't in the generic library | ExtendedValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtendedValidator:
"""Add functionalities which doesn't in the generic library"""
def _validate_pairing_length(self, other, field, value):
"""Test length of MSA pairing order against length of sequences. The rule's arguments are validated against this schema: {'type': 'string'}"""
... | stack_v2_sparse_classes_75kplus_train_001426 | 8,295 | no_license | [
{
"docstring": "Test length of MSA pairing order against length of sequences. The rule's arguments are validated against this schema: {'type': 'string'}",
"name": "_validate_pairing_length",
"signature": "def _validate_pairing_length(self, other, field, value)"
},
{
"docstring": "Test validity o... | 2 | stack_v2_sparse_classes_30k_train_037553 | Implement the Python class `ExtendedValidator` described below.
Class description:
Add functionalities which doesn't in the generic library
Method signatures and docstrings:
- def _validate_pairing_length(self, other, field, value): Test length of MSA pairing order against length of sequences. The rule's arguments ar... | Implement the Python class `ExtendedValidator` described below.
Class description:
Add functionalities which doesn't in the generic library
Method signatures and docstrings:
- def _validate_pairing_length(self, other, field, value): Test length of MSA pairing order against length of sequences. The rule's arguments ar... | 386aeaf2c9f04fce50863eb4a13ea7ef718fe41a | <|skeleton|>
class ExtendedValidator:
"""Add functionalities which doesn't in the generic library"""
def _validate_pairing_length(self, other, field, value):
"""Test length of MSA pairing order against length of sequences. The rule's arguments are validated against this schema: {'type': 'string'}"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtendedValidator:
"""Add functionalities which doesn't in the generic library"""
def _validate_pairing_length(self, other, field, value):
"""Test length of MSA pairing order against length of sequences. The rule's arguments are validated against this schema: {'type': 'string'}"""
if othe... | the_stack_v2_python_sparse | MSA/Validators/msa_validator.py | budvinchathura/BioViz | train | 0 |
29d57f444f291f0ad38639c32c618d19589f0c97 | [
"self.max_count = 256\nself.bit_lenth = 8\nself.in_name = in_name\nself.out_name = out_name",
"curr_bit = 0\ncount = 0\nwith BitIO(self.out_name, 'w') as bo:\n with BitIO(self.in_name, 'r') as bi:\n while not bi.is_empty():\n if bi.read_bits(1) == curr_bit:\n count += 1\n ... | <|body_start_0|>
self.max_count = 256
self.bit_lenth = 8
self.in_name = in_name
self.out_name = out_name
<|end_body_0|>
<|body_start_1|>
curr_bit = 0
count = 0
with BitIO(self.out_name, 'w') as bo:
with BitIO(self.in_name, 'r') as bi:
... | class for run-length encoding | RunLength | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunLength:
"""class for run-length encoding"""
def __init__(self, in_name, out_name):
"""initialization"""
<|body_0|>
def compress(self):
"""compress"""
<|body_1|>
def expand(self):
"""compress"""
<|body_2|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_001427 | 1,921 | no_license | [
{
"docstring": "initialization",
"name": "__init__",
"signature": "def __init__(self, in_name, out_name)"
},
{
"docstring": "compress",
"name": "compress",
"signature": "def compress(self)"
},
{
"docstring": "compress",
"name": "expand",
"signature": "def expand(self)"
... | 3 | null | Implement the Python class `RunLength` described below.
Class description:
class for run-length encoding
Method signatures and docstrings:
- def __init__(self, in_name, out_name): initialization
- def compress(self): compress
- def expand(self): compress | Implement the Python class `RunLength` described below.
Class description:
class for run-length encoding
Method signatures and docstrings:
- def __init__(self, in_name, out_name): initialization
- def compress(self): compress
- def expand(self): compress
<|skeleton|>
class RunLength:
"""class for run-length enco... | 35754ade4d87f3ae289407cf74a2719b5db4041d | <|skeleton|>
class RunLength:
"""class for run-length encoding"""
def __init__(self, in_name, out_name):
"""initialization"""
<|body_0|>
def compress(self):
"""compress"""
<|body_1|>
def expand(self):
"""compress"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunLength:
"""class for run-length encoding"""
def __init__(self, in_name, out_name):
"""initialization"""
self.max_count = 256
self.bit_lenth = 8
self.in_name = in_name
self.out_name = out_name
def compress(self):
"""compress"""
curr_bit = 0
... | the_stack_v2_python_sparse | mooc/algorithms_II/run_length.py | j2sdk408/misc | train | 0 |
1dba2fc0eedf3346a22d55a8da465066eecdfa0f | [
"if n <= 1:\n return 1\nugly = []\nfactor = {}\nfor _ in primes:\n factor[_] = 0\nugly.append(1)\nfor i in xrange(1, n):\n ugly.append(sys.maxint)\n for p in factor:\n ugly[i] = min(ugly[i], ugly[factor[p]] * p)\n for p in factor:\n if ugly[i] == ugly[factor[p]] * p:\n factor... | <|body_start_0|>
if n <= 1:
return 1
ugly = []
factor = {}
for _ in primes:
factor[_] = 0
ugly.append(1)
for i in xrange(1, n):
ugly.append(sys.maxint)
for p in factor:
ugly[i] = min(ugly[i], ugly[factor[p]] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_0|>
def nthSuperUglyNumber_heapq_TLE(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_001428 | 2,165 | no_license | [
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber",
"signature": "def nthSuperUglyNumber(self, n, primes)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber_heapq_TLE",
"signature": "def nthSuper... | 2 | stack_v2_sparse_classes_30k_train_035582 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthSuperUglyNumber_heapq_TLE(self, n, primes): :type n: int :type primes: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthSuperUglyNumber_heapq_TLE(self, n, primes): :type n: int :type primes: List[int... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_0|>
def nthSuperUglyNumber_heapq_TLE(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
if n <= 1:
return 1
ugly = []
factor = {}
for _ in primes:
factor[_] = 0
ugly.append(1)
for i in xrange(1, n):
u... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00313.Super Ugly Number.py | roger6blog/LeetCode | train | 0 | |
5ea35cec5e3e8874fc7985945e730465b16e1782 | [
"self.itemUserMatrix = userItemMatrix.transpose()\nself.sim = np.zeros((userItemMatrix.shape[1], userItemMatrix.shape[1]))\nself.sim = computeCosSim(self.sim, self.itemUserMatrix)\nself.userItemMatrix = userItemMatrix\nif n > self.sim.shape[0]:\n n = self.sim.shape[0]\norder = self.sim.argsort(1)\nfor j in xrang... | <|body_start_0|>
self.itemUserMatrix = userItemMatrix.transpose()
self.sim = np.zeros((userItemMatrix.shape[1], userItemMatrix.shape[1]))
self.sim = computeCosSim(self.sim, self.itemUserMatrix)
self.userItemMatrix = userItemMatrix
if n > self.sim.shape[0]:
n = self.si... | Class for item based knn. | itemKnn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class itemKnn:
"""Class for item based knn."""
def __init__(self, userItemMatrix, n):
"""Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number of neighbors which are getting computed. Uses the cosine f... | stack_v2_sparse_classes_75kplus_train_001429 | 4,559 | no_license | [
{
"docstring": "Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number of neighbors which are getting computed. Uses the cosine for similarity.",
"name": "__init__",
"signature": "def __init__(self, userItemMatrix, n... | 2 | stack_v2_sparse_classes_30k_train_044673 | Implement the Python class `itemKnn` described below.
Class description:
Class for item based knn.
Method signatures and docstrings:
- def __init__(self, userItemMatrix, n): Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number o... | Implement the Python class `itemKnn` described below.
Class description:
Class for item based knn.
Method signatures and docstrings:
- def __init__(self, userItemMatrix, n): Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number o... | b01698c180cb86baa97394f7b3b51e3c849847cb | <|skeleton|>
class itemKnn:
"""Class for item based knn."""
def __init__(self, userItemMatrix, n):
"""Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number of neighbors which are getting computed. Uses the cosine f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class itemKnn:
"""Class for item based knn."""
def __init__(self, userItemMatrix, n):
"""Builds a model for Item based knn. userItemMatrix -- A matrix where an entry at i, j is the rating the ith user gave the jth item. n -- number of neighbors which are getting computed. Uses the cosine for similarity... | the_stack_v2_python_sparse | bin/recommender/knn.py | Foolius/recsyslab | train | 2 |
69cc0b61d83b54ff2507ecf58441f73b8def71a9 | [
"super(DaffyTrackPlotHelper, self).__init__(usage_string=usage_string)\nself.shade_lines_by_intensity = shadeLines\nself.decorate_map()\nif draw_nature_track:\n self.draw_nature_run_track(axes=axes)",
"log.debug('plotting nature run data')\nnature_data = self.cfg.truth_track.tracker_entries\nnrLats = [x.lat fo... | <|body_start_0|>
super(DaffyTrackPlotHelper, self).__init__(usage_string=usage_string)
self.shade_lines_by_intensity = shadeLines
self.decorate_map()
if draw_nature_track:
self.draw_nature_run_track(axes=axes)
<|end_body_0|>
<|body_start_1|>
log.debug('plotting natur... | Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class. | DaffyTrackPlotHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a ... | stack_v2_sparse_classes_75kplus_train_001430 | 27,841 | no_license | [
{
"docstring": "Instantiate a DaffyTrackPlotHelper @param shadeLines If True, the shade of the line will be intensified according to the max wind speed @param axes Axes object to use to dra the nature run track. TODO: This is not a good place to plot the nature run track since the axes on which the tracks will ... | 3 | stack_v2_sparse_classes_30k_train_002409 | Implement the Python class `DaffyTrackPlotHelper` described below.
Class description:
Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class.
Method signatures and docstrings:
- def __init__(self, usage_string=None, draw_nature_tra... | Implement the Python class `DaffyTrackPlotHelper` described below.
Class description:
Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class.
Method signatures and docstrings:
- def __init__(self, usage_string=None, draw_nature_tra... | ea02c68f30a61b8a8048b7801f3d0433b9adecc9 | <|skeleton|>
class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a DaffyTrackPlo... | the_stack_v2_python_sparse | daffy_plot/plot_helper.py | JavierDelgadoNoaa/daffyplot | train | 0 |
7e78d9b7713c1b8aecaf76ecc260307b0613c03a | [
"super(EncoderLayer, self).__init__()\nself.self_attn = self_attn\nself.feed_forward = feed_forward\nself.norm1 = nn.LayerNorm(size)\nself.norm2 = nn.LayerNorm(size)\nself.dropout = nn.Dropout(dropout_rate)\nself.size = size\nself.normalize_before = normalize_before\nself.concat_after = concat_after\nif self.concat... | <|body_start_0|>
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.norm1 = nn.LayerNorm(size)
self.norm2 = nn.LayerNorm(size)
self.dropout = nn.Dropout(dropout_rate)
self.size = size
self.normalize_before... | Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward module instance. `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear`... | EncoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderLayer:
"""Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward module instance. `PositionwiseFeedForward`,... | stack_v2_sparse_classes_75kplus_train_001431 | 3,854 | permissive | [
{
"docstring": "Construct an EncoderLayer object.",
"name": "__init__",
"signature": "def __init__(self, size, self_attn, feed_forward, dropout_rate, normalize_before=True, concat_after=False)"
},
{
"docstring": "Compute encoded features. Parameters ---------- x_input : paddle.Tensor Input tenso... | 2 | stack_v2_sparse_classes_30k_train_002972 | Implement the Python class `EncoderLayer` described below.
Class description:
Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward modu... | Implement the Python class `EncoderLayer` described below.
Class description:
Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward modu... | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | <|skeleton|>
class EncoderLayer:
"""Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward module instance. `PositionwiseFeedForward`,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderLayer:
"""Encoder layer module. Parameters ---------- size : int Input dimension. self_attn : paddle.nn.Layer Self-attention module instance. `MultiHeadedAttention` instance can be used as the argument. feed_forward : paddle.nn.Layer Feed-forward module instance. `PositionwiseFeedForward`, `MultiLayere... | the_stack_v2_python_sparse | parakeet/modules/fastspeech2_transformer/encoder_layer.py | PaddlePaddle/Parakeet | train | 609 |
a541f49df019c81910410ca04e628af8a4e8777b | [
"if TvbProfile.SUBPARAM_PROFILE in script_argv:\n index = script_argv.index(TvbProfile.SUBPARAM_PROFILE)\n if len(script_argv) > index + 1:\n return script_argv[index + 1]\nreturn None",
"selected_profile = TvbProfile.get_profile(script_argv)\nif try_reload:\n sys.path = os.environ.get('PYTHONPATH... | <|body_start_0|>
if TvbProfile.SUBPARAM_PROFILE in script_argv:
index = script_argv.index(TvbProfile.SUBPARAM_PROFILE)
if len(script_argv) > index + 1:
return script_argv[index + 1]
return None
<|end_body_0|>
<|body_start_1|>
selected_profile = TvbProfile... | ENUM-like class with current TVB profile values. | TvbProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TvbProfile:
"""ENUM-like class with current TVB profile values."""
def get_profile(script_argv):
"""Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string arguments. If the script_argv contains the string '-profile... | stack_v2_sparse_classes_75kplus_train_001432 | 6,210 | no_license | [
{
"docstring": "Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string arguments. If the script_argv contains the string '-profile', than TVB profile will be set to the next element. E.g.: if script_argv=['$param1', ..., '-profile', 'TEST_SQL... | 3 | stack_v2_sparse_classes_30k_train_014627 | Implement the Python class `TvbProfile` described below.
Class description:
ENUM-like class with current TVB profile values.
Method signatures and docstrings:
- def get_profile(script_argv): Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string ar... | Implement the Python class `TvbProfile` described below.
Class description:
ENUM-like class with current TVB profile values.
Method signatures and docstrings:
- def get_profile(script_argv): Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string ar... | dd4beb028719abaa70c639f64c97ba23bd4a1f3a | <|skeleton|>
class TvbProfile:
"""ENUM-like class with current TVB profile values."""
def get_profile(script_argv):
"""Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string arguments. If the script_argv contains the string '-profile... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TvbProfile:
"""ENUM-like class with current TVB profile values."""
def get_profile(script_argv):
"""Returns the user given profile or None if the user didn't specify a profile. :param script_argv: represents a list of string arguments. If the script_argv contains the string '-profile', than TVB p... | the_stack_v2_python_sparse | tvb/basic/profile.py | HuifangWang/the-virtual-brain-website | train | 0 |
e0bc5929e95c2429360a00f4b8025981f41836cd | [
"if not a:\n return list()\nt = a[0]\nn = len(a)\nm = len(a[0])\ni = 0\nj = m - 1\nfor s, x in enumerate(self.gen_sect_len(n, m)):\n for y in range(0, x):\n i, j = self.eval_next_loc(s, i, j)\n t.append(a[i][j])\nreturn t",
"if m >= n:\n l = 2 * (n - 1)\nelse:\n l = 2 * m - 1\nfor x in r... | <|body_start_0|>
if not a:
return list()
t = a[0]
n = len(a)
m = len(a[0])
i = 0
j = m - 1
for s, x in enumerate(self.gen_sect_len(n, m)):
for y in range(0, x):
i, j = self.eval_next_loc(s, i, j)
t.append(a[i... | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_spiral_order(self, a):
"""Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2D array in spiral order :rtype: list[int]"""
<|body_0|>
def gen_sect_len(self, n, m)... | stack_v2_sparse_classes_75kplus_train_001433 | 3,177 | permissive | [
{
"docstring": "Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2D array in spiral order :rtype: list[int]",
"name": "get_spiral_order",
"signature": "def get_spiral_order(self, a)"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_train_030567 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_spiral_order(self, a): Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_spiral_order(self, a): Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
def get_spiral_order(self, a):
"""Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2D array in spiral order :rtype: list[int]"""
<|body_0|>
def gen_sect_len(self, n, m)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def get_spiral_order(self, a):
"""Traverses all elements of 2D array in spiral order. :param list[list[int]] a: 2D array of positive integers :return: array of elements from input 2D array in spiral order :rtype: list[int]"""
if not a:
return list()
t = a[0]
... | the_stack_v2_python_sparse | 0054_spiral_matrix/python_source.py | arthurdysart/LeetCode | train | 0 | |
c6d740ad29d04c2baf02a229e3a66cd45861ed85 | [
"self.letter = letter\nself.is_word = is_word\nself.children = {}",
"if start >= len(word):\n return ('', None)\nelif word[start] == self.letter or word[start].swapcase() == self.letter:\n if start == len(word) - 1:\n return (self.letter, self)\n for child in self.children:\n correct_substr... | <|body_start_0|>
self.letter = letter
self.is_word = is_word
self.children = {}
<|end_body_0|>
<|body_start_1|>
if start >= len(word):
return ('', None)
elif word[start] == self.letter or word[start].swapcase() == self.letter:
if start == len(word) - 1:
... | A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes that are adjacent to this node. Representation Invariants: - self not in sel... | TrieNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrieNode:
"""A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes that are adjacent to this node. Represen... | stack_v2_sparse_classes_75kplus_train_001434 | 6,537 | no_license | [
{
"docstring": "Initializing a new TrieNode with the given letter and is_word value. By default, the is_word attribute is set to False.",
"name": "__init__",
"signature": "def __init__(self, letter: Optional[str], is_word: Optional[bool]=False) -> None"
},
{
"docstring": "Find a node that match ... | 2 | null | Implement the Python class `TrieNode` described below.
Class description:
A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes t... | Implement the Python class `TrieNode` described below.
Class description:
A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes t... | de602e6f543a42be869da952b402f235ff9a33e8 | <|skeleton|>
class TrieNode:
"""A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes that are adjacent to this node. Represen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrieNode:
"""A TrieNode in the Trie data structure. Instance Attributes: - letter: The letter contained in this TrieNode, None if this is the root of the Trie. - is_word: True if this node indicates the end of a word, False otherwise. - children: The nodes that are adjacent to this node. Representation Invari... | the_stack_v2_python_sparse | trie_auto_complete.py | Mondlicht1/MyAnimeRecommendations | train | 0 |
383e364e2b922a047fdc0958e0790935b29716f8 | [
"self.mfd_model = 'Characteristic'\nself.mfd_weight = mfd_conf['Model_Weight']\nself.bin_width = mfd_conf['MFD_spacing']\nself.mmin = None\nself.mmax = None\nself.mmax_sigma = None\nself.lower_bound = mfd_conf['Lower_Bound']\nself.upper_bound = mfd_conf['Upper_Bound']\nself.sigma = mfd_conf['Sigma']\nself.occurrenc... | <|body_start_0|>
self.mfd_model = 'Characteristic'
self.mfd_weight = mfd_conf['Model_Weight']
self.bin_width = mfd_conf['MFD_spacing']
self.mmin = None
self.mmax = None
self.mmax_sigma = None
self.lower_bound = mfd_conf['Lower_Bound']
self.upper_bound = mf... | Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width: Width of the magnitude bin (rates are gi... | Characteristic | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width... | stack_v2_sparse_classes_75kplus_train_001435 | 7,443 | permissive | [
{
"docstring": "Input core configuration parameters as specified in the configuration file :param dict mfd_conf: Configuration file containing the following attributes: * 'Model_Weight' - Logic tree weight of model type (float) * 'MFD_spacing' - Width of MFD bin (float) * 'Minimum_Magnitude' - Minimum magnitude... | 3 | stack_v2_sparse_classes_30k_train_017193 | Implement the Python class `Characteristic` described below.
Class description:
Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic ... | Implement the Python class `Characteristic` described below.
Class description:
Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic ... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Characteristic:
"""Class to implement the characteristic earthquake model assuming a truncated Gaussian distribution :param str mfd_model: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bin_width: Width of th... | the_stack_v2_python_sparse | openquake/hmtk/faults/mfd/characteristic.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
ef93018ff9bae252391ecf792140f3df878af736 | [
"try:\n scopes = get_scopes(account, vo=request.environ.get('vo'))\nexcept AccountNotFound as error:\n return generate_http_error_flask(404, error)\nif not len(scopes):\n return generate_http_error_flask(404, ScopeNotFound.__name__, f\"no scopes found for account ID '{account}'\")\nreturn jsonify(scopes)",... | <|body_start_0|>
try:
scopes = get_scopes(account, vo=request.environ.get('vo'))
except AccountNotFound as error:
return generate_http_error_flask(404, error)
if not len(scopes):
return generate_http_error_flask(404, ScopeNotFound.__name__, f"no scopes found f... | Scopes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scopes:
def get(self, account):
"""--- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier. schema: type: string style: simple responses: 200: description: OK content: application/x-jso... | stack_v2_sparse_classes_75kplus_train_001436 | 37,031 | permissive | [
{
"docstring": "--- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier. schema: type: string style: simple responses: 200: description: OK content: application/x-json-stream: schema: description: All scopes f... | 2 | stack_v2_sparse_classes_30k_val_002707 | Implement the Python class `Scopes` described below.
Class description:
Implement the Scopes class.
Method signatures and docstrings:
- def get(self, account): --- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier... | Implement the Python class `Scopes` described below.
Class description:
Implement the Scopes class.
Method signatures and docstrings:
- def get(self, account): --- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class Scopes:
def get(self, account):
"""--- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier. schema: type: string style: simple responses: 200: description: OK content: application/x-jso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scopes:
def get(self, account):
"""--- summary: List scopes description: List all scopse for an account. tags: - Account parameters: - name: account in: path description: The account identifier. schema: type: string style: simple responses: 200: description: OK content: application/x-json-stream: sche... | the_stack_v2_python_sparse | lib/rucio/web/rest/flaskapi/v1/accounts.py | rucio/rucio | train | 232 | |
70e4adff849c53d2efc692d5a0b0b7be6a6948f3 | [
"m = {}\nfor index, num in enumerate(nums):\n if m.get(num, None):\n m[num][1].append(index)\n m[num][0] += 1\n else:\n m[num] = [1, [index]]\nfrequency_record = -1\nlength_record = -1\nfor num, info in m.items():\n length = info[1][-1] - info[1][0] + 1\n frequency = info[0]\n if... | <|body_start_0|>
m = {}
for index, num in enumerate(nums):
if m.get(num, None):
m[num][1].append(index)
m[num][0] += 1
else:
m[num] = [1, [index]]
frequency_record = -1
length_record = -1
for num, info in m.i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = {}
for index, ... | stack_v2_sparse_classes_75kplus_train_001437 | 1,968 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray1",
"signature": "def findShortestSubArray1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024949 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray1(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
m = {}
for index, num in enumerate(nums):
if m.get(num, None):
m[num][1].append(index)
m[num][0] += 1
else:
m[num] = [1, [inde... | the_stack_v2_python_sparse | python/leetcode_bak/697_Degree_of_an_Array.py | bobcaoge/my-code | train | 0 | |
177cde5d86701bdcdacd807fa0d22d4081ee179f | [
"assignees = [(r.source, tuple(r.attrs['AssigneeType'].split(','))) for r in self.related_sources if 'AssigneeType' in r.attrs]\nassignees += [(r.destination, tuple(r.attrs['AssigneeType'].split(','))) for r in self.related_destinations if 'AssigneeType' in r.attrs]\nreturn assignees",
"if filter_ is None:\n r... | <|body_start_0|>
assignees = [(r.source, tuple(r.attrs['AssigneeType'].split(','))) for r in self.related_sources if 'AssigneeType' in r.attrs]
assignees += [(r.destination, tuple(r.attrs['AssigneeType'].split(','))) for r in self.related_destinations if 'AssigneeType' in r.attrs]
return assigne... | Mixin for models with assignees | Assignable | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Assignable:
"""Mixin for models with assignees"""
def assignees(self):
"""Property that returns assignees Returns: A set of assignees."""
<|body_0|>
def get_assignees(self, filter_=None):
"""Get assignees by type. This is helper for fetching only specific assigne... | stack_v2_sparse_classes_75kplus_train_001438 | 4,070 | permissive | [
{
"docstring": "Property that returns assignees Returns: A set of assignees.",
"name": "assignees",
"signature": "def assignees(self)"
},
{
"docstring": "Get assignees by type. This is helper for fetching only specific assignee types. Args: filter_: String containing assignee type or a list with... | 4 | null | Implement the Python class `Assignable` described below.
Class description:
Mixin for models with assignees
Method signatures and docstrings:
- def assignees(self): Property that returns assignees Returns: A set of assignees.
- def get_assignees(self, filter_=None): Get assignees by type. This is helper for fetching ... | Implement the Python class `Assignable` described below.
Class description:
Mixin for models with assignees
Method signatures and docstrings:
- def assignees(self): Property that returns assignees Returns: A set of assignees.
- def get_assignees(self, filter_=None): Get assignees by type. This is helper for fetching ... | b82333664db3978d85109f2d968239bd1260ee85 | <|skeleton|>
class Assignable:
"""Mixin for models with assignees"""
def assignees(self):
"""Property that returns assignees Returns: A set of assignees."""
<|body_0|>
def get_assignees(self, filter_=None):
"""Get assignees by type. This is helper for fetching only specific assigne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Assignable:
"""Mixin for models with assignees"""
def assignees(self):
"""Property that returns assignees Returns: A set of assignees."""
assignees = [(r.source, tuple(r.attrs['AssigneeType'].split(','))) for r in self.related_sources if 'AssigneeType' in r.attrs]
assignees += [(r... | the_stack_v2_python_sparse | src/ggrc/models/mixins/assignable.py | xferra/ggrc-core | train | 1 |
131474ddd9a0dd101459add6060030e48d2365e5 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = self.__nb_objects",
"if list_dictionaries and len(list_dictionaries) != 0:\n return json.dumps(list_dictionaries)\nreturn '[]'",
"new_file = '{}.json'.format(cls.__name__)\nlist_wri = []\nif list_objs is not None:\n li... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries and len(list_dictionaries) != 0:
return json.dumps(list_dictionaries)
return '[]... | New class base | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""New class base"""
def __init__(self, id=None):
"""new var"""
<|body_0|>
def to_json_string(list_dictionaries):
"""change to stri"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Write json in a new file"""
<|body_2|>
d... | stack_v2_sparse_classes_75kplus_train_001439 | 1,907 | no_license | [
{
"docstring": "new var",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "change to stri",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "Write json in a new file",
"name": "save_to_file",
... | 6 | stack_v2_sparse_classes_30k_val_001576 | Implement the Python class `Base` described below.
Class description:
New class base
Method signatures and docstrings:
- def __init__(self, id=None): new var
- def to_json_string(list_dictionaries): change to stri
- def save_to_file(cls, list_objs): Write json in a new file
- def from_json_string(json_string): return... | Implement the Python class `Base` described below.
Class description:
New class base
Method signatures and docstrings:
- def __init__(self, id=None): new var
- def to_json_string(list_dictionaries): change to stri
- def save_to_file(cls, list_objs): Write json in a new file
- def from_json_string(json_string): return... | 1974538edc45cf49f9bbe2af83de639176aa03cb | <|skeleton|>
class Base:
"""New class base"""
def __init__(self, id=None):
"""new var"""
<|body_0|>
def to_json_string(list_dictionaries):
"""change to stri"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Write json in a new file"""
<|body_2|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""New class base"""
def __init__(self, id=None):
"""new var"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
def to_json_string(list_dictionaries):
"""change to stri"""
if li... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | katgzco/holbertonschool-higher_level_programming | train | 0 |
f1bd9715d132746b0d658375c57ed3ed0ef8e10e | [
"self.entity_description = description\nself._client = htu21d_client\nself._attr_name = f'{name}_{description.key}'",
"await self.hass.async_add_executor_job(self._client.update)\nif self._client.sensor.sample_ok:\n if self.entity_description.key == SENSOR_TEMPERATURE:\n value = round(self._client.senso... | <|body_start_0|>
self.entity_description = description
self._client = htu21d_client
self._attr_name = f'{name}_{description.key}'
<|end_body_0|>
<|body_start_1|>
await self.hass.async_add_executor_job(self._client.update)
if self._client.sensor.sample_ok:
if self.ent... | Implementation of the HTU21D sensor. | HTU21DSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTU21DSensor:
"""Implementation of the HTU21D sensor."""
def __init__(self, htu21d_client, name, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the HTU21D sensor and update ... | stack_v2_sparse_classes_75kplus_train_001440 | 3,360 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, htu21d_client, name, description: SensorEntityDescription)"
},
{
"docstring": "Get the latest data from the HTU21D sensor and update the state.",
"name": "async_update",
"signature": "async def ... | 2 | stack_v2_sparse_classes_30k_train_038891 | Implement the Python class `HTU21DSensor` described below.
Class description:
Implementation of the HTU21D sensor.
Method signatures and docstrings:
- def __init__(self, htu21d_client, name, description: SensorEntityDescription): Initialize the sensor.
- async def async_update(self): Get the latest data from the HTU2... | Implement the Python class `HTU21DSensor` described below.
Class description:
Implementation of the HTU21D sensor.
Method signatures and docstrings:
- def __init__(self, htu21d_client, name, description: SensorEntityDescription): Initialize the sensor.
- async def async_update(self): Get the latest data from the HTU2... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class HTU21DSensor:
"""Implementation of the HTU21D sensor."""
def __init__(self, htu21d_client, name, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
async def async_update(self):
"""Get the latest data from the HTU21D sensor and update ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTU21DSensor:
"""Implementation of the HTU21D sensor."""
def __init__(self, htu21d_client, name, description: SensorEntityDescription):
"""Initialize the sensor."""
self.entity_description = description
self._client = htu21d_client
self._attr_name = f'{name}_{description.k... | the_stack_v2_python_sparse | homeassistant/components/htu21d/sensor.py | AlexxIT/home-assistant | train | 9 |
fe0994f1d2bfb444bbdfc8aba8201e31f8f7a469 | [
"filename = Core.Config.Get('PLUGIN_REPORT_REGISTER')\nself.core = Core\nself.filesize = 0\nself.num_plugins = 0\nif os.path.exists(filename):\n self.filesize = os.path.getsize(filename)\n with open(filename) as f:\n lines = f.read().splitlines()\n self.num_plugins = len(lines)\ntry:\n start_time... | <|body_start_0|>
filename = Core.Config.Get('PLUGIN_REPORT_REGISTER')
self.core = Core
self.filesize = 0
self.num_plugins = 0
if os.path.exists(filename):
self.filesize = os.path.getsize(filename)
with open(filename) as f:
lines = f.read().... | reporting_process | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class reporting_process:
def start(self, Core, reporting_time, queue):
"""This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if not then after every reporting_time second it calls generate_reports"""
<|body_0|>
def generate... | stack_v2_sparse_classes_75kplus_train_001441 | 5,607 | no_license | [
{
"docstring": "This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if not then after every reporting_time second it calls generate_reports",
"name": "start",
"signature": "def start(self, Core, reporting_time, queue)"
},
{
"docstring": "T... | 3 | stack_v2_sparse_classes_30k_train_048604 | Implement the Python class `reporting_process` described below.
Class description:
Implement the reporting_process class.
Method signatures and docstrings:
- def start(self, Core, reporting_time, queue): This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if no... | Implement the Python class `reporting_process` described below.
Class description:
Implement the reporting_process class.
Method signatures and docstrings:
- def start(self, Core, reporting_time, queue): This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if no... | 4d90bdc260edd226385e736831abcd450b9f107b | <|skeleton|>
class reporting_process:
def start(self, Core, reporting_time, queue):
"""This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if not then after every reporting_time second it calls generate_reports"""
<|body_0|>
def generate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class reporting_process:
def start(self, Core, reporting_time, queue):
"""This function after each 1 second checks if the owtf execution is completed if yes it calls generate_reports if not then after every reporting_time second it calls generate_reports"""
filename = Core.Config.Get('PLUGIN_REPORT_... | the_stack_v2_python_sparse | framework/report/reporting_process.py | assem-ch/owtf | train | 9 | |
6f65977557756c58f199538cda4e69dda130cbee | [
"if not arr or k == 0:\n return 0\ncount = 0\nlow, high = (0, k - 1)\nwhile high <= len(arr) - 1:\n if sum(arr[low:high + 1]) / k >= threshold:\n count += 1\n low += 1\n high += 1\n else:\n low += 1\n high += 1\nreturn count",
"if not arr or k == 0:\n return 0\ncount... | <|body_start_0|>
if not arr or k == 0:
return 0
count = 0
low, high = (0, k - 1)
while high <= len(arr) - 1:
if sum(arr[low:high + 1]) / k >= threshold:
count += 1
low += 1
high += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int:
"""滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中"""
<|body_0|>
def numOfSubarrays(self, arr: list, k: int, threshold: int) -> int:
"""滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子... | stack_v2_sparse_classes_75kplus_train_001442 | 2,177 | no_license | [
{
"docstring": "滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中",
"name": "numOfSubarrays_1",
"signature": "def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int"
},
{
"docstring": "滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 法2:法1的问题在于每次循环都调用sum()计算当前子数组的... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int: 滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中
- def numOfSubarrays(self, arr: list, k: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int: 滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中
- def numOfSubarrays(self, arr: list, k: i... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int:
"""滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中"""
<|body_0|>
def numOfSubarrays(self, arr: list, k: int, threshold: int) -> int:
"""滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numOfSubarrays_1(self, arr: list, k: int, threshold: int) -> int:
"""滑动窗口 法1:仅使用两个指针滑动时: 还是属于暴力法,一个一个子数组遍历 只适合小数据,大数据超时 时间消耗在sum()的计算中"""
if not arr or k == 0:
return 0
count = 0
low, high = (0, k - 1)
while high <= len(arr) - 1:
if... | the_stack_v2_python_sparse | algorithm/leetcode/list/04-大小为K且平均值大于等于阈值的子数组数目.py | lxconfig/UbuntuCode_bak | train | 0 | |
e06972728f124a062bb6bfa5cc9e3e229bb5d43a | [
"if coins == [] or amount == 0:\n return 0\ncoins = sorted(coins)\ndp = [-1 for i in range(amount + 1)]\nfor i in range(coins[0], amount + 1):\n if i in coins:\n dp[i] = 1\n else:\n for k in range(1, i // 2 + 1):\n print(k, i)\n if dp[i - k] != -1 and dp[k] != -1:\n ... | <|body_start_0|>
if coins == [] or amount == 0:
return 0
coins = sorted(coins)
dp = [-1 for i in range(amount + 1)]
for i in range(coins[0], amount + 1):
if i in coins:
dp[i] = 1
else:
for k in range(1, i // 2 + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_1(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int 572ms bfs"""
<|body_1|>
def coinChange_2(s... | stack_v2_sparse_classes_75kplus_train_001443 | 3,462 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int 572ms bfs",
"name": "coinChange_1",
"signature": "def coinChange_1(self,... | 4 | stack_v2_sparse_classes_30k_train_040432 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_1(self, coins, amount): :type coins: List[int] :type amount: int :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_1(self, coins, amount): :type coins: List[int] :type amount: int :rtype... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_1(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int 572ms bfs"""
<|body_1|>
def coinChange_2(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if coins == [] or amount == 0:
return 0
coins = sorted(coins)
dp = [-1 for i in range(amount + 1)]
for i in range(coins[0], amount + 1):
if ... | the_stack_v2_python_sparse | CoinChange_MID_322.py | 953250587/leetcode-python | train | 2 | |
c61d08b9b377b9ccc9a1fc011d7fa348b7853d9a | [
"self.heap = nums\nself.k = k\nheapq.heapify(self.heap)\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelif val > self.heap[0]:\n heapq.heappushpop(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.heap = nums
self.k = k
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif val > self.heap[0]:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.heap = nums
self.k = k
heapq.heapify(... | stack_v2_sparse_classes_75kplus_train_001444 | 1,404 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 9126c2089e41d4d7fd3a204115eba2b5074076ad | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.heap = nums
self.k = k
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
""":type val: int :rtype: int"""
... | the_stack_v2_python_sparse | 703_Kth Largest Element in a Stream.py | Shwan-Yu/Data_Structures_and_Algorithms | train | 0 | |
87dc3f2b3e51cc94e4b26c922b24cb47fdf0b3f8 | [
"for columnName, number in self.nameToNumberReqs:\n result = self.tester.columnNameToColumnNumber(columnName)\n self.assertEqual(number, result)",
"for columnNumber, name in self.numberToColumnReqs:\n result = self.tester.columnNumberToColumnName(columnNumber)\n self.assertEqual(name, result)"
] | <|body_start_0|>
for columnName, number in self.nameToNumberReqs:
result = self.tester.columnNameToColumnNumber(columnName)
self.assertEqual(number, result)
<|end_body_0|>
<|body_start_1|>
for columnNumber, name in self.numberToColumnReqs:
result = self.tester.column... | Requirements | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requirements:
def testNameToNumber(self):
"""columnNameToColumnNumber should give expected results"""
<|body_0|>
def testNumberToColumnReqs(self):
"""columnNumberToColumnName should give expected results which are the inverse of columnNameToColumnNumber"""
<|... | stack_v2_sparse_classes_75kplus_train_001445 | 3,394 | no_license | [
{
"docstring": "columnNameToColumnNumber should give expected results",
"name": "testNameToNumber",
"signature": "def testNameToNumber(self)"
},
{
"docstring": "columnNumberToColumnName should give expected results which are the inverse of columnNameToColumnNumber",
"name": "testNumberToColu... | 2 | null | Implement the Python class `Requirements` described below.
Class description:
Implement the Requirements class.
Method signatures and docstrings:
- def testNameToNumber(self): columnNameToColumnNumber should give expected results
- def testNumberToColumnReqs(self): columnNumberToColumnName should give expected result... | Implement the Python class `Requirements` described below.
Class description:
Implement the Requirements class.
Method signatures and docstrings:
- def testNameToNumber(self): columnNameToColumnNumber should give expected results
- def testNumberToColumnReqs(self): columnNumberToColumnName should give expected result... | d900f58f0ddc1891831b298d9b37fbe98193719d | <|skeleton|>
class Requirements:
def testNameToNumber(self):
"""columnNameToColumnNumber should give expected results"""
<|body_0|>
def testNumberToColumnReqs(self):
"""columnNumberToColumnName should give expected results which are the inverse of columnNameToColumnNumber"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Requirements:
def testNameToNumber(self):
"""columnNameToColumnNumber should give expected results"""
for columnName, number in self.nameToNumberReqs:
result = self.tester.columnNameToColumnNumber(columnName)
self.assertEqual(number, result)
def testNumberToColumnR... | the_stack_v2_python_sparse | Assignment1/Task1Test.py | pombreda/comp304 | train | 1 | |
4b33f84939e545a9cec7089545c98779be03a490 | [
"job = self.project.create.job.Gpaw('gpaw', delete_existing_job=True)\njob.input['encut'] = 100\njob.input['kpoints'] = 3 * [1]\ns1 = self.project.atomistics.structure.bulk('Al', cubic=True)\ns2 = self.project.atomistics.structure.bulk('Al', cubic=True)\ns2.positions[0, 0] += 0.2\njob.structure = s1\nwith job.inter... | <|body_start_0|>
job = self.project.create.job.Gpaw('gpaw', delete_existing_job=True)
job.input['encut'] = 100
job.input['kpoints'] = 3 * [1]
s1 = self.project.atomistics.structure.bulk('Al', cubic=True)
s2 = self.project.atomistics.structure.bulk('Al', cubic=True)
s2.pos... | TestGpaw | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGpaw:
def test_interactive_run(self):
"""Gpaw should run interactively, even if you update the structure to a new object."""
<|body_0|>
def test_interface_initialization(self):
"""Make sure that you can initialize the interactive interface without having already ... | stack_v2_sparse_classes_75kplus_train_001446 | 1,399 | permissive | [
{
"docstring": "Gpaw should run interactively, even if you update the structure to a new object.",
"name": "test_interactive_run",
"signature": "def test_interactive_run(self)"
},
{
"docstring": "Make sure that you can initialize the interactive interface without having already run the code.",
... | 2 | stack_v2_sparse_classes_30k_train_008610 | Implement the Python class `TestGpaw` described below.
Class description:
Implement the TestGpaw class.
Method signatures and docstrings:
- def test_interactive_run(self): Gpaw should run interactively, even if you update the structure to a new object.
- def test_interface_initialization(self): Make sure that you can... | Implement the Python class `TestGpaw` described below.
Class description:
Implement the TestGpaw class.
Method signatures and docstrings:
- def test_interactive_run(self): Gpaw should run interactively, even if you update the structure to a new object.
- def test_interface_initialization(self): Make sure that you can... | 4bebd2dd19df34f94bc043f78d497a890dc47fa7 | <|skeleton|>
class TestGpaw:
def test_interactive_run(self):
"""Gpaw should run interactively, even if you update the structure to a new object."""
<|body_0|>
def test_interface_initialization(self):
"""Make sure that you can initialize the interactive interface without having already ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGpaw:
def test_interactive_run(self):
"""Gpaw should run interactively, even if you update the structure to a new object."""
job = self.project.create.job.Gpaw('gpaw', delete_existing_job=True)
job.input['encut'] = 100
job.input['kpoints'] = 3 * [1]
s1 = self.projec... | the_stack_v2_python_sparse | test_integration/test_gpaw.py | pyiron/pyiron_atomistics | train | 33 | |
cc878044d30b3563836322d6f429d72294c9dd17 | [
"request = current.request\nsettings = current.deployment_settings\nscope = 'profile'\nredirect_uri = '%s/%s/default/humanitarian_id/login' % (settings.get_base_public_url(), request.application)\nOAuthAccount.__init__(self, client_id=channel['id'], client_secret=channel['secret'], auth_url=self.AUTH_URL, token_url... | <|body_start_0|>
request = current.request
settings = current.deployment_settings
scope = 'profile'
redirect_uri = '%s/%s/default/humanitarian_id/login' % (settings.get_base_public_url(), request.application)
OAuthAccount.__init__(self, client_id=channel['id'], client_secret=chan... | OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0 | HumanitarianIDAccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecr... | stack_v2_sparse_classes_75kplus_train_001447 | 31,965 | permissive | [
{
"docstring": "Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecret}",
"name": "__init__",
"signature": "def __init__(self, channel)"
},
{
"docstring": "Build the url opener for managing HTTP Basic Authentication",
"name": "__build_url_ope... | 6 | stack_v2_sparse_classes_30k_train_033827 | Implement the Python class `HumanitarianIDAccount` described below.
Class description:
OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: dict with Humanit... | Implement the Python class `HumanitarianIDAccount` described below.
Class description:
OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: dict with Humanit... | 7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6 | <|skeleton|>
class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HumanitarianIDAccount:
"""OAuth implementation for Humanitarian.ID https://docs.google.com/document/d/1-FGDOo2BkhuclxqHcBjCprywZKE_wA6IFTbrs8W26i0"""
def __init__(self, channel):
"""Constructor @param channel: dict with Humanitarian.ID API credentials: {id=clientID, secret=clientSecret}"""
... | the_stack_v2_python_sparse | modules/core/aaa/oauth.py | nursix/drkcm | train | 3 |
ebd95f70adc67ebd1248021e37104250a9948f0b | [
"x = input if 1.0 == sigma else sigma * input\nsigmoid_x = 1.0 / (1.0 + torch.exp(-x))\ngrad = sigmoid_x * (1.0 - sigmoid_x) if 1.0 == sigma else sigma * sigmoid_x * (1.0 - sigmoid_x)\nctx.save_for_backward(grad)\nreturn sigmoid_x",
"grad = ctx.saved_tensors[0]\nbg = grad_output * grad\nreturn (bg, None)"
] | <|body_start_0|>
x = input if 1.0 == sigma else sigma * input
sigmoid_x = 1.0 / (1.0 + torch.exp(-x))
grad = sigmoid_x * (1.0 - sigmoid_x) if 1.0 == sigma else sigma * sigmoid_x * (1.0 - sigmoid_x)
ctx.save_for_backward(grad)
return sigmoid_x
<|end_body_0|>
<|body_start_1|>
... | The vanilla sigmoid operator with a specified sigma | Vanilla_Sigmoid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vanilla_Sigmoid:
"""The vanilla sigmoid operator with a specified sigma"""
def forward(ctx, input, sigma=1.0):
""":param ctx: :param input: the input tensor :param sigma: the scaling constant :return:"""
<|body_0|>
def backward(ctx, grad_output):
""":param ctx: :... | stack_v2_sparse_classes_75kplus_train_001448 | 5,775 | permissive | [
{
"docstring": ":param ctx: :param input: the input tensor :param sigma: the scaling constant :return:",
"name": "forward",
"signature": "def forward(ctx, input, sigma=1.0)"
},
{
"docstring": ":param ctx: :param grad_output: backpropagated gradients from upper module(s) :return:",
"name": "b... | 2 | stack_v2_sparse_classes_30k_train_018433 | Implement the Python class `Vanilla_Sigmoid` described below.
Class description:
The vanilla sigmoid operator with a specified sigma
Method signatures and docstrings:
- def forward(ctx, input, sigma=1.0): :param ctx: :param input: the input tensor :param sigma: the scaling constant :return:
- def backward(ctx, grad_o... | Implement the Python class `Vanilla_Sigmoid` described below.
Class description:
The vanilla sigmoid operator with a specified sigma
Method signatures and docstrings:
- def forward(ctx, input, sigma=1.0): :param ctx: :param input: the input tensor :param sigma: the scaling constant :return:
- def backward(ctx, grad_o... | 076646aac80341ac4a428f710ba6718e27b44a0c | <|skeleton|>
class Vanilla_Sigmoid:
"""The vanilla sigmoid operator with a specified sigma"""
def forward(ctx, input, sigma=1.0):
""":param ctx: :param input: the input tensor :param sigma: the scaling constant :return:"""
<|body_0|>
def backward(ctx, grad_output):
""":param ctx: :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vanilla_Sigmoid:
"""The vanilla sigmoid operator with a specified sigma"""
def forward(ctx, input, sigma=1.0):
""":param ctx: :param input: the input tensor :param sigma: the scaling constant :return:"""
x = input if 1.0 == sigma else sigma * input
sigmoid_x = 1.0 / (1.0 + torch.e... | the_stack_v2_python_sparse | ptranking/base/neural_utils.py | diegogranziol/ptranking | train | 1 |
8283f6ea9a3e758bac786adc6cc13ca761efdc1e | [
"from sktime.distances._distance_alignment_paths import compute_twe_return_path\nfrom sktime.distances._twe_numba import _twe_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_m... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_twe_return_path
from sktime.distances._twe_numba import _twe_cost_matrix
from sktime.distances.lower_bounding import resolve_bounding_matrix
from sktime.utils.numba.njit import njit
_bounding_matrix =... | Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE is a metric. Its computati... | _TweDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_75kplus_train_001449 | 7,764 | permissive | [
{
"docstring": "Create a no_python compiled twe distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array of shape (d,m2)). Second time series. return_cost... | 2 | stack_v2_sparse_classes_30k_train_002766 | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE... | the_stack_v2_python_sparse | sktime/distances/_twe.py | sktime/sktime | train | 1,117 |
6a163677610ac84225bfba4488e1d17aa3eb5af6 | [
"visited = set([0])\n\ndef dfs(i):\n for r in rooms[i]:\n if r not in visited:\n visited.add(r)\n dfs(r)\ndfs(0)\nreturn len(visited) == len(rooms)",
"n = len(rooms)\nvisited = [False] * n\nkeys = deque([0])\nwhile keys:\n key = keys.popleft()\n if visited[key]:\n cont... | <|body_start_0|>
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return len(visited) == len(rooms)
<|end_body_0|>
<|body_start_1|>
n = len(rooms)
visi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
visited = set... | stack_v2_sparse_classes_75kplus_train_001450 | 2,415 | no_license | [
{
"docstring": "Sep 26, 2020 15:10",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
},
{
"docstring": "Feb 19, 2023 17:13",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_026670 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13
<|skeleton|>
clas... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return... | the_stack_v2_python_sparse | leetcode/solved/871_Keys_and_Rooms/solution.py | sungminoh/algorithms | train | 0 | |
069a78f6d08d9da6214e04de9e55354470edcde9 | [
"import hashlib\nh = hashlib.sha1(user.password + unicode(user.last_login_date) + unicode(user.id)).hexdigest()[::2]\nreturn '%s-%s' % (int_to_base36(user.id), h)",
"try:\n ts_b36 = token.split('-')[0]\nexcept ValueError:\n return False\ntry:\n uid = base36_to_int(ts_b36)\nexcept ValueError:\n return ... | <|body_start_0|>
import hashlib
h = hashlib.sha1(user.password + unicode(user.last_login_date) + unicode(user.id)).hexdigest()[::2]
return '%s-%s' % (int_to_base36(user.id), h)
<|end_body_0|>
<|body_start_1|>
try:
ts_b36 = token.split('-')[0]
except ValueError:
... | Class for generating tokens during password reset. | PasswordResetTokenGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetTokenGenerator:
"""Class for generating tokens during password reset."""
def make_token(self, user):
"""@parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with timestamp generated for specified User"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001451 | 2,235 | permissive | [
{
"docstring": "@parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with timestamp generated for specified User",
"name": "make_token",
"signature": "def make_token(self, user)"
},
{
"docstring": "@parameter{user,User} instance of the User whose T... | 2 | stack_v2_sparse_classes_30k_train_044513 | Implement the Python class `PasswordResetTokenGenerator` described below.
Class description:
Class for generating tokens during password reset.
Method signatures and docstrings:
- def make_token(self, user): @parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with time... | Implement the Python class `PasswordResetTokenGenerator` described below.
Class description:
Class for generating tokens during password reset.
Method signatures and docstrings:
- def make_token(self, user): @parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with time... | 8113673fa13b6fe195cea99dedab9616aeca3ae8 | <|skeleton|>
class PasswordResetTokenGenerator:
"""Class for generating tokens during password reset."""
def make_token(self, user):
"""@parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with timestamp generated for specified User"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordResetTokenGenerator:
"""Class for generating tokens during password reset."""
def make_token(self, user):
"""@parameter{user,User} instance of the User whom Token should be generated for @returns{string} Token with timestamp generated for specified User"""
import hashlib
h... | the_stack_v2_python_sparse | src/clm/utils/tokens.py | jochym/cc1 | train | 0 |
097de4c5caa47f8a87e50a394ae3155a5eea6302 | [
"if not isinstance(params, dict):\n raise ValueError('No parameter dictionary given.')\nself.params = params\nself.worker_information = worker_information",
"if not isinstance(other, Candidate):\n return False\nif self.params == other.params:\n return True\nreturn False",
"string = 'Candidate\\n'\nstri... | <|body_start_0|>
if not isinstance(params, dict):
raise ValueError('No parameter dictionary given.')
self.params = params
self.worker_information = worker_information
<|end_body_0|>
<|body_start_1|>
if not isinstance(other, Candidate):
return False
if sel... | A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, then updated with the result and cost of the evaluation. Attributes ---------- ... | Candidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Candidate:
"""A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, then updated with the result and cost of t... | stack_v2_sparse_classes_75kplus_train_001452 | 5,067 | no_license | [
{
"docstring": "Initializes the unevaluated candidate object. Parameters ---------- params : dict of string keys A dictionary of parameter value. The keys must correspond to the problem definition. The dictionary requires one key - and value - per parameter defined. worker_information : string, optional This is... | 6 | stack_v2_sparse_classes_30k_train_000625 | Implement the Python class `Candidate` described below.
Class description:
A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, the... | Implement the Python class `Candidate` described below.
Class description:
A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, the... | 8dd8798397debdde9392c5a6c2aee2dcaa921d92 | <|skeleton|>
class Candidate:
"""A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, then updated with the result and cost of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Candidate:
"""A Candidate is a dictionary of parameter values, which should - or have been - evaluated. A Candidate object can be seen as a single iteration of the experiment. It is first generated as a suggestion of which parameter set to evaluate next, then updated with the result and cost of the evaluation... | the_stack_v2_python_sparse | apsis/models/candidate.py | vinodrajendran001/Molecules-Prediction | train | 1 |
d2ba865d7a5511d866ccb99e2ef62699191ea8c3 | [
"cls.check_logos(values)\ncls.check_urls(values)\ncls.check_quality_time_source_types(values)\nreturn values",
"logos_path = pathlib.Path(__file__).parent.parent / 'logos'\nfor source_type in values:\n logo_path = logos_path / f'{source_type}.png'\n if not logo_path.exists():\n msg = f'No logo exists... | <|body_start_0|>
cls.check_logos(values)
cls.check_urls(values)
cls.check_quality_time_source_types(values)
return values
<|end_body_0|>
<|body_start_1|>
logos_path = pathlib.Path(__file__).parent.parent / 'logos'
for source_type in values:
logo_path = logos_... | Sources mapping. | Sources | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sources:
"""Sources mapping."""
def check_sources(cls, values: dict) -> dict:
"""Check the sources."""
<|body_0|>
def check_logos(cls, values: dict) -> None:
"""Check that a logo exists for each source and vice versa."""
<|body_1|>
def check_urls(cls... | stack_v2_sparse_classes_75kplus_train_001453 | 4,210 | permissive | [
{
"docstring": "Check the sources.",
"name": "check_sources",
"signature": "def check_sources(cls, values: dict) -> dict"
},
{
"docstring": "Check that a logo exists for each source and vice versa.",
"name": "check_logos",
"signature": "def check_logos(cls, values: dict) -> None"
},
... | 4 | null | Implement the Python class `Sources` described below.
Class description:
Sources mapping.
Method signatures and docstrings:
- def check_sources(cls, values: dict) -> dict: Check the sources.
- def check_logos(cls, values: dict) -> None: Check that a logo exists for each source and vice versa.
- def check_urls(cls, va... | Implement the Python class `Sources` described below.
Class description:
Sources mapping.
Method signatures and docstrings:
- def check_sources(cls, values: dict) -> dict: Check the sources.
- def check_logos(cls, values: dict) -> None: Check that a logo exists for each source and vice versa.
- def check_urls(cls, va... | 5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3 | <|skeleton|>
class Sources:
"""Sources mapping."""
def check_sources(cls, values: dict) -> dict:
"""Check the sources."""
<|body_0|>
def check_logos(cls, values: dict) -> None:
"""Check that a logo exists for each source and vice versa."""
<|body_1|>
def check_urls(cls... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sources:
"""Sources mapping."""
def check_sources(cls, values: dict) -> dict:
"""Check the sources."""
cls.check_logos(values)
cls.check_urls(values)
cls.check_quality_time_source_types(values)
return values
def check_logos(cls, values: dict) -> None:
... | the_stack_v2_python_sparse | components/shared_code/src/shared_data_model/meta/source.py | ICTU/quality-time | train | 43 |
d27121161963f15af62348f949255722e495d330 | [
"if isinstance(key, int):\n return Option(key)\nif key not in Option._member_map_:\n extend_enum(Option, key, default)\nreturn Option[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nextend_enum(cls, 'Unassigned [0x%s]' % h... | <|body_start_0|>
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
return Option[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise ValueErro... | [Option] Destination Options and Hop-by-Hop Options | Option | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""[Option] Destination Options and Hop-by-Hop Options"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_001454 | 2,899 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | null | Implement the Python class `Option` described below.
Class description:
[Option] Destination Options and Hop-by-Hop Options
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Option` described below.
Class description:
[Option] Destination Options and Hop-by-Hop Options
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class ... | 71363d7948003fec88cedcf5bc80b6befa2ba244 | <|skeleton|>
class Option:
"""[Option] Destination Options and Hop-by-Hop Options"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Option:
"""[Option] Destination Options and Hop-by-Hop Options"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
r... | the_stack_v2_python_sparse | pcapkit/const/ipv6/option.py | hiok2000/PyPCAPKit | train | 0 |
49e2e64348c5563e3bedafceb853bf9ffc423d4a | [
"if isinstance(final_states, Qobj) or final_states is None:\n self.final_states = [final_states]\n self.probabilities = [probabilities]\n if cbits:\n self.cbits = [cbits]\nelse:\n inds = list(filter(lambda x: final_states[x] is not None, range(len(final_states))))\n self.final_states = [final_... | <|body_start_0|>
if isinstance(final_states, Qobj) or final_states is None:
self.final_states = [final_states]
self.probabilities = [probabilities]
if cbits:
self.cbits = [cbits]
else:
inds = list(filter(lambda x: final_states[x] is not Non... | Result of a quantum circuit simulation. | CircuitResult | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircuitResult:
"""Result of a quantum circuit simulation."""
def __init__(self, final_states, probabilities, cbits=None):
"""Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output kets or density matrices. probabilities: list of float. List... | stack_v2_sparse_classes_75kplus_train_001455 | 23,944 | permissive | [
{
"docstring": "Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output kets or density matrices. probabilities: list of float. List of probabilities of obtaining each output state. cbits: list of list of int, optional List of cbits for each output.",
"name": "__in... | 4 | stack_v2_sparse_classes_30k_train_014784 | Implement the Python class `CircuitResult` described below.
Class description:
Result of a quantum circuit simulation.
Method signatures and docstrings:
- def __init__(self, final_states, probabilities, cbits=None): Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output ket... | Implement the Python class `CircuitResult` described below.
Class description:
Result of a quantum circuit simulation.
Method signatures and docstrings:
- def __init__(self, final_states, probabilities, cbits=None): Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output ket... | a5e97023cc84ba7509b0ee65d742b8a0ae19fdf0 | <|skeleton|>
class CircuitResult:
"""Result of a quantum circuit simulation."""
def __init__(self, final_states, probabilities, cbits=None):
"""Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output kets or density matrices. probabilities: list of float. List... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CircuitResult:
"""Result of a quantum circuit simulation."""
def __init__(self, final_states, probabilities, cbits=None):
"""Store result of CircuitSimulator. Parameters ---------- final_states: list of Qobj. List of output kets or density matrices. probabilities: list of float. List of probabili... | the_stack_v2_python_sparse | src/qutip_qip/circuit/circuitsimulator.py | qutip/qutip-qip | train | 84 |
4eb250f22cb9f6e1f36a92113e601476ad177826 | [
"if not language in ACCEPTED_LANGUAGES:\n raise ValueError(f'Language {language} is not supported yet')\nself._language = language\nself._matcher = PhraseMatcher(nlp.vocab, attr='LOWER')\nself._connectives = []\nif language == 'es':\n self._connectives = ['actualmente', 'ahora', 'después', 'más tarde', 'más a... | <|body_start_0|>
if not language in ACCEPTED_LANGUAGES:
raise ValueError(f'Language {language} is not supported yet')
self._language = language
self._matcher = PhraseMatcher(nlp.vocab, attr='LOWER')
self._connectives = []
if language == 'es':
self._connect... | This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component. | TemporalConnectivesTagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalConnectivesTagger:
"""This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component."""
def __init__(self, nlp, language: str='es') -> None:
"""This constructor will initialize the object that tags temporal conne... | stack_v2_sparse_classes_75kplus_train_001456 | 2,617 | no_license | [
{
"docstring": "This constructor will initialize the object that tags temporal connectives. Parameters: nlp: The Spacy model to use this tagger with. language: The language that this pipeline will be used in. Returns: None.",
"name": "__init__",
"signature": "def __init__(self, nlp, language: str='es') ... | 2 | stack_v2_sparse_classes_30k_train_040393 | Implement the Python class `TemporalConnectivesTagger` described below.
Class description:
This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component.
Method signatures and docstrings:
- def __init__(self, nlp, language: str='es') -> None: This constr... | Implement the Python class `TemporalConnectivesTagger` described below.
Class description:
This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component.
Method signatures and docstrings:
- def __init__(self, nlp, language: str='es') -> None: This constr... | f23342fbf2cb54a89cd381813ad9eee754b61094 | <|skeleton|>
class TemporalConnectivesTagger:
"""This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component."""
def __init__(self, nlp, language: str='es') -> None:
"""This constructor will initialize the object that tags temporal conne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporalConnectivesTagger:
"""This tagger has the task to find all temporal connectives in a document. It needs to go after the 'Tagger' pipeline component."""
def __init__(self, nlp, language: str='es') -> None:
"""This constructor will initialize the object that tags temporal connectives. Param... | the_stack_v2_python_sparse | src/processing/pipes/temporal_connectives_tagger.py | persuaide/Tesis_Chatbot | train | 0 |
b19d04a16672a6e82ef0ac5031a632a46feb1e78 | [
"super(ModelGRUCell6, self).__init__()\nself.trg_embeder = Embedding(100, 32)\nself.output_layer = Linear(32, 32)\nself.decoder_cell = GRUCell(input_size=32, hidden_size=32)\nself.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4, embedding_fn=self.trg_embeder, output_fn=self.ou... | <|body_start_0|>
super(ModelGRUCell6, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = GRUCell(input_size=32, hidden_size=32)
self.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4, ... | GRUCell model2 | ModelGRUCell6 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelGRUCell6:
"""GRUCell model2"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ModelGRUCell6, self).__init__()
self.trg_embeder = Embedding(100, 32)... | stack_v2_sparse_classes_75kplus_train_001457 | 20,209 | no_license | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self)"
}
] | 2 | null | Implement the Python class `ModelGRUCell6` described below.
Class description:
GRUCell model2
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward | Implement the Python class `ModelGRUCell6` described below.
Class description:
GRUCell model2
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward
<|skeleton|>
class ModelGRUCell6:
"""GRUCell model2"""
def __init__(self):
"""initialize"""
<|body_0|>... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class ModelGRUCell6:
"""GRUCell model2"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelGRUCell6:
"""GRUCell model2"""
def __init__(self):
"""initialize"""
super(ModelGRUCell6, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = GRUCell(input_size=32, hidden_size=32)
self.decoder =... | the_stack_v2_python_sparse | framework/api/nn/test_dynamicdecode.py | PaddlePaddle/PaddleTest | train | 42 |
5d2fd7c60f2cfd14d6252fc63e311c44af87b410 | [
"self.client = client\nself.poll_interval = poll_interval\nself.is_async = is_async\nself.service = service\nself.tasks = dict()",
"if run_id in self.tasks:\n workflow_id = self.tasks[run_id]\n try:\n self.client.stop_workflow(workflow_id)\n except Exception as ex:\n logging.error(ex)\n ... | <|body_start_0|>
self.client = client
self.poll_interval = poll_interval
self.is_async = is_async
self.service = service
self.tasks = dict()
<|end_body_0|>
<|body_start_1|>
if run_id in self.tasks:
workflow_id = self.tasks[run_id]
try:
... | Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state. | RemoteWorkflowController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteWorkflowController:
"""Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state."""
def __init__(self, client: RemoteClient, poll_inte... | stack_v2_sparse_classes_75kplus_train_001458 | 7,730 | permissive | [
{
"docstring": "Initialize the client that is used to interact with the remote workflow engine. Parameters ---------- client: flowserv.controller.remote.client.RemoteClient Engine-specific implementation of the remote client that is used by the controller to interact with the workflow engine. poll_interval: int... | 3 | stack_v2_sparse_classes_30k_val_001183 | Implement the Python class `RemoteWorkflowController` described below.
Class description:
Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state.
Method signatures ... | Implement the Python class `RemoteWorkflowController` described below.
Class description:
Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state.
Method signatures ... | 7116b7060aa68ab36bf08e6393be166dc5db955f | <|skeleton|>
class RemoteWorkflowController:
"""Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state."""
def __init__(self, client: RemoteClient, poll_inte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteWorkflowController:
"""Workflow controller that executes workflow templates for a given set of arguments using an external workflow engine. Each workflow is monitored by a separate process that continuously polls the workflow state."""
def __init__(self, client: RemoteClient, poll_interval: float, ... | the_stack_v2_python_sparse | flowserv/controller/remote/engine.py | anrunw/flowserv-core-1 | train | 0 |
d3fceccb65a52320447e9be139261e875a1506a7 | [
"global tree_level, current_module, module_type, return_report, last_text\ntext = bpy.context.space_data.text\nif text:\n if text.name != 'api_doc_':\n last_text = bpy.context.space_data.text.name\n elif bpy.data.texts.__len__() < 2:\n last_text = None\nelse:\n last_text = None\nbpy.context.w... | <|body_start_0|>
global tree_level, current_module, module_type, return_report, last_text
text = bpy.context.space_data.text
if text:
if text.name != 'api_doc_':
last_text = bpy.context.space_data.text.name
elif bpy.data.texts.__len__() < 2:
... | Parent class for API Navigator | ApiNavigator | [
"GPL-3.0-only",
"Font-exception-2.0",
"GPL-3.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer",
"Bitstream-Vera",
"LicenseRef-scancode-blender-2010",
"LGPL-2.1-or-later",
"GPL-2.0-or-lat... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiNavigator:
"""Parent class for API Navigator"""
def generate_global_values():
"""Populate the level attributes to display the panel buttons and the documentation"""
<|body_0|>
def generate_api_doc():
"""Format the doc string for API Navigator"""
<|body... | stack_v2_sparse_classes_75kplus_train_001459 | 23,528 | permissive | [
{
"docstring": "Populate the level attributes to display the panel buttons and the documentation",
"name": "generate_global_values",
"signature": "def generate_global_values()"
},
{
"docstring": "Format the doc string for API Navigator",
"name": "generate_api_doc",
"signature": "def gene... | 3 | stack_v2_sparse_classes_30k_train_004692 | Implement the Python class `ApiNavigator` described below.
Class description:
Parent class for API Navigator
Method signatures and docstrings:
- def generate_global_values(): Populate the level attributes to display the panel buttons and the documentation
- def generate_api_doc(): Format the doc string for API Naviga... | Implement the Python class `ApiNavigator` described below.
Class description:
Parent class for API Navigator
Method signatures and docstrings:
- def generate_global_values(): Populate the level attributes to display the panel buttons and the documentation
- def generate_api_doc(): Format the doc string for API Naviga... | f7d23a489c2b4bcc3c1961ac955926484ff8b8d9 | <|skeleton|>
class ApiNavigator:
"""Parent class for API Navigator"""
def generate_global_values():
"""Populate the level attributes to display the panel buttons and the documentation"""
<|body_0|>
def generate_api_doc():
"""Format the doc string for API Navigator"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiNavigator:
"""Parent class for API Navigator"""
def generate_global_values():
"""Populate the level attributes to display the panel buttons and the documentation"""
global tree_level, current_module, module_type, return_report, last_text
text = bpy.context.space_data.text
... | the_stack_v2_python_sparse | engine/2.80/scripts/addons/development_api_navigator.py | byteinc/Phasor | train | 3 |
119bdb99874d8beac14a2fc7ab45ee35eba86139 | [
"super(ProfileForm, self).__init__(*args, **kwargs)\ntry:\n self.fields['email'].initial = self.instance.user.email\n self.fields['first_name'].initial = self.instance.user.first_name\n self.fields['last_name'].initial = self.instance.user.last_name\nexcept User.DoesNotExist:\n pass",
"u = self.instan... | <|body_start_0|>
super(ProfileForm, self).__init__(*args, **kwargs)
try:
self.fields['email'].initial = self.instance.user.email
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
e... | A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields | ProfileForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileForm:
"""A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields"""
def __init__(self, *args, **kwargs):... | stack_v2_sparse_classes_75kplus_train_001460 | 1,642 | no_license | [
{
"docstring": "Fill in the extra fields with the right dat afrom the user object",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Update the email address and name on the related User object as well.",
"name": "save",
"signature": "def save(sel... | 2 | stack_v2_sparse_classes_30k_train_005333 | Implement the Python class `ProfileForm` described below.
Class description:
A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields
Meth... | Implement the Python class `ProfileForm` described below.
Class description:
A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields
Meth... | 104166a2a444fe36f3a5dba954527139fee08e8d | <|skeleton|>
class ProfileForm:
"""A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields"""
def __init__(self, *args, **kwargs):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileForm:
"""A custom form to make editing a profile more powerful. Fields like email and name are part of the User object, not the user's profile, so they cannot be edited with the default profile edit form. This custom form adds these extra fields"""
def __init__(self, *args, **kwargs):
"""F... | the_stack_v2_python_sparse | profiles/forms.py | NabeelaMSIT/digitalchef | train | 0 |
656c0cd26627ba95641cff3474151d1d93b49b9d | [
"if self.cleaned_data.get('username', None):\n try:\n user = User.objects.get(username__exact=self.cleaned_data['username'])\n except User.DoesNotExist:\n return self.cleaned_data['username']\n raise forms.ValidationError(u'Username is unavailable.')",
"if self.cleaned_data.get('email', Non... | <|body_start_0|>
if self.cleaned_data.get('username', None):
try:
user = User.objects.get(username__exact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(u'Username is un... | Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken. | RegistrationForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken."""
def clean_username(self):
"""Validates that the username is not already in use."""
<|body_0|>
def clean_... | stack_v2_sparse_classes_75kplus_train_001461 | 12,835 | permissive | [
{
"docstring": "Validates that the username is not already in use.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Validates that the email is not already in use.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_046847 | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken.
Method signatures and docstrings:
- def clean_username(self): Validates that the username is ... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken.
Method signatures and docstrings:
- def clean_username(self): Validates that the username is ... | ef0496d5ec1e45f5f40f5d6a9ba695f359c7946b | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken."""
def clean_username(self):
"""Validates that the username is not already in use."""
<|body_0|>
def clean_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationForm:
"""Form for registering a new user account. Validates that the password is entered twice and matches, and that the username is not already taken."""
def clean_username(self):
"""Validates that the username is not already in use."""
if self.cleaned_data.get('username', No... | the_stack_v2_python_sparse | registration/forms.py | msquaresystems/itechtalents-12-10-2014 | train | 0 |
9d4e2e06f3d7d3d7a5e27c6cc2889de2dd81e767 | [
"klass = cls._instances.get(name)\nif klass is None:\n klass = cls._instances[name] = super().__new__(cls)\nreturn klass",
"self._name = name\nif not hasattr(self, '_rules'):\n super().__init__()"
] | <|body_start_0|>
klass = cls._instances.get(name)
if klass is None:
klass = cls._instances[name] = super().__new__(cls)
return klass
<|end_body_0|>
<|body_start_1|>
self._name = name
if not hasattr(self, '_rules'):
super().__init__()
<|end_body_1|>
| The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instance. | Marshal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Marshal:
"""The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instance."""
def __new__(cls, *, name: s... | stack_v2_sparse_classes_75kplus_train_001462 | 11,646 | permissive | [
{
"docstring": "Create a marshal instance. Args: name (str): The name of the marshal. Instantiating multiple marshals with the same ``name`` argument will provide the same marshal each time.",
"name": "__new__",
"signature": "def __new__(cls, *, name: str)"
},
{
"docstring": "Instantiate a marsh... | 2 | null | Implement the Python class `Marshal` described below.
Class description:
The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instan... | Implement the Python class `Marshal` described below.
Class description:
The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instan... | 9d524420cde12a2994939a817c60647bf04e253a | <|skeleton|>
class Marshal:
"""The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instance."""
def __new__(cls, *, name: s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Marshal:
"""The translator between protocol buffer and Python instances. The bulk of the implementation is in :class:`BaseMarshal`. This class adds identity tracking: multiple instantiations of :class:`Marshal` with the same name will provide the same instance."""
def __new__(cls, *, name: str):
... | the_stack_v2_python_sparse | proto/marshal/marshal.py | googleapis/proto-plus-python | train | 140 |
876f3e1c3a60dcf83591ce5da6a55e04ec41b237 | [
"self.optimizer_type = optimizer_type\nself.base_lr = base_lr\nself.min_lr = min_lr\nself.exp_gamma = exp_gamma\nself.steps_per_epoch = steps_per_epoch\nself.warmup_epochs = warmup_epochs\nself.hold_epochs = hold_epochs\nself.current_lr = None\nself.max_weight_norm = max_weight_norm if max_weight_norm is not None e... | <|body_start_0|>
self.optimizer_type = optimizer_type
self.base_lr = base_lr
self.min_lr = min_lr
self.exp_gamma = exp_gamma
self.steps_per_epoch = steps_per_epoch
self.warmup_epochs = warmup_epochs
self.hold_epochs = hold_epochs
self.current_lr = None
... | TransducerOptimizerFactory | [
"MIT",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating an... | stack_v2_sparse_classes_75kplus_train_001463 | 4,334 | permissive | [
{
"docstring": "Class for creating and updating popart optimizers :param str optimizer_type: optimizer type - 'SGD' or 'LAMB' :param float base_lr: base learning rate :param float min_lr: minimum learning rate :param float exp_gamma: gamma factor for exponential lr scheduler :param int steps_per_epoch: training... | 3 | stack_v2_sparse_classes_30k_train_022746 | Implement the Python class `TransducerOptimizerFactory` described below.
Class description:
Implement the TransducerOptimizerFactory class.
Method signatures and docstrings:
- def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_dec... | Implement the Python class `TransducerOptimizerFactory` described below.
Class description:
Implement the TransducerOptimizerFactory class.
Method signatures and docstrings:
- def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_dec... | 46d2b7687b829778369fc6328170a7b14761e5c6 | <|skeleton|>
class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating and updating pop... | the_stack_v2_python_sparse | applications/popart/transformer_transducer/training/transducer_optimizer.py | payoto/graphcore_examples | train | 0 | |
5fcbf9e26312bdeb82d6991a2b3d7997501675eb | [
"src_type, src_path = cls.identify_path_type(src)\ndest_type, dest_path = cls.identify_path_type(dest)\nformat_table = {'s3': cls.format_s3_path, 'local': cls.format_local_path}\nsrc_path = format_table[src_type](src_path)[0]\ndest_path, use_src_name = format_table[dest_type](dest_path)\nreturn {'dest': {'path': de... | <|body_start_0|>
src_type, src_path = cls.identify_path_type(src)
dest_type, dest_path = cls.identify_path_type(dest)
format_table = {'s3': cls.format_s3_path, 'local': cls.format_local_path}
src_path = format_table[src_type](src_path)[0]
dest_path, use_src_name = format_table[de... | Path format base class. | FormatPath | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormatPath:
"""Path format base class."""
def format(cls, src: str, dest: str) -> FormatPathResult:
"""Format the source and destination for use in the file factory."""
<|body_0|>
def format_local_path(path: str, dir_op: bool=True) -> Tuple[str, bool]:
"""Format ... | stack_v2_sparse_classes_75kplus_train_001464 | 4,460 | permissive | [
{
"docstring": "Format the source and destination for use in the file factory.",
"name": "format",
"signature": "def format(cls, src: str, dest: str) -> FormatPathResult"
},
{
"docstring": "Format the path of local files. Returns whether the destination will keep its own name or take the source'... | 4 | stack_v2_sparse_classes_30k_val_000340 | Implement the Python class `FormatPath` described below.
Class description:
Path format base class.
Method signatures and docstrings:
- def format(cls, src: str, dest: str) -> FormatPathResult: Format the source and destination for use in the file factory.
- def format_local_path(path: str, dir_op: bool=True) -> Tupl... | Implement the Python class `FormatPath` described below.
Class description:
Path format base class.
Method signatures and docstrings:
- def format(cls, src: str, dest: str) -> FormatPathResult: Format the source and destination for use in the file factory.
- def format_local_path(path: str, dir_op: bool=True) -> Tupl... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class FormatPath:
"""Path format base class."""
def format(cls, src: str, dest: str) -> FormatPathResult:
"""Format the source and destination for use in the file factory."""
<|body_0|>
def format_local_path(path: str, dir_op: bool=True) -> Tuple[str, bool]:
"""Format ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FormatPath:
"""Path format base class."""
def format(cls, src: str, dest: str) -> FormatPathResult:
"""Format the source and destination for use in the file factory."""
src_type, src_path = cls.identify_path_type(src)
dest_type, dest_path = cls.identify_path_type(dest)
for... | the_stack_v2_python_sparse | runway/core/providers/aws/s3/_helpers/format_path.py | onicagroup/runway | train | 156 |
5d38f5c163c0867c095f5cdfa16848a3ed3b84e8 | [
"if root == None:\n return 0\n\ndef numberOfBinaryTree(root):\n if root.right == None and root.left == None:\n count_right = 0\n count_left = 0\n maxsum = 0\n return (count_right, count_left, maxsum)\n if root.right != None:\n count_right_r, count_left_r, maxsum_right = n... | <|body_start_0|>
if root == None:
return 0
def numberOfBinaryTree(root):
if root.right == None and root.left == None:
count_right = 0
count_left = 0
maxsum = 0
return (count_right, count_left, maxsum)
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
<|body_0|>
def diameterOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 72ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root == None:
... | stack_v2_sparse_classes_75kplus_train_001465 | 2,564 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int 79ms",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int 72ms",
"name": "diameterOfBinaryTree_1",
"signature": "def diameterOfBinaryTree_1(self, root)"
... | 2 | stack_v2_sparse_classes_30k_train_026902 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 79ms
- def diameterOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 72ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 79ms
- def diameterOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 72ms
<|skeleton|>
class So... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
<|body_0|>
def diameterOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 72ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
if root == None:
return 0
def numberOfBinaryTree(root):
if root.right == None and root.left == None:
count_right = 0
count_left = 0
... | the_stack_v2_python_sparse | DiameterOfBinaryTree_543.py | 953250587/leetcode-python | train | 2 | |
c55c037d6fbb5b296c01dffe3b93606d5a2d48f4 | [
"user_id = request.args.get('user_id', None, type=int)\nif user_id is None:\n user_id = g.user_id\nuser = UserModel.get_by_id(user_id)\nif user is not None:\n return ApiResponse.success(UserSchema().dump(user), 200)\nreturn ApiResponse.error('User not found.', 402)",
"from api.modules.user.model import User... | <|body_start_0|>
user_id = request.args.get('user_id', None, type=int)
if user_id is None:
user_id = g.user_id
user = UserModel.get_by_id(user_id)
if user is not None:
return ApiResponse.success(UserSchema().dump(user), 200)
return ApiResponse.error('User ... | UserProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfile:
def get(self):
"""Get User data"""
<|body_0|>
def put(self):
"""Update user profile data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user_id = request.args.get('user_id', None, type=int)
if user_id is None:
user_... | stack_v2_sparse_classes_75kplus_train_001466 | 7,679 | no_license | [
{
"docstring": "Get User data",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update user profile data",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035706 | Implement the Python class `UserProfile` described below.
Class description:
Implement the UserProfile class.
Method signatures and docstrings:
- def get(self): Get User data
- def put(self): Update user profile data | Implement the Python class `UserProfile` described below.
Class description:
Implement the UserProfile class.
Method signatures and docstrings:
- def get(self): Get User data
- def put(self): Update user profile data
<|skeleton|>
class UserProfile:
def get(self):
"""Get User data"""
<|body_0|>
... | 8e61e2e9564410d3eec4cf2862e2dbc4c5058efc | <|skeleton|>
class UserProfile:
def get(self):
"""Get User data"""
<|body_0|>
def put(self):
"""Update user profile data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserProfile:
def get(self):
"""Get User data"""
user_id = request.args.get('user_id', None, type=int)
if user_id is None:
user_id = g.user_id
user = UserModel.get_by_id(user_id)
if user is not None:
return ApiResponse.success(UserSchema().dump(us... | the_stack_v2_python_sparse | api/modules/user/resource.py | abhit9l/nasih | train | 0 | |
69b81cc80db56cf33dbd3a597105095c825d3d7d | [
"self.start = start\nself.is_end = False\nself.children = []",
"if len(word) == 0:\n self.is_end = True\n return\nfirst = word[0]\nlast = word[1:]\nfor c in self.children:\n if c.start == first:\n c.insert(last)\n break\nelse:\n trie = Trie(first)\n trie.insert(last)\n self.childre... | <|body_start_0|>
self.start = start
self.is_end = False
self.children = []
<|end_body_0|>
<|body_start_1|>
if len(word) == 0:
self.is_end = True
return
first = word[0]
last = word[1:]
for c in self.children:
if c.start == first... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self, start=None):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
<|body_1|>
def search(self, word):
"""Returns if the word is in t... | stack_v2_sparse_classes_75kplus_train_001467 | 1,627 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self, start=None)"
},
{
"docstring": "Inserts a word into the trie. :type word: str :rtype: None",
"name": "insert",
"signature": "def insert(self, word)"
},
{
"docstring": "Retu... | 4 | null | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self, start=None): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: None
- def search(self, word): Return... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self, start=None): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: None
- def search(self, word): Return... | 193c27273eeacc7ceb159154fd87f7d7d9a70ae0 | <|skeleton|>
class Trie:
def __init__(self, start=None):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
<|body_1|>
def search(self, word):
"""Returns if the word is in t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trie:
def __init__(self, start=None):
"""Initialize your data structure here."""
self.start = start
self.is_end = False
self.children = []
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: None"""
if len(word) == 0:
... | the_stack_v2_python_sparse | leetcode/ds/lc_208.py | shoppon/leetcode | train | 0 | |
5bace45a65dd5ee972f2f2e16334338be5c6bb18 | [
"if pk is None or pk == '':\n return None\ntable_name = self.model._meta.db_table\ncache = FireHydrantCacheFactory(('model_cache', table_name))\nobj = cache.get_cache(pk)\nif obj is None:\n try:\n obj = super().get_queryset().get(pk=pk)\n cache.set_cache(pk, obj)\n except:\n return Non... | <|body_start_0|>
if pk is None or pk == '':
return None
table_name = self.model._meta.db_table
cache = FireHydrantCacheFactory(('model_cache', table_name))
obj = cache.get_cache(pk)
if obj is None:
try:
obj = super().get_queryset().get(pk=p... | FireHydrantModelManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
<|body_0|>
def all_cache(self):
"""全部缓存 :return:"""
<|body_1|>
def filter_cache(self, **kwargs):
"""过滤缓存 :param kwargs: :return:"""
... | stack_v2_sparse_classes_75kplus_train_001468 | 1,776 | no_license | [
{
"docstring": "缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:",
"name": "get_once",
"signature": "def get_once(self, pk)"
},
{
"docstring": "全部缓存 :return:",
"name": "all_cache",
"signature": "def all_cache(self)"
},
{
"docstring": "过滤缓存 :param kwargs: :return:",
"name... | 4 | stack_v2_sparse_classes_30k_train_028576 | Implement the Python class `FireHydrantModelManager` described below.
Class description:
Implement the FireHydrantModelManager class.
Method signatures and docstrings:
- def get_once(self, pk): 缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:
- def all_cache(self): 全部缓存 :return:
- def filter_cache(self, **kwargs... | Implement the Python class `FireHydrantModelManager` described below.
Class description:
Implement the FireHydrantModelManager class.
Method signatures and docstrings:
- def get_once(self, pk): 缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:
- def all_cache(self): 全部缓存 :return:
- def filter_cache(self, **kwargs... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
<|body_0|>
def all_cache(self):
"""全部缓存 :return:"""
<|body_1|>
def filter_cache(self, **kwargs):
"""过滤缓存 :param kwargs: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
if pk is None or pk == '':
return None
table_name = self.model._meta.db_table
cache = FireHydrantCacheFactory(('model_cache', table_name))
obj = cach... | the_stack_v2_python_sparse | FireHydrant/common/core/dao/cache/model_manager.py | shoogoome/FireHydrant | train | 4 | |
e5c985594fd7c781250e91b09ffbc396856cb7d8 | [
"self._synapse_client = syn\nself._project = syn.get(project_id)\nself.entitylist = entitylist\nself.center = center\nself._format_registry = format_registry\nself.file_type = self.determine_filetype() if file_type is None else file_type\nself.genie_config = genie_config\nself.ancillary_files = ancillary_files",
... | <|body_start_0|>
self._synapse_client = syn
self._project = syn.get(project_id)
self.entitylist = entitylist
self.center = center
self._format_registry = format_registry
self.file_type = self.determine_filetype() if file_type is None else file_type
self.genie_conf... | ValidationHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidationHelper:
def __init__(self, syn: synapseclient.Synapse, project_id: str, center: str, entitylist: List[synapseclient.File], format_registry: Optional[Dict]=None, file_type: Optional[str]=None, genie_config: Optional[Dict]=None, ancillary_files: Optional[list]=None):
"""A validat... | stack_v2_sparse_classes_75kplus_train_001469 | 12,242 | permissive | [
{
"docstring": "A validator helper class for a center's files. Args: syn: a synapseclient.Synapse object project_id: Synapse Project ID where files are stored and configured. center: The participating center name. entitylist: a list of file paths. format_registry: A dictionary mapping file format name to the fo... | 3 | stack_v2_sparse_classes_30k_train_049955 | Implement the Python class `ValidationHelper` described below.
Class description:
Implement the ValidationHelper class.
Method signatures and docstrings:
- def __init__(self, syn: synapseclient.Synapse, project_id: str, center: str, entitylist: List[synapseclient.File], format_registry: Optional[Dict]=None, file_type... | Implement the Python class `ValidationHelper` described below.
Class description:
Implement the ValidationHelper class.
Method signatures and docstrings:
- def __init__(self, syn: synapseclient.Synapse, project_id: str, center: str, entitylist: List[synapseclient.File], format_registry: Optional[Dict]=None, file_type... | 1513cc2fcb5aa3867fce810d0db9b5479e962f05 | <|skeleton|>
class ValidationHelper:
def __init__(self, syn: synapseclient.Synapse, project_id: str, center: str, entitylist: List[synapseclient.File], format_registry: Optional[Dict]=None, file_type: Optional[str]=None, genie_config: Optional[Dict]=None, ancillary_files: Optional[list]=None):
"""A validat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidationHelper:
def __init__(self, syn: synapseclient.Synapse, project_id: str, center: str, entitylist: List[synapseclient.File], format_registry: Optional[Dict]=None, file_type: Optional[str]=None, genie_config: Optional[Dict]=None, ancillary_files: Optional[list]=None):
"""A validator helper clas... | the_stack_v2_python_sparse | genie/validate.py | Sage-Bionetworks/Genie | train | 12 | |
9a632a13f84f726e65ee8c484c2955b7b5a12238 | [
"if validate:\n name = ComplexName.validate(name)\nreturn str.__new__(cls, name)",
"try:\n if ComplexName.pattern.match(name) is None:\n if len(name) > ComplexName.max_chars:\n message = \"'%s' is too long. Valid names must contain at most %s characters.\" % (name, ComplexName.max_chars)\n... | <|body_start_0|>
if validate:
name = ComplexName.validate(name)
return str.__new__(cls, name)
<|end_body_0|>
<|body_start_1|>
try:
if ComplexName.pattern.match(name) is None:
if len(name) > ComplexName.max_chars:
message = "'%s' is too... | Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and dash | ComplexName | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexName:
"""Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and dash"""
def __new__(cls, name, va... | stack_v2_sparse_classes_75kplus_train_001470 | 2,116 | permissive | [
{
"docstring": "Simple name creation. @param name: string containing the desired name @param validate: checks for valid complex name. default True",
"name": "__new__",
"signature": "def __new__(cls, name, validate=True)"
},
{
"docstring": "Check for name compliance with pattern rules",
"name... | 2 | stack_v2_sparse_classes_30k_train_045975 | Implement the Python class `ComplexName` described below.
Class description:
Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and... | Implement the Python class `ComplexName` described below.
Class description:
Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and... | 45e9ca902be7bbbdd73dafe3ab8957bc4a006020 | <|skeleton|>
class ComplexName:
"""Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and dash"""
def __new__(cls, name, va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComplexName:
"""Complex biicode name Stores a name for every group_name.name (block name) and branch names Valid names MUST begin with a letter or number, and contain a min of 3 chars and max of 20 characters, including: letters, numbers, underscore, dot and dash"""
def __new__(cls, name, validate=True):... | the_stack_v2_python_sparse | model/brl/complex_name.py | biicode/common | train | 17 |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value is self.field.missing_value:\n return []\nkey_converter = self._get_converter(self.field.key_type)\nconverter = self._get_converter(self.field.value_type)\nreturn [(key_converter.to_widget_value(k), converter.to_widget_value(v)) for k, v in value.items()]",
"if len(value) == 0:\n return self.field... | <|body_start_0|>
if value is self.field.missing_value:
return []
key_converter = self._get_converter(self.field.key_type)
converter = self._get_converter(self.field.value_type)
return [(key_converter.to_widget_value(k), converter.to_widget_value(v)) for k, v in value.items()]... | Data converter for IMultiWidget. | DictMultiConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def to_widget_value(self, value):
"""Just dispatch it."""
<|body_0|>
def to_field_value(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is sel... | stack_v2_sparse_classes_75kplus_train_001471 | 16,755 | permissive | [
{
"docstring": "Just dispatch it.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "Just dispatch it.",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005730 | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Just dispatch it.
- def to_field_value(self, value): Just dispatch it. | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def to_widget_value(self, value): Just dispatch it.
- def to_field_value(self, value): Just dispatch it.
<|skeleton|>
class DictMultiConverter:
"""Data converte... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def to_widget_value(self, value):
"""Just dispatch it."""
<|body_0|>
def to_field_value(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictMultiConverter:
"""Data converter for IMultiWidget."""
def to_widget_value(self, value):
"""Just dispatch it."""
if value is self.field.missing_value:
return []
key_converter = self._get_converter(self.field.key_type)
converter = self._get_converter(self.fi... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
12492e47e30ceeb472638c84bc3c17c54aa0f22e | [
"opts = setup_options()\nopt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', delete=False)\nopts.write_to_stream(opt_file)\nopt_file.close()\nproblem = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'mock_problems', 'all_parsers_set'))\nrun([problem], options_file=opt_file.name, debu... | <|body_start_0|>
opts = setup_options()
opt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', delete=False)
opts.write_to_stream(opt_file)
opt_file.close()
problem = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'mock_problems', 'all_parsers_set'))
... | Regression tests for the Fitbenchmarking software with all fitting software packages | TestRegressionAll | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent_all(self):
"""Regression testing t... | stack_v2_sparse_classes_75kplus_train_001472 | 8,084 | permissive | [
{
"docstring": "Create an options file, run it, and get the results.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Regression testing that the results of fitting a set of problems containing all problem types against a single minimizer from each of the supported s... | 3 | stack_v2_sparse_classes_30k_train_014845 | Implement the Python class `TestRegressionAll` described below.
Class description:
Regression tests for the Fitbenchmarking software with all fitting software packages
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent_all(self):... | Implement the Python class `TestRegressionAll` described below.
Class description:
Regression tests for the Fitbenchmarking software with all fitting software packages
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent_all(self):... | edae46c0361568bc537de2425d603e7b271eabe7 | <|skeleton|>
class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent_all(self):
"""Regression testing t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
opts = setup_options()
opt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', dele... | the_stack_v2_python_sparse | fitbenchmarking/systests/test_regression.py | dsotiropoulos/fitbenchmarking | train | 0 |
352916463f336f6edd384d4d928660e2e87be7dd | [
"self.data_folder = data_folder\nself.dataset_name = dataset_name\nself.cols_dict = cols_dict\nself.clean_names = clean_names\nself.final_csv_path = final_csv_path\nself.raw_df = None\nself.cols_to_extract = list(self.cols_dict.keys())[3:]",
"df_full = pd.DataFrame(columns=list(self.cols_dict.keys()))\nlgd_url = ... | <|body_start_0|>
self.data_folder = data_folder
self.dataset_name = dataset_name
self.cols_dict = cols_dict
self.clean_names = clean_names
self.final_csv_path = final_csv_path
self.raw_df = None
self.cols_to_extract = list(self.cols_dict.keys())[3:]
<|end_body_0|>... | An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain column names and values contains StatVar names) | NHMDataLoaderBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain col... | stack_v2_sparse_classes_75kplus_train_001473 | 7,077 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data_folder, dataset_name, cols_dict, clean_names, final_csv_path)"
},
{
"docstring": "Class method to preprocess the data file for each available year, extract t he columns and map the columns to schema. The data... | 4 | stack_v2_sparse_classes_30k_train_008042 | Implement the Python class `NHMDataLoaderBase` described below.
Class description:
An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data fil... | Implement the Python class `NHMDataLoaderBase` described below.
Class description:
An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data fil... | 615cc10bbee274d888c1bc58a78ffc93d424861c | <|skeleton|>
class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain col... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain column names and... | the_stack_v2_python_sparse | scripts/india_nhm/base/data_cleaner.py | Ghaiyur-wipro/data | train | 0 |
82589894bc21b5b625f212a845d33d0848d905da | [
"first_class = m_obj.__class__\nsubclass_ls = first_class.__subclasses__()\nif subclass_ls:\n for subcls in subclass_ls:\n try:\n m_obj = subcls(ls_entries)\n except MatrixError:\n pass\nif first_class == m_obj.__class__:\n return m_obj\nelse:\n return self.get_matrix_cl... | <|body_start_0|>
first_class = m_obj.__class__
subclass_ls = first_class.__subclasses__()
if subclass_ls:
for subcls in subclass_ls:
try:
m_obj = subcls(ls_entries)
except MatrixError:
pass
if first_class... | MatrixFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
<|body_0|>
def __call__(self, ls_entries=None):
"""Returns the most relevant matrix type that exists."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_001474 | 992 | no_license | [
{
"docstring": "recursively loop through the subclasses to get the most relevant type",
"name": "get_matrix_class",
"signature": "def get_matrix_class(self, m_obj, ls_entries)"
},
{
"docstring": "Returns the most relevant matrix type that exists.",
"name": "__call__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_009484 | Implement the Python class `MatrixFactory` described below.
Class description:
Implement the MatrixFactory class.
Method signatures and docstrings:
- def get_matrix_class(self, m_obj, ls_entries): recursively loop through the subclasses to get the most relevant type
- def __call__(self, ls_entries=None): Returns the ... | Implement the Python class `MatrixFactory` described below.
Class description:
Implement the MatrixFactory class.
Method signatures and docstrings:
- def get_matrix_class(self, m_obj, ls_entries): recursively loop through the subclasses to get the most relevant type
- def __call__(self, ls_entries=None): Returns the ... | 339567a672e12ebc4847dfd97e9d1a2a7d45f655 | <|skeleton|>
class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
<|body_0|>
def __call__(self, ls_entries=None):
"""Returns the most relevant matrix type that exists."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatrixFactory:
def get_matrix_class(self, m_obj, ls_entries):
"""recursively loop through the subclasses to get the most relevant type"""
first_class = m_obj.__class__
subclass_ls = first_class.__subclasses__()
if subclass_ls:
for subcls in subclass_ls:
... | the_stack_v2_python_sparse | matrix/choose_matrix_type.py | KerimovEmil/HigherMathInvestigations | train | 2 | |
05b6c57fd058c86d07ec22963ae423e59fd24951 | [
"min, max = params.z_range\nself._absc = np.linspace(min, max, round((max - min) / resolution + 1), dtype=float)\nself._curve_x, self._curve_y = params.sigma_from_z(self._absc)",
"dw = (np.sqrt(data['size_x'].to_numpy()[:, np.newaxis]) - np.sqrt(self._curve_x[np.newaxis, :])) ** 2 + (np.sqrt(data['size_y'].to_num... | <|body_start_0|>
min, max = params.z_range
self._absc = np.linspace(min, max, round((max - min) / resolution + 1), dtype=float)
self._curve_x, self._curve_y = params.sigma_from_z(self._absc)
<|end_body_0|>
<|body_start_1|>
dw = (np.sqrt(data['size_x'].to_numpy()[:, np.newaxis]) - np.sqr... | Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See the `fitz` program in the `sa_util... | Fitter | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See ... | stack_v2_sparse_classes_75kplus_train_001475 | 13,366 | permissive | [
{
"docstring": "Parameters ---------- params : Parameters Z fit parameters resolution : float, optional Resolution, i. e. smallest z change detectable. Defaults to 1e-3.",
"name": "__init__",
"signature": "def __init__(self, params, resolution=0.001)"
},
{
"docstring": "Fit the z position Takes ... | 2 | stack_v2_sparse_classes_30k_val_001101 | Implement the Python class `Fitter` described below.
Class description:
Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum... | Implement the Python class `Fitter` described below.
Class description:
Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See the `fitz` pr... | the_stack_v2_python_sparse | sdt/loc/z_fit.py | schuetzgroup/sdt-python | train | 31 |
09c463b527e98a07e274a6bddaf499d1e10bf7e0 | [
"api = api_instance(TEMPLATE_ORG_NAME)\ntemplate_repo_urls = [api.insert_auth(url) for url in api.get_repo_urls(assignment_names)]\ngit_commands = ['git clone {}'.format(url) for url in template_repo_urls]\nfor cmd in git_commands:\n subprocess.run(shlex.split(cmd), check=True, cwd=str(tmpdir))\nreturn assignmen... | <|body_start_0|>
api = api_instance(TEMPLATE_ORG_NAME)
template_repo_urls = [api.insert_auth(url) for url in api.get_repo_urls(assignment_names)]
git_commands = ['git clone {}'.format(url) for url in template_repo_urls]
for cmd in git_commands:
subprocess.run(shlex.split(cmd)... | Integration tests for the migrate command. | TestMigrate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMigrate:
"""Integration tests for the migrate command."""
def local_master_repos(self, restore, tmpdir):
"""Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture."""
<|body_0|>
def test_happy_path(self, local... | stack_v2_sparse_classes_75kplus_train_001476 | 27,380 | permissive | [
{
"docstring": "Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture.",
"name": "local_master_repos",
"signature": "def local_master_repos(self, restore, tmpdir)"
},
{
"docstring": "Migrate a few repos from the existing master repo into... | 2 | null | Implement the Python class `TestMigrate` described below.
Class description:
Integration tests for the migrate command.
Method signatures and docstrings:
- def local_master_repos(self, restore, tmpdir): Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture.
-... | Implement the Python class `TestMigrate` described below.
Class description:
Integration tests for the migrate command.
Method signatures and docstrings:
- def local_master_repos(self, restore, tmpdir): Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture.
-... | 5db5e78a9eba685a85211a31e3b2033338e03ab5 | <|skeleton|>
class TestMigrate:
"""Integration tests for the migrate command."""
def local_master_repos(self, restore, tmpdir):
"""Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture."""
<|body_0|>
def test_happy_path(self, local... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMigrate:
"""Integration tests for the migrate command."""
def local_master_repos(self, restore, tmpdir):
"""Clone the master repos to disk. The restore fixture is explicitly included as it must be run before this fixture."""
api = api_instance(TEMPLATE_ORG_NAME)
template_repo_... | the_stack_v2_python_sparse | system_tests/gitlab/test_gitlab_system.py | repobee/repobee | train | 62 |
e883a52df92d56d2e023a658eb9c35c10cae5c81 | [
"login_page.LoginPage(self.driver).login()\nsleep(3)\nlandlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()\nlandlord_nav_page.LandlordNavPage(self.driver).close_weiChat()\nsleep(4)\npo = landlord_serach_page.LandlordSerachPage(self.driver)\npo.beginCheckInDay()\npo.endCheckInDay()\nsleep(2)\npo.serach()\nsl... | <|body_start_0|>
login_page.LoginPage(self.driver).login()
sleep(3)
landlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()
landlord_nav_page.LandlordNavPage(self.driver).close_weiChat()
sleep(4)
po = landlord_serach_page.LandlordSerachPage(self.driver)
po.be... | 搜索 | TestLandlordSerach | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLandlordSerach:
"""搜索"""
def test_date_serach(self):
"""按日期搜索"""
<|body_0|>
def test_orderid_or_phone(self):
"""按手机号或订单号搜索"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
login_page.LoginPage(self.driver).login()
sleep(3)
lan... | stack_v2_sparse_classes_75kplus_train_001477 | 1,534 | permissive | [
{
"docstring": "按日期搜索",
"name": "test_date_serach",
"signature": "def test_date_serach(self)"
},
{
"docstring": "按手机号或订单号搜索",
"name": "test_orderid_or_phone",
"signature": "def test_orderid_or_phone(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027696 | Implement the Python class `TestLandlordSerach` described below.
Class description:
搜索
Method signatures and docstrings:
- def test_date_serach(self): 按日期搜索
- def test_orderid_or_phone(self): 按手机号或订单号搜索 | Implement the Python class `TestLandlordSerach` described below.
Class description:
搜索
Method signatures and docstrings:
- def test_date_serach(self): 按日期搜索
- def test_orderid_or_phone(self): 按手机号或订单号搜索
<|skeleton|>
class TestLandlordSerach:
"""搜索"""
def test_date_serach(self):
"""按日期搜索"""
<... | 192c70c49a8e9e072b9d0d0136f02c653c589410 | <|skeleton|>
class TestLandlordSerach:
"""搜索"""
def test_date_serach(self):
"""按日期搜索"""
<|body_0|>
def test_orderid_or_phone(self):
"""按手机号或订单号搜索"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLandlordSerach:
"""搜索"""
def test_date_serach(self):
"""按日期搜索"""
login_page.LoginPage(self.driver).login()
sleep(3)
landlord_nav_page.LandlordNavPage(self.driver).Iamlandlord()
landlord_nav_page.LandlordNavPage(self.driver).close_weiChat()
sleep(4)
... | the_stack_v2_python_sparse | mayi/test_case/test_landlord_serach.py | 18701016443/mayi | train | 0 |
5be01831a9154025192a9f9733c96b568501898d | [
"super().__init__()\nself._handle_show_login_view = handle_show_login_view\nself.left = 10\nself.top = 10\nself.width = 1500\nself.height = 1000\nself._username_line = QLineEdit()\nself._password_line = QLineEdit()\nself._initialise()",
"msg = QMessageBox()\nuser = kks.create_user(self._username_line.text(), self... | <|body_start_0|>
super().__init__()
self._handle_show_login_view = handle_show_login_view
self.left = 10
self.top = 10
self.width = 1500
self.height = 1000
self._username_line = QLineEdit()
self._password_line = QLineEdit()
self._initialise()
<|end... | Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui. | CreateUserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login-... | stack_v2_sparse_classes_75kplus_train_001478 | 3,135 | no_license | [
{
"docstring": "Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login- ui. left, top, width, height: Page geometry values. username_line: QLineEdit widget for entering the username password_line: QLineEdit widget for entering the password",
"name": "__init_... | 3 | stack_v2_sparse_classes_30k_val_001483 | Implement the Python class `CreateUserView` described below.
Class description:
Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui.
Method signatures and docstrings:
- def __init__(self, handle_show_login_view=None): Class constructor. Creates a new create user ui.... | Implement the Python class `CreateUserView` described below.
Class description:
Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui.
Method signatures and docstrings:
- def __init__(self, handle_show_login_view=None): Class constructor. Creates a new create user ui.... | 37e859857570f398b5c237dacd283e7b00bb1b26 | <|skeleton|>
class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateUserView:
"""Class responsible for create user ui. Attributes: handle_show_login_view: A method to open a -login- ui."""
def __init__(self, handle_show_login_view=None):
"""Class constructor. Creates a new create user ui. Args: handle_show_login_view: A method to open a -login- ui. left, to... | the_stack_v2_python_sparse | src/ui/create_user_view.py | Noissi/ot_harjoitustyo | train | 0 |
cfbbd6b39e914142109e4cd7154ce1b886a62fff | [
"self.before_get_collection(qs, view_kwargs)\nquery = self.query(view_kwargs)\nif filters:\n query = query.filter_by(**filters)\nif qs.filters:\n query = self.filter_query(query, qs.filters, self.model)\nobject_count = query.count()\nif getattr(self, 'eagerload_includes', True):\n query = self.eagerload_in... | <|body_start_0|>
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if filters:
query = query.filter_by(**filters)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
object_count = query.count()
if geta... | Sqlalchemy data layer specifically to use python sorting. | SearchDataLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param... | stack_v2_sparse_classes_75kplus_train_001479 | 2,921 | permissive | [
{
"docstring": "Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kwargs: kwargs from the resource view :param dict filters: A dictionary of key/value filters to apply to the eventual query :return tuple: the... | 3 | stack_v2_sparse_classes_30k_train_031837 | Implement the Python class `SearchDataLayer` described below.
Class description:
Sqlalchemy data layer specifically to use python sorting.
Method signatures and docstrings:
- def get_collection(self, qs, view_kwargs, filters=None): Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a qu... | Implement the Python class `SearchDataLayer` described below.
Class description:
Sqlalchemy data layer specifically to use python sorting.
Method signatures and docstrings:
- def get_collection(self, qs, view_kwargs, filters=None): Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a qu... | 21c7597b35f83f0c9ff6197db702268f05e98be2 | <|skeleton|>
class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kw... | the_stack_v2_python_sparse | resolver/api/data_layers.py | Chemical-Curation/resolver | train | 0 |
032505289b688c7a1c1558d4c5e43acf538f7c86 | [
"self.category = category\nself.dataset = dataset\nself.silent = True\n'Quite console'\nsuper().__init__(*args, **kwargs)",
"imgs = [x for x in _voc.get_image_url_list(self.category, self.dataset)]\nfor fname in imgs:\n if pathonly:\n yield (None, fname, None)\n else:\n try:\n img =... | <|body_start_0|>
self.category = category
self.dataset = dataset
self.silent = True
'Quite console'
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
imgs = [x for x in _voc.get_image_url_list(self.category, self.dataset)]
for fname in imgs:
... | Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' filters: Keyword argument containi... | VOC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' fil... | stack_v2_sparse_classes_75kplus_train_001480 | 47,799 | no_license | [
{
"docstring": "(str, str) -> void",
"name": "__init__",
"signature": "def __init__(self, category, *args, dataset='train', **kwargs)"
},
{
"docstring": "(cv2.imread option, bool, bool) -> ndarray|None, str, dict|None Yields the images with the bounding boxes and category name of all objects in ... | 2 | stack_v2_sparse_classes_30k_train_005272 | Implement the Python class `VOC` described below.
Class description:
Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 't... | Implement the Python class `VOC` described below.
Class description:
Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 't... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' fil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VOC:
"""Generate images from the Pascal VOC data Yields images of a requested category type (train, val or trainval) with the bounding boxes from the PASCAL VOC image set. category: The object category, e.g. cat dataset: String specifyig the dataset. i.e. 'test', 'train', 'val' or 'train_val' filters: Keyword... | the_stack_v2_python_sparse | opencvlib/imgpipes/generators.py | gmonkman/python | train | 0 |
875a7f3220088ce9c46c968cfab587625f324583 | [
"self.start = np.array(start)\nself.end = np.array(end)\nself.length = np.linalg.norm(self.start - self.end)",
"from numpy.linalg import norm\nnpoints = nlong + 1\nx = np.linspace(self.start[0], self.end[0], npoints)\ny = np.linspace(self.start[1], self.end[1], npoints)\nz = np.linspace(self.start[2], self.end[2]... | <|body_start_0|>
self.start = np.array(start)
self.end = np.array(end)
self.length = np.linalg.norm(self.start - self.end)
<|end_body_0|>
<|body_start_1|>
from numpy.linalg import norm
npoints = nlong + 1
x = np.linspace(self.start[0], self.end[0], npoints)
y = n... | GeometricLine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometricLine:
def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3)):
"""Constructs a line given the start and ending points"""
<|body_0|>
def ComputeExtrusion(self, nlong=10):
"""Computes extrusion of base_mesh along self (line) using equal spacing input: nlo... | stack_v2_sparse_classes_75kplus_train_001481 | 6,773 | permissive | [
{
"docstring": "Constructs a line given the start and ending points",
"name": "__init__",
"signature": "def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3))"
},
{
"docstring": "Computes extrusion of base_mesh along self (line) using equal spacing input: nlong: [int] number of discretisat... | 2 | stack_v2_sparse_classes_30k_train_027987 | Implement the Python class `GeometricLine` described below.
Class description:
Implement the GeometricLine class.
Method signatures and docstrings:
- def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3)): Constructs a line given the start and ending points
- def ComputeExtrusion(self, nlong=10): Computes extru... | Implement the Python class `GeometricLine` described below.
Class description:
Implement the GeometricLine class.
Method signatures and docstrings:
- def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3)): Constructs a line given the start and ending points
- def ComputeExtrusion(self, nlong=10): Computes extru... | 256777e369b0d2774887bd4ea69e1c42d1bc82f0 | <|skeleton|>
class GeometricLine:
def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3)):
"""Constructs a line given the start and ending points"""
<|body_0|>
def ComputeExtrusion(self, nlong=10):
"""Computes extrusion of base_mesh along self (line) using equal spacing input: nlo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeometricLine:
def __init__(self, start=(0.0, 0.0, 0.0), end=(1.0, 2.0, 3)):
"""Constructs a line given the start and ending points"""
self.start = np.array(start)
self.end = np.array(end)
self.length = np.linalg.norm(self.start - self.end)
def ComputeExtrusion(self, nlong... | the_stack_v2_python_sparse | Florence/MeshGeneration/GeometricPath.py | romeric/florence | train | 79 | |
ef8c6d0f9594ac8273f5ab09744c1f3096aab49e | [
"if not fpath:\n fpath = self.generate_fpath(rootdir, product, utc)\nsuper().__init__(fpath)",
"valid_products = ('PRECIPRATE',)\npdb.set_trace()\nif prod not in valid_products:\n raise Exception('Product name not valid.')\nfname = '{0}.{1}{2}{3}.{4}{5}{6}'.format(prod, utc.year, utc.month, utc.day, utc.hou... | <|body_start_0|>
if not fpath:
fpath = self.generate_fpath(rootdir, product, utc)
super().__init__(fpath)
<|end_body_0|>
<|body_start_1|>
valid_products = ('PRECIPRATE',)
pdb.set_trace()
if prod not in valid_products:
raise Exception('Product name not val... | MRMS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRMS:
def __init__(self, fpath=False, rootdir=False, product=False, utc=False):
"""A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, optional): file path to data. If False, other information must be presented to search for data (bel... | stack_v2_sparse_classes_75kplus_train_001482 | 18,802 | no_license | [
{
"docstring": "A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, optional): file path to data. If False, other information must be presented to search for data (below). rootdir (str, optional): if fpath is False, this is required to search for data based ... | 2 | stack_v2_sparse_classes_30k_train_028346 | Implement the Python class `MRMS` described below.
Class description:
Implement the MRMS class.
Method signatures and docstrings:
- def __init__(self, fpath=False, rootdir=False, product=False, utc=False): A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, option... | Implement the Python class `MRMS` described below.
Class description:
Implement the MRMS class.
Method signatures and docstrings:
- def __init__(self, fpath=False, rootdir=False, product=False, utc=False): A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, option... | 08f0472a59a910aaeb1c52baedffc2cec45fb54d | <|skeleton|>
class MRMS:
def __init__(self, fpath=False, rootdir=False, product=False, utc=False):
"""A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, optional): file path to data. If False, other information must be presented to search for data (bel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MRMS:
def __init__(self, fpath=False, rootdir=False, product=False, utc=False):
"""A helper function to automatically generate file name to load needs to be written. Arguments: fpath (str, optional): file path to data. If False, other information must be presented to search for data (below). rootdir (... | the_stack_v2_python_sparse | postWRF/postWRF/obs.py | johnrobertlawson/WEM | train | 33 | |
c7a01a53ac69010d506c37cb2fba8e7f5614455a | [
"if os.path.exists(outputPath):\n raise ValueError(\"The supplied 'output' path laready exists and cannot be overwritten. Manually delete the file before continuing.\", outputPath)\nself.db = h5py.File(outputPath, 'w')\nself.data = self.db.create_dataset(dataKey, dims, dtype='float')\nself.labels = self.db.creat... | <|body_start_0|>
if os.path.exists(outputPath):
raise ValueError("The supplied 'output' path laready exists and cannot be overwritten. Manually delete the file before continuing.", outputPath)
self.db = h5py.File(outputPath, 'w')
self.data = self.db.create_dataset(dataKey, dims, dtyp... | HDF5DatasetWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDF5DatasetWriter:
def __init__(self, dims, outputPath, dataKey='images', bufSize=1000):
""":param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000, 32, 32, 3) :param outputPath: path to save .hdf5 :param dataKey: name of dataset file. dataKey.hdf5 :para... | stack_v2_sparse_classes_75kplus_train_001483 | 2,719 | no_license | [
{
"docstring": ":param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000, 32, 32, 3) :param outputPath: path to save .hdf5 :param dataKey: name of dataset file. dataKey.hdf5 :param bufSize: number of samples before flushing data in memory to",
"name": "__init__",
"signat... | 5 | stack_v2_sparse_classes_30k_train_048452 | Implement the Python class `HDF5DatasetWriter` described below.
Class description:
Implement the HDF5DatasetWriter class.
Method signatures and docstrings:
- def __init__(self, dims, outputPath, dataKey='images', bufSize=1000): :param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000,... | Implement the Python class `HDF5DatasetWriter` described below.
Class description:
Implement the HDF5DatasetWriter class.
Method signatures and docstrings:
- def __init__(self, dims, outputPath, dataKey='images', bufSize=1000): :param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000,... | 46cda997697c80e6e9d1ca51218d5e8d1620eb29 | <|skeleton|>
class HDF5DatasetWriter:
def __init__(self, dims, outputPath, dataKey='images', bufSize=1000):
""":param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000, 32, 32, 3) :param outputPath: path to save .hdf5 :param dataKey: name of dataset file. dataKey.hdf5 :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HDF5DatasetWriter:
def __init__(self, dims, outputPath, dataKey='images', bufSize=1000):
""":param dims: shape of the data we stored. same as numpy.shape. i.e. store CIFAR-10 (60000, 32, 32, 3) :param outputPath: path to save .hdf5 :param dataKey: name of dataset file. dataKey.hdf5 :param bufSize: num... | the_stack_v2_python_sparse | BlogTutorials/pyimagesearch/io_module/hdf5datasetwriter.py | mplefort/Python_Learning | train | 0 | |
a535b5415b2cb102dafd44a4135a7e282ea15348 | [
"self.n_nodes: int = len(log_psis1)\nself.node_potentials: List[np.ndarray] = log_psis1\nself.edge_potentials: List[np.ndarray] = log_psis2\nself._forward_computed: bool = False\nself._backward_computed: bool = False\nself.forward_messages: List[np.ndarray] = [np.zeros(self.node_potentials[k + 1].shape) for k in ra... | <|body_start_0|>
self.n_nodes: int = len(log_psis1)
self.node_potentials: List[np.ndarray] = log_psis1
self.edge_potentials: List[np.ndarray] = log_psis2
self._forward_computed: bool = False
self._backward_computed: bool = False
self.forward_messages: List[np.ndarray] = [... | Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod_{i=1}^{n-1} \\phi_{i, i+1}(x_i, x_{i+1}) Everything is represented on the log-sca... | UndirectedChain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UndirectedChain:
"""Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod_{i=1}^{n-1} \\phi_{i, i+1}(x_i, x_{i+1... | stack_v2_sparse_classes_75kplus_train_001484 | 9,693 | no_license | [
{
"docstring": "Initialization of the undirected chain. Parameters ---------- log_psis1: list of arrays, len self.n_nodes The 1D-array indexed by i corresponds to the potential (function) of the node i. The arrays can have different sizes (that is why a list is used). log_psis2: list of arrays, len self.n_nodes... | 4 | stack_v2_sparse_classes_30k_train_039020 | Implement the Python class `UndirectedChain` described below.
Class description:
Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod... | Implement the Python class `UndirectedChain` described below.
Class description:
Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod... | be41088f3036fb1eaef6b41ccc6be30b11d99a08 | <|skeleton|>
class UndirectedChain:
"""Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod_{i=1}^{n-1} \\phi_{i, i+1}(x_i, x_{i+1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UndirectedChain:
"""Class representing the graphical model of an undirected chain. Denoting by :math:`\\phi` the potentials, the joint probability of the nodes :math:`x_1, \\dots, x_n` is given by: .. math:: p(x) = \\frac1Z \\prod_{i=1}^n \\phi_i(x_i) \\prod_{i=1}^{n-1} \\phi_{i, i+1}(x_i, x_{i+1}) Everything... | the_stack_v2_python_sparse | probabilistic_graphical_models/HW2/src_ex2/undirected_chain.py | antoine-moulin/MVA | train | 18 |
5dff5c57b6504327d3e559c14ea77aa7d1cf8deb | [
"user_input = None\nwhile user_input != 2:\n print('\\n\\n=== The Pokemon Tamagotchi Game ===\\n')\n print('Hello there! Welcome to the world of POKEMON!\\nMy name is EUCALYPTUS. People call me the \\nPOKEMON PROF!\\n')\n print('This world is inhabited by creatures called \\nPOKEMON! For some people, POKEM... | <|body_start_0|>
user_input = None
while user_input != 2:
print('\n\n=== The Pokemon Tamagotchi Game ===\n')
print('Hello there! Welcome to the world of POKEMON!\nMy name is EUCALYPTUS. People call me the \nPOKEMON PROF!\n')
print('This world is inhabited by creatures... | Display menu items and control the flow of logic for the menu itself. | GameUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameUI:
"""Display menu items and control the flow of logic for the menu itself."""
def display_start_menu(cls, game):
"""Display start menu (with no Pokemon hatched)."""
<|body_0|>
def display_pet_menu(cls, game):
"""Display list of possible pet interactions."""... | stack_v2_sparse_classes_75kplus_train_001485 | 9,307 | no_license | [
{
"docstring": "Display start menu (with no Pokemon hatched).",
"name": "display_start_menu",
"signature": "def display_start_menu(cls, game)"
},
{
"docstring": "Display list of possible pet interactions.",
"name": "display_pet_menu",
"signature": "def display_pet_menu(cls, game)"
},
... | 5 | stack_v2_sparse_classes_30k_train_030239 | Implement the Python class `GameUI` described below.
Class description:
Display menu items and control the flow of logic for the menu itself.
Method signatures and docstrings:
- def display_start_menu(cls, game): Display start menu (with no Pokemon hatched).
- def display_pet_menu(cls, game): Display list of possible... | Implement the Python class `GameUI` described below.
Class description:
Display menu items and control the flow of logic for the menu itself.
Method signatures and docstrings:
- def display_start_menu(cls, game): Display start menu (with no Pokemon hatched).
- def display_pet_menu(cls, game): Display list of possible... | b7695cc7cf0860aa9c8bf492b1bd06bd88b9af41 | <|skeleton|>
class GameUI:
"""Display menu items and control the flow of logic for the menu itself."""
def display_start_menu(cls, game):
"""Display start menu (with no Pokemon hatched)."""
<|body_0|>
def display_pet_menu(cls, game):
"""Display list of possible pet interactions."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameUI:
"""Display menu items and control the flow of logic for the menu itself."""
def display_start_menu(cls, game):
"""Display start menu (with no Pokemon hatched)."""
user_input = None
while user_input != 2:
print('\n\n=== The Pokemon Tamagotchi Game ===\n')
... | the_stack_v2_python_sparse | Lectures/Assignment2a/game.py | sakshambhardwaj523/Python-OOP-Projects | train | 0 |
aef4684aa0a78c136e357c62ad0a1623a244d660 | [
"with tables(db.engine, 'vcfs') as (con, runs):\n q = select(runs.c).where(runs.c.id == run_id)\n run = dict(_abort_if_none(q.execute().fetchone(), run_id))\nbams.attach_bams_to_vcfs([run])\nreturn run",
"with tables(db.engine, 'vcfs') as (con, runs):\n q = runs.update(runs.c.id == run_id).values(**reque... | <|body_start_0|>
with tables(db.engine, 'vcfs') as (con, runs):
q = select(runs.c).where(runs.c.id == run_id)
run = dict(_abort_if_none(q.execute().fetchone(), run_id))
bams.attach_bams_to_vcfs([run])
return run
<|end_body_0|>
<|body_start_1|>
with tables(db.engi... | Run | [
"Apache-2.0",
"CC-BY-3.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Run:
def get(self, run_id):
"""Return a vcf with a given ID."""
<|body_0|>
def put(self, run_id):
"""Update the run by its ID."""
<|body_1|>
def delete(self, run_id):
"""Delete a run by its ID."""
<|body_2|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_001486 | 7,342 | permissive | [
{
"docstring": "Return a vcf with a given ID.",
"name": "get",
"signature": "def get(self, run_id)"
},
{
"docstring": "Update the run by its ID.",
"name": "put",
"signature": "def put(self, run_id)"
},
{
"docstring": "Delete a run by its ID.",
"name": "delete",
"signature... | 3 | stack_v2_sparse_classes_30k_train_017730 | Implement the Python class `Run` described below.
Class description:
Implement the Run class.
Method signatures and docstrings:
- def get(self, run_id): Return a vcf with a given ID.
- def put(self, run_id): Update the run by its ID.
- def delete(self, run_id): Delete a run by its ID. | Implement the Python class `Run` described below.
Class description:
Implement the Run class.
Method signatures and docstrings:
- def get(self, run_id): Return a vcf with a given ID.
- def put(self, run_id): Update the run by its ID.
- def delete(self, run_id): Delete a run by its ID.
<|skeleton|>
class Run:
de... | a436c4fc212e4429fb5196a9a4d36c37bd050c52 | <|skeleton|>
class Run:
def get(self, run_id):
"""Return a vcf with a given ID."""
<|body_0|>
def put(self, run_id):
"""Update the run by its ID."""
<|body_1|>
def delete(self, run_id):
"""Delete a run by its ID."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Run:
def get(self, run_id):
"""Return a vcf with a given ID."""
with tables(db.engine, 'vcfs') as (con, runs):
q = select(runs.c).where(runs.c.id == run_id)
run = dict(_abort_if_none(q.execute().fetchone(), run_id))
bams.attach_bams_to_vcfs([run])
return... | the_stack_v2_python_sparse | cycledash/api/runs.py | haoziyeung/cycledash | train | 0 | |
7e2642811b17392adf07f375f495fd57aeb24639 | [
"super().__init__()\nself.last_batch = data.get('last_batch', None)\nself.batch_size: Optional[int] = data.get('batch_size')\nself.dataset: Optional[Dataset] = None\nif data.get('dataset'):\n self.set_dataset(data.get('dataset', {}))\nself.transform: OrderedDict = OrderedDict()\nif data.get('transform'):\n fo... | <|body_start_0|>
super().__init__()
self.last_batch = data.get('last_batch', None)
self.batch_size: Optional[int] = data.get('batch_size')
self.dataset: Optional[Dataset] = None
if data.get('dataset'):
self.set_dataset(data.get('dataset', {}))
self.transform: ... | Configuration Dataloader class. | Dataloader | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
<|body_0|>
def set_dataset(self, dataset_data: Dict[str, Any]) -> None:
"""Set dataset for dataloader."""
... | stack_v2_sparse_classes_75kplus_train_001487 | 4,560 | permissive | [
{
"docstring": "Initialize Configuration Dataloader class.",
"name": "__init__",
"signature": "def __init__(self, data: Dict[str, Any]={}) -> None"
},
{
"docstring": "Set dataset for dataloader.",
"name": "set_dataset",
"signature": "def set_dataset(self, dataset_data: Dict[str, Any]) ->... | 3 | stack_v2_sparse_classes_30k_train_012162 | Implement the Python class `Dataloader` described below.
Class description:
Configuration Dataloader class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataloader class.
- def set_dataset(self, dataset_data: Dict[str, Any]) -> None: Set dataset for... | Implement the Python class `Dataloader` described below.
Class description:
Configuration Dataloader class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataloader class.
- def set_dataset(self, dataset_data: Dict[str, Any]) -> None: Set dataset for... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
<|body_0|>
def set_dataset(self, dataset_data: Dict[str, Any]) -> None:
"""Set dataset for dataloader."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
super().__init__()
self.last_batch = data.get('last_batch', None)
self.batch_size: Optional[int] = data.get('batch_size')... | the_stack_v2_python_sparse | neural_compressor/ux/utils/workload/dataloader.py | Skp80/neural-compressor | train | 0 |
59ae0be6aee066b244be3a1273993f1d3771d220 | [
"results = []\nn = len(nums)\n\ndef backtrack(start=0):\n if start == n:\n if nums not in results:\n results.append(nums[:])\n for i in range(start, n):\n nums[start], nums[i] = (nums[i], nums[start])\n backtrack(start + 1)\n nums[start], nums[i] = (nums[i], nums[start])... | <|body_start_0|>
results = []
n = len(nums)
def backtrack(start=0):
if start == n:
if nums not in results:
results.append(nums[:])
for i in range(start, n):
nums[start], nums[i] = (nums[i], nums[start])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
results = []
... | stack_v2_sparse_classes_75kplus_train_001488 | 1,314 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique2",
"signature": "def permuteUnique2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033871 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class S... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
results = []
n = len(nums)
def backtrack(start=0):
if start == n:
if nums not in results:
results.append(nums[:])
for i in r... | the_stack_v2_python_sparse | leetcode/47.py | yanggelinux/algorithm-data-structure | train | 0 | |
c4dfe1a8ae4eb825f7659bfcf00fe9cc734c6494 | [
"self.ps = PastaSauce()\nself.desired_capabilities['name'] = self.id()\nself.user = None",
"if not LOCAL_RUN:\n self.ps.update_job(job_id=str(self.user.driver.session_id), **self.ps.test_updates)\ntry:\n self.user.delete()\nexcept:\n pass",
"self.ps.test_updates['name'] = 't1.38.001' + inspect.currentf... | <|body_start_0|>
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
self.user = None
<|end_body_0|>
<|body_start_1|>
if not LOCAL_RUN:
self.ps.update_job(job_id=str(self.user.driver.session_id), **self.ps.test_updates)
try:
self.user.del... | T1.38 - Choose Course. | TestChooseCourse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChooseCourse:
"""T1.38 - Choose Course."""
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_student_select_a_course_8254(self):
"""Select a course. Steps: Click on a Tutor ... | stack_v2_sparse_classes_75kplus_train_001489 | 6,295 | no_license | [
{
"docstring": "Pretest settings.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test destructor.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Select a course. Steps: Click on a Tutor course name Expected Result: The user select... | 5 | stack_v2_sparse_classes_30k_train_019110 | Implement the Python class `TestChooseCourse` described below.
Class description:
T1.38 - Choose Course.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_student_select_a_course_8254(self): Select a course. Steps: Click on a Tutor course name Exp... | Implement the Python class `TestChooseCourse` described below.
Class description:
T1.38 - Choose Course.
Method signatures and docstrings:
- def setUp(self): Pretest settings.
- def tearDown(self): Test destructor.
- def test_student_select_a_course_8254(self): Select a course. Steps: Click on a Tutor course name Exp... | 39751799858ac30df90760b8bb753d338e8edc46 | <|skeleton|>
class TestChooseCourse:
"""T1.38 - Choose Course."""
def setUp(self):
"""Pretest settings."""
<|body_0|>
def tearDown(self):
"""Test destructor."""
<|body_1|>
def test_student_select_a_course_8254(self):
"""Select a course. Steps: Click on a Tutor ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestChooseCourse:
"""T1.38 - Choose Course."""
def setUp(self):
"""Pretest settings."""
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
self.user = None
def tearDown(self):
"""Test destructor."""
if not LOCAL_RUN:
self.... | the_stack_v2_python_sparse | tutor/OldTests/test_t1_38_ChooseCourse.py | openstax/test-automation | train | 4 |
dc2ed195da5938c32155a718418c6594076a876c | [
"assert lambdacheck in self.parent().coroot_lattice() or lambdacheck in self.parent().coroot_space()\nzero = self.parent().base_ring().zero()\ncartan_matrix = self.parent().dynkin_diagram()\nreturn sum((sum((lambdacheck[i] * s for i, s in cartan_matrix.column(j)), zero) * c for j, c in self), zero)",
"for c in se... | <|body_start_0|>
assert lambdacheck in self.parent().coroot_lattice() or lambdacheck in self.parent().coroot_space()
zero = self.parent().base_ring().zero()
cartan_matrix = self.parent().dynkin_diagram()
return sum((sum((lambdacheck[i] * s for i, s in cartan_matrix.column(j)), zero) * c ... | RootSpaceElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootSpaceElement:
def scalar(self, lambdacheck):
"""The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: cr = RootSystem(['A',4]).coroot_lattice() sage: a1 = r.simple_root(1) sage: ac1 = cr.simple_root(1) sage: ... | stack_v2_sparse_classes_75kplus_train_001490 | 4,833 | no_license | [
{
"docstring": "The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: cr = RootSystem(['A',4]).coroot_lattice() sage: a1 = r.simple_root(1) sage: ac1 = cr.simple_root(1) sage: a1.scalar(ac1) 2",
"name": "scalar",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_025909 | Implement the Python class `RootSpaceElement` described below.
Class description:
Implement the RootSpaceElement class.
Method signatures and docstrings:
- def scalar(self, lambdacheck): The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: c... | Implement the Python class `RootSpaceElement` described below.
Class description:
Implement the RootSpaceElement class.
Method signatures and docstrings:
- def scalar(self, lambdacheck): The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: c... | 7627c0e9cfd01178afda71fe5dbf9046c5546d11 | <|skeleton|>
class RootSpaceElement:
def scalar(self, lambdacheck):
"""The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: cr = RootSystem(['A',4]).coroot_lattice() sage: a1 = r.simple_root(1) sage: ac1 = cr.simple_root(1) sage: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RootSpaceElement:
def scalar(self, lambdacheck):
"""The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: r = RootSystem(['A',4]).root_lattice() sage: cr = RootSystem(['A',4]).coroot_lattice() sage: a1 = r.simple_root(1) sage: ac1 = cr.simple_root(1) sage: a1.scalar(ac1)... | the_stack_v2_python_sparse | sage/combinat/root_system/root_space.py | jwbober/sagelib | train | 0 | |
3f9fdf7919f98171dfd68d7dc8854cd3f16cbe93 | [
"req_data, _ = init_views(request)\ndata = ExecutionLog.query_log_list(**req_data['data'])\nreturn Response(data)",
"req_data, _ = init_views(request)\ntry:\n log = ExecutionLog.create_log(**req_data['data'])\n data = {'id': log.pk}\nexcept Exception as e:\n logger.error(f'create_log error:{str(e)}')\n ... | <|body_start_0|>
req_data, _ = init_views(request)
data = ExecutionLog.query_log_list(**req_data['data'])
return Response(data)
<|end_body_0|>
<|body_start_1|>
req_data, _ = init_views(request)
try:
log = ExecutionLog.create_log(**req_data['data'])
data =... | 日志操作 | ExecutionLogViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
<|body_0|>
def create_log(self, request):
"""创建日志"""
<|body_1|>
def update_log(self, request):
"""更新日志"""
<|body_2|>
def describe_records(self, request)... | stack_v2_sparse_classes_75kplus_train_001491 | 4,019 | permissive | [
{
"docstring": "获取日志",
"name": "describe_logs",
"signature": "def describe_logs(self, request)"
},
{
"docstring": "创建日志",
"name": "create_log",
"signature": "def create_log(self, request)"
},
{
"docstring": "更新日志",
"name": "update_log",
"signature": "def update_log(self, ... | 4 | stack_v2_sparse_classes_30k_train_049662 | Implement the Python class `ExecutionLogViewSet` described below.
Class description:
日志操作
Method signatures and docstrings:
- def describe_logs(self, request): 获取日志
- def create_log(self, request): 创建日志
- def update_log(self, request): 更新日志
- def describe_records(self, request): 获取平台执行记录 | Implement the Python class `ExecutionLogViewSet` described below.
Class description:
日志操作
Method signatures and docstrings:
- def describe_logs(self, request): 获取日志
- def create_log(self, request): 创建日志
- def update_log(self, request): 更新日志
- def describe_records(self, request): 获取平台执行记录
<|skeleton|>
class Execution... | da37fb2197142eae32158cdb5c2b658100133fff | <|skeleton|>
class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
<|body_0|>
def create_log(self, request):
"""创建日志"""
<|body_1|>
def update_log(self, request):
"""更新日志"""
<|body_2|>
def describe_records(self, request)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
req_data, _ = init_views(request)
data = ExecutionLog.query_log_list(**req_data['data'])
return Response(data)
def create_log(self, request):
"""创建日志"""
req_data, _ = init_vie... | the_stack_v2_python_sparse | module_intent/views/log_views.py | cz-qq/bk-chatbot | train | 0 |
2abf6fd1cd8fad8a261d1d38564ebde731111e66 | [
"warehouse = self.cleaned_data.get('warehouse')\nif self.instance.type.by_warehouse and (not warehouse):\n raise forms.ValidationError(_('Warehouse missing'))\nreturn warehouse",
"start = self.cleaned_data['start']\nend = self.cleaned_data['end']\nif start > end:\n raise forms.ValidationError(_('End date mu... | <|body_start_0|>
warehouse = self.cleaned_data.get('warehouse')
if self.instance.type.by_warehouse and (not warehouse):
raise forms.ValidationError(_('Warehouse missing'))
return warehouse
<|end_body_0|>
<|body_start_1|>
start = self.cleaned_data['start']
end = self.... | Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence. | UsagePriceForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
<|body_... | stack_v2_sparse_classes_75kplus_train_001492 | 8,678 | permissive | [
{
"docstring": "If usage type is by_warehouse check if warehouse was provided",
"name": "clean_warehouse",
"signature": "def clean_warehouse(self)"
},
{
"docstring": "Test if end date is later or equal to the start date :returns string: the end of the time interval :rtype string:",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_051669 | Implement the Python class `UsagePriceForm` described below.
Class description:
Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence.
Method signatures and docstrings:
- def clean_warehouse(self): If usage type is by_war... | Implement the Python class `UsagePriceForm` described below.
Class description:
Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence.
Method signatures and docstrings:
- def clean_warehouse(self): If usage type is by_war... | cbfd7227ebe97d44fbe1d286f90184d9feb9eced | <|skeleton|>
class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsagePriceForm:
"""Used by factory to create UsagesFormSet. Contain basic form infromation like fields and widgets and simple validation like warehouse and team presence."""
def clean_warehouse(self):
"""If usage type is by_warehouse check if warehouse was provided"""
warehouse = self.cle... | the_stack_v2_python_sparse | src/ralph_scrooge/forms.py | mkurek/ralph_pricing | train | 0 |
2fd2b022924359c529bbb013722c8240e56a971f | [
"try:\n interface = await self.application.objects.get(Interfaces, id=int(interface_id))\n await self.application.objects.delete(interface)\n return self.json(JsonResponse(code=1, data={'id': interface_id}))\nexcept Interfaces.DoesNotExist:\n self.set_status(400)\n return self.json(JsonResponse(code=... | <|body_start_0|>
try:
interface = await self.application.objects.get(Interfaces, id=int(interface_id))
await self.application.objects.delete(interface)
return self.json(JsonResponse(code=1, data={'id': interface_id}))
except Interfaces.DoesNotExist:
self.s... | InterfacesChangeHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfacesChangeHandler:
async def delete(self, interface_id, *args, **kwargs):
"""删除接口数据 :param interface_id: 删除的接口id"""
<|body_0|>
async def patch(self, interface_id, *args, **kwargs):
"""更新接口数据 :param interface_id: 更新的接口id"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_001493 | 30,636 | permissive | [
{
"docstring": "删除接口数据 :param interface_id: 删除的接口id",
"name": "delete",
"signature": "async def delete(self, interface_id, *args, **kwargs)"
},
{
"docstring": "更新接口数据 :param interface_id: 更新的接口id",
"name": "patch",
"signature": "async def patch(self, interface_id, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047564 | Implement the Python class `InterfacesChangeHandler` described below.
Class description:
Implement the InterfacesChangeHandler class.
Method signatures and docstrings:
- async def delete(self, interface_id, *args, **kwargs): 删除接口数据 :param interface_id: 删除的接口id
- async def patch(self, interface_id, *args, **kwargs): 更... | Implement the Python class `InterfacesChangeHandler` described below.
Class description:
Implement the InterfacesChangeHandler class.
Method signatures and docstrings:
- async def delete(self, interface_id, *args, **kwargs): 删除接口数据 :param interface_id: 删除的接口id
- async def patch(self, interface_id, *args, **kwargs): 更... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class InterfacesChangeHandler:
async def delete(self, interface_id, *args, **kwargs):
"""删除接口数据 :param interface_id: 删除的接口id"""
<|body_0|>
async def patch(self, interface_id, *args, **kwargs):
"""更新接口数据 :param interface_id: 更新的接口id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterfacesChangeHandler:
async def delete(self, interface_id, *args, **kwargs):
"""删除接口数据 :param interface_id: 删除的接口id"""
try:
interface = await self.application.objects.get(Interfaces, id=int(interface_id))
await self.application.objects.delete(interface)
r... | the_stack_v2_python_sparse | apps/interface_test/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
e4bdbf2a4998f27860b792cef24e10410af57dcd | [
"self.contact_id = contact_id\nself.object_id = object_id\nself.affiliate_id = affiliate_id\nself.billing_address = billing_address\nself.charge_now = charge_now\nself.gateway_id = gateway_id\nself.invoice_template = invoice_template\nself.offer = offer\nself.payer = payer\nself.names = {'contact_id': 'contact_id',... | <|body_start_0|>
self.contact_id = contact_id
self.object_id = object_id
self.affiliate_id = affiliate_id
self.billing_address = billing_address
self.charge_now = charge_now
self.gateway_id = gateway_id
self.invoice_template = invoice_template
self.offer =... | Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type description here. charge_now (ChargeNowEnum): TODO: type description he... | Order | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Order:
"""Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type description here. charge_now (ChargeNo... | stack_v2_sparse_classes_75kplus_train_001494 | 4,069 | permissive | [
{
"docstring": "Constructor for the Order class",
"name": "__init__",
"signature": "def __init__(self, contact_id=None, object_id=None, affiliate_id=None, billing_address=None, charge_now=None, gateway_id=None, invoice_template=None, offer=None, payer=None)"
},
{
"docstring": "Creates an instanc... | 2 | stack_v2_sparse_classes_30k_train_051723 | Implement the Python class `Order` described below.
Class description:
Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type... | Implement the Python class `Order` described below.
Class description:
Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type... | fb4834e89b897dce3475c89c7e6c34bf8756880e | <|skeleton|>
class Order:
"""Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type description here. charge_now (ChargeNo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Order:
"""Implementation of the 'Order' model. TODO: type model description here. Attributes: contact_id (int): TODO: type description here. object_id (int): TODO: type description here. affiliate_id (int): Affiliate ID. billing_address (Address): TODO: type description here. charge_now (ChargeNowEnum): TODO:... | the_stack_v2_python_sparse | ontraportlib/models/order.py | LifePosts/ontraportlib | train | 0 |
e415802e6f832e7b30742144afb896102e797185 | [
"x_axis = randn(20)\ny_axis = randn(20)\nplt.scatter(x_axis, y_axis, color='r')\nplt.title('Random distribution in X and Y')\nplt.xlabel('X-axis')\nplt.ylabel('Y_axis')\nplt.savefig('data/4_1.scatter_plot.png')\nplt.show()",
"x_axis = randn(20)\ny_axis = randn(20)\nplt.scatter(x_axis, y_axis, facecolors='none', e... | <|body_start_0|>
x_axis = randn(20)
y_axis = randn(20)
plt.scatter(x_axis, y_axis, color='r')
plt.title('Random distribution in X and Y')
plt.xlabel('X-axis')
plt.ylabel('Y_axis')
plt.savefig('data/4_1.scatter_plot.png')
plt.show()
<|end_body_0|>
<|body_s... | programScatterplot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class programScatterplot:
def scatter_plot(self):
"""Draw a scatter graph taking a random distribution in X and Y and plotted against each other"""
<|body_0|>
def scatter_plot_empty_circle(self):
"""Draw a scatter plot with empty circles taking a random distribution in X a... | stack_v2_sparse_classes_75kplus_train_001495 | 4,609 | no_license | [
{
"docstring": "Draw a scatter graph taking a random distribution in X and Y and plotted against each other",
"name": "scatter_plot",
"signature": "def scatter_plot(self)"
},
{
"docstring": "Draw a scatter plot with empty circles taking a random distribution in X and Y and plotted against each o... | 5 | stack_v2_sparse_classes_30k_train_000396 | Implement the Python class `programScatterplot` described below.
Class description:
Implement the programScatterplot class.
Method signatures and docstrings:
- def scatter_plot(self): Draw a scatter graph taking a random distribution in X and Y and plotted against each other
- def scatter_plot_empty_circle(self): Dra... | Implement the Python class `programScatterplot` described below.
Class description:
Implement the programScatterplot class.
Method signatures and docstrings:
- def scatter_plot(self): Draw a scatter graph taking a random distribution in X and Y and plotted against each other
- def scatter_plot_empty_circle(self): Dra... | 9a137436df58ff4d32c36e58f6b67679346167b9 | <|skeleton|>
class programScatterplot:
def scatter_plot(self):
"""Draw a scatter graph taking a random distribution in X and Y and plotted against each other"""
<|body_0|>
def scatter_plot_empty_circle(self):
"""Draw a scatter plot with empty circles taking a random distribution in X a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class programScatterplot:
def scatter_plot(self):
"""Draw a scatter graph taking a random distribution in X and Y and plotted against each other"""
x_axis = randn(20)
y_axis = randn(20)
plt.scatter(x_axis, y_axis, color='r')
plt.title('Random distribution in X and Y')
... | the_stack_v2_python_sparse | Python-Matplotlib/matplotlibScatter.py | shivamgupta7/python-program | train | 0 | |
4ccaa98a6e567222f80f0a5bc1c713cf7919553b | [
"super(ActivateResponsePayload, self).__init__()\nif unique_identifier is None:\n self.unique_identifier = attributes.UniqueIdentifier()\nelse:\n self.unique_identifier = unique_identifier\nself.validate()",
"super(ActivateResponsePayload, self).read(istream, kmip_version=kmip_version)\ntstream = BytearrayS... | <|body_start_0|>
super(ActivateResponsePayload, self).__init__()
if unique_identifier is None:
self.unique_identifier = attributes.UniqueIdentifier()
else:
self.unique_identifier = unique_identifier
self.validate()
<|end_body_0|>
<|body_start_1|>
super(Ac... | A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object. | ActivateResponsePayload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivateResponsePayload:
"""A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
... | stack_v2_sparse_classes_75kplus_train_001496 | 6,907 | permissive | [
{
"docstring": "Construct a ActivateResponsePayload object. Args: unique_identifier (UniqueIdentifier): The UUID of a managed cryptographic object.",
"name": "__init__",
"signature": "def __init__(self, unique_identifier=None)"
},
{
"docstring": "Read the data encoding the ActivateResponsePayloa... | 4 | null | Implement the Python class `ActivateResponsePayload` described below.
Class description:
A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID ... | Implement the Python class `ActivateResponsePayload` described below.
Class description:
A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID ... | f0a44b26ce902d8b9c330634d5b3603959edf1d4 | <|skeleton|>
class ActivateResponsePayload:
"""A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivateResponsePayload:
"""A response payload for the Activate operation. The payload contains the server response to the initial Activate request. See Section 4.19 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
def __ini... | the_stack_v2_python_sparse | kmip/core/messages/payloads/activate.py | OpenKMIP/PyKMIP | train | 232 |
017ceb2cb39160a89c6d761d1ffe7ad72256531f | [
"from collections import deque\nself.track = deque()\nself.score = 0\nself.pos = [0, 0]\nself.width = width\nself.height = height\nself.food = food",
"d = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nstep = d[direction]\nif self.track:\n temp = self.track.popleft()\n print('temp', temp)\n prin... | <|body_start_0|>
from collections import deque
self.track = deque()
self.score = 0
self.pos = [0, 0]
self.width = width
self.height = height
self.food = food
<|end_body_0|>
<|body_start_1|>
d = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus_train_001497 | 2,333 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 111ec32660f071cd3b07619b19d5dac2bb5e8477 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | simulation_interview/bytedance_2.py | azhu51/leetcode-practice | train | 0 | |
65210560a0a1e25f94576bc2336c13b7e5bee31a | [
"self.parent = parent\nself.power = power\nself.isPhysical = isPhysical\nself.pierce = pierce",
"damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)\nif target.dodge == self.pierce:\n return 2 * damage\nelse:\n return damage"
] | <|body_start_0|>
self.parent = parent
self.power = power
self.isPhysical = isPhysical
self.pierce = pierce
<|end_body_0|>
<|body_start_1|>
damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)
if target.dodge == self.pierce:
return 2 * damage
... | Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner | PierceDodge2XDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_75kplus_train_001498 | 842 | no_license | [
{
"docstring": "Build the Damage Delegate with the dodge it pierces",
"name": "__init__",
"signature": "def __init__(self, parent, power, isPhysical, pierce)"
},
{
"docstring": "Doubles the damage when the opponent is dodging in the manner that is pierced",
"name": "coreDamage",
"signatu... | 2 | stack_v2_sparse_classes_30k_val_000591 | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
self.parent = parent
self.power = po... | the_stack_v2_python_sparse | src/Battle/Attack/DamageDelegates/piercedodge_2Xdelegate.py | sgtnourry/Pokemon-Project | train | 0 |
48ed01c731e16f0bb6c6dbec489f999e63dc50af | [
"super(Project, self).__init__()\nself._zk_client = zk_client\nself._projects_manager = projects_manager\nself.project_id = project_id\nself._stopped = False\nself.services_node = '/appscale/projects/{}/services'.format(project_id)\nself._zk_client.ensure_path(self.services_node)\nservices = self._zk_client.get_chi... | <|body_start_0|>
super(Project, self).__init__()
self._zk_client = zk_client
self._projects_manager = projects_manager
self.project_id = project_id
self._stopped = False
self.services_node = '/appscale/projects/{}/services'.format(project_id)
self._zk_client.ensur... | Keeps track of project details. | Project | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Project:
"""Keeps track of project details."""
def __init__(self, zk_client, projects_manager, project_id):
"""Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id: A string specifying a project ID."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001499 | 12,944 | permissive | [
{
"docstring": "Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id: A string specifying a project ID.",
"name": "__init__",
"signature": "def __init__(self, zk_client, projects_manager, project_id)"
},
{
"docstring": "Establishes w... | 4 | null | Implement the Python class `Project` described below.
Class description:
Keeps track of project details.
Method signatures and docstrings:
- def __init__(self, zk_client, projects_manager, project_id): Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id:... | Implement the Python class `Project` described below.
Class description:
Keeps track of project details.
Method signatures and docstrings:
- def __init__(self, zk_client, projects_manager, project_id): Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id:... | be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f | <|skeleton|>
class Project:
"""Keeps track of project details."""
def __init__(self, zk_client, projects_manager, project_id):
"""Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id: A string specifying a project ID."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Project:
"""Keeps track of project details."""
def __init__(self, zk_client, projects_manager, project_id):
"""Creates a new Project. Args: zk_client: A KazooClient. projects_manager: A GlobalProjectsManager object. project_id: A string specifying a project ID."""
super(Project, self).__i... | the_stack_v2_python_sparse | AdminServer/appscale/admin/instance_manager/projects_manager.py | obino/appscale | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.