blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
742506e84be93de338c3d4a6376f141ffd57eed1
[ "self.b = block\nself.p = pblock\nself.nstops = nstops\nif not xend:\n if self.p == self.b:\n xend = np.random.uniform(self.p.xb0, self.p.xb1)\n else:\n bxmin, bxmax = self.b.xrange_at_y(self.p.y0)\n pxmin, pxmax = self.p.xrange_at_y(self.p.y0)\n xmin = max(pxmin, bxmin)\n x...
<|body_start_0|> self.b = block self.p = pblock self.nstops = nstops if not xend: if self.p == self.b: xend = np.random.uniform(self.p.xb0, self.p.xb1) else: bxmin, bxmax = self.b.xrange_at_y(self.p.y0) pxmin, pxmax ...
Wiggle
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Wiggle: def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops): """Calculate slope to sample points. __/ /\\ \\ / \\ \\ \\ /____/\\_\\ \\_\\""" <|body_0|> def get_line(self): """Samples points within bounds to connect lower to upper edge. \\ \\ _______...
stack_v2_sparse_classes_36k_train_002900
19,966
permissive
[ { "docstring": "Calculate slope to sample points. __/ /\\\\ \\\\ / \\\\ \\\\ \\\\ /____/\\\\_\\\\ \\\\_\\\\", "name": "__init__", "signature": "def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops)" }, { "docstring": "Samples points within bounds to connect lower to upper edge. \...
2
stack_v2_sparse_classes_30k_train_002106
Implement the Python class `Wiggle` described below. Class description: Implement the Wiggle class. Method signatures and docstrings: - def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops): Calculate slope to sample points. __/ /\\ \\ / \\ \\ \\ /____/\\_\\ \\_\\ - def get_line(self): Samples points ...
Implement the Python class `Wiggle` described below. Class description: Implement the Wiggle class. Method signatures and docstrings: - def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops): Calculate slope to sample points. __/ /\\ \\ / \\ \\ \\ /____/\\_\\ \\_\\ - def get_line(self): Samples points ...
9d706e7caad63a17f2a8a6b97e752bc79c5eefed
<|skeleton|> class Wiggle: def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops): """Calculate slope to sample points. __/ /\\ \\ / \\ \\ \\ /____/\\_\\ \\_\\""" <|body_0|> def get_line(self): """Samples points within bounds to connect lower to upper edge. \\ \\ _______...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Wiggle: def __init__(self, block, pblock, xstart, xend, ystart, yend, nstops): """Calculate slope to sample points. __/ /\\ \\ / \\ \\ \\ /____/\\_\\ \\_\\""" self.b = block self.p = pblock self.nstops = nstops if not xend: if self.p == self.b: ...
the_stack_v2_python_sparse
toytree/Container.py
eaton-lab/toytree
train
155
7761259dab72aad87d471ba08bf6310965a2fbd9
[ "context = super(ObjectDetailView, self).get_context_data(**kwargs)\nobj = self.get_object()\nattribute_list = OrderedDict()\nfor attribute in self.attributes:\n if attribute in self.typeclass._meta._property_names:\n attribute_list[attribute.title()] = getattr(obj, attribute, '')\n else:\n attr...
<|body_start_0|> context = super(ObjectDetailView, self).get_context_data(**kwargs) obj = self.get_object() attribute_list = OrderedDict() for attribute in self.attributes: if attribute in self.typeclass._meta._property_names: attribute_list[attribute.title()]...
This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting it has permissions to actually *do* things to it.
ObjectDetailView
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectDetailView: """This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting it has permissions to actually *do* th...
stack_v2_sparse_classes_36k_train_002901
35,922
permissive
[ { "docstring": "Adds an 'attributes' list to the request context consisting of the attributes specified at the class level, and in the order provided. Django views do not provide a way to reference dynamic attributes, so we have to grab them all before we render the template. Returns: context (dict): Django con...
2
null
Implement the Python class `ObjectDetailView` described below. Class description: This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting...
Implement the Python class `ObjectDetailView` described below. Class description: This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting...
5e97df013399e1a401d0a7ec184c4b9eb3100edd
<|skeleton|> class ObjectDetailView: """This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting it has permissions to actually *do* th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectDetailView: """This is an important view. Any view you write that deals with displaying, updating or deleting a specific object will want to inherit from this. It provides the mechanisms by which to retrieve the object and make sure the user requesting it has permissions to actually *do* things to it.""...
the_stack_v2_python_sparse
evennia-engine/evennia/evennia/web/website/views.py
rajammanabrolu/WorldGeneration
train
69
cd45939921a9137f3d1bd6b5ff6846ec36087f3c
[ "output_file_name = 'sshd_config_analysis.txt'\noutput_file_path = os.path.join(self.output_dir, output_file_name)\noutput_evidence = ReportText(source_path=output_file_path)\nwith open(evidence.local_path, 'r') as input_file:\n sshd_config = input_file.read()\nreport, priority, summary = self.analyse_sshd_confi...
<|body_start_0|> output_file_name = 'sshd_config_analysis.txt' output_file_path = os.path.join(self.output_dir, output_file_name) output_evidence = ReportText(source_path=output_file_path) with open(evidence.local_path, 'r') as input_file: sshd_config = input_file.read() ...
Task to analyze a sshd_config file.
SSHDAnalysisTask
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SSHDAnalysisTask: """Task to analyze a sshd_config file.""" def run(self, evidence, result): """Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTa...
stack_v2_sparse_classes_36k_train_002902
3,612
permissive
[ { "docstring": "Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTaskResult object.", "name": "run", "signature": "def run(self, evidence, result)" }, { "docst...
2
null
Implement the Python class `SSHDAnalysisTask` described below. Class description: Task to analyze a sshd_config file. Method signatures and docstrings: - def run(self, evidence, result): Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): T...
Implement the Python class `SSHDAnalysisTask` described below. Class description: Task to analyze a sshd_config file. Method signatures and docstrings: - def run(self, evidence, result): Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): T...
e73717549c6919e869ce4963449c36f227e3ccd6
<|skeleton|> class SSHDAnalysisTask: """Task to analyze a sshd_config file.""" def run(self, evidence, result): """Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SSHDAnalysisTask: """Task to analyze a sshd_config file.""" def run(self, evidence, result): """Run the sshd_config analysis worker. Args: evidence (Evidence object): The evidence we will process. result (TurbiniaTaskResult): The object to place task results into. Returns: TurbiniaTaskResult obje...
the_stack_v2_python_sparse
turbinia/workers/sshd.py
Ash515/turbinia
train
6
c753697354826e8b9e43c4002a7a239160d4cdd3
[ "self.ap = AxesSetupPanel(self.MovieFrames)\nself.dp = DisplayPanel()\nself.cp = ControlPanel()\nctrl_box = gtk.VBox()\nctrl_box.set_border_width(3)\nctrl_box.pack_start(self.dp, False, False, 5)\nctrl_box.pack_start(self.ap, False, False, 5)\nctrl_box.pack_end(self.cp, False, False, 5)\nreturn ctrl_box", "self.M...
<|body_start_0|> self.ap = AxesSetupPanel(self.MovieFrames) self.dp = DisplayPanel() self.cp = ControlPanel() ctrl_box = gtk.VBox() ctrl_box.set_border_width(3) ctrl_box.pack_start(self.dp, False, False, 5) ctrl_box.pack_start(self.ap, False, False, 5) ctr...
GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar
MovieGUI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovieGUI: """GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar""" def make_control_box(self): """make VBox with various control panels""" <|body_0|> def __init__(self...
stack_v2_sparse_classes_36k_train_002903
2,542
no_license
[ { "docstring": "make VBox with various control panels", "name": "make_control_box", "signature": "def make_control_box(self)" }, { "docstring": "canvas should set size request before", "name": "__init__", "signature": "def __init__(self, movie_frames, movie_file_maker, *args, **kwargs)" ...
2
null
Implement the Python class `MovieGUI` described below. Class description: GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar Method signatures and docstrings: - def make_control_box(self): make VBox with various co...
Implement the Python class `MovieGUI` described below. Class description: GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar Method signatures and docstrings: - def make_control_box(self): make VBox with various co...
775dc841b1d8538584c8c68a5f75ae997191e685
<|skeleton|> class MovieGUI: """GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar""" def make_control_box(self): """make VBox with various control panels""" <|body_0|> def __init__(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovieGUI: """GTK Window with movie frame and control elements Members: canvas -- MPL canvas ap -- Axis panel dp -- Display panel cp -- Control panel toolbar -- Toolbar""" def make_control_box(self): """make VBox with various control panels""" self.ap = AxesSetupPanel(self.MovieFrames) ...
the_stack_v2_python_sparse
Movie/Movie_GUI/GUI/movie_gui.py
atimokhin/tdc_vis
train
0
a58ec008eeabfbba9c1aa4d084a25c526455dc1c
[ "if self.twitter_link or self.facebook_link or self.pinterest_link or self.youtube_link or self.github_link or self.linkedin_link or self.vk_link or self.gplus_link:\n self.has_social_network_links = True\nelse:\n self.has_social_network_links = False\nsuper(SiteConfiguration, self).save(*args, **kwargs)", ...
<|body_start_0|> if self.twitter_link or self.facebook_link or self.pinterest_link or self.youtube_link or self.github_link or self.linkedin_link or self.vk_link or self.gplus_link: self.has_social_network_links = True else: self.has_social_network_links = False super(Sit...
A model to edit sitewide content
SiteConfiguration
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SiteConfiguration: """A model to edit sitewide content""" def save(self, *args, **kwargs): """Set has_social_network_links""" <|body_0|> def render_copyright(self): """Render the footer""" <|body_1|> <|end_skeleton|> <|body_start_0|> if self.twi...
stack_v2_sparse_classes_36k_train_002904
16,707
permissive
[ { "docstring": "Set has_social_network_links", "name": "save", "signature": "def save(self, *args, **kwargs)" }, { "docstring": "Render the footer", "name": "render_copyright", "signature": "def render_copyright(self)" } ]
2
null
Implement the Python class `SiteConfiguration` described below. Class description: A model to edit sitewide content Method signatures and docstrings: - def save(self, *args, **kwargs): Set has_social_network_links - def render_copyright(self): Render the footer
Implement the Python class `SiteConfiguration` described below. Class description: A model to edit sitewide content Method signatures and docstrings: - def save(self, *args, **kwargs): Set has_social_network_links - def render_copyright(self): Render the footer <|skeleton|> class SiteConfiguration: """A model to...
69855813052243c702c9b0108d2eac3f4f1a768f
<|skeleton|> class SiteConfiguration: """A model to edit sitewide content""" def save(self, *args, **kwargs): """Set has_social_network_links""" <|body_0|> def render_copyright(self): """Render the footer""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SiteConfiguration: """A model to edit sitewide content""" def save(self, *args, **kwargs): """Set has_social_network_links""" if self.twitter_link or self.facebook_link or self.pinterest_link or self.youtube_link or self.github_link or self.linkedin_link or self.vk_link or self.gplus_link...
the_stack_v2_python_sparse
theme/models.py
hydroshare/hydroshare
train
207
667426322e8b20be95be8415c8b544312fa8f4f5
[ "role = db.Role.get(id)\nif not role:\n return ({'msg': f'Role with id={id} not found.'}, HTTPStatus.NOT_FOUND)\nif not (self.r.v_glo.can() or role in g.user.roles):\n if not (self.r.v_org.can() and role.organization == g.user.organization):\n return ({'msg': 'You do not have permission to view this.'}...
<|body_start_0|> role = db.Role.get(id) if not role: return ({'msg': f'Role with id={id} not found.'}, HTTPStatus.NOT_FOUND) if not (self.r.v_glo.can() or role in g.user.roles): if not (self.r.v_org.can() and role.organization == g.user.organization): retu...
Role
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Role: def get(self, id): """Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View all roles| |Role|Organization|View|❌|❌|View rol...
stack_v2_sparse_classes_36k_train_002905
26,260
permissive
[ { "docstring": "Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View all roles| |Role|Organization|View|❌|❌|View roles that are part of your organizatio...
3
stack_v2_sparse_classes_30k_train_006643
Implement the Python class `Role` described below. Class description: Implement the Role class. Method signatures and docstrings: - def get(self, id): Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |...
Implement the Python class `Role` described below. Class description: Implement the Role class. Method signatures and docstrings: - def get(self, id): Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |...
b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca
<|skeleton|> class Role: def get(self, id): """Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View all roles| |Role|Organization|View|❌|❌|View rol...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Role: def get(self, id): """Get roles --- description: >- Get role based on role identifier. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View all roles| |Role|Organization|View|❌|❌|View roles that are pa...
the_stack_v2_python_sparse
vantage6-server/vantage6/server/resource/role.py
vantage6/vantage6
train
15
fe8fb2713f503e8047df614596d39cf51a68a3d5
[ "if annotation_file:\n if annotation_file.startswith('gs://'):\n _, local_val_json = tempfile.mkstemp(suffix='.json')\n tf.gfile.Remove(local_val_json)\n tf.gfile.Copy(annotation_file, local_val_json)\n atexit.register(tf.gfile.Remove, local_val_json)\n else:\n local_val_jso...
<|body_start_0|> if annotation_file: if annotation_file.startswith('gs://'): _, local_val_json = tempfile.mkstemp(suffix='.json') tf.gfile.Remove(local_val_json) tf.gfile.Copy(annotation_file, local_val_json) atexit.register(tf.gfile.Re...
LVIS evaluation metric class.
LVISEvaluator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LVISEvaluator: """LVIS evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): """Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes dete...
stack_v2_sparse_classes_36k_train_002906
20,065
permissive
[ { "docstring": "Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in LVIS annotation format as the groundtruths and runs LVIS evaluation. Args: an...
2
stack_v2_sparse_classes_30k_train_009586
Implement the Python class `LVISEvaluator` described below. Class description: LVIS evaluation metric class. Method signatures and docstrings: - def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): Constructs LVIS evaluation class. The class provides the interface t...
Implement the Python class `LVISEvaluator` described below. Class description: LVIS evaluation metric class. Method signatures and docstrings: - def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): Constructs LVIS evaluation class. The class provides the interface t...
0f7adb97a93ec3e3485c261d030c507eb16b33e4
<|skeleton|> class LVISEvaluator: """LVIS evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): """Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes dete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LVISEvaluator: """LVIS evaluation metric class.""" def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): """Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from e...
the_stack_v2_python_sparse
models/official/detection/evaluation/coco_evaluator.py
tensorflow/tpu
train
5,627
3248b044a38f8f177a84c24d2eda205f09e9c038
[ "diagnostic = SchedResetAIRCx()\nif isinstance(diagnostic, SchedResetAIRCx):\n assert True\nelse:\n assert False", "diagnostic = SchedResetAIRCx()\ndiagnostic.set_class_values({1.0}, {2.0}, {}, {}, {}, {}, {}, {}, {}, 1, {3.0}, {4.0}, 'test', [])\nassert diagnostic.no_req_data == 1\nassert diagnostic.analys...
<|body_start_0|> diagnostic = SchedResetAIRCx() if isinstance(diagnostic, SchedResetAIRCx): assert True else: assert False <|end_body_0|> <|body_start_1|> diagnostic = SchedResetAIRCx() diagnostic.set_class_values({1.0}, {2.0}, {}, {}, {}, {}, {}, {}, {},...
Contains all the tests for SchedResetAIRCx Diagnostic
TestDiagnosticsScheduleResetAIRCx
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDiagnosticsScheduleResetAIRCx: """Contains all the tests for SchedResetAIRCx Diagnostic""" def test_schedule_reset_dx_creation(self): """test the creation of schedule reset diagnostic class""" <|body_0|> def test_duct_static_dx_set_class_values(self): """test...
stack_v2_sparse_classes_36k_train_002907
14,928
permissive
[ { "docstring": "test the creation of schedule reset diagnostic class", "name": "test_schedule_reset_dx_creation", "signature": "def test_schedule_reset_dx_creation(self)" }, { "docstring": "test the creation of schedule reset diagnostic class", "name": "test_duct_static_dx_set_class_values",...
4
null
Implement the Python class `TestDiagnosticsScheduleResetAIRCx` described below. Class description: Contains all the tests for SchedResetAIRCx Diagnostic Method signatures and docstrings: - def test_schedule_reset_dx_creation(self): test the creation of schedule reset diagnostic class - def test_duct_static_dx_set_cla...
Implement the Python class `TestDiagnosticsScheduleResetAIRCx` described below. Class description: Contains all the tests for SchedResetAIRCx Diagnostic Method signatures and docstrings: - def test_schedule_reset_dx_creation(self): test the creation of schedule reset diagnostic class - def test_duct_static_dx_set_cla...
24d50729aef8d91036cc13b0f5c03be76f3237ed
<|skeleton|> class TestDiagnosticsScheduleResetAIRCx: """Contains all the tests for SchedResetAIRCx Diagnostic""" def test_schedule_reset_dx_creation(self): """test the creation of schedule reset diagnostic class""" <|body_0|> def test_duct_static_dx_set_class_values(self): """test...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDiagnosticsScheduleResetAIRCx: """Contains all the tests for SchedResetAIRCx Diagnostic""" def test_schedule_reset_dx_creation(self): """test the creation of schedule reset diagnostic class""" diagnostic = SchedResetAIRCx() if isinstance(diagnostic, SchedResetAIRCx): ...
the_stack_v2_python_sparse
EnergyEfficiency/AirsideRCxAgent/airside/test.py
shwethanidd/volttron-pnnl-applications-2
train
0
bf60b88048d06d59d634d7a70c9308fad5a51d0d
[ "if randint_function is not None:\n if not hasattr(randint_function, '__call__'):\n raise TypeError('randint_function has to be a function')\n self.randint_function = randint_function\n if period is None:\n period = self.period\nif period is not None and permutation_table is not None:\n ra...
<|body_start_0|> if randint_function is not None: if not hasattr(randint_function, '__call__'): raise TypeError('randint_function has to be a function') self.randint_function = randint_function if period is None: period = self.period if...
Noise abstract base class
BaseNoise
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseNoise: """Noise abstract base class""" def __init__(self, period=None, permutation_table=None, randint_function=None): """Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact ...
stack_v2_sparse_classes_36k_train_002908
13,275
permissive
[ { "docstring": "Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each time. An integer period can be specified, to generate a random permutation table with period elements. The period ...
2
stack_v2_sparse_classes_30k_val_000108
Implement the Python class `BaseNoise` described below. Class description: Noise abstract base class Method signatures and docstrings: - def __init__(self, period=None, permutation_table=None, randint_function=None): Initialize the noise generator. With no arguments, the default period and permutation table are used ...
Implement the Python class `BaseNoise` described below. Class description: Noise abstract base class Method signatures and docstrings: - def __init__(self, period=None, permutation_table=None, randint_function=None): Initialize the noise generator. With no arguments, the default period and permutation table are used ...
6fc0ccbc6fb24dcc2a8532aa22eb9574f1afdb3a
<|skeleton|> class BaseNoise: """Noise abstract base class""" def __init__(self, period=None, permutation_table=None, randint_function=None): """Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseNoise: """Noise abstract base class""" def __init__(self, period=None, permutation_table=None, randint_function=None): """Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pa...
the_stack_v2_python_sparse
pyrt/math/perlin.py
martinchristen/pyRT
train
79
0d88b97c9a45bf96b5c9ccd1af1f6f65453f6025
[ "params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True)\nparams['mlp_num_units'] = 256\nparams.get('mlp_num_units').hyper_space = hyper_spaces.quniform(16, 512)\nparams.get('mlp_num_layers').hyper_space = hyper_spaces.quniform(1, 5)\nreturn params", "self.embeddinng = self._mak...
<|body_start_0|> params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True) params['mlp_num_units'] = 256 params.get('mlp_num_units').hyper_space = hyper_spaces.quniform(16, 512) params.get('mlp_num_layers').hyper_space = hyper_spaces.quniform(1, 5) ...
A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build()
DenseBaseline
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DenseBaseline: """A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_mis...
stack_v2_sparse_classes_36k_train_002909
1,829
permissive
[ { "docstring": ":return: model default parameters.", "name": "get_default_params", "signature": "def get_default_params(cls) -> ParamTable" }, { "docstring": "Build.", "name": "build", "signature": "def build(self)" }, { "docstring": "Forward.", "name": "forward", "signat...
3
stack_v2_sparse_classes_30k_train_016861
Implement the Python class `DenseBaseline` described below. Class description: A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'...
Implement the Python class `DenseBaseline` described below. Class description: A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'...
4198ebce942f4afe7ddca6a96ab6f4464ade4518
<|skeleton|> class DenseBaseline: """A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_mis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DenseBaseline: """A simple densely connected baseline model. Examples: >>> model = DenseBaseline() >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(v...
the_stack_v2_python_sparse
poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/dense_baseline.py
microsoft/ContextualSP
train
332
5559435aeacca1df61b99c1b032b3ac647dbea87
[ "self._x = 123456789\nself._y = 362436069\nself._z = 521288629\nself._w = 88675123 ^ seed & 4294967295", "t = (self._x ^ self._x << 11) & 4294967295\nself._x = self._y\nself._y = self._z\nself._z = self._w\nself._w = self._w ^ self._w >> 19 ^ (t ^ t >> 8)\nreturn self._w" ]
<|body_start_0|> self._x = 123456789 self._y = 362436069 self._z = 521288629 self._w = 88675123 ^ seed & 4294967295 <|end_body_0|> <|body_start_1|> t = (self._x ^ self._x << 11) & 4294967295 self._x = self._y self._y = self._z self._z = self._w se...
An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is the top priority in your application (e.g. bench- marks), you may consider us...
XorShift
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XorShift: """An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is the top priority in your application (e.g...
stack_v2_sparse_classes_36k_train_002910
3,359
permissive
[ { "docstring": "Initialize an XorShift PRNG with a seed. Args: seed (:obj:`int`): Seed for initialization. Note that only the lowest 32 bits in :obj:`seed` are used to seed this PRNG.", "name": "__init__", "signature": "def __init__(self, seed) -> None" }, { "docstring": "Return a random integer...
2
null
Implement the Python class `XorShift` described below. Class description: An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is th...
Implement the Python class `XorShift` described below. Class description: An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is th...
710d953ebe8a181ff14a35daad80d56f6aa0fee8
<|skeleton|> class XorShift: """An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is the top priority in your application (e.g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XorShift: """An XorShift pseudo-random number generator (PRNG) with period 2^128-1. Although Python supplies an easy-to-use :obj:`random` module, it does not necessarily ensure the reproducibility across different versions of Python. If reproducibility is the top priority in your application (e.g. bench- mark...
the_stack_v2_python_sparse
cspuz/generator/deterministic_random.py
semiexp/cspuz
train
20
20d42b7157317b34797d9b02e37422aed6a157b6
[ "def _is_valid(act):\n return act.get('text', '') in quick_replies if quick_replies else True\nact = None\ncurr_time = time.time()\nallowed_timeout = timeout\nwhile act is None and time.time() - curr_time < allowed_timeout:\n act = agent.act()\n if act is not None and (not _is_valid(act)):\n agent.o...
<|body_start_0|> def _is_valid(act): return act.get('text', '') in quick_replies if quick_replies else True act = None curr_time = time.time() allowed_timeout = timeout while act is None and time.time() - curr_time < allowed_timeout: act = agent.act() ...
Provide interface for getting an agent's act with timeout.
TimeoutUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeoutUtils: """Provide interface for getting an agent's act with timeout.""" def get_timeout_act(agent: Agent, timeout: int=DEFAULT_TIMEOUT, quick_replies: Optional[List[str]]=None) -> Optional[Message]: """Return an agent's act, with a specified timeout. :param agent: Agent who is...
stack_v2_sparse_classes_36k_train_002911
2,763
permissive
[ { "docstring": "Return an agent's act, with a specified timeout. :param agent: Agent who is acting :param timeout: how long to wait :param quick_replies: If given, agent's message *MUST* be one of the quick replies :return: An act dictionary if no timeout; else, None", "name": "get_timeout_act", "signat...
2
stack_v2_sparse_classes_30k_train_021525
Implement the Python class `TimeoutUtils` described below. Class description: Provide interface for getting an agent's act with timeout. Method signatures and docstrings: - def get_timeout_act(agent: Agent, timeout: int=DEFAULT_TIMEOUT, quick_replies: Optional[List[str]]=None) -> Optional[Message]: Return an agent's ...
Implement the Python class `TimeoutUtils` described below. Class description: Provide interface for getting an agent's act with timeout. Method signatures and docstrings: - def get_timeout_act(agent: Agent, timeout: int=DEFAULT_TIMEOUT, quick_replies: Optional[List[str]]=None) -> Optional[Message]: Return an agent's ...
e1d899edfb92471552bae153f59ad30aa7fca468
<|skeleton|> class TimeoutUtils: """Provide interface for getting an agent's act with timeout.""" def get_timeout_act(agent: Agent, timeout: int=DEFAULT_TIMEOUT, quick_replies: Optional[List[str]]=None) -> Optional[Message]: """Return an agent's act, with a specified timeout. :param agent: Agent who is...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TimeoutUtils: """Provide interface for getting an agent's act with timeout.""" def get_timeout_act(agent: Agent, timeout: int=DEFAULT_TIMEOUT, quick_replies: Optional[List[str]]=None) -> Optional[Message]: """Return an agent's act, with a specified timeout. :param agent: Agent who is acting :para...
the_stack_v2_python_sparse
parlai/chat_service/utils/timeout.py
facebookresearch/ParlAI
train
10,943
74516029ec1c00c14d4399a6f6de56f91eab217e
[ "if not type(ff) is FFSocket and (not type(ff) is FFCavPhSocket):\n raise TypeError('The type ' + type(ff).__name__ + ' is not a valid socket forcefield')\nsuper(InputFFSocket, self).store(ff)\nself.address.store(ff.socket.address)\nself.port.store(ff.socket.port)\nself.timeout.store(ff.socket.timeout)\nself.slo...
<|body_start_0|> if not type(ff) is FFSocket and (not type(ff) is FFCavPhSocket): raise TypeError('The type ' + type(ff).__name__ + ' is not a valid socket forcefield') super(InputFFSocket, self).store(ff) self.address.store(ff.socket.address) self.port.store(ff.socket.port) ...
Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server socket binding address. port: The port number for the socket. slots: The number of...
InputFFSocket
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputFFSocket: """Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server socket binding address. port: The port nu...
stack_v2_sparse_classes_36k_train_002912
33,115
no_license
[ { "docstring": "Takes a ForceField instance and stores a minimal representation of it. Args: ff: A ForceField object with a FFSocket forcemodel object.", "name": "store", "signature": "def store(self, ff)" }, { "docstring": "Creates a ForceSocket object. Returns: A ForceSocket object with the co...
3
null
Implement the Python class `InputFFSocket` described below. Class description: Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server so...
Implement the Python class `InputFFSocket` described below. Class description: Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server so...
57f255266d4668bafef0881d1e7cbf8a27270ddd
<|skeleton|> class InputFFSocket: """Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server socket binding address. port: The port nu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InputFFSocket: """Creates a ForceField object with a socket interface. Handles generating one instance of a socket interface forcefield class. Attributes: mode: Describes whether the socket will be a unix or an internet socket. Fields: address: The server socket binding address. port: The port number for the ...
the_stack_v2_python_sparse
ipi/inputs/forcefields.py
i-pi/i-pi
train
170
976402db022bf67f63dfed5157ba4f203c6a85e9
[ "super().__init__(netatmo_device.data_handler)\nself.entity_description = description\nself._module = netatmo_device.device\nself._id = self._module.entity_id\nself._publishers.extend([{'name': HOME, 'home_id': netatmo_device.device.home.entity_id, SIGNAL_NAME: netatmo_device.signal_name}])\nself._attr_name = f'{se...
<|body_start_0|> super().__init__(netatmo_device.data_handler) self.entity_description = description self._module = netatmo_device.device self._id = self._module.entity_id self._publishers.extend([{'name': HOME, 'home_id': netatmo_device.device.home.entity_id, SIGNAL_NAME: netatm...
Implementation of a Netatmo sensor.
NetatmoSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetatmoSensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def async_update_callback(self) -> None: """Update the entity'...
stack_v2_sparse_classes_36k_train_002913
25,750
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None" }, { "docstring": "Update the entity's state.", "name": "async_update_callback", "signature": "def async_upda...
2
null
Implement the Python class `NetatmoSensor` described below. Class description: Implementation of a Netatmo sensor. Method signatures and docstrings: - def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor. - def async_update_callback(self) -> Non...
Implement the Python class `NetatmoSensor` described below. Class description: Implementation of a Netatmo sensor. Method signatures and docstrings: - def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor. - def async_update_callback(self) -> Non...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class NetatmoSensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: """Initialize the sensor.""" <|body_0|> def async_update_callback(self) -> None: """Update the entity'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetatmoSensor: """Implementation of a Netatmo sensor.""" def __init__(self, netatmo_device: NetatmoDevice, description: NetatmoSensorEntityDescription) -> None: """Initialize the sensor.""" super().__init__(netatmo_device.data_handler) self.entity_description = description ...
the_stack_v2_python_sparse
homeassistant/components/netatmo/sensor.py
home-assistant/core
train
35,501
f0fabbe17090ab9dc795fdec5de5dffd7d655622
[ "from django.conf import settings\nif 'db_britpick_app' not in settings.DATABASES:\n return None\nif model._meta.app_label == 'britpick_app':\n return 'db_britpick_app'\nreturn None", "from django.conf import settings\nif 'db_britpick_app' not in settings.DATABASES:\n return None\nif model._meta.app_labe...
<|body_start_0|> from django.conf import settings if 'db_britpick_app' not in settings.DATABASES: return None if model._meta.app_label == 'britpick_app': return 'db_britpick_app' return None <|end_body_0|> <|body_start_1|> from django.conf import settings...
A router to control britpick_app db operations
BritpickAppDBRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BritpickAppDBRouter: """A router to control britpick_app db operations""" def db_for_read(self, model, **hints): """Point all operations on britpick_app models to 'db_britpick_app'""" <|body_0|> def db_for_write(self, model, **hints): """Point all operations on b...
stack_v2_sparse_classes_36k_train_002914
1,641
no_license
[ { "docstring": "Point all operations on britpick_app models to 'db_britpick_app'", "name": "db_for_read", "signature": "def db_for_read(self, model, **hints)" }, { "docstring": "Point all operations on britpick_app models to 'db_britpick_app'", "name": "db_for_write", "signature": "def d...
4
stack_v2_sparse_classes_30k_train_021073
Implement the Python class `BritpickAppDBRouter` described below. Class description: A router to control britpick_app db operations Method signatures and docstrings: - def db_for_read(self, model, **hints): Point all operations on britpick_app models to 'db_britpick_app' - def db_for_write(self, model, **hints): Poin...
Implement the Python class `BritpickAppDBRouter` described below. Class description: A router to control britpick_app db operations Method signatures and docstrings: - def db_for_read(self, model, **hints): Point all operations on britpick_app models to 'db_britpick_app' - def db_for_write(self, model, **hints): Poin...
f0608c8cb035b805196deaf14d61d7548f94470f
<|skeleton|> class BritpickAppDBRouter: """A router to control britpick_app db operations""" def db_for_read(self, model, **hints): """Point all operations on britpick_app models to 'db_britpick_app'""" <|body_0|> def db_for_write(self, model, **hints): """Point all operations on b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BritpickAppDBRouter: """A router to control britpick_app db operations""" def db_for_read(self, model, **hints): """Point all operations on britpick_app models to 'db_britpick_app'""" from django.conf import settings if 'db_britpick_app' not in settings.DATABASES: retu...
the_stack_v2_python_sparse
britpick_app/dbRouter.py
htw229/hazelsworks
train
0
b89781535e16a88c7c85e626eb77d4c6d645ffc4
[ "self.img1 = cv2.imread(path1)\nself.img2 = cv2.imread(path2)\nself.img1_g = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY)\nself.img2_g = cv2.cvtColor(self.img2, cv2.COLOR_BGR2GRAY)", "detector = cv2.xfeatures2d.SIFT_create()\nself.kp1, self.f1 = detector.detectAndCompute(self.img1_g, None)\nself.kp2, self.f2 = det...
<|body_start_0|> self.img1 = cv2.imread(path1) self.img2 = cv2.imread(path2) self.img1_g = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY) self.img2_g = cv2.cvtColor(self.img2, cv2.COLOR_BGR2GRAY) <|end_body_0|> <|body_start_1|> detector = cv2.xfeatures2d.SIFT_create() self....
Simple class to stitch two images together
MyStitcher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyStitcher: """Simple class to stitch two images together""" def __init__(self, path1, path2): """Load and store the the imags in path1 and path2""" <|body_0|> def detect_and_compute(self): """Detect and compute SIFT features for both images""" <|body_1|>...
stack_v2_sparse_classes_36k_train_002915
2,053
no_license
[ { "docstring": "Load and store the the imags in path1 and path2", "name": "__init__", "signature": "def __init__(self, path1, path2)" }, { "docstring": "Detect and compute SIFT features for both images", "name": "detect_and_compute", "signature": "def detect_and_compute(self)" }, { ...
3
stack_v2_sparse_classes_30k_train_001231
Implement the Python class `MyStitcher` described below. Class description: Simple class to stitch two images together Method signatures and docstrings: - def __init__(self, path1, path2): Load and store the the imags in path1 and path2 - def detect_and_compute(self): Detect and compute SIFT features for both images ...
Implement the Python class `MyStitcher` described below. Class description: Simple class to stitch two images together Method signatures and docstrings: - def __init__(self, path1, path2): Load and store the the imags in path1 and path2 - def detect_and_compute(self): Detect and compute SIFT features for both images ...
ca8f934f3787144335f4b160e1a10c04fbe005a2
<|skeleton|> class MyStitcher: """Simple class to stitch two images together""" def __init__(self, path1, path2): """Load and store the the imags in path1 and path2""" <|body_0|> def detect_and_compute(self): """Detect and compute SIFT features for both images""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyStitcher: """Simple class to stitch two images together""" def __init__(self, path1, path2): """Load and store the the imags in path1 and path2""" self.img1 = cv2.imread(path1) self.img2 = cv2.imread(path2) self.img1_g = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY) ...
the_stack_v2_python_sparse
Courses/understanding_Images_Sanja/solutions/A3/image_stitching.py
anassBelcaid/ComputerVision
train
0
f44c78dfb5ff7dbc7f0ce6b906f916e804432361
[ "self.name = name\nself.weight = weight\nself.total_weight += weight\nself.children = []\nself.vertices[name] = self", "parent = edge.vertex1\nchild = edge.vertex2\nif child in self.vertices:\n if parent in self.vertices:\n raise ValueError('Edge links two nodes already in tree')\n parent, child = (c...
<|body_start_0|> self.name = name self.weight = weight self.total_weight += weight self.children = [] self.vertices[name] = self <|end_body_0|> <|body_start_1|> parent = edge.vertex1 child = edge.vertex2 if child in self.vertices: if parent in...
A representation of a spanning tree.
SpanningTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpanningTree: """A representation of a spanning tree.""" def __init__(self, name, weight): """Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float, the weight between this node and its parent. Should be 0...
stack_v2_sparse_classes_36k_train_002916
6,794
no_license
[ { "docstring": "Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float, the weight between this node and its parent. Should be 0 for the root, or a positive number otherwise.", "name": "__init__", "signature": "def __init__(se...
2
stack_v2_sparse_classes_30k_train_008814
Implement the Python class `SpanningTree` described below. Class description: A representation of a spanning tree. Method signatures and docstrings: - def __init__(self, name, weight): Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float,...
Implement the Python class `SpanningTree` described below. Class description: A representation of a spanning tree. Method signatures and docstrings: - def __init__(self, name, weight): Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float,...
bf622efcfad26f95696aa0bb72edb8fadfb2f717
<|skeleton|> class SpanningTree: """A representation of a spanning tree.""" def __init__(self, name, weight): """Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float, the weight between this node and its parent. Should be 0...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpanningTree: """A representation of a spanning tree.""" def __init__(self, name, weight): """Creates a new SpanningTree node with no edges. Args: name: The name to assign to this node. May be a number or string. weight: Float, the weight between this node and its parent. Should be 0 for the root...
the_stack_v2_python_sparse
span/mst.py
mmweber2/adm
train
3
d4bb66368c814069f1e2e2ef3abeec0904656b6d
[ "while SocketHandler.alive:\n filenos = list(SocketHandler.socket_map.keys())\n if filenos == []:\n time.sleep(0.001)\n continue\n for fileno in filenos:\n try:\n if not SocketHandler.socket_map[fileno].alive:\n del SocketHandler.socket_map[fileno]\n ex...
<|body_start_0|> while SocketHandler.alive: filenos = list(SocketHandler.socket_map.keys()) if filenos == []: time.sleep(0.001) continue for fileno in filenos: try: if not SocketHandler.socket_map[fileno].ali...
Call select() for all sockets of Server and Peer instances created in currently executing program.
SocketHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocketHandler: """Call select() for all sockets of Server and Peer instances created in currently executing program.""" def loop(): """Infite loop calling select().""" <|body_0|> def handle_sockets(read, write, exc): """Call appropriate methods for sockets.""" ...
stack_v2_sparse_classes_36k_train_002917
14,729
no_license
[ { "docstring": "Infite loop calling select().", "name": "loop", "signature": "def loop()" }, { "docstring": "Call appropriate methods for sockets.", "name": "handle_sockets", "signature": "def handle_sockets(read, write, exc)" }, { "docstring": "Stop loop().", "name": "close"...
3
stack_v2_sparse_classes_30k_test_000701
Implement the Python class `SocketHandler` described below. Class description: Call select() for all sockets of Server and Peer instances created in currently executing program. Method signatures and docstrings: - def loop(): Infite loop calling select(). - def handle_sockets(read, write, exc): Call appropriate metho...
Implement the Python class `SocketHandler` described below. Class description: Call select() for all sockets of Server and Peer instances created in currently executing program. Method signatures and docstrings: - def loop(): Infite loop calling select(). - def handle_sockets(read, write, exc): Call appropriate metho...
7b19b0ec1b8f4ac1322487b7be71a1cd18480a42
<|skeleton|> class SocketHandler: """Call select() for all sockets of Server and Peer instances created in currently executing program.""" def loop(): """Infite loop calling select().""" <|body_0|> def handle_sockets(read, write, exc): """Call appropriate methods for sockets.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SocketHandler: """Call select() for all sockets of Server and Peer instances created in currently executing program.""" def loop(): """Infite loop calling select().""" while SocketHandler.alive: filenos = list(SocketHandler.socket_map.keys()) if filenos == []: ...
the_stack_v2_python_sparse
BitTorrent/core/network.py
melanholy/python-tasks
train
0
754d3a0a02fb2655478b3d9efbbd2f17777ca101
[ "self.access_zone_name = access_zone_name\nself.nfs_mount_point = nfs_mount_point\nself.path = path\nself.protocols = protocols\nself.smb_mount_points = smb_mount_points", "if dictionary is None:\n return None\naccess_zone_name = dictionary.get('accessZoneName')\nnfs_mount_point = cohesity_management_sdk.model...
<|body_start_0|> self.access_zone_name = access_zone_name self.nfs_mount_point = nfs_mount_point self.path = path self.protocols = protocols self.smb_mount_points = smb_mount_points <|end_body_0|> <|body_start_1|> if dictionary is None: return None ac...
Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. This field is set if the file system supports ...
IsilonMountPoint
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IsilonMountPoint: """Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. Th...
stack_v2_sparse_classes_36k_train_002918
3,464
permissive
[ { "docstring": "Constructor for the IsilonMountPoint class", "name": "__init__", "signature": "def __init__(self, access_zone_name=None, nfs_mount_point=None, path=None, protocols=None, smb_mount_points=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionar...
2
stack_v2_sparse_classes_30k_train_008484
Implement the Python class `IsilonMountPoint` described below. Class description: Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specif...
Implement the Python class `IsilonMountPoint` described below. Class description: Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specif...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class IsilonMountPoint: """Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IsilonMountPoint: """Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. This field is s...
the_stack_v2_python_sparse
cohesity_management_sdk/models/isilon_mount_point.py
cohesity/management-sdk-python
train
24
48ee17016ff2aecac0be04500feafeb60d6e2294
[ "location_report_query = LocationReport.query().filter(LocationReport.tags == self.key)\nlocation_reports = location_report_query.fetch()\nreturn location_reports", "location_report_keys = self.location_reports\nlocation_report_names = []\nfor lrk in location_report_keys:\n location_report_names.append(lrk.get...
<|body_start_0|> location_report_query = LocationReport.query().filter(LocationReport.tags == self.key) location_reports = location_report_query.fetch() return location_reports <|end_body_0|> <|body_start_1|> location_report_keys = self.location_reports location_report_names = [...
Unique
Tag
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tag: """Unique""" def location_reports(self): """returns keys for location reports associated with tag""" <|body_0|> def location_report_names(self): """returns list of location report names associated with tag""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_002919
1,827
permissive
[ { "docstring": "returns keys for location reports associated with tag", "name": "location_reports", "signature": "def location_reports(self)" }, { "docstring": "returns list of location report names associated with tag", "name": "location_report_names", "signature": "def location_report_...
2
stack_v2_sparse_classes_30k_train_016330
Implement the Python class `Tag` described below. Class description: Unique Method signatures and docstrings: - def location_reports(self): returns keys for location reports associated with tag - def location_report_names(self): returns list of location report names associated with tag
Implement the Python class `Tag` described below. Class description: Unique Method signatures and docstrings: - def location_reports(self): returns keys for location reports associated with tag - def location_report_names(self): returns list of location report names associated with tag <|skeleton|> class Tag: ""...
a7c1b92521ec086644e2d7dc6a62f24a43a78d94
<|skeleton|> class Tag: """Unique""" def location_reports(self): """returns keys for location reports associated with tag""" <|body_0|> def location_report_names(self): """returns list of location report names associated with tag""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tag: """Unique""" def location_reports(self): """returns keys for location reports associated with tag""" location_report_query = LocationReport.query().filter(LocationReport.tags == self.key) location_reports = location_report_query.fetch() return location_reports de...
the_stack_v2_python_sparse
models/models.py
anuja1011/Pick-Up-Sports
train
0
9bae1fa633e3c92f65354aad69627d8ee4b18c33
[ "parser = config_file.SshdConfigParser()\nresults = list(parser.ParseFile(None, None, io.BytesIO(CFG)))\nself.assertLen(results, 1)\nreturn results[0]", "result = self.GetConfig()\nself.assertIsInstance(result, rdf_config_file.SshdConfig)\nself.assertCountEqual([2], result.config.protocol)\nexpect = ['aes128-ctr'...
<|body_start_0|> parser = config_file.SshdConfigParser() results = list(parser.ParseFile(None, None, io.BytesIO(CFG))) self.assertLen(results, 1) return results[0] <|end_body_0|> <|body_start_1|> result = self.GetConfig() self.assertIsInstance(result, rdf_config_file.Ssh...
Test parsing of an sshd configuration.
SshdConfigTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SshdConfigTest: """Test parsing of an sshd configuration.""" def GetConfig(self): """Read in the test configuration file.""" <|body_0|> def testParseConfig(self): """Ensure we can extract sshd settings.""" <|body_1|> def testFindNumericValues(self): ...
stack_v2_sparse_classes_36k_train_002920
28,097
permissive
[ { "docstring": "Read in the test configuration file.", "name": "GetConfig", "signature": "def GetConfig(self)" }, { "docstring": "Ensure we can extract sshd settings.", "name": "testParseConfig", "signature": "def testParseConfig(self)" }, { "docstring": "Keywords with numeric se...
4
stack_v2_sparse_classes_30k_train_002407
Implement the Python class `SshdConfigTest` described below. Class description: Test parsing of an sshd configuration. Method signatures and docstrings: - def GetConfig(self): Read in the test configuration file. - def testParseConfig(self): Ensure we can extract sshd settings. - def testFindNumericValues(self): Keyw...
Implement the Python class `SshdConfigTest` described below. Class description: Test parsing of an sshd configuration. Method signatures and docstrings: - def GetConfig(self): Read in the test configuration file. - def testParseConfig(self): Ensure we can extract sshd settings. - def testFindNumericValues(self): Keyw...
44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6
<|skeleton|> class SshdConfigTest: """Test parsing of an sshd configuration.""" def GetConfig(self): """Read in the test configuration file.""" <|body_0|> def testParseConfig(self): """Ensure we can extract sshd settings.""" <|body_1|> def testFindNumericValues(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SshdConfigTest: """Test parsing of an sshd configuration.""" def GetConfig(self): """Read in the test configuration file.""" parser = config_file.SshdConfigParser() results = list(parser.ParseFile(None, None, io.BytesIO(CFG))) self.assertLen(results, 1) return resu...
the_stack_v2_python_sparse
grr/core/grr_response_core/lib/parsers/config_file_test.py
google/grr
train
4,683
af7701e084d96e61f35705798cf82747af601c85
[ "n = len(nums) - 1\nleft, right = (1, n)\nwhile left < right:\n mid = left + (right - left) // 2\n count = 0\n for num in nums:\n if num <= mid:\n count += 1\n if count > mid:\n right = mid\n else:\n left = mid + 1\nreturn right", "slow, fast = (nums[0], nums[nums[0]...
<|body_start_0|> n = len(nums) - 1 left, right = (1, n) while left < right: mid = left + (right - left) // 2 count = 0 for num in nums: if num <= mid: count += 1 if count > mid: right = mid ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate1(self, nums: List[int]) -> int: """一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。""" <|body_0|> def findDuplicate2(self, nums: List[int]) -> int: """快慢指针,比较难理解,参考142题解""" ...
stack_v2_sparse_classes_36k_train_002921
2,089
no_license
[ { "docstring": "一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。", "name": "findDuplicate1", "signature": "def findDuplicate1(self, nums: List[int]) -> int" }, { "docstring": "快慢指针,比较难理解,参考142题解", "name": "findDuplicate2", "...
2
stack_v2_sparse_classes_30k_train_020961
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate1(self, nums: List[int]) -> int: 一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。 - def findDupli...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate1(self, nums: List[int]) -> int: 一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。 - def findDupli...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: def findDuplicate1(self, nums: List[int]) -> int: """一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。""" <|body_0|> def findDuplicate2(self, nums: List[int]) -> int: """快慢指针,比较难理解,参考142题解""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate1(self, nums: List[int]) -> int: """一般意义上,我们都在索引维度上(空间),在给定target的情况下去二分查找。 为什么能二分,是因为索引维度上数组有序。 本题是在数值维度上去二分查找 为什么能二分,是因为在数值维度上元素分布不均,存在二分条件(抽屉原理)。""" n = len(nums) - 1 left, right = (1, n) while left < right: mid = left + (right - left) ...
the_stack_v2_python_sparse
287_find-the-duplicate-number.py
helloocc/algorithm
train
1
9a0a0d3ec27905246514210f4a7ab9d6fc043992
[ "if not callable(condition):\n bad_type = type(condition)\n msg = f'Expected callable function for condition, got {bad_type}'\n raise TypeError(msg)\nself.condition = condition\nself.workflow = Workflow(workflow)", "old_circuit = circuit.copy()\nold_data = data.copy()\nawait self.workflow.run(circuit, da...
<|body_start_0|> if not callable(condition): bad_type = type(condition) msg = f'Expected callable function for condition, got {bad_type}' raise TypeError(msg) self.condition = condition self.workflow = Workflow(workflow) <|end_body_0|> <|body_start_1|> ...
The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.
DoThenDecide
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoThenDecide: """The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.""" def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None: """Con...
stack_v2_sparse_classes_36k_train_002922
2,346
permissive
[ { "docstring": "Construct a DoThenDecide. Args: condition (Callable[[Circuit, Circuit], bool]): The condition function that determines if the new circuit (second parameter) after running `workflow` should replace the original circuit (first parameter). If the condition returns True, then replace the original ci...
2
stack_v2_sparse_classes_30k_train_009631
Implement the Python class `DoThenDecide` described below. Class description: The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state. Method signatures and docstrings: - def __init__(self, condition: Callable[[Circu...
Implement the Python class `DoThenDecide` described below. Class description: The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state. Method signatures and docstrings: - def __init__(self, condition: Callable[[Circu...
c89112d15072e8ffffb68cf1757b184e2aeb3dc8
<|skeleton|> class DoThenDecide: """The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.""" def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None: """Con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DoThenDecide: """The DoThenDecide class. This is a control pass that executes a workflow and then conditionally accepts the resulting circuit or reverts to the original state.""" def __init__(self, condition: Callable[[Circuit, Circuit], bool], workflow: WorkflowLike) -> None: """Construct a DoTh...
the_stack_v2_python_sparse
bqskit/passes/control/dothendecide.py
BQSKit/bqskit
train
54
c947f0277a106e692da2ec18fa03cc0049c88267
[ "self.output_filename = output_filename\nself.onet_source = onet_source\nself.hash_function = hash_function\nself.ksa_types = ksa_types or KSA_TYPE_CONFIG.keys()", "logging.info('Converting ONET %s to pandas', filename)\nwith self.onet_source.ensure_file(filename) as fullpath:\n with open(fullpath) as f:\n ...
<|body_start_0|> self.output_filename = output_filename self.onet_source = onet_source self.hash_function = hash_function self.ksa_types = ksa_types or KSA_TYPE_CONFIG.keys() <|end_body_0|> <|body_start_1|> logging.info('Converting ONET %s to pandas', filename) with self...
An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson
OnetSkillListProcessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnetSkillListProcessor: """An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson""" def __init__(self, onet_source, output_filename, hash_function, ksa_types=None): """Args: output_filename: A filename to write the final dataset onet_sourc...
stack_v2_sparse_classes_36k_train_002923
4,463
permissive
[ { "docstring": "Args: output_filename: A filename to write the final dataset onet_source: An object that is able to fetch ONET files by name hash_function: A function that can hash a given string ksa_types: A list of onet skill types to include. All strings must be keys in KSA_TYPE_CONFIG. Defaults to all keys ...
3
stack_v2_sparse_classes_30k_train_009425
Implement the Python class `OnetSkillListProcessor` described below. Class description: An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson Method signatures and docstrings: - def __init__(self, onet_source, output_filename, hash_function, ksa_types=None): Args: output_f...
Implement the Python class `OnetSkillListProcessor` described below. Class description: An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson Method signatures and docstrings: - def __init__(self, onet_source, output_filename, hash_function, ksa_types=None): Args: output_f...
feffead90815ccdecf24bf1a995f79683442b046
<|skeleton|> class OnetSkillListProcessor: """An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson""" def __init__(self, onet_source, output_filename, hash_function, ksa_types=None): """Args: output_filename: A filename to write the final dataset onet_sourc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OnetSkillListProcessor: """An object that creates a skills CSV based on ONET data Originally written by Kwame Porter Robinson""" def __init__(self, onet_source, output_filename, hash_function, ksa_types=None): """Args: output_filename: A filename to write the final dataset onet_source: An object ...
the_stack_v2_python_sparse
skills_ml/datasets/skills/onet_ksat.py
workforce-data-initiative/skills-ml
train
164
7678f4c421ff69dd93275c0a0215d12d27df056e
[ "if self.get_object().owner == self.request.user:\n return True\nreturn False", "project = self.get_object()\ndelete_project(project)\nmessages.success(self.request, self.success_message)\nreturn HttpResponseRedirect(self.success_url)" ]
<|body_start_0|> if self.get_object().owner == self.request.user: return True return False <|end_body_0|> <|body_start_1|> project = self.get_object() delete_project(project) messages.success(self.request, self.success_message) return HttpResponseRedirect(sel...
Delete a project. Only the project owner can delete the project.
ProjectDelete
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectDelete: """Delete a project. Only the project owner can delete the project.""" def has_permission(self): """Overrides method from PermissionRequiredMixin.""" <|body_0|> def delete(self, request, *args, **kwargs): """Overrides method from DeleteView.""" ...
stack_v2_sparse_classes_36k_train_002924
21,511
permissive
[ { "docstring": "Overrides method from PermissionRequiredMixin.", "name": "has_permission", "signature": "def has_permission(self)" }, { "docstring": "Overrides method from DeleteView.", "name": "delete", "signature": "def delete(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_004415
Implement the Python class `ProjectDelete` described below. Class description: Delete a project. Only the project owner can delete the project. Method signatures and docstrings: - def has_permission(self): Overrides method from PermissionRequiredMixin. - def delete(self, request, *args, **kwargs): Overrides method fr...
Implement the Python class `ProjectDelete` described below. Class description: Delete a project. Only the project owner can delete the project. Method signatures and docstrings: - def has_permission(self): Overrides method from PermissionRequiredMixin. - def delete(self, request, *args, **kwargs): Overrides method fr...
598b3bc10b72b7b277510cf40e1a4bc56b07452a
<|skeleton|> class ProjectDelete: """Delete a project. Only the project owner can delete the project.""" def has_permission(self): """Overrides method from PermissionRequiredMixin.""" <|body_0|> def delete(self, request, *args, **kwargs): """Overrides method from DeleteView.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectDelete: """Delete a project. Only the project owner can delete the project.""" def has_permission(self): """Overrides method from PermissionRequiredMixin.""" if self.get_object().owner == self.request.user: return True return False def delete(self, request,...
the_stack_v2_python_sparse
jenkins_auth/views.py
antony-wilson/jenkins_auth
train
0
823f68d160608aa15c52a2bf3043785db3cc4e52
[ "super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(...
<|body_start_0|> super(EncoderBlock, self).__init__() self.mha = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu') self.dense_output = tf.keras.layers.Dense(dm) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06) ...
class EncoderBlock
EncoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderBlock: """class EncoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """class constructor""" <|body_0|> def call(self, x, training, mask=None): """call function""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(EncoderBlo...
stack_v2_sparse_classes_36k_train_002925
1,207
no_license
[ { "docstring": "class constructor", "name": "__init__", "signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)" }, { "docstring": "call function", "name": "call", "signature": "def call(self, x, training, mask=None)" } ]
2
null
Implement the Python class `EncoderBlock` described below. Class description: class EncoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): class constructor - def call(self, x, training, mask=None): call function
Implement the Python class `EncoderBlock` described below. Class description: class EncoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): class constructor - def call(self, x, training, mask=None): call function <|skeleton|> class EncoderBlock: """class EncoderBlock""...
a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2
<|skeleton|> class EncoderBlock: """class EncoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """class constructor""" <|body_0|> def call(self, x, training, mask=None): """call function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncoderBlock: """class EncoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """class constructor""" super(EncoderBlock, self).__init__() self.mha = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu') self.dens...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/7-transformer_encoder_block.py
salmenz/holbertonschool-machine_learning
train
4
2662eab3094ce1b4b0db9369edac940ffe9ada52
[ "self.controller = controller\nself.deserializer = deserializer or RequestDeserializer()\nself.serializer = serializer or ResponseSerializer()\nself._fault_body_function = fault_body_function", "LOG.info('%(method)s %(url)s', {'method': request.method, 'url': request.url})\ntry:\n action, args, accept = self.d...
<|body_start_0|> self.controller = controller self.deserializer = deserializer or RequestDeserializer() self.serializer = serializer or ResponseSerializer() self._fault_body_function = fault_body_function <|end_body_0|> <|body_start_1|> LOG.info('%(method)s %(url)s', {'method': ...
WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the operation is a PUT or PO...
Resource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resource: """WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Requ...
stack_v2_sparse_classes_36k_train_002926
29,625
permissive
[ { "docstring": "Object initialization. :param controller: object that implement methods created by routes lib :param deserializer: object that can serialize the output of a controller into a webob response :param serializer: object that can deserialize a webob request into necessary pieces :param fault_body_fun...
3
stack_v2_sparse_classes_30k_val_000472
Implement the Python class `Resource` described below. Class description: WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' ar...
Implement the Python class `Resource` described below. Class description: WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' ar...
dde31aae392b80341f6440eb38db1583563d7d1f
<|skeleton|> class Resource: """WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Requ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Resource: """WSGI app that handles (de)serialization and controller dispatch. WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a 'req' argument, which is the incoming wsgi.Request. If the o...
the_stack_v2_python_sparse
neutron/wsgi.py
openstack/neutron
train
1,174
b830e3460892bf9fe1d1cb33d1dc7d10f857c14c
[ "Gridder.__init__(self, master=master, row=row, col=col, sticky=sticky)\nif numStatusCols is not None:\n numStatusCols = int(numStatusCols)\nself._numStatusCols = numStatusCols", "basicArgs = self._basicKArgs(**kargs)\nbasicArgs.setdefault('numStatusCols', self._numStatusCols)\ngs = _StatusConfigGridSet(master...
<|body_start_0|> Gridder.__init__(self, master=master, row=row, col=col, sticky=sticky) if numStatusCols is not None: numStatusCols = int(numStatusCols) self._numStatusCols = numStatusCols <|end_body_0|> <|body_start_1|> basicArgs = self._basicKArgs(**kargs) basicArg...
StatusConfigGridder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatusConfigGridder: def __init__(self, master, row=0, col=0, sticky='e', numStatusCols=None): """Create an object that grids a set of status and configuration widgets. Inputs: - master Master widget into which to grid - row Starting row - col Starting column - sticky Default sticky sett...
stack_v2_sparse_classes_36k_train_002927
10,102
no_license
[ { "docstring": "Create an object that grids a set of status and configuration widgets. Inputs: - master Master widget into which to grid - row Starting row - col Starting column - sticky Default sticky setting for the status and config widgets - numStatusCols default number of columns for status widgets (includ...
2
stack_v2_sparse_classes_30k_train_013663
Implement the Python class `StatusConfigGridder` described below. Class description: Implement the StatusConfigGridder class. Method signatures and docstrings: - def __init__(self, master, row=0, col=0, sticky='e', numStatusCols=None): Create an object that grids a set of status and configuration widgets. Inputs: - m...
Implement the Python class `StatusConfigGridder` described below. Class description: Implement the StatusConfigGridder class. Method signatures and docstrings: - def __init__(self, master, row=0, col=0, sticky='e', numStatusCols=None): Create an object that grids a set of status and configuration widgets. Inputs: - m...
fe5578ba978e8a9cd81c08be271c2ef874a84927
<|skeleton|> class StatusConfigGridder: def __init__(self, master, row=0, col=0, sticky='e', numStatusCols=None): """Create an object that grids a set of status and configuration widgets. Inputs: - master Master widget into which to grid - row Starting row - col Starting column - sticky Default sticky sett...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatusConfigGridder: def __init__(self, master, row=0, col=0, sticky='e', numStatusCols=None): """Create an object that grids a set of status and configuration widgets. Inputs: - master Master widget into which to grid - row Starting row - col Starting column - sticky Default sticky setting for the st...
the_stack_v2_python_sparse
python/RO-3.6.9/Wdg/StatusConfigGridder.py
Subaru-PFS/tron_actorcore
train
3
c7645ca2b6483552dc3395a2abfce2562cfeb6df
[ "caller = auth.get_current_identity()\nif not caller.is_user:\n self.abort_with_error(400, text='Caller must use email-based auth')\nreturn caller.name", "try:\n return self.send_response({'topic': pubsub.topic_name(), 'authorized': pubsub.is_authorized_subscriber(self.caller_email()), 'gs': {'auth_db_gs_pa...
<|body_start_0|> caller = auth.get_current_identity() if not caller.is_user: self.abort_with_error(400, text='Caller must use email-based auth') return caller.name <|end_body_0|> <|body_start_1|> try: return self.send_response({'topic': pubsub.topic_name(), 'auth...
Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read Google Storage object that contains AuthDB dump.
AuthDBSubscriptionAuthHandler
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthDBSubscriptionAuthHandler: """Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read Google Storage object that contains Auth...
stack_v2_sparse_classes_36k_train_002928
16,263
permissive
[ { "docstring": "Validates caller is using email for auth, returns it. Raises HTTP 400 if some other kind of authentication is used.", "name": "caller_email", "signature": "def caller_email(self)" }, { "docstring": "Queries whether the caller is authorized to access AuthDB already. Response body:...
4
null
Implement the Python class `AuthDBSubscriptionAuthHandler` described below. Class description: Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read G...
Implement the Python class `AuthDBSubscriptionAuthHandler` described below. Class description: Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read G...
10cc5fdcca53e2a1690867acbe6fce099273f092
<|skeleton|> class AuthDBSubscriptionAuthHandler: """Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read Google Storage object that contains Auth...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthDBSubscriptionAuthHandler: """Manages authorization to AuthDB PubSub topic and Google Storage object. Members of 'auth-trusted-services' group may use this endpoint to make sure they: 1. Can subscribe to AuthDB change notification PubSub topic. 2. Read Google Storage object that contains AuthDB dump.""" ...
the_stack_v2_python_sparse
appengine/auth_service/handlers_frontend.py
luci/luci-py
train
84
9f53640abd3d57af76b055223b2130a284e044a2
[ "self.element = element\nself.need_update = need_update\nself.callout = None", "points = self._get_up_down_points(offset)\nself.callout = MyView.create_callout(view.Id, view.GetTypeId(), *points)\nif self.need_update:\n self._update(symbol_point=points, rotated=rotated)\nif template_view:\n self.callout.App...
<|body_start_0|> self.element = element self.need_update = need_update self.callout = None <|end_body_0|> <|body_start_1|> points = self._get_up_down_points(offset) self.callout = MyView.create_callout(view.Id, view.GetTypeId(), *points) if self.need_update: ...
MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop
MyCalloutCreator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyCalloutCreator: """MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop""" def __init__(self, element, need_update=True): """Initialization of instance :param element: :type element: MyElementG...
stack_v2_sparse_classes_36k_train_002929
2,951
permissive
[ { "docstring": "Initialization of instance :param element: :type element: MyElementGeom", "name": "__init__", "signature": "def __init__(self, element, need_update=True)" }, { "docstring": "Create callout on given view, offset and rotate if it needed :param view: view on which the callout will b...
5
stack_v2_sparse_classes_30k_train_008169
Implement the Python class `MyCalloutCreator` described below. Class description: MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop Method signatures and docstrings: - def __init__(self, element, need_update=True): Initializat...
Implement the Python class `MyCalloutCreator` described below. Class description: MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop Method signatures and docstrings: - def __init__(self, element, need_update=True): Initializat...
c4ea77428111d186fab55501243ad4319376482b
<|skeleton|> class MyCalloutCreator: """MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop""" def __init__(self, element, need_update=True): """Initialization of instance :param element: :type element: MyElementG...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyCalloutCreator: """MetaClass for Callout. Need overrides: - _calc_origin_and_orientation - _get_symbol_points _need_update determines whether to rotate and crop""" def __init__(self, element, need_update=True): """Initialization of instance :param element: :type element: MyElementGeom""" ...
the_stack_v2_python_sparse
scripts/my_class/my_callout.py
appolimp/Dynamo_scripts
train
1
efca7c33e0d874a48280ab7284dfeecce280622c
[ "self.dim = dim\nself.scale = scale\nself.density = density\nself.width = dim[0] // scale\nself.height = dim[1] // scale\nself.surface = pygame.Surface(dim)\nself.cells = [[0 for x in range(self.width)] for y in range(self.height)]\nfor i in range(self.width * self.height // density):\n x = random.randint(1, sel...
<|body_start_0|> self.dim = dim self.scale = scale self.density = density self.width = dim[0] // scale self.height = dim[1] // scale self.surface = pygame.Surface(dim) self.cells = [[0 for x in range(self.width)] for y in range(self.height)] for i in range...
simple Cellular Automata - Conways Game of Life
GameOfLife
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameOfLife: """simple Cellular Automata - Conways Game of Life""" def __init__(self, dim: tuple, scale=2, density=15): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" <|body_0|> def update(self) -> pygame.Surface: """every frame a...
stack_v2_sparse_classes_36k_train_002930
2,813
no_license
[ { "docstring": ":param dim: dimension of surface to draw on :param ruleset: ruleset to use", "name": "__init__", "signature": "def __init__(self, dim: tuple, scale=2, density=15)" }, { "docstring": "every frame a new generation", "name": "update", "signature": "def update(self) -> pygame...
2
stack_v2_sparse_classes_30k_train_019784
Implement the Python class `GameOfLife` described below. Class description: simple Cellular Automata - Conways Game of Life Method signatures and docstrings: - def __init__(self, dim: tuple, scale=2, density=15): :param dim: dimension of surface to draw on :param ruleset: ruleset to use - def update(self) -> pygame.S...
Implement the Python class `GameOfLife` described below. Class description: simple Cellular Automata - Conways Game of Life Method signatures and docstrings: - def __init__(self, dim: tuple, scale=2, density=15): :param dim: dimension of surface to draw on :param ruleset: ruleset to use - def update(self) -> pygame.S...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class GameOfLife: """simple Cellular Automata - Conways Game of Life""" def __init__(self, dim: tuple, scale=2, density=15): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" <|body_0|> def update(self) -> pygame.Surface: """every frame a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameOfLife: """simple Cellular Automata - Conways Game of Life""" def __init__(self, dim: tuple, scale=2, density=15): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" self.dim = dim self.scale = scale self.density = density self.wid...
the_stack_v2_python_sparse
effects/GameOfLife.py
gunny26/pygame
train
5
8d2d7c499358b08cea4fd4c350bead222a568644
[ "if type(data) is not np.ndarray:\n raise TypeError('data must be a 2D numpy.ndarray')\nif len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd, n = data.shape\nself.mean = np.mean(data, axis=1).res...
<|body_start_0|> if type(data) is not np.ndarray: raise TypeError('data must be a 2D numpy.ndarray') if len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') if data.shape[1] < 2: raise ValueError('data must contain multiple data points') ...
Multinormal class that represents a Multivariate Normal distribution
MultiNormal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiNormal: """Multinormal class that represents a Multivariate Normal distribution""" def __init__(self, data): """Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is...
stack_v2_sparse_classes_36k_train_002931
2,602
no_license
[ { "docstring": "Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2D numpy.ndarray If n is less than 2, raise a ValueErr...
2
stack_v2_sparse_classes_30k_train_010027
Implement the Python class `MultiNormal` described below. Class description: Multinormal class that represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d ...
Implement the Python class `MultiNormal` described below. Class description: Multinormal class that represents a Multivariate Normal distribution Method signatures and docstrings: - def __init__(self, data): Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d ...
e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58
<|skeleton|> class MultiNormal: """Multinormal class that represents a Multivariate Normal distribution""" def __init__(self, data): """Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiNormal: """Multinormal class that represents a Multivariate Normal distribution""" def __init__(self, data): """Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D num...
the_stack_v2_python_sparse
math/0x06-multivariate_prob/multinormal.py
AndrewMiranda/holbertonschool-machine_learning-1
train
0
0274e7d795b46e40021b4930afbaf1b7a419833a
[ "url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill'\nself.driver.get(url)\nif self.isDispalyed(self.loc12) == True:\n self.click(self.loc12)\nself.click(self.loc1)\nself.clear(self.loc2)\nself.sendKyes(self.loc2, fir...
<|body_start_0|> url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill' self.driver.get(url) if self.isDispalyed(self.loc12) == True: self.click(self.loc12) self.click(self.loc1) ...
分销
Distribuiton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Distribuiton: """分销""" def distributionRule(self, first_Commission, second_Commission): """分销规则设置""" <|body_0|> def is_distrition_rule_sucess(self, _text): """是否添加成功""" <|body_1|> <|end_skeleton|> <|body_start_0|> url = 'http://www.zhichiwangluo...
stack_v2_sparse_classes_36k_train_002932
4,645
no_license
[ { "docstring": "分销规则设置", "name": "distributionRule", "signature": "def distributionRule(self, first_Commission, second_Commission)" }, { "docstring": "是否添加成功", "name": "is_distrition_rule_sucess", "signature": "def is_distrition_rule_sucess(self, _text)" } ]
2
stack_v2_sparse_classes_30k_train_017184
Implement the Python class `Distribuiton` described below. Class description: 分销 Method signatures and docstrings: - def distributionRule(self, first_Commission, second_Commission): 分销规则设置 - def is_distrition_rule_sucess(self, _text): 是否添加成功
Implement the Python class `Distribuiton` described below. Class description: 分销 Method signatures and docstrings: - def distributionRule(self, first_Commission, second_Commission): 分销规则设置 - def is_distrition_rule_sucess(self, _text): 是否添加成功 <|skeleton|> class Distribuiton: """分销""" def distributionRule(sel...
3b441375fade9ebff025054cedee107217fa2e98
<|skeleton|> class Distribuiton: """分销""" def distributionRule(self, first_Commission, second_Commission): """分销规则设置""" <|body_0|> def is_distrition_rule_sucess(self, _text): """是否添加成功""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Distribuiton: """分销""" def distributionRule(self, first_Commission, second_Commission): """分销规则设置""" url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill' self.driver.get(url) if ...
the_stack_v2_python_sparse
pages/distribution.py
srf123/zhichi
train
0
749b586b896d2236c4ef6c81750399b137c37347
[ "super(RBPDecisionMaker, self).__init__(search_context, logger)\nself.__patience = patience\nself.__random = Random()\nself.__random.seed(base_seed + 1024)", "rank = self._search_context.get_current_serp_position()\nrbp_score = self.__patience ** (rank - 1)\ndp = self.__random.random()\nif dp > rbp_score:\n re...
<|body_start_0|> super(RBPDecisionMaker, self).__init__(search_context, logger) self.__patience = patience self.__random = Random() self.__random.seed(base_seed + 1024) <|end_body_0|> <|body_start_1|> rank = self._search_context.get_current_serp_position() rbp_score = se...
An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008).
RBPDecisionMaker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RBPDecisionMaker: """An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008).""" def __init__(self, search_context, logger, patience=0.5, bas...
stack_v2_sparse_classes_36k_train_002933
1,377
permissive
[ { "docstring": "Instantiates the decision maker, with a patience factor (defaulting to 0.5). The patience factor of RBP determines how patient a searcher is. The closer to 1.0, the deeper the searcher will go.", "name": "__init__", "signature": "def __init__(self, search_context, logger, patience=0.5, b...
2
stack_v2_sparse_classes_30k_train_001405
Implement the Python class `RBPDecisionMaker` described below. Class description: An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008). Method signatures and docstr...
Implement the Python class `RBPDecisionMaker` described below. Class description: An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008). Method signatures and docstr...
c6f5b48cc9916c29f109d5ef74876ff8c073a44c
<|skeleton|> class RBPDecisionMaker: """An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008).""" def __init__(self, search_context, logger, patience=0.5, bas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RBPDecisionMaker: """An implementation of Rank-Biased Precision, operationalised as a stopping strategy. Uses a stochastic roll of the dice to determine if a searcher continues or not. Implemented as per Moffat and Zobel (2008).""" def __init__(self, search_context, logger, patience=0.5, base_seed=0): ...
the_stack_v2_python_sparse
simiir/stopping_decision_makers/rbp_decision_maker.py
ArthurCamara/simiir
train
0
b726738dee9448c668c8883b3c63d0cb11912bd1
[ "super().__init__()\nself.capacity = capacity\nself.cache = OrderedDict()", "value = self.cache.pop(key)\nself.cache[key] = value\nreturn value", "try:\n self.cache.pop(key)\nexcept KeyError:\n if len(self.cache) >= self.capacity:\n self.cache.popitem(last=False)\nself.cache[key] = value" ]
<|body_start_0|> super().__init__() self.capacity = capacity self.cache = OrderedDict() <|end_body_0|> <|body_start_1|> value = self.cache.pop(key) self.cache[key] = value return value <|end_body_1|> <|body_start_2|> try: self.cache.pop(key) ...
LRUCache
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity: int=512): """:param capacity: The Maximum number of key-value pairs can be cached.""" <|body_0|> def get(self, key: str) -> Any: """Look up the value in cache using the associated key. Returns the value if found. Raises :class:`...
stack_v2_sparse_classes_36k_train_002934
1,314
permissive
[ { "docstring": ":param capacity: The Maximum number of key-value pairs can be cached.", "name": "__init__", "signature": "def __init__(self, capacity: int=512)" }, { "docstring": "Look up the value in cache using the associated key. Returns the value if found. Raises :class:`KeyError` otherwise....
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity: int=512): :param capacity: The Maximum number of key-value pairs can be cached. - def get(self, key: str) -> Any: Look up the value in cache using th...
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity: int=512): :param capacity: The Maximum number of key-value pairs can be cached. - def get(self, key: str) -> Any: Look up the value in cache using th...
4f11d7596488194fc740936fe987f42864003d41
<|skeleton|> class LRUCache: def __init__(self, capacity: int=512): """:param capacity: The Maximum number of key-value pairs can be cached.""" <|body_0|> def get(self, key: str) -> Any: """Look up the value in cache using the associated key. Returns the value if found. Raises :class:`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity: int=512): """:param capacity: The Maximum number of key-value pairs can be cached.""" super().__init__() self.capacity = capacity self.cache = OrderedDict() def get(self, key: str) -> Any: """Look up the value in cache using t...
the_stack_v2_python_sparse
boxsdk/util/lru_cache.py
box/box-python-sdk
train
424
a16a8cedc3c3950bffc511a7f213b8715110bf6b
[ "if not strs:\n return ''\noutput = []\nfor s in strs:\n if not s:\n output.append('e')\n continue\n line = []\n for c in s:\n line.append(str(ord(c)))\n output.append('|'.join(line))\nreturn '*'.join(output)", "if not s:\n return []\noutput = []\nfor line in s.split('*'):\n...
<|body_start_0|> if not strs: return '' output = [] for s in strs: if not s: output.append('e') continue line = [] for c in s: line.append(str(ord(c))) output.append('|'.join(line)) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_002935
1,352
no_license
[ { "docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str", "name": "encode", "signature": "def encode(self, strs)" }, { "docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]", "name": "decode", "signature": "def ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str - def decode(self, s): Decodes a single string to a list of strings. :type s: st...
ccc3d86000367f809fe34a1b000ec8bbe0506a36
<|skeleton|> class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" <|body_0|> def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str""" if not strs: return '' output = [] for s in strs: if not s: output.append('e') continue line ...
the_stack_v2_python_sparse
strings/codecstring.py
AdsophicSolutions/freecodecamp
train
1
92d64889fbd888a966aa6ba04dddd59272162435
[ "if plan is None:\n plan = self.migration_plan(targets)\nfull_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)\nstate = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)\nself.check_replacements()\nreturn state", "migrations_to_run = {m[0] for m in pl...
<|body_start_0|> if plan is None: plan = self.migration_plan(targets) full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True) state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) self.check_replacements() ...
BackupMigrationExecutor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BackupMigrationExecutor: def migrate(self, targets, plan=None, fake=False, fake_initial=False): """Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations.""" ...
stack_v2_sparse_classes_36k_train_002936
2,168
no_license
[ { "docstring": "Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations.", "name": "migrate", "signature": "def migrate(self, targets, plan=None, fake=False, fake_initial=False)"...
2
stack_v2_sparse_classes_30k_train_020480
Implement the Python class `BackupMigrationExecutor` described below. Class description: Implement the BackupMigrationExecutor class. Method signatures and docstrings: - def migrate(self, targets, plan=None, fake=False, fake_initial=False): Migrates the database up to the given targets. Django first needs to create a...
Implement the Python class `BackupMigrationExecutor` described below. Class description: Implement the BackupMigrationExecutor class. Method signatures and docstrings: - def migrate(self, targets, plan=None, fake=False, fake_initial=False): Migrates the database up to the given targets. Django first needs to create a...
879111874d1ef70418b4890cf970720b0a2be4d8
<|skeleton|> class BackupMigrationExecutor: def migrate(self, targets, plan=None, fake=False, fake_initial=False): """Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BackupMigrationExecutor: def migrate(self, targets, plan=None, fake=False, fake_initial=False): """Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations.""" if plan i...
the_stack_v2_python_sparse
apps/backups/executor.py
faierbol/syncano-platform
train
0
31a76b940b47708ebb4677bb82eae177799cca71
[ "cb = EarlyStopping(2, tolerance=-10)\n'when training is not improveing'\nwith DF_AB_10.model() as m:\n m.fit(SkModel(MLPRegressor([1, 2, 1]), FeaturesAndLabels(['a'], ['b'])), FittingParameter(epochs=50), verbose=1, callbacks=cb)\n'then not all epochs were executed'\nself.assertLess(cb.call_counter, 50)\nself.a...
<|body_start_0|> cb = EarlyStopping(2, tolerance=-10) 'when training is not improveing' with DF_AB_10.model() as m: m.fit(SkModel(MLPRegressor([1, 2, 1]), FeaturesAndLabels(['a'], ['b'])), FittingParameter(epochs=50), verbose=1, callbacks=cb) 'then not all epochs were execute...
TestCallBack
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCallBack: def test_early_stopping(self): """given an early stopping callback""" <|body_0|> def test_confidence(self): """given a confidence interval test callback""" <|body_1|> <|end_skeleton|> <|body_start_0|> cb = EarlyStopping(2, tolerance=-1...
stack_v2_sparse_classes_36k_train_002937
1,962
permissive
[ { "docstring": "given an early stopping callback", "name": "test_early_stopping", "signature": "def test_early_stopping(self)" }, { "docstring": "given a confidence interval test callback", "name": "test_confidence", "signature": "def test_confidence(self)" } ]
2
null
Implement the Python class `TestCallBack` described below. Class description: Implement the TestCallBack class. Method signatures and docstrings: - def test_early_stopping(self): given an early stopping callback - def test_confidence(self): given a confidence interval test callback
Implement the Python class `TestCallBack` described below. Class description: Implement the TestCallBack class. Method signatures and docstrings: - def test_early_stopping(self): given an early stopping callback - def test_confidence(self): given a confidence interval test callback <|skeleton|> class TestCallBack: ...
650a8e8f77bc4d71136518d1c7ee65c194a99cf0
<|skeleton|> class TestCallBack: def test_early_stopping(self): """given an early stopping callback""" <|body_0|> def test_confidence(self): """given a confidence interval test callback""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCallBack: def test_early_stopping(self): """given an early stopping callback""" cb = EarlyStopping(2, tolerance=-10) 'when training is not improveing' with DF_AB_10.model() as m: m.fit(SkModel(MLPRegressor([1, 2, 1]), FeaturesAndLabels(['a'], ['b'])), FittingPar...
the_stack_v2_python_sparse
pandas-ml-utils/pandas_ml_utils_test/ml/model/test_callback.py
jcoffi/pandas-ml-quant
train
0
5f0ff1eaf11698158d404e3a5d1565c841b9709f
[ "result = []\nfor i in range(len(nums)):\n current = nums[i]\n two_sum = self.twoSum_for_3sum(nums, 0 - current, i)\n if two_sum:\n for ts in two_sum:\n ans = sorted([current] + ts)\n if ans not in result:\n result.append(ans)\nreturn sorted(result)", "result =...
<|body_start_0|> result = [] for i in range(len(nums)): current = nums[i] two_sum = self.twoSum_for_3sum(nums, 0 - current, i) if two_sum: for ts in two_sum: ans = sorted([current] + ts) if ans not in result: ...
Solution_A
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_A: def threeSum(self, nums: List[int]) -> List[List[int]]: """Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded""" <|body_0|> def twoSum_for_3sum(self...
stack_v2_sparse_classes_36k_train_002938
8,683
permissive
[ { "docstring": "Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded", "name": "threeSum", "signature": "def threeSum(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "Hel...
2
stack_v2_sparse_classes_30k_train_008116
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def threeSum(self, nums: List[int]) -> List[List[int]]: Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_su...
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def threeSum(self, nums: List[int]) -> List[List[int]]: Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_su...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution_A: def threeSum(self, nums: List[int]) -> List[List[int]]: """Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded""" <|body_0|> def twoSum_for_3sum(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_A: def threeSum(self, nums: List[int]) -> List[List[int]]: """Hstable method from LC001 Use modified method of two_sum (Above) with every number, check the rest of array for two_sum of (0-number) O(N^2), max time limit exceeded""" result = [] for i in range(len(nums)): ...
the_stack_v2_python_sparse
LeetCode/LC015_3sum.py
jxie0755/Learning_Python
train
0
aa6015d69e4779f780c7dbc2e0d8761a79aa4a14
[ "check_required_roles(required_roles, 'code')\nfor rr in required_roles:\n if not isinstance(self, rr):\n return False\nreturn True", "from lino.modlib.users.choicelists import UserTypes\nfor p in UserTypes.items():\n if p.has_required_roles([cls]):\n yield p" ]
<|body_start_0|> check_required_roles(required_roles, 'code') for rr in required_roles: if not isinstance(self, rr): return False return True <|end_body_0|> <|body_start_1|> from lino.modlib.users.choicelists import UserTypes for p in UserTypes.items(...
Base class for all user roles. Even anonymous users have this role.
UserRole
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRole: """Base class for all user roles. Even anonymous users have this role.""" def satisfies_requirement(self, required_roles): """Return `True` if this user role satisfies the specified role requirement. `required_roles` is the set of required roles (class objects). Every item ...
stack_v2_sparse_classes_36k_train_002939
3,271
permissive
[ { "docstring": "Return `True` if this user role satisfies the specified role requirement. `required_roles` is the set of required roles (class objects). Every item is either a class object (subclass of :class:`<UserRole>`) or a tuple thereof. This role (an instance) must satisfy *every* specified requirement.",...
2
stack_v2_sparse_classes_30k_train_005949
Implement the Python class `UserRole` described below. Class description: Base class for all user roles. Even anonymous users have this role. Method signatures and docstrings: - def satisfies_requirement(self, required_roles): Return `True` if this user role satisfies the specified role requirement. `required_roles` ...
Implement the Python class `UserRole` described below. Class description: Base class for all user roles. Even anonymous users have this role. Method signatures and docstrings: - def satisfies_requirement(self, required_roles): Return `True` if this user role satisfies the specified role requirement. `required_roles` ...
64f7ca9c9b83459b5b9f26174e5e3c26a137459d
<|skeleton|> class UserRole: """Base class for all user roles. Even anonymous users have this role.""" def satisfies_requirement(self, required_roles): """Return `True` if this user role satisfies the specified role requirement. `required_roles` is the set of required roles (class objects). Every item ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserRole: """Base class for all user roles. Even anonymous users have this role.""" def satisfies_requirement(self, required_roles): """Return `True` if this user role satisfies the specified role requirement. `required_roles` is the set of required roles (class objects). Every item is either a c...
the_stack_v2_python_sparse
lino/core/roles.py
khchine5/lino
train
1
232800e01be035ed65131ed093c849f42f97c82f
[ "rindex = {c: i for i, c in enumerate(s)}\nresult = ''\nfor i, c in enumerate(s):\n if c not in result:\n while c < result[-1:] and i < rindex[result[-1]]:\n result = result[:-1]\n result += c\nreturn result", "result = ''\nwhile s:\n i = min(map(s.rindex, set(s)))\n c = min(s[:i...
<|body_start_0|> rindex = {c: i for i, c in enumerate(s)} result = '' for i, c in enumerate(s): if c not in result: while c < result[-1:] and i < rindex[result[-1]]: result = result[:-1] result += c return result <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeDuplicateLetters(self, s): """:type s: str :rtype: str beats 82.59%""" <|body_0|> def removeDuplicateLetters1(self, s): """:type s: str :rtype: str beats 70.31%""" <|body_1|> def removeDuplicateLetters2(self, s): """:type s: s...
stack_v2_sparse_classes_36k_train_002940
1,175
no_license
[ { "docstring": ":type s: str :rtype: str beats 82.59%", "name": "removeDuplicateLetters", "signature": "def removeDuplicateLetters(self, s)" }, { "docstring": ":type s: str :rtype: str beats 70.31%", "name": "removeDuplicateLetters1", "signature": "def removeDuplicateLetters1(self, s)" ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicateLetters(self, s): :type s: str :rtype: str beats 82.59% - def removeDuplicateLetters1(self, s): :type s: str :rtype: str beats 70.31% - def removeDuplicateLett...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicateLetters(self, s): :type s: str :rtype: str beats 82.59% - def removeDuplicateLetters1(self, s): :type s: str :rtype: str beats 70.31% - def removeDuplicateLett...
7e0e917c15d3e35f49da3a00ef395bd5ff180d79
<|skeleton|> class Solution: def removeDuplicateLetters(self, s): """:type s: str :rtype: str beats 82.59%""" <|body_0|> def removeDuplicateLetters1(self, s): """:type s: str :rtype: str beats 70.31%""" <|body_1|> def removeDuplicateLetters2(self, s): """:type s: s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeDuplicateLetters(self, s): """:type s: str :rtype: str beats 82.59%""" rindex = {c: i for i, c in enumerate(s)} result = '' for i, c in enumerate(s): if c not in result: while c < result[-1:] and i < rindex[result[-1]]: ...
the_stack_v2_python_sparse
LeetCode/316_remove_duplicate_letters.py
yao23/Machine_Learning_Playground
train
12
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_36k_train_002941
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
null
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_36k
data/stack_v2_sparse_classes_30k
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
65f8d879de2f5b8527549214dbf9e4e3e6e03fec
[ "if n == 0:\n return 1\nif n == 1:\n return 0\ndp = []\ndp.append(1)\ndp.append(0)\nfor i in range(2, n + 1):\n dp.append((i - 1) * (dp[1] + dp[0]) % (10 ** 9 + 7))\n dp.pop(0)\nreturn dp[1]", "ans, a, b = (1, 1, 0)\nfor i in range(2, n):\n ans, a, b = (i * (a + b) % 1000000007, i * (a + b) % 10000...
<|body_start_0|> if n == 0: return 1 if n == 1: return 0 dp = [] dp.append(1) dp.append(0) for i in range(2, n + 1): dp.append((i - 1) * (dp[1] + dp[0]) % (10 ** 9 + 7)) dp.pop(0) return dp[1] <|end_body_0|> <|body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDerangement(self, n): """:type n: int :rtype: int""" <|body_0|> def findDerangement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n == 0: return 1 if n == 1: ...
stack_v2_sparse_classes_36k_train_002942
1,354
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "findDerangement", "signature": "def findDerangement(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "findDerangement2", "signature": "def findDerangement2(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDerangement(self, n): :type n: int :rtype: int - def findDerangement2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDerangement(self, n): :type n: int :rtype: int - def findDerangement2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def findDerangement(self, n): ...
b155895c90169ec97372b2517f556fd50deac2bc
<|skeleton|> class Solution: def findDerangement(self, n): """:type n: int :rtype: int""" <|body_0|> def findDerangement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDerangement(self, n): """:type n: int :rtype: int""" if n == 0: return 1 if n == 1: return 0 dp = [] dp.append(1) dp.append(0) for i in range(2, n + 1): dp.append((i - 1) * (dp[1] + dp[0]) % (10 ** 9 ...
the_stack_v2_python_sparse
derangement.py
claytonjwong/Sandbox-Python
train
0
32498d3315a038fba8a5e6f02cb6513c62f564d5
[ "res = 1\nfor _ in range(k):\n res *= m\n res %= 1337\nreturn res", "if not b or a == 1:\n return 1\na %= 1337\ns1 = self.mypow(a, b[-1])\ns2 = self.mypow(self.superPow(a, b[:-1]), 10)\nreturn s1 * s2" ]
<|body_start_0|> res = 1 for _ in range(k): res *= m res %= 1337 return res <|end_body_0|> <|body_start_1|> if not b or a == 1: return 1 a %= 1337 s1 = self.mypow(a, b[-1]) s2 = self.mypow(self.superPow(a, b[:-1]), 10) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mypow(self, m, k): """求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k""" <|body_0|> def superPow(self, a: int, b: list) -> int: """递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^10""" <|body_1|> <|end_skeleton|> <|body_start_0|> res =...
stack_v2_sparse_classes_36k_train_002943
879
no_license
[ { "docstring": "求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k", "name": "mypow", "signature": "def mypow(self, m, k)" }, { "docstring": "递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^10", "name": "superPow", "signature": "def superPow(self, a: int, b: list) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mypow(self, m, k): 求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k - def superPow(self, a: int, b: list) -> int: 递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^10
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mypow(self, m, k): 求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k - def superPow(self, a: int, b: list) -> int: 递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^10 <|skeleto...
a1e624f0afc24ea5f159fa66fed178aa61bb0179
<|skeleton|> class Solution: def mypow(self, m, k): """求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k""" <|body_0|> def superPow(self, a: int, b: list) -> int: """递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^10""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mypow(self, m, k): """求 m^k 并对 1337 取模 利用: (a * b) % k = ((a % k) * (b % k)) % k""" res = 1 for _ in range(k): res *= m res %= 1337 return res def superPow(self, a: int, b: list) -> int: """递归,利用: a ^ [1,2,3] = a^3 * (a^[1,2])^...
the_stack_v2_python_sparse
LeetCode/372_Super_Pow.py
HappyRocky/pythonAI
train
2
600b474162e535fa590fe388601d73e476261085
[ "super().__init__()\nself.n_patches = int(np.prod([i / patch_size for i in img_size]))\nself.pos_embed = nn.Parameter(torch.zeros(1, self.n_patches, embed_size))\nself.patch_embed = Conv(in_channels=in_feats, out_channels=embed_size, kernel_size=patch_size, stride=patch_size)", "x = self.patch_embed(x)\nx = x.fla...
<|body_start_0|> super().__init__() self.n_patches = int(np.prod([i / patch_size for i in img_size])) self.pos_embed = nn.Parameter(torch.zeros(1, self.n_patches, embed_size)) self.patch_embed = Conv(in_channels=in_feats, out_channels=embed_size, kernel_size=patch_size, stride=patch_size...
_Embedding
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Embedding: def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): """A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided...
stack_v2_sparse_classes_36k_train_002944
24,719
permissive
[ { "docstring": "A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided into. in_feats (int): The number of input channels in the image tensor. embed_size (int): Th...
2
stack_v2_sparse_classes_30k_test_000929
Implement the Python class `_Embedding` described below. Class description: Implement the _Embedding class. Method signatures and docstrings: - def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the inpu...
Implement the Python class `_Embedding` described below. Class description: Implement the _Embedding class. Method signatures and docstrings: - def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the inpu...
72eb99f68205afd5f8d49a3bb6cfc08cfd467582
<|skeleton|> class _Embedding: def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): """A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Embedding: def __init__(self, img_size, patch_size, in_feats, embed_size, Conv): """A module that creates embeddings from an image tensor. Args: img_size (tuple[int]): The size of the input image tensor (H, W, C). patch_size (int): The size of each square patch that the image is divided into. in_feat...
the_stack_v2_python_sparse
GANDLF/models/unetr.py
mlcommons/GaNDLF
train
45
9a1fec6a5f68cf484ebbfd2566c6515dbbe380aa
[ "my_module_path = str_plugin_path\nmy_plugin = str_plugin\ntry:\n my_module = importlib.import_module(my_module_path)\n evaluated_plugin_str = 'my_module.%s' % my_plugin\n my_class = eval(evaluated_plugin_str)\nexcept Exception:\n raise Exception('Failed to evaluate ExecEngine plugin %s.%s' % (str_plugi...
<|body_start_0|> my_module_path = str_plugin_path my_plugin = str_plugin try: my_module = importlib.import_module(my_module_path) evaluated_plugin_str = 'my_module.%s' % my_plugin my_class = eval(evaluated_plugin_str) except Exception: rais...
Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separating steps : initializing algo...
FacadeExecution
[ "LGPL-3.0-only", "LGPL-2.0-or-later", "LGPL-3.0-or-later", "Zlib", "BSD-3-Clause", "Python-2.0", "ZPL-2.0", "LicenseRef-scancode-openssl-exception-lgpl3.0plus", "ZPL-2.1", "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FacadeExecution: """Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( .....
stack_v2_sparse_classes_36k_train_002945
6,584
permissive
[ { "docstring": "private class method evaluate the configured engine from module+plugin :param cls: :type cls: :param str_plugin_path: :type str_plugin_path: :param str_plugin: :type str_plugin: :return: subclass of ExecEngine (!!! not an instance !!!)", "name": "__eval_exec_engine_class", "signature": "...
3
stack_v2_sparse_classes_30k_train_015558
Implement the Python class `FacadeExecution` described below. Class description: Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, ex...
Implement the Python class `FacadeExecution` described below. Class description: Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, ex...
0b04ab448faf1ffdc89687268c6192e69d61f890
<|skeleton|> class FacadeExecution: """Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( .....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FacadeExecution: """Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separa...
the_stack_v2_python_sparse
src/ikats/processing/apps/algo/execute/models/business/facade.py
IKATS/ikats-pybase
train
0
03fda521bbe5e29bb4b667e00ac2bca7a3b8dd5a
[ "if BLOCK_TARGET_MIN <= celsius <= BLOCK_TARGET_MAX:\n return celsius\nraise InvalidTargetTemperatureError(f'Thermocycler block temperature must be between {BLOCK_TARGET_MIN} and {BLOCK_TARGET_MAX}, but got {celsius}.')", "if BLOCK_VOL_MIN <= volume <= BLOCK_VOL_MAX:\n return volume\nraise InvalidBlockVolum...
<|body_start_0|> if BLOCK_TARGET_MIN <= celsius <= BLOCK_TARGET_MAX: return celsius raise InvalidTargetTemperatureError(f'Thermocycler block temperature must be between {BLOCK_TARGET_MIN} and {BLOCK_TARGET_MAX}, but got {celsius}.') <|end_body_0|> <|body_start_1|> if BLOCK_VOL_MIN <...
Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module.
ThermocyclerModuleSubState
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThermocyclerModuleSubState: """Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module.""" def validate_target_block_temperature(celsius: float) -> float: """Validate a given target block temperature. Args: celsius: T...
stack_v2_sparse_classes_36k_train_002946
4,389
permissive
[ { "docstring": "Validate a given target block temperature. Args: celsius: The requested block temperature. Raises: InvalidTargetTemperatureError: The given temperature is outside the thermocycler's operating range. Returns: The validated temperature in degrees Celsius.", "name": "validate_target_block_tempe...
6
stack_v2_sparse_classes_30k_train_008021
Implement the Python class `ThermocyclerModuleSubState` described below. Class description: Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module. Method signatures and docstrings: - def validate_target_block_temperature(celsius: float) -> float: Va...
Implement the Python class `ThermocyclerModuleSubState` described below. Class description: Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module. Method signatures and docstrings: - def validate_target_block_temperature(celsius: float) -> float: Va...
026b523c8c9e5d45910c490efb89194d72595be9
<|skeleton|> class ThermocyclerModuleSubState: """Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module.""" def validate_target_block_temperature(celsius: float) -> float: """Validate a given target block temperature. Args: celsius: T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThermocyclerModuleSubState: """Thermocycler-specific state. Provides calculations and read-only state access for an individual loaded Thermocycler Module.""" def validate_target_block_temperature(celsius: float) -> float: """Validate a given target block temperature. Args: celsius: The requested ...
the_stack_v2_python_sparse
api/src/opentrons/protocol_engine/state/module_substates/thermocycler_module_substate.py
Opentrons/opentrons
train
326
6d749a4f82084b210b4a0b90d11a59ca99d1e67e
[ "if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'):\n return ssh_config['identity']['ssh_key']['label']\nreturn None", "if 'identityfile' not in config:\n return None\nidentityfile = self.choose_ssh_key(config['identityfile'], config)\nif not identityfile:\n return None\ncontent = ident...
<|body_start_0|> if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'): return ssh_config['identity']['ssh_key']['label'] return None <|end_body_0|> <|body_start_1|> if 'identityfile' not in config: return None identityfile = self.choose_ssh_key(con...
Class for adapting app host and ssh config hosts.
SSHConfigHostAdapter
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SSHConfigHostAdapter: """Class for adapting app host and ssh config hosts.""" def get_instance_ssh_key_label(self, ssh_config): """Retrieve the ssh_key lable.""" <|body_0|> def create_key(self, config): """Construct new application ssh key instance.""" <|...
stack_v2_sparse_classes_36k_train_002947
2,943
permissive
[ { "docstring": "Retrieve the ssh_key lable.", "name": "get_instance_ssh_key_label", "signature": "def get_instance_ssh_key_label(self, ssh_config)" }, { "docstring": "Construct new application ssh key instance.", "name": "create_key", "signature": "def create_key(self, config)" }, { ...
5
stack_v2_sparse_classes_30k_test_000928
Implement the Python class `SSHConfigHostAdapter` described below. Class description: Class for adapting app host and ssh config hosts. Method signatures and docstrings: - def get_instance_ssh_key_label(self, ssh_config): Retrieve the ssh_key lable. - def create_key(self, config): Construct new application ssh key in...
Implement the Python class `SSHConfigHostAdapter` described below. Class description: Class for adapting app host and ssh config hosts. Method signatures and docstrings: - def get_instance_ssh_key_label(self, ssh_config): Retrieve the ssh_key lable. - def create_key(self, config): Construct new application ssh key in...
2664d0c70d3d682ad931b885b4965447b156c280
<|skeleton|> class SSHConfigHostAdapter: """Class for adapting app host and ssh config hosts.""" def get_instance_ssh_key_label(self, ssh_config): """Retrieve the ssh_key lable.""" <|body_0|> def create_key(self, config): """Construct new application ssh key instance.""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SSHConfigHostAdapter: """Class for adapting app host and ssh config hosts.""" def get_instance_ssh_key_label(self, ssh_config): """Retrieve the ssh_key lable.""" if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'): return ssh_config['identity']['ssh_key']['labe...
the_stack_v2_python_sparse
termius/porting/providers/ssh/adapter.py
termius/termius-cli
train
262
d50131fd4f3e378cc4ed773a7329192382337942
[ "filename = utils.normalize_paths(filename)[0]\nwith_doctest = self.with_doctest\nincluded_by = [include for include in self.include_in_doctest if include != '' and filename.startswith(include)]\nif included_by:\n with_doctest = True\nfor exclude in self.exclude_from_doctest:\n if exclude != '' and filename.s...
<|body_start_0|> filename = utils.normalize_paths(filename)[0] with_doctest = self.with_doctest included_by = [include for include in self.include_in_doctest if include != '' and filename.startswith(include)] if included_by: with_doctest = True for exclude in self.exc...
Subclass the Pyflakes checker to conform with the flake8 API.
FlakesChecker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlakesChecker: """Subclass the Pyflakes checker to conform with the flake8 API.""" def __init__(self, tree, filename): """Initialize the PyFlakes plugin with an AST tree and filename.""" <|body_0|> def add_options(cls, parser): """Register options for PyFlakes on...
stack_v2_sparse_classes_36k_train_002948
5,661
permissive
[ { "docstring": "Initialize the PyFlakes plugin with an AST tree and filename.", "name": "__init__", "signature": "def __init__(self, tree, filename)" }, { "docstring": "Register options for PyFlakes on the Flake8 OptionManager.", "name": "add_options", "signature": "def add_options(cls, ...
4
stack_v2_sparse_classes_30k_train_015708
Implement the Python class `FlakesChecker` described below. Class description: Subclass the Pyflakes checker to conform with the flake8 API. Method signatures and docstrings: - def __init__(self, tree, filename): Initialize the PyFlakes plugin with an AST tree and filename. - def add_options(cls, parser): Register op...
Implement the Python class `FlakesChecker` described below. Class description: Subclass the Pyflakes checker to conform with the flake8 API. Method signatures and docstrings: - def __init__(self, tree, filename): Initialize the PyFlakes plugin with an AST tree and filename. - def add_options(cls, parser): Register op...
0473ea71751d9086a835c6ae2d34d3bf0b149f4e
<|skeleton|> class FlakesChecker: """Subclass the Pyflakes checker to conform with the flake8 API.""" def __init__(self, tree, filename): """Initialize the PyFlakes plugin with an AST tree and filename.""" <|body_0|> def add_options(cls, parser): """Register options for PyFlakes on...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlakesChecker: """Subclass the Pyflakes checker to conform with the flake8 API.""" def __init__(self, tree, filename): """Initialize the PyFlakes plugin with an AST tree and filename.""" filename = utils.normalize_paths(filename)[0] with_doctest = self.with_doctest include...
the_stack_v2_python_sparse
env/lib/python3.4/site-packages/flake8/plugins/pyflakes.py
tlksio/tlksio
train
1
640aa914aeeec944f37d3092afa50b193b0b17b7
[ "role = Role.get_role_by_id(role_id=role_id)\nif not role:\n raise SystemGlobalException(status_code_message_obj=StatusCodeMessage.ROLE_NOT_EXISTS)\nserializer = RoleListSerializer(role)\nreturn APIResponse(data=serializer.data).get_result()", "role = Role.get_role_by_id(role_id=role_id)\nif not role:\n rai...
<|body_start_0|> role = Role.get_role_by_id(role_id=role_id) if not role: raise SystemGlobalException(status_code_message_obj=StatusCodeMessage.ROLE_NOT_EXISTS) serializer = RoleListSerializer(role) return APIResponse(data=serializer.data).get_result() <|end_body_0|> <|body_...
角色查询,修改,删除APIView
RoleFindPutDelAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoleFindPutDelAPIView: """角色查询,修改,删除APIView""" def get(_, role_id): """角色查询""" <|body_0|> def put(request, role_id): """角色修改""" <|body_1|> def delete(_, role_id): """角色删除""" <|body_2|> <|end_skeleton|> <|body_start_0|> role ...
stack_v2_sparse_classes_36k_train_002949
2,780
no_license
[ { "docstring": "角色查询", "name": "get", "signature": "def get(_, role_id)" }, { "docstring": "角色修改", "name": "put", "signature": "def put(request, role_id)" }, { "docstring": "角色删除", "name": "delete", "signature": "def delete(_, role_id)" } ]
3
stack_v2_sparse_classes_30k_train_013711
Implement the Python class `RoleFindPutDelAPIView` described below. Class description: 角色查询,修改,删除APIView Method signatures and docstrings: - def get(_, role_id): 角色查询 - def put(request, role_id): 角色修改 - def delete(_, role_id): 角色删除
Implement the Python class `RoleFindPutDelAPIView` described below. Class description: 角色查询,修改,删除APIView Method signatures and docstrings: - def get(_, role_id): 角色查询 - def put(request, role_id): 角色修改 - def delete(_, role_id): 角色删除 <|skeleton|> class RoleFindPutDelAPIView: """角色查询,修改,删除APIView""" def get(_,...
bb85b52598d68956bde8756c8321ade7b8479ba7
<|skeleton|> class RoleFindPutDelAPIView: """角色查询,修改,删除APIView""" def get(_, role_id): """角色查询""" <|body_0|> def put(request, role_id): """角色修改""" <|body_1|> def delete(_, role_id): """角色删除""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoleFindPutDelAPIView: """角色查询,修改,删除APIView""" def get(_, role_id): """角色查询""" role = Role.get_role_by_id(role_id=role_id) if not role: raise SystemGlobalException(status_code_message_obj=StatusCodeMessage.ROLE_NOT_EXISTS) serializer = RoleListSerializer(role) ...
the_stack_v2_python_sparse
rbac_v1/v1/rbac_app/views/role/role_views.py
huiiiuh/huihuiproject
train
0
ff9ddca5f5fcae922243d5a07ca737197b28eb38
[ "self.bridgeRotation = None\nself.rotatedLoopLayers = []\nself.sliceDictionary = None\nself.stopProcessing = False\nself.z = 0.0", "for loop in rotatedLoopLayer.loops:\n for pointIndex, point in enumerate(loop):\n loop[pointIndex] = complex(point.real, -point.imag)\ntriangle_mesh.sortLoopsInOrderOfArea(...
<|body_start_0|> self.bridgeRotation = None self.rotatedLoopLayers = [] self.sliceDictionary = None self.stopProcessing = False self.z = 0.0 <|end_body_0|> <|body_start_1|> for loop in rotatedLoopLayer.loops: for pointIndex, point in enumerate(loop): ...
An svg carving.
SVGReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SVGReader: """An svg carving.""" def __init__(self): """Add empty lists.""" <|body_0|> def flipDirectLayer(self, rotatedLoopLayer): """Flip the y coordinate of the layer and direct the loops.""" <|body_1|> def getRotatedLoopLayer(self): """Re...
stack_v2_sparse_classes_36k_train_002950
39,231
no_license
[ { "docstring": "Add empty lists.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Flip the y coordinate of the layer and direct the loops.", "name": "flipDirectLayer", "signature": "def flipDirectLayer(self, rotatedLoopLayer)" }, { "docstring": "Return t...
6
stack_v2_sparse_classes_30k_train_014049
Implement the Python class `SVGReader` described below. Class description: An svg carving. Method signatures and docstrings: - def __init__(self): Add empty lists. - def flipDirectLayer(self, rotatedLoopLayer): Flip the y coordinate of the layer and direct the loops. - def getRotatedLoopLayer(self): Return the rotate...
Implement the Python class `SVGReader` described below. Class description: An svg carving. Method signatures and docstrings: - def __init__(self): Add empty lists. - def flipDirectLayer(self, rotatedLoopLayer): Flip the y coordinate of the layer and direct the loops. - def getRotatedLoopLayer(self): Return the rotate...
c1b00a76f1550df2cbb457248205159e51fd4308
<|skeleton|> class SVGReader: """An svg carving.""" def __init__(self): """Add empty lists.""" <|body_0|> def flipDirectLayer(self, rotatedLoopLayer): """Flip the y coordinate of the layer and direct the loops.""" <|body_1|> def getRotatedLoopLayer(self): """Re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SVGReader: """An svg carving.""" def __init__(self): """Add empty lists.""" self.bridgeRotation = None self.rotatedLoopLayers = [] self.sliceDictionary = None self.stopProcessing = False self.z = 0.0 def flipDirectLayer(self, rotatedLoopLayer): ...
the_stack_v2_python_sparse
fabmetheus_utilities/svg_reader.py
amsler/skeinforge
train
10
913d0fe63d4598c97a7f5bd212341eb3615e320e
[ "self.only_direct = kwargs.get('only_direct', False)\ntry:\n del kwargs['only_direct']\nexcept KeyError:\n pass\nsuper(MUCJabberBot, self).__init__(*args, **kwargs)\nuser, domain = str(self.jid).split('@')\nself.direct_message_re = re.compile('^%s(@%s)?[^\\\\w]? ' % (user, domain))", "message = mess.getBody...
<|body_start_0|> self.only_direct = kwargs.get('only_direct', False) try: del kwargs['only_direct'] except KeyError: pass super(MUCJabberBot, self).__init__(*args, **kwargs) user, domain = str(self.jid).split('@') self.direct_message_re = re.compil...
Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).
MUCJabberBot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MUCJabberBot: """Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).""" def __init__(self, *args, **kwargs): """Initialize variables.""" <|body_0|> def callback_message(self, conn, mess): """Changes the behav...
stack_v2_sparse_classes_36k_train_002951
2,341
no_license
[ { "docstring": "Initialize variables.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Changes the behaviour of the JabberBot in order to allow it to answer direct messages. This is used often when it is connected in MUCs (multiple users chatroom).", ...
2
stack_v2_sparse_classes_30k_train_002501
Implement the Python class `MUCJabberBot` described below. Class description: Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC). Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize variables. - def callback_message(self, conn, mes...
Implement the Python class `MUCJabberBot` described below. Class description: Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC). Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize variables. - def callback_message(self, conn, mes...
1897867f2db96cc24ba76a4cb7ef3a7c373b4289
<|skeleton|> class MUCJabberBot: """Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).""" def __init__(self, *args, **kwargs): """Initialize variables.""" <|body_0|> def callback_message(self, conn, mess): """Changes the behav...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MUCJabberBot: """Add features in JabberBot to allow it to handle specific caractheristics of multiple users chatroom (MUC).""" def __init__(self, *args, **kwargs): """Initialize variables.""" self.only_direct = kwargs.get('only_direct', False) try: del kwargs['only_dir...
the_stack_v2_python_sparse
eve_django/eve_bot/mucbot.py
zhyrohaad/eve-code
train
0
f3037a1d461ece66e5fae87be3335f615c2ece9d
[ "if table_size < 1:\n raise ValueError('table_size must be at least 1.')\nif repetitions < 3:\n raise ValueError('repetitions must be at least 3.')\nif rescale_factor <= 0 or rescale_factor > table_size - 1:\n raise ValueError(f'rescale_factor must be positive and no greater than table_size - 1. Found tabl...
<|body_start_0|> if table_size < 1: raise ValueError('table_size must be at least 1.') if repetitions < 3: raise ValueError('repetitions must be at least 3.') if rescale_factor <= 0 or rescale_factor > table_size - 1: raise ValueError(f'rescale_factor must be ...
Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf.
CoupledHyperEdgeHasher
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoupledHyperEdgeHasher: """Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf.""" def __init__(self, seed: int, table_size: int, repetitions: int, rescale...
stack_v2_sparse_classes_36k_train_002952
10,259
permissive
[ { "docstring": "Initialize CoupledHyperEdgeHasher. Args: seed: An integer seed for hash functions. table_size: The hash table size of the IBLT. Must be a positive integer. repetitions: The number of repetitions in IBLT data structure. Must be at least 3. rescale_factor: A float to rescale `table_size` to `table...
6
stack_v2_sparse_classes_30k_train_007114
Implement the Python class `CoupledHyperEdgeHasher` described below. Class description: Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf. Method signatures and docstrings: - def ...
Implement the Python class `CoupledHyperEdgeHasher` described below. Class description: Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf. Method signatures and docstrings: - def ...
ad4bca66f4b483e09d8396e9948630813a343d27
<|skeleton|> class CoupledHyperEdgeHasher: """Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf.""" def __init__(self, seed: int, table_size: int, repetitions: int, rescale...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CoupledHyperEdgeHasher: """Hashes a string to an hyper-edge with coupled indices. For a string, generates a set of indices such that the indices are close to each as described in https://arxiv.org/pdf/2001.10500.pdf.""" def __init__(self, seed: int, table_size: int, repetitions: int, rescale_factor: floa...
the_stack_v2_python_sparse
tensorflow_federated/python/analytics/heavy_hitters/iblt/hyperedge_hashers.py
tensorflow/federated
train
2,297
1012df63414f91078b958f37ccc2db56e7b0405a
[ "if is_any_instance(value, str, Integral, float):\n return value\nraise TypeError", "if value is None:\n return None\nelif not isinstance(value, str):\n raise TypeError\nelse:\n try:\n return str(value)\n except:\n return value" ]
<|body_start_0|> if is_any_instance(value, str, Integral, float): return value raise TypeError <|end_body_0|> <|body_start_1|> if value is None: return None elif not isinstance(value, str): raise TypeError else: try: ...
通用类型转换类,可以处理 str/unicode/int/float 类型值。
GenericTypeCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GenericTypeCase: """通用类型转换类,可以处理 str/unicode/int/float 类型值。""" def to_redis(value): """接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。""" <|body_0|> def to_python(value): """将传入值转换成 int/long/str/unicode/float 等格式。 因为 redis 只返回字符串值,这个函数也只接受字符串值,否则抛出 TypeError ...
stack_v2_sparse_classes_36k_train_002953
1,235
no_license
[ { "docstring": "接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。", "name": "to_redis", "signature": "def to_redis(value)" }, { "docstring": "将传入值转换成 int/long/str/unicode/float 等格式。 因为 redis 只返回字符串值,这个函数也只接受字符串值,否则抛出 TypeError 。", "name": "to_python", "signature": "def to_python(value)...
2
null
Implement the Python class `GenericTypeCase` described below. Class description: 通用类型转换类,可以处理 str/unicode/int/float 类型值。 Method signatures and docstrings: - def to_redis(value): 接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。 - def to_python(value): 将传入值转换成 int/long/str/unicode/float 等格式。 因为 redis 只返回字符串值,这个函数也只接...
Implement the Python class `GenericTypeCase` described below. Class description: 通用类型转换类,可以处理 str/unicode/int/float 类型值。 Method signatures and docstrings: - def to_redis(value): 接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。 - def to_python(value): 将传入值转换成 int/long/str/unicode/float 等格式。 因为 redis 只返回字符串值,这个函数也只接...
f9fb551afbf47aaca7cdeba8b64a32d2fe3e30d6
<|skeleton|> class GenericTypeCase: """通用类型转换类,可以处理 str/unicode/int/float 类型值。""" def to_redis(value): """接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。""" <|body_0|> def to_python(value): """将传入值转换成 int/long/str/unicode/float 等格式。 因为 redis 只返回字符串值,这个函数也只接受字符串值,否则抛出 TypeError ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GenericTypeCase: """通用类型转换类,可以处理 str/unicode/int/float 类型值。""" def to_redis(value): """接受 int/long/str/unicode/float 类型值, 否则抛出 TypeError 。""" if is_any_instance(value, str, Integral, float): return value raise TypeError def to_python(value): """将传入值转换成 int...
the_stack_v2_python_sparse
mysite/base/ooredis/type_case/generic_type_case.py
RockyLiys/erp
train
1
58ac35541d30e1e96a6a242ea29e29c3f8cba894
[ "super().__init__()\nassert len(transforms_list) > 0, 'Argument transforms_list cannot be empty.'\nassert num_sample_op > 0, 'Need to sample at least one transform.'\nassert num_sample_op <= len(transforms_list), 'Argument num_sample_op cannot be greater than number of available transforms.'\nif transforms_prob is ...
<|body_start_0|> super().__init__() assert len(transforms_list) > 0, 'Argument transforms_list cannot be empty.' assert num_sample_op > 0, 'Need to sample at least one transform.' assert num_sample_op <= len(transforms_list), 'Argument num_sample_op cannot be greater than number of avail...
Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.
OpSampler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, rando...
stack_v2_sparse_classes_36k_train_002954
10,994
permissive
[ { "docstring": "Args: transforms_list (List[Callable]): A list of tuples of all available transforms to sample from. transforms_prob (Optional[List[float]]): The probabilities associated with each transform in transforms_list. If not provided, the sampler assumes a uniform distribution over all transforms. They...
2
stack_v2_sparse_classes_30k_train_015646
Implement the Python class `OpSampler` described below. Class description: Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input. Method signatures and docstrings: - def __init__(self, transforms_list: List[Callable], tran...
Implement the Python class `OpSampler` described below. Class description: Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input. Method signatures and docstrings: - def __init__(self, transforms_list: List[Callable], tran...
16f2abf2f8aa174915316007622bbb260215dee8
<|skeleton|> class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, rando...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, randomly_sample_de...
the_stack_v2_python_sparse
pytorchvideo/transforms/transforms.py
xchani/pytorchvideo
train
0
6e14bf0472e328dbac299c7c80ed27b62685cbd9
[ "if out_frames not in self.VALID_OUT_FRAMES:\n raise ValueError('Invalid number of frames in desired output: %d' % out_frames)\nsuper(Deconv, self).__init__()\nself.deconv_name = deconv_name\nself.out_frames = out_frames\nself.conv3d_1a = nn.Conv3d(in_channels=in_channels, out_channels=256, kernel_size=(3, 3, 3)...
<|body_start_0|> if out_frames not in self.VALID_OUT_FRAMES: raise ValueError('Invalid number of frames in desired output: %d' % out_frames) super(Deconv, self).__init__() self.deconv_name = deconv_name self.out_frames = out_frames self.conv3d_1a = nn.Conv3d(in_channe...
Class representing the Deconvolutional network that is used to estimate the video keypoints.
Deconv
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Deconv: """Class representing the Deconvolutional network that is used to estimate the video keypoints.""" def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): """Initializes the Deconvolutional network. :param in_channels: (int) The number of channels ...
stack_v2_sparse_classes_36k_train_002955
2,862
no_license
[ { "docstring": "Initializes the Deconvolutional network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The number of frames desired in the generated output video. Legal values: 8, 16 :param deconv_name: (str, optional) The name of the network (default 'Deconvolut...
2
stack_v2_sparse_classes_30k_test_000245
Implement the Python class `Deconv` described below. Class description: Class representing the Deconvolutional network that is used to estimate the video keypoints. Method signatures and docstrings: - def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): Initializes the Deconvolutional n...
Implement the Python class `Deconv` described below. Class description: Class representing the Deconvolutional network that is used to estimate the video keypoints. Method signatures and docstrings: - def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): Initializes the Deconvolutional n...
6de28b5a8992f6122f2e9813de8b92d9e97ccbf3
<|skeleton|> class Deconv: """Class representing the Deconvolutional network that is used to estimate the video keypoints.""" def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): """Initializes the Deconvolutional network. :param in_channels: (int) The number of channels ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Deconv: """Class representing the Deconvolutional network that is used to estimate the video keypoints.""" def __init__(self, in_channels, out_frames, deconv_name='Deconvolutional Network'): """Initializes the Deconvolutional network. :param in_channels: (int) The number of channels in the input ...
the_stack_v2_python_sparse
archive/phase1/netWith2828i3dOutput/deconv3.py
schatzkara/REU2019
train
0
0627d2caafcfd47f44e0c6288fc802ec50349495
[ "super().__init__()\nself.dataframe = self.process_data(data_path, file_geometries=file_geometries)\nself.clean_dataframe(sanitize=sanitize)\nif 'positions' not in self.dataframe:\n self.dataframe['positions'] = guess_positions(self.dataframe.molecules, optimize_molecule)\nif properties is not None:\n self.la...
<|body_start_0|> super().__init__() self.dataframe = self.process_data(data_path, file_geometries=file_geometries) self.clean_dataframe(sanitize=sanitize) if 'positions' not in self.dataframe: self.dataframe['positions'] = guess_positions(self.dataframe.molecules, optimize_mo...
Base class for the Data represented as graphs.
SwanGraphData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SwanGraphData: """Base class for the Data represented as graphs.""" def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None: """Generate a dataset u...
stack_v2_sparse_classes_36k_train_002956
2,301
permissive
[ { "docstring": "Generate a dataset using graphs Parameters ---------- data_path path of the csv file properties Labels names sanitize Check that molecules have a valid conformer file_geometries Path to a file with the geometries in PDB format optimize_molecule Perform a molecular optimization using a force fiel...
2
stack_v2_sparse_classes_30k_train_000837
Implement the Python class `SwanGraphData` described below. Class description: Base class for the Data represented as graphs. Method signatures and docstrings: - def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, opt...
Implement the Python class `SwanGraphData` described below. Class description: Base class for the Data represented as graphs. Method signatures and docstrings: - def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, opt...
4edc9dc363ce901b1fcc19444bec42fc5930c4b9
<|skeleton|> class SwanGraphData: """Base class for the Data represented as graphs.""" def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None: """Generate a dataset u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SwanGraphData: """Base class for the Data represented as graphs.""" def __init__(self, data_path: PathLike, properties: Optional[Union[str, List[str]]]=None, sanitize: bool=True, file_geometries: Optional[PathLike]=None, optimize_molecule: bool=False) -> None: """Generate a dataset using graphs P...
the_stack_v2_python_sparse
swan/dataset/data_graph_base.py
nlesc-nano/swan
train
15
60cfdbe48aae286d02fda3f6c3359b1a9d9a7663
[ "data = self.get_initial()\npassword1 = value\npassword2 = data.get('new_password2')\nif password1 != password2:\n raise serializers.ValidationError('The two Passwords must match.')\nreturn value", "try:\n password = data.get('new_password1')\n token = data.get('token')\n uidb64 = data.get('uidb64')\n...
<|body_start_0|> data = self.get_initial() password1 = value password2 = data.get('new_password2') if password1 != password2: raise serializers.ValidationError('The two Passwords must match.') return value <|end_body_0|> <|body_start_1|> try: pass...
Password reset serializer.
PasswordResetSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordResetSerializer: """Password reset serializer.""" def validate_new_password1(self, value): """Validate passwords.""" <|body_0|> def validate(self, data): """Validate entered data.""" <|body_1|> <|end_skeleton|> <|body_start_0|> data = se...
stack_v2_sparse_classes_36k_train_002957
9,392
no_license
[ { "docstring": "Validate passwords.", "name": "validate_new_password1", "signature": "def validate_new_password1(self, value)" }, { "docstring": "Validate entered data.", "name": "validate", "signature": "def validate(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_006871
Implement the Python class `PasswordResetSerializer` described below. Class description: Password reset serializer. Method signatures and docstrings: - def validate_new_password1(self, value): Validate passwords. - def validate(self, data): Validate entered data.
Implement the Python class `PasswordResetSerializer` described below. Class description: Password reset serializer. Method signatures and docstrings: - def validate_new_password1(self, value): Validate passwords. - def validate(self, data): Validate entered data. <|skeleton|> class PasswordResetSerializer: """Pa...
6c2e8bc6b0a172ff34d0f3191dfdebbd85584525
<|skeleton|> class PasswordResetSerializer: """Password reset serializer.""" def validate_new_password1(self, value): """Validate passwords.""" <|body_0|> def validate(self, data): """Validate entered data.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PasswordResetSerializer: """Password reset serializer.""" def validate_new_password1(self, value): """Validate passwords.""" data = self.get_initial() password1 = value password2 = data.get('new_password2') if password1 != password2: raise serializers.V...
the_stack_v2_python_sparse
accounts/serializers.py
OmarFateh/api-ecommerce
train
1
8b65721c96a813cd8ed57b5ebfb86526a81fdfb0
[ "self.grid_size = Vector2(config.get('GRID_SIZE'))\nself.pixel_count = globals.mapping_data.pixel_count\nsize = self.pixel_count * 4\nself.data = bytearray(size)\nself.clear_data()\nself.spi_index = 0\nself.updated = None\nself.packet_length = 0\nself._dirty = True\nself._signal_startrecv = blinker.signal('stripdat...
<|body_start_0|> self.grid_size = Vector2(config.get('GRID_SIZE')) self.pixel_count = globals.mapping_data.pixel_count size = self.pixel_count * 4 self.data = bytearray(size) self.clear_data() self.spi_index = 0 self.updated = None self.packet_length = 0 ...
StripData
[ "OFL-1.1", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StripData: def __init__(self): """Data model of a strip of LED's and also handles processes received data packets. :return:""" <|body_0|> def spi_recv(self, msg): """Currently no checking of msg integrity or first four bytes being 0x00 is done. Msg is assumed to be c...
stack_v2_sparse_classes_36k_train_002958
4,170
permissive
[ { "docstring": "Data model of a strip of LED's and also handles processes received data packets. :return:", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Currently no checking of msg integrity or first four bytes being 0x00 is done. Msg is assumed to be correct. Future...
6
stack_v2_sparse_classes_30k_train_009043
Implement the Python class `StripData` described below. Class description: Implement the StripData class. Method signatures and docstrings: - def __init__(self): Data model of a strip of LED's and also handles processes received data packets. :return: - def spi_recv(self, msg): Currently no checking of msg integrity ...
Implement the Python class `StripData` described below. Class description: Implement the StripData class. Method signatures and docstrings: - def __init__(self): Data model of a strip of LED's and also handles processes received data packets. :return: - def spi_recv(self, msg): Currently no checking of msg integrity ...
9302ca1ae8c5089c9f2ce4ba471e6b4649609c5c
<|skeleton|> class StripData: def __init__(self): """Data model of a strip of LED's and also handles processes received data packets. :return:""" <|body_0|> def spi_recv(self, msg): """Currently no checking of msg integrity or first four bytes being 0x00 is done. Msg is assumed to be c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StripData: def __init__(self): """Data model of a strip of LED's and also handles processes received data packets. :return:""" self.grid_size = Vector2(config.get('GRID_SIZE')) self.pixel_count = globals.mapping_data.pixel_count size = self.pixel_count * 4 self.data = b...
the_stack_v2_python_sparse
DotStar_Emulator/emulator/data/strip_data.py
nicofirst1/DotStar_Emulator
train
1
d17b0ac3ac62cf0d442ec7efab84c5548c61e747
[ "wallet_query = wallets.select().where(wallets.c.id == wallet_id)\nwallet = await self._db.fetch_one(wallet_query)\nif wallet:\n return WalletEntity(**wallet)\nreturn None", "wallet_query = wallets.select().where(wallets.c.user_id == user_id)\nwallet = await self._db.fetch_one(wallet_query)\nif wallet:\n re...
<|body_start_0|> wallet_query = wallets.select().where(wallets.c.id == wallet_id) wallet = await self._db.fetch_one(wallet_query) if wallet: return WalletEntity(**wallet) return None <|end_body_0|> <|body_start_1|> wallet_query = wallets.select().where(wallets.c.user...
Implementation of wallet repository.
WalletRepository
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WalletRepository: """Implementation of wallet repository.""" async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: """Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema""" <|body_0|> async def get_by_user_id(self, user...
stack_v2_sparse_classes_36k_train_002959
4,539
no_license
[ { "docstring": "Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema", "name": "get_by_id", "signature": "async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]" }, { "docstring": "Retrieve wallet record by user id. :param user_id: ID of use :retu...
5
stack_v2_sparse_classes_30k_train_021228
Implement the Python class `WalletRepository` described below. Class description: Implementation of wallet repository. Method signatures and docstrings: - async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema - asy...
Implement the Python class `WalletRepository` described below. Class description: Implementation of wallet repository. Method signatures and docstrings: - async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema - asy...
4cd339bdbe9ca1ac9ab01849dcd43c81e068488d
<|skeleton|> class WalletRepository: """Implementation of wallet repository.""" async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: """Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema""" <|body_0|> async def get_by_user_id(self, user...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WalletRepository: """Implementation of wallet repository.""" async def get_by_id(self, wallet_id: int) -> Optional[WalletEntity]: """Retrieve wallet record by wallet id. :param wallet_id: ID of use :returns: Wallet schema""" wallet_query = wallets.select().where(wallets.c.id == wallet_id)...
the_stack_v2_python_sparse
app/repositories/wallet.py
vsokoltsov/billing_system_test_task
train
0
02ca29ae508ea1fcd2935150a9170381a800aff2
[ "super(Critic, self).__init__()\nself.critic1 = tf.keras.Sequential([tf.keras.layers.Dense(256, input_shape=(state_dim + action_dim,), activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(256, activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(1, kernel_initiali...
<|body_start_0|> super(Critic, self).__init__() self.critic1 = tf.keras.Sequential([tf.keras.layers.Dense(256, input_shape=(state_dim + action_dim,), activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.layers.Dense(256, activation=tf.nn.relu, kernel_initializer='orthogonal'), tf.keras.laye...
A critic network that estimates a dual Q-function.
Critic
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Critic: """A critic network that estimates a dual Q-function.""" def __init__(self, state_dim, action_dim): """Creates networks. Args: state_dim: State size. action_dim: Action size.""" <|body_0|> def call(self, states, actions): """Returns Q-value estimates for ...
stack_v2_sparse_classes_36k_train_002960
13,412
permissive
[ { "docstring": "Creates networks. Args: state_dim: State size. action_dim: Action size.", "name": "__init__", "signature": "def __init__(self, state_dim, action_dim)" }, { "docstring": "Returns Q-value estimates for given states and actions. Args: states: A batch of states. actions: A batch of a...
2
stack_v2_sparse_classes_30k_train_011265
Implement the Python class `Critic` described below. Class description: A critic network that estimates a dual Q-function. Method signatures and docstrings: - def __init__(self, state_dim, action_dim): Creates networks. Args: state_dim: State size. action_dim: Action size. - def call(self, states, actions): Returns Q...
Implement the Python class `Critic` described below. Class description: A critic network that estimates a dual Q-function. Method signatures and docstrings: - def __init__(self, state_dim, action_dim): Creates networks. Args: state_dim: State size. action_dim: Action size. - def call(self, states, actions): Returns Q...
727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7
<|skeleton|> class Critic: """A critic network that estimates a dual Q-function.""" def __init__(self, state_dim, action_dim): """Creates networks. Args: state_dim: State size. action_dim: Action size.""" <|body_0|> def call(self, states, actions): """Returns Q-value estimates for ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Critic: """A critic network that estimates a dual Q-function.""" def __init__(self, state_dim, action_dim): """Creates networks. Args: state_dim: State size. action_dim: Action size.""" super(Critic, self).__init__() self.critic1 = tf.keras.Sequential([tf.keras.layers.Dense(256, i...
the_stack_v2_python_sparse
value_dice/twin_sac.py
Ayoob7/google-research
train
2
c47418b0559807e90f5df83f59e0413944bf4a20
[ "base_url = case.get_full_base_url()\nkwargs = case.as_requests_kwargs(base_url)\nrequest = requests.Request(**kwargs)\nprepared = session.prepare_request(request)\nreturn cls.from_prepared_request(prepared)", "body = prepared.body or b''\nif isinstance(body, str):\n body = body.encode('utf-8')\nuri = cast(str...
<|body_start_0|> base_url = case.get_full_base_url() kwargs = case.as_requests_kwargs(base_url) request = requests.Request(**kwargs) prepared = session.prepare_request(request) return cls.from_prepared_request(prepared) <|end_body_0|> <|body_start_1|> body = prepared.bod...
Request data extracted from `Case`.
Request
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Request: """Request data extracted from `Case`.""" def from_case(cls, case: Case, session: requests.Session) -> 'Request': """Create a new `Request` instance from `Case`.""" <|body_0|> def from_prepared_request(cls, prepared: requests.PreparedRequest) -> 'Request': ...
stack_v2_sparse_classes_36k_train_002961
32,203
permissive
[ { "docstring": "Create a new `Request` instance from `Case`.", "name": "from_case", "signature": "def from_case(cls, case: Case, session: requests.Session) -> 'Request'" }, { "docstring": "A prepared request version is already stored in `requests.Response`.", "name": "from_prepared_request",...
2
stack_v2_sparse_classes_30k_train_018630
Implement the Python class `Request` described below. Class description: Request data extracted from `Case`. Method signatures and docstrings: - def from_case(cls, case: Case, session: requests.Session) -> 'Request': Create a new `Request` instance from `Case`. - def from_prepared_request(cls, prepared: requests.Prep...
Implement the Python class `Request` described below. Class description: Request data extracted from `Case`. Method signatures and docstrings: - def from_case(cls, case: Case, session: requests.Session) -> 'Request': Create a new `Request` instance from `Case`. - def from_prepared_request(cls, prepared: requests.Prep...
9ba2244bf0e52db6f149243de403c8c7c157216f
<|skeleton|> class Request: """Request data extracted from `Case`.""" def from_case(cls, case: Case, session: requests.Session) -> 'Request': """Create a new `Request` instance from `Case`.""" <|body_0|> def from_prepared_request(cls, prepared: requests.PreparedRequest) -> 'Request': ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Request: """Request data extracted from `Case`.""" def from_case(cls, case: Case, session: requests.Session) -> 'Request': """Create a new `Request` instance from `Case`.""" base_url = case.get_full_base_url() kwargs = case.as_requests_kwargs(base_url) request = requests.R...
the_stack_v2_python_sparse
schemathesis/models.py
ngalongc/openapi_security_scanner
train
167
c1c03a353afa75881332d04cfbc335811935317c
[ "flowerbed = [1, 0] + flowerbed + [0, 1]\ncur = 0\nresult = 0\nfor flower in flowerbed:\n if flower == 0:\n cur += 1\n else:\n result += int((cur - 1) / 2)\n cur = 0\nreturn result >= n", "s = ('10' + ''.join([str(x) for x in flowerbed]) + '01').split('1')\nprint(s)\nresult = 0\nfor x i...
<|body_start_0|> flowerbed = [1, 0] + flowerbed + [0, 1] cur = 0 result = 0 for flower in flowerbed: if flower == 0: cur += 1 else: result += int((cur - 1) / 2) cur = 0 return result >= n <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPlaceFlowers(self, flowerbed, n): """:type flowerbed: List[int] :type n: int :rtype: bool""" <|body_0|> def canPlaceFlowers1(self, flowerbed, n): """:type flowerbed: List[int] :type n: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_002962
1,040
no_license
[ { "docstring": ":type flowerbed: List[int] :type n: int :rtype: bool", "name": "canPlaceFlowers", "signature": "def canPlaceFlowers(self, flowerbed, n)" }, { "docstring": ":type flowerbed: List[int] :type n: int :rtype: bool", "name": "canPlaceFlowers1", "signature": "def canPlaceFlowers...
2
stack_v2_sparse_classes_30k_train_018319
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool - def canPlaceFlowers1(self, flowerbed, n): :type flowerbed: List[int] :type n: int ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool - def canPlaceFlowers1(self, flowerbed, n): :type flowerbed: List[int] :type n: int ...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def canPlaceFlowers(self, flowerbed, n): """:type flowerbed: List[int] :type n: int :rtype: bool""" <|body_0|> def canPlaceFlowers1(self, flowerbed, n): """:type flowerbed: List[int] :type n: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPlaceFlowers(self, flowerbed, n): """:type flowerbed: List[int] :type n: int :rtype: bool""" flowerbed = [1, 0] + flowerbed + [0, 1] cur = 0 result = 0 for flower in flowerbed: if flower == 0: cur += 1 else: ...
the_stack_v2_python_sparse
python/leetcode/605_Can_Place_Flowers.py
bobcaoge/my-code
train
0
cc7cf4c7058db216aa09c6ebbd7fc7632a939ed3
[ "if not nums:\n return\ncounter = {}\nfor i in nums:\n if not counter.get(i, None):\n counter[i] = 1\n else:\n return i\nreturn", "l, r = (0, len(nums) - 1)\nwhile l < r:\n m = (l + r) // 2\n if sum([i <= m for i in nums]) > m:\n r = m\n else:\n l = m + 1\nreturn l" ]
<|body_start_0|> if not nums: return counter = {} for i in nums: if not counter.get(i, None): counter[i] = 1 else: return i return <|end_body_0|> <|body_start_1|> l, r = (0, len(nums) - 1) while l < r: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/72912/Python-solution-with-detaile...
stack_v2_sparse_classes_36k_train_002963
2,067
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findDuplicate", "signature": "def findDuplicate(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/72912/Python-solution-with-detailed-explanation ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int discuss: https://leetcode.com/problems/find-th...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums): :type nums: List[int] :rtype: int - def findDuplicate(self, nums): :type nums: List[int] :rtype: int discuss: https://leetcode.com/problems/find-th...
673e51199a2d07198894a283479d459bef0272c5
<|skeleton|> class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findDuplicate(self, nums): """:type nums: List[int] :rtype: int discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/72912/Python-solution-with-detaile...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findDuplicate(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return counter = {} for i in nums: if not counter.get(i, None): counter[i] = 1 else: return i return de...
the_stack_v2_python_sparse
binary_search_medium/1219_find_the_duplicate_number.py
myungwooko/algorithm
train
1
0bbeb7d60c7634768afe97dc21b55acca44fd6ba
[ "self.size = capacity\nself.lru_hashmap = {}\nself.dll = DLL()", "if key not in self.lru_hashmap:\n return -1\nnode = self.lru_hashmap[key]\nvalue = node.value\nself.dll.delete_node(node)\nnode = self.dll.appned_node_at_front(key, value)\nself.lru_hashmap[key] = node\nreturn value", "if key in self.lru_hashm...
<|body_start_0|> self.size = capacity self.lru_hashmap = {} self.dll = DLL() <|end_body_0|> <|body_start_1|> if key not in self.lru_hashmap: return -1 node = self.lru_hashmap[key] value = node.value self.dll.delete_node(node) node = self.dll.a...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_002964
4,210
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
1211eac167f33084f536007468ea10c1a0ceab08
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.size = capacity self.lru_hashmap = {} self.dll = DLL() def get(self, key): """:type key: int :rtype: int""" if key not in self.lru_hashmap: return -1 node = self.lru_...
the_stack_v2_python_sparse
146_LRUCache.py
renukadeshmukh/Leetcode_Solutions
train
3
2f0cfa672d6a1069d0647c0dd3593ccaa8527330
[ "self.SetTitle('This is an example Dialog')\nself.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)\nreturn True", "if messageId == c4d.DLG_OK:\n print('User Click on Ok')\n return True\nelif messageId == c4d.DLG_CANCEL:\n print('User Click on Cancel')\n self.Close()\n return True\nreturn True" ]
<|body_start_0|> self.SetTitle('This is an example Dialog') self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) return True <|end_body_0|> <|body_start_1|> if messageId == c4d.DLG_OK: print('User Click on Ok') return True elif messageId == c4d.DLG_CANCEL: ...
ExampleDialog
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.""" <|body_0|> def Command(self, messageId, bc): """This Method is called automat...
stack_v2_sparse_classes_36k_train_002965
7,074
permissive
[ { "docstring": "This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.", "name": "CreateLayout", "signature": "def CreateLayout(self)" }, { "docstring": "This Method is called automatically when the user cl...
2
stack_v2_sparse_classes_30k_train_007920
Implement the Python class `ExampleDialog` described below. Class description: Implement the ExampleDialog class. Method signatures and docstrings: - def CreateLayout(self): This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True....
Implement the Python class `ExampleDialog` described below. Class description: Implement the ExampleDialog class. Method signatures and docstrings: - def CreateLayout(self): This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True....
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.""" <|body_0|> def Command(self, messageId, bc): """This Method is called automat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D creates the Layout of the Dialog. Returns: bool: False if there was an error, otherwise True.""" self.SetTitle('This is an example Dialog') self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) ...
the_stack_v2_python_sparse
plugins/py-ies_meta_r12/py-ies-meta_loader.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
aeaed8de414b3a6dc826524e7d24600dbfc657d0
[ "range = max(nums) + 1\ncounts = [0] * range\nfor num in nums:\n counts[num] += 1\nidx = 0\nfor i, count in enumerate(counts):\n while count > 0:\n nums[idx] = i\n idx += 1\n count -= 1", "def swap(a, i, j):\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\nzero_idx = 0\nfor i...
<|body_start_0|> range = max(nums) + 1 counts = [0] * range for num in nums: counts[num] += 1 idx = 0 for i, count in enumerate(counts): while count > 0: nums[idx] = i idx += 1 count -= 1 <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortColors(self, nums): """This is a simple counting sort solution for the problem""" <|body_0|> def sort_colors_2(self, arr): """Second approach. Two pass still. Shift all zeros to beginning of the list in one scan. Shift all ones in second scan.""" ...
stack_v2_sparse_classes_36k_train_002966
3,103
no_license
[ { "docstring": "This is a simple counting sort solution for the problem", "name": "sortColors", "signature": "def sortColors(self, nums)" }, { "docstring": "Second approach. Two pass still. Shift all zeros to beginning of the list in one scan. Shift all ones in second scan.", "name": "sort_c...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums): This is a simple counting sort solution for the problem - def sort_colors_2(self, arr): Second approach. Two pass still. Shift all zeros to beginning ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums): This is a simple counting sort solution for the problem - def sort_colors_2(self, arr): Second approach. Two pass still. Shift all zeros to beginning ...
8da310a8bbaf5369be2448e8de72d28eed1a5410
<|skeleton|> class Solution: def sortColors(self, nums): """This is a simple counting sort solution for the problem""" <|body_0|> def sort_colors_2(self, arr): """Second approach. Two pass still. Shift all zeros to beginning of the list in one scan. Shift all ones in second scan.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def sortColors(self, nums): """This is a simple counting sort solution for the problem""" range = max(nums) + 1 counts = [0] * range for num in nums: counts[num] += 1 idx = 0 for i, count in enumerate(counts): while count > 0: ...
the_stack_v2_python_sparse
leetcode/75_sort_colors.py
varunkudva/Programming
train
0
2e6c8a09c9640b5f7aa0c6933f1c02fcf95bcd69
[ "self._cmd = cmd\nself._preexec_fn = preexec_fn\nself._timeout_secs = timeout_secs", "try:\n subprocess.check_call(self._cmd, timeout=self._timeout_secs, shell=True, preexec_fn=self._preexec_fn)\n return (True, None)\nexcept subprocess.CalledProcessError as reason:\n return (False, str(reason))\nexcept s...
<|body_start_0|> self._cmd = cmd self._preexec_fn = preexec_fn self._timeout_secs = timeout_secs <|end_body_0|> <|body_start_1|> try: subprocess.check_call(self._cmd, timeout=self._timeout_secs, shell=True, preexec_fn=self._preexec_fn) return (True, None) ...
ShellHealthCheck
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShellHealthCheck: def __init__(self, cmd, preexec_fn=None, timeout_secs=None): """Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the c...
stack_v2_sparse_classes_36k_train_002967
2,179
permissive
[ { "docstring": "Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the child shell process is executed. :type preexec_fn: callable :param timeout_secs: Timeout in...
2
stack_v2_sparse_classes_30k_train_000081
Implement the Python class `ShellHealthCheck` described below. Class description: Implement the ShellHealthCheck class. Method signatures and docstrings: - def __init__(self, cmd, preexec_fn=None, timeout_secs=None): Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected t...
Implement the Python class `ShellHealthCheck` described below. Class description: Implement the ShellHealthCheck class. Method signatures and docstrings: - def __init__(self, cmd, preexec_fn=None, timeout_secs=None): Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected t...
88dddb51ed9ad070340edb33eef9fd12745b9f8a
<|skeleton|> class ShellHealthCheck: def __init__(self, cmd, preexec_fn=None, timeout_secs=None): """Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ShellHealthCheck: def __init__(self, cmd, preexec_fn=None, timeout_secs=None): """Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the child shell pro...
the_stack_v2_python_sparse
Chapter4/Aurora/src/main/python/apache/aurora/common/health_check/shell.py
PacktPublishing/Mastering-Mesos
train
12
bf5c591488cc48dc66f8e75f8670472dada4dbf4
[ "node_list = response.xpath(\"//tr[@class='even'] | //tr[@class='odd']\")\nfor node in node_list:\n item = TenmultiItem()\n item['position_name'] = node.xpath('./td[1]/a/text()').extract_first()\n item['position_link'] = 'https://hr.tencent.com/' + node.xpath('./td[1]/a/@href').extract_first()\n item['p...
<|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TenmultiItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() item['position_link'] = 'https://hr.tencent.com/' + node.xpath('...
TencMultiGradeSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TencMultiGradeSpider: def parse(self, response): """列表页解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|> <|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") ...
stack_v2_sparse_classes_36k_train_002968
2,257
no_license
[ { "docstring": "列表页解析方法", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "解析详情页的响应内容", "name": "parse_detail", "signature": "def parse_detail(self, response)" } ]
2
null
Implement the Python class `TencMultiGradeSpider` described below. Class description: Implement the TencMultiGradeSpider class. Method signatures and docstrings: - def parse(self, response): 列表页解析方法 - def parse_detail(self, response): 解析详情页的响应内容
Implement the Python class `TencMultiGradeSpider` described below. Class description: Implement the TencMultiGradeSpider class. Method signatures and docstrings: - def parse(self, response): 列表页解析方法 - def parse_detail(self, response): 解析详情页的响应内容 <|skeleton|> class TencMultiGradeSpider: def parse(self, response)...
298869fa9fb0291b9e364fbf4a6d8bd992840eb2
<|skeleton|> class TencMultiGradeSpider: def parse(self, response): """列表页解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TencMultiGradeSpider: def parse(self, response): """列表页解析方法""" node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TenmultiItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() ...
the_stack_v2_python_sparse
Scrapy/Tenc/TenMulti/TenMulti/spiders/tenc_multi_grade.py
AssassinHotstrip/personal_spider_pra
train
0
2abbdba1ee0368edab09cc38e7b874c08a189183
[ "self.sess = sess\nself.name_map = {v.name: v for v in vars_to_update}\nself.ignore_mismatch = ignore_mismatch", "assert isinstance(var, tf.Variable)\nname = var.op.name\nvarshape = tuple(var.get_shape().as_list())\nif varshape != value.shape:\n if np.prod(varshape) != np.prod(value.shape):\n if ignore_...
<|body_start_0|> self.sess = sess self.name_map = {v.name: v for v in vars_to_update} self.ignore_mismatch = ignore_mismatch <|end_body_0|> <|body_start_1|> assert isinstance(var, tf.Variable) name = var.op.name varshape = tuple(var.get_shape().as_list()) if vars...
Update the variables in a session
SessionUpdate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionUpdate: """Update the variables in a session""" def __init__(self, sess, vars_to_update, ignore_mismatch=False): """Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mismatch (bool): ignore failures when the value and the vari...
stack_v2_sparse_classes_36k_train_002969
10,466
permissive
[ { "docstring": "Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mismatch (bool): ignore failures when the value and the variable does not match.", "name": "__init__", "signature": "def __init__(self, sess, vars_to_update, ignore_mismatch=False)" }, ...
3
null
Implement the Python class `SessionUpdate` described below. Class description: Update the variables in a session Method signatures and docstrings: - def __init__(self, sess, vars_to_update, ignore_mismatch=False): Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mis...
Implement the Python class `SessionUpdate` described below. Class description: Update the variables in a session Method signatures and docstrings: - def __init__(self, sess, vars_to_update, ignore_mismatch=False): Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mis...
1547a54e8546494614ca31c984a1bfd1d0e24b77
<|skeleton|> class SessionUpdate: """Update the variables in a session""" def __init__(self, sess, vars_to_update, ignore_mismatch=False): """Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mismatch (bool): ignore failures when the value and the vari...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionUpdate: """Update the variables in a session""" def __init__(self, sess, vars_to_update, ignore_mismatch=False): """Args: sess (tf.Session): a session object vars_to_update: a collection of variables to update ignore_mismatch (bool): ignore failures when the value and the variable does not...
the_stack_v2_python_sparse
tensorpack/tfutils/varmanip.py
tensorpack/tensorpack
train
4,600
e42462dd0a4417d7d473fe26708c502fd5b28a28
[ "self.ontology_file_path = path\nself.ontology = self.load_ontology()\nself.agent_requestable = self.ontology['system_requestable']\nself.user_requestable = self.ontology['user_requestable']\nself.slots_not_required_NLU = self.ontology['slots_not_required_NLU']\nself.slots_annotation = self.ontology['slots_annotati...
<|body_start_0|> self.ontology_file_path = path self.ontology = self.load_ontology() self.agent_requestable = self.ontology['system_requestable'] self.user_requestable = self.ontology['user_requestable'] self.slots_not_required_NLU = self.ontology['slots_not_required_NLU'] ...
Ontology is a class that loads ontology files (in .json format) into IAI MovieBot.
Ontology
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ontology: """Ontology is a class that loads ontology files (in .json format) into IAI MovieBot.""" def __init__(self, path): """Initializes the internal structures of the Domain Args: path: path to load the ontology from""" <|body_0|> def load_ontology(self): """...
stack_v2_sparse_classes_36k_train_002970
1,114
permissive
[ { "docstring": "Initializes the internal structures of the Domain Args: path: path to load the ontology from", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": "Loads the ontology file Returns: nothing", "name": "load_ontology", "signature": "def load_ontolog...
2
stack_v2_sparse_classes_30k_train_009077
Implement the Python class `Ontology` described below. Class description: Ontology is a class that loads ontology files (in .json format) into IAI MovieBot. Method signatures and docstrings: - def __init__(self, path): Initializes the internal structures of the Domain Args: path: path to load the ontology from - def ...
Implement the Python class `Ontology` described below. Class description: Ontology is a class that loads ontology files (in .json format) into IAI MovieBot. Method signatures and docstrings: - def __init__(self, path): Initializes the internal structures of the Domain Args: path: path to load the ontology from - def ...
172966ba2b90e22037b17467d69068dad5e26b09
<|skeleton|> class Ontology: """Ontology is a class that loads ontology files (in .json format) into IAI MovieBot.""" def __init__(self, path): """Initializes the internal structures of the Domain Args: path: path to load the ontology from""" <|body_0|> def load_ontology(self): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ontology: """Ontology is a class that loads ontology files (in .json format) into IAI MovieBot.""" def __init__(self, path): """Initializes the internal structures of the Domain Args: path: path to load the ontology from""" self.ontology_file_path = path self.ontology = self.load_...
the_stack_v2_python_sparse
moviebot/ontology/ontology.py
fseimb/moviebot-1
train
0
3a6aeef4edcd56416e6a73d27400accceaefdef3
[ "chart = pygal.Bar()\nword_counter_list = Counter(word_cut_list).most_common(topk)\nx_labels = [word[0] for word in word_counter_list]\ny_values = [{'value': word[1], 'color': color} for word in word_counter_list]\nchart.title = title\nchart.x_labels = map(str, x_labels)\nchart.add('频次', y_values)\nchart.render_to_...
<|body_start_0|> chart = pygal.Bar() word_counter_list = Counter(word_cut_list).most_common(topk) x_labels = [word[0] for word in word_counter_list] y_values = [{'value': word[1], 'color': color} for word in word_counter_list] chart.title = title chart.x_labels = map(str,...
Chart
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chart: def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green'): """高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_chart_images')""" <|body_0|> def chart_word_positive(cls, app=None, word_positive_li...
stack_v2_sparse_classes_36k_train_002971
6,157
no_license
[ { "docstring": "高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_chart_images')", "name": "chart_word_frequency", "signature": "def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green')" }, { "docstring": "积极性词 条状图 通过积极词字典筛...
4
null
Implement the Python class `Chart` described below. Class description: Implement the Chart class. Method signatures and docstrings: - def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green'): 高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_cha...
Implement the Python class `Chart` described below. Class description: Implement the Chart class. Method signatures and docstrings: - def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green'): 高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_cha...
9afe9ec7809529af05a971993d9ee17421364f76
<|skeleton|> class Chart: def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green'): """高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_chart_images')""" <|body_0|> def chart_word_positive(cls, app=None, word_positive_li...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Chart: def chart_word_frequency(cls, app=None, word_cut_list=[], title=None, topk=20, color='green'): """高频词 条状图 :param app: :param word_cut_list: :param title: :return: url('static', 'pygal_chart_images')""" chart = pygal.Bar() word_counter_list = Counter(word_cut_list).most_common(to...
the_stack_v2_python_sparse
tutorial/L46数据分析和图表可视化/jd_spider/service/pygal.py
liuxiaoxiao666/python_study
train
0
403e9ea96fbe85646a9b856d519ef02afda2cc45
[ "def memoize(i, j):\n if i == 0:\n return 1\n if j == 0:\n return 1\n if cache[i][j] != 0:\n return cache[i][j]\n cache[i][j] = memoize(i, j - 1) + memoize(i - 1, j)\n return cache[i][j]\nif m <= 0 or n <= 0:\n return 0\ncache = [[0 for _ in range(n)] for _ in range(m)]\nretur...
<|body_start_0|> def memoize(i, j): if i == 0: return 1 if j == 0: return 1 if cache[i][j] != 0: return cache[i][j] cache[i][j] = memoize(i, j - 1) + memoize(i - 1, j) return cache[i][j] if m <= 0...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def uniquePaths(self, m: int, n: int) -> int: """状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n]""" <|body_0|> def uniquePaths1(self, m: int, n: int) -> int: """状态转移方程:自底向上 dp[m][n] = dp[m][n-1] + dp[m-1][n]""" <|body_1|> def uniquePaths2(self, ...
stack_v2_sparse_classes_36k_train_002972
3,174
permissive
[ { "docstring": "状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n]", "name": "uniquePaths", "signature": "def uniquePaths(self, m: int, n: int) -> int" }, { "docstring": "状态转移方程:自底向上 dp[m][n] = dp[m][n-1] + dp[m-1][n]", "name": "uniquePaths1", "signature": "def uniquePaths1(self, m: int, n: ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m: int, n: int) -> int: 状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n] - def uniquePaths1(self, m: int, n: int) -> int: 状态转移方程:自底向上 dp[m][n] = dp[m][n-1] + ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m: int, n: int) -> int: 状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n] - def uniquePaths1(self, m: int, n: int) -> int: 状态转移方程:自底向上 dp[m][n] = dp[m][n-1] + ...
e8a1c6cae6547cbcb6e8494be6df685f3e7c837c
<|skeleton|> class Solution: def uniquePaths(self, m: int, n: int) -> int: """状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n]""" <|body_0|> def uniquePaths1(self, m: int, n: int) -> int: """状态转移方程:自底向上 dp[m][n] = dp[m][n-1] + dp[m-1][n]""" <|body_1|> def uniquePaths2(self, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def uniquePaths(self, m: int, n: int) -> int: """状态转移方程:自顶向下 dp[m][n] = dp[m][n-1] + dp[m-1][n]""" def memoize(i, j): if i == 0: return 1 if j == 0: return 1 if cache[i][j] != 0: return cache[i][j] ...
the_stack_v2_python_sparse
62-unique-paths.py
yuenliou/leetcode
train
0
94239537bd6c69e1b6ee9abcdb4f8b5907df5e21
[ "flag = 1 if x > -1 else -1\npositiveX = flag * x\nstrX = str(positiveX)\nrevsedX = strX[::-1]\nrevsedIntX = int(revsedX) * flag\nif revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1:\n revsedIntX = 0\nreturn revsedIntX", "flag = 1 if x > -1 else -1\npositiveX = flag * x\nres = 0\nwhile positiveX > 0:\n res...
<|body_start_0|> flag = 1 if x > -1 else -1 positiveX = flag * x strX = str(positiveX) revsedX = strX[::-1] revsedIntX = int(revsedX) * flag if revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1: revsedIntX = 0 return revsedIntX <|end_body_0|> <|body_s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse2(self, x): """:type x: int :rtype: int""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> flag = 1 if x > -1 else -1 positiveX = flag * x strX = str(p...
stack_v2_sparse_classes_36k_train_002973
790
no_license
[ { "docstring": ":type x: int :rtype: int", "name": "reverse2", "signature": "def reverse2(self, x)" }, { "docstring": ":type x: int :rtype: int", "name": "reverse", "signature": "def reverse(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_016646
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse2(self, x): :type x: int :rtype: int - def reverse(self, x): :type x: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse2(self, x): :type x: int :rtype: int - def reverse(self, x): :type x: int :rtype: int <|skeleton|> class Solution: def reverse2(self, x): """:type x: int...
238995bd23c8a6c40c6035890e94baa2473d4bbc
<|skeleton|> class Solution: def reverse2(self, x): """:type x: int :rtype: int""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse2(self, x): """:type x: int :rtype: int""" flag = 1 if x > -1 else -1 positiveX = flag * x strX = str(positiveX) revsedX = strX[::-1] revsedIntX = int(revsedX) * flag if revsedIntX < -2 ** 31 or revsedIntX > 2 ** 31 - 1: ...
the_stack_v2_python_sparse
problems/ReverseInteger.py
wan-catherine/Leetcode
train
5
9bb6b023b0c1f489f9175d0d8326b86d147ae98c
[ "_input = DataFrame({'a': [0, 1, 'b']})\n_expected = DataFrame({'a': [0, 1, 2]})\n_groupings = [{'operator': 'replace', 'columns': ['a'], 'value': ['b', 2]}]\n_vc = VariableCleaner(_input)\n_vc.clean(_groupings)\nassert_frame_equal(_expected, _vc.frame)", "_input = DataFrame({'a': [0, 1, 'b']})\n_expected = DataF...
<|body_start_0|> _input = DataFrame({'a': [0, 1, 'b']}) _expected = DataFrame({'a': [0, 1, 2]}) _groupings = [{'operator': 'replace', 'columns': ['a'], 'value': ['b', 2]}] _vc = VariableCleaner(_input) _vc.clean(_groupings) assert_frame_equal(_expected, _vc.frame) <|end_b...
CleanReplaceTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CleanReplaceTests: def test_clean_replace_string_values(): """Replace strings in a column.""" <|body_0|> def test_clean_replace_int_values(): """Replace an int in a column.""" <|body_1|> def test_clean_replace_nan_values(): """Replace NaN values ...
stack_v2_sparse_classes_36k_train_002974
1,560
permissive
[ { "docstring": "Replace strings in a column.", "name": "test_clean_replace_string_values", "signature": "def test_clean_replace_string_values()" }, { "docstring": "Replace an int in a column.", "name": "test_clean_replace_int_values", "signature": "def test_clean_replace_int_values()" ...
3
stack_v2_sparse_classes_30k_train_020416
Implement the Python class `CleanReplaceTests` described below. Class description: Implement the CleanReplaceTests class. Method signatures and docstrings: - def test_clean_replace_string_values(): Replace strings in a column. - def test_clean_replace_int_values(): Replace an int in a column. - def test_clean_replace...
Implement the Python class `CleanReplaceTests` described below. Class description: Implement the CleanReplaceTests class. Method signatures and docstrings: - def test_clean_replace_string_values(): Replace strings in a column. - def test_clean_replace_int_values(): Replace an int in a column. - def test_clean_replace...
2e89bc55a61ce2a4ce77646bb427f5b3040f672c
<|skeleton|> class CleanReplaceTests: def test_clean_replace_string_values(): """Replace strings in a column.""" <|body_0|> def test_clean_replace_int_values(): """Replace an int in a column.""" <|body_1|> def test_clean_replace_nan_values(): """Replace NaN values ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CleanReplaceTests: def test_clean_replace_string_values(): """Replace strings in a column.""" _input = DataFrame({'a': [0, 1, 'b']}) _expected = DataFrame({'a': [0, 1, 2]}) _groupings = [{'operator': 'replace', 'columns': ['a'], 'value': ['b', 2]}] _vc = VariableCleaner...
the_stack_v2_python_sparse
numom2b_preprocessing/unittests/cleaning_tests/test_replace.py
hayesall/nuMoM2b_preprocessing
train
2
4488f5a28e056f5348d9a6fe51aca8f41c006500
[ "@wraps(func)\ndef wrapper(*args, **kwargs):\n print(' \\n\\n _ooOoo_\\n o8888888o\\n 88\" . \"88\\n (| -_- |)\\n O\\\\ = /O\\n ____/`---\\'\\\\____\\n .\\' \\\\| ...
<|body_start_0|> @wraps(func) def wrapper(*args, **kwargs): print(' \n\n _ooOoo_\n o8888888o\n 88" . "88\n (| -_- |)\n O\\ = /O\n ____/`---\'\\____\n ...
DecoratorUtil
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoratorUtil: def buddha_bless_me(func): """佛祖保佑""" <|body_0|> def sleipmon_bless_me(func): """神兽羊驼保佑""" <|body_1|> def tangbohu(func): """佛祖保佑""" <|body_2|> def no_bug_forever(func): """永无bug,一个永无 bug 的文字瀑布在程序运行的时候慢慢晃过""" ...
stack_v2_sparse_classes_36k_train_002975
4,089
no_license
[ { "docstring": "佛祖保佑", "name": "buddha_bless_me", "signature": "def buddha_bless_me(func)" }, { "docstring": "神兽羊驼保佑", "name": "sleipmon_bless_me", "signature": "def sleipmon_bless_me(func)" }, { "docstring": "佛祖保佑", "name": "tangbohu", "signature": "def tangbohu(func)" ...
5
null
Implement the Python class `DecoratorUtil` described below. Class description: Implement the DecoratorUtil class. Method signatures and docstrings: - def buddha_bless_me(func): 佛祖保佑 - def sleipmon_bless_me(func): 神兽羊驼保佑 - def tangbohu(func): 佛祖保佑 - def no_bug_forever(func): 永无bug,一个永无 bug 的文字瀑布在程序运行的时候慢慢晃过 - def time...
Implement the Python class `DecoratorUtil` described below. Class description: Implement the DecoratorUtil class. Method signatures and docstrings: - def buddha_bless_me(func): 佛祖保佑 - def sleipmon_bless_me(func): 神兽羊驼保佑 - def tangbohu(func): 佛祖保佑 - def no_bug_forever(func): 永无bug,一个永无 bug 的文字瀑布在程序运行的时候慢慢晃过 - def time...
32e64be10a6cd2856850f6720d70b4c6e7033f4e
<|skeleton|> class DecoratorUtil: def buddha_bless_me(func): """佛祖保佑""" <|body_0|> def sleipmon_bless_me(func): """神兽羊驼保佑""" <|body_1|> def tangbohu(func): """佛祖保佑""" <|body_2|> def no_bug_forever(func): """永无bug,一个永无 bug 的文字瀑布在程序运行的时候慢慢晃过""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoratorUtil: def buddha_bless_me(func): """佛祖保佑""" @wraps(func) def wrapper(*args, **kwargs): print(' \n\n _ooOoo_\n o8888888o\n 88" . "88\n (| -_- |)\n O\\ = ...
the_stack_v2_python_sparse
Report/DecoratorUtil.py
newjokker/PyUtil
train
0
24a62a9b5454dd71d0b49e60ee00322806989144
[ "timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)", "query_hash = hash(query)\nevent_data = MacOSApplicationUsageEventData()\nevent_data.application = self._GetRowValue(query_hash, row, 'app_path')\neven...
<|body_start_0|> timestamp = self._GetRowValue(query_hash, row, value_name) if timestamp is None: return None return dfdatetime_posix_time.PosixTime(timestamp=timestamp) <|end_body_0|> <|body_start_1|> query_hash = hash(query) event_data = MacOSApplicationUsageEventD...
SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries triggered by NSWorkspaceWillLaunchApplicationNotification and NSWorkspaceDidTerminateApplicationNot...
MacOSApplicationUsagePlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MacOSApplicationUsagePlugin: """SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries triggered by NSWorkspaceWillLaunchApplicatio...
stack_v2_sparse_classes_36k_train_002976
4,191
permissive
[ { "docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if not available.", "name...
2
null
Implement the Python class `MacOSApplicationUsagePlugin` described below. Class description: SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries trigg...
Implement the Python class `MacOSApplicationUsagePlugin` described below. Class description: SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries trigg...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class MacOSApplicationUsagePlugin: """SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries triggered by NSWorkspaceWillLaunchApplicatio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MacOSApplicationUsagePlugin: """SQLite parser plugin for MacOS application usage database files. The MacOS application usage database is typically stored in: /var/db/application_usage.sqlite Application usage is a SQLite database that logs down entries triggered by NSWorkspaceWillLaunchApplicationNotification...
the_stack_v2_python_sparse
plaso/parsers/sqlite_plugins/macos_appusage.py
log2timeline/plaso
train
1,506
df01075832f54c7c78874828d901c42eb7348d1c
[ "v = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 1, 1))\nr = RendererCocoa(v)\nself.assertEqual(r.nsview, v)", "import matplotlib.transforms as transforms\nm = transforms.Affine2D.identity()\npass", "star_path = Path.unit_regular_star(10)\nr = RendererCocoa(None, None)\nbpath = r.mpl_to_bezier_path(star_path...
<|body_start_0|> v = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 1, 1)) r = RendererCocoa(v) self.assertEqual(r.nsview, v) <|end_body_0|> <|body_start_1|> import matplotlib.transforms as transforms m = transforms.Affine2D.identity() pass <|end_body_1|> <|body_start_2...
Unit tests for RendererCocoa
RendererCocoaTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RendererCocoaTests: """Unit tests for RendererCocoa""" def test_init_sets_properties(self): """test_init""" <|body_0|> def test_mpl_to_affine_transform(self): """test_mpl_to_affine_transform""" <|body_1|> def test_mpl_to_bezier_path(self): ""...
stack_v2_sparse_classes_36k_train_002977
24,942
no_license
[ { "docstring": "test_init", "name": "test_init_sets_properties", "signature": "def test_init_sets_properties(self)" }, { "docstring": "test_mpl_to_affine_transform", "name": "test_mpl_to_affine_transform", "signature": "def test_mpl_to_affine_transform(self)" }, { "docstring": "t...
4
stack_v2_sparse_classes_30k_train_001715
Implement the Python class `RendererCocoaTests` described below. Class description: Unit tests for RendererCocoa Method signatures and docstrings: - def test_init_sets_properties(self): test_init - def test_mpl_to_affine_transform(self): test_mpl_to_affine_transform - def test_mpl_to_bezier_path(self): test_mpl_to_be...
Implement the Python class `RendererCocoaTests` described below. Class description: Unit tests for RendererCocoa Method signatures and docstrings: - def test_init_sets_properties(self): test_init - def test_mpl_to_affine_transform(self): test_mpl_to_affine_transform - def test_mpl_to_bezier_path(self): test_mpl_to_be...
e648a6acd6230025e422f15b0a3573a5439d5ab4
<|skeleton|> class RendererCocoaTests: """Unit tests for RendererCocoa""" def test_init_sets_properties(self): """test_init""" <|body_0|> def test_mpl_to_affine_transform(self): """test_mpl_to_affine_transform""" <|body_1|> def test_mpl_to_bezier_path(self): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RendererCocoaTests: """Unit tests for RendererCocoa""" def test_init_sets_properties(self): """test_init""" v = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 1, 1)) r = RendererCocoa(v) self.assertEqual(r.nsview, v) def test_mpl_to_affine_transform(self): """...
the_stack_v2_python_sparse
CocoaInteraction/cocoa_backend.py
zoccolan/eyetracker
train
0
69cd7a004977df6951dda67690458c86b1397761
[ "if isinstance(expressions, tuple):\n expressions = [expressions]\nmasks = map(list, [comp(self.loc[(slice(None), method), :], thr).any(axis=1) for method, comp, thr in expressions])\nif len(masks) > 1:\n masks = numpy.logical_and(*masks)\nelse:\n masks = masks[0]\nidx = [f for f in masks for _ in xrange(l...
<|body_start_0|> if isinstance(expressions, tuple): expressions = [expressions] masks = map(list, [comp(self.loc[(slice(None), method), :], thr).any(axis=1) for method, comp, thr in expressions]) if len(masks) > 1: masks = numpy.logical_and(*masks) else: ...
A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core.Peptide.Peptide`) and the second row ID the predic...
EpitopePredictionResult
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EpitopePredictionResult: """A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core...
stack_v2_sparse_classes_36k_train_002978
14,645
permissive
[ { "docstring": "Filters a result data frame based on a specified expression consisting of a list of triple with (method_name, comparator, threshold). The expression is applied to each row. If any of the columns fulfill the criteria the row remains. :param list((str,comparator,float)) expressions: A list of trip...
2
stack_v2_sparse_classes_30k_train_017773
Implement the Python class `EpitopePredictionResult` described below. Class description: A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of t...
Implement the Python class `EpitopePredictionResult` described below. Class description: A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of t...
b3e54c8c4ed12b780b61f74672e9667245a7bb78
<|skeleton|> class EpitopePredictionResult: """A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EpitopePredictionResult: """A :class:`~Fred2.Core.Result.EpitopePredictionResult` object is a DataFrame with multi-indexing, where column Ids are the prediction model (i.e HLA :class:`~Fred2.Core.Allele.Allele` for epitope prediction), row ID the target of the prediction (i.e. :class:`~Fred2.Core.Peptide.Pept...
the_stack_v2_python_sparse
Fred2/Core/Result.py
FRED-2/Fred2
train
42
6fc65ffd5d0fffc67d1404693d6c601dedca93ce
[ "self.left_pq = []\nself.right_pq = []\nself.l = 0", "self.l += 1\nif len(self.right_pq) > len(self.left_pq):\n rightmin = heappop(self.right_pq)\n heappush(self.left_pq, -min(num, rightmin))\n heappush(self.right_pq, max(num, rightmin))\n return\nheappush(self.left_pq, -num)\nheappush(self.right_pq, ...
<|body_start_0|> self.left_pq = [] self.right_pq = [] self.l = 0 <|end_body_0|> <|body_start_1|> self.l += 1 if len(self.right_pq) > len(self.left_pq): rightmin = heappop(self.right_pq) heappush(self.left_pq, -min(num, rightmin)) heappush(self...
MedianFinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: void""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_002979
1,282
no_license
[ { "docstring": "initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":type num: int :rtype: void", "name": "addNum", "signature": "def addNum(self, num)" }, { "docstring": ":rtype: float", "name": "findMedian", "s...
3
stack_v2_sparse_classes_30k_train_003160
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: void - def findMedian(self): :rtype: float
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: void - def findMedian(self): :rtype: float <|skeleton|> class Me...
b0ce69985c51a9a794397cd98a996fca0e91d7d1
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: void""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MedianFinder: def __init__(self): """initialize your data structure here.""" self.left_pq = [] self.right_pq = [] self.l = 0 def addNum(self, num): """:type num: int :rtype: void""" self.l += 1 if len(self.right_pq) > len(self.left_pq): ...
the_stack_v2_python_sparse
Solutions/295-Find-Median-from-Data-Stream/python.py
JerryHu1994/LeetCode-Practice
train
0
3979e7236a2560c99b09f91a9097478c850e43d4
[ "global result\nif len(s) < 4 or len(s) > 12:\n return result\nself.search_helper(s, 0, 0)\nreturn result", "global COUNT\nglobal segment\nglobal result\nif seg_id == COUNT:\n if start == len(s):\n result.append('.'.join(segment))\n return\nif start == len(s):\n return\nif s[start] == '0':\n ...
<|body_start_0|> global result if len(s) < 4 or len(s) > 12: return result self.search_helper(s, 0, 0) return result <|end_body_0|> <|body_start_1|> global COUNT global segment global result if seg_id == COUNT: if start == len(s): ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def restore_ip_addresses(self, s: str) -> List[str]: """修复ip Args: s: 字符串 Returns: ip的list""" <|body_0|> def search_helper(self, s: str, seg_id: int, start: int) -> None: """查找帮助类 Args: s: 字符串 seg_id: 区域id start: 开始位置 Returns: None""" <|body_1|> <|...
stack_v2_sparse_classes_36k_train_002980
2,850
permissive
[ { "docstring": "修复ip Args: s: 字符串 Returns: ip的list", "name": "restore_ip_addresses", "signature": "def restore_ip_addresses(self, s: str) -> List[str]" }, { "docstring": "查找帮助类 Args: s: 字符串 seg_id: 区域id start: 开始位置 Returns: None", "name": "search_helper", "signature": "def search_helper(...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restore_ip_addresses(self, s: str) -> List[str]: 修复ip Args: s: 字符串 Returns: ip的list - def search_helper(self, s: str, seg_id: int, start: int) -> None: 查找帮助类 Args: s: 字符串 seg...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restore_ip_addresses(self, s: str) -> List[str]: 修复ip Args: s: 字符串 Returns: ip的list - def search_helper(self, s: str, seg_id: int, start: int) -> None: 查找帮助类 Args: s: 字符串 seg...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def restore_ip_addresses(self, s: str) -> List[str]: """修复ip Args: s: 字符串 Returns: ip的list""" <|body_0|> def search_helper(self, s: str, seg_id: int, start: int) -> None: """查找帮助类 Args: s: 字符串 seg_id: 区域id start: 开始位置 Returns: None""" <|body_1|> <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def restore_ip_addresses(self, s: str) -> List[str]: """修复ip Args: s: 字符串 Returns: ip的list""" global result if len(s) < 4 or len(s) > 12: return result self.search_helper(s, 0, 0) return result def search_helper(self, s: str, seg_id: int, star...
the_stack_v2_python_sparse
src/leetcodepython/string/restore_ip_addresses_93.py
zhangyu345293721/leetcode
train
101
add111fd03470d7634a0f93240a92f8aca439b24
[ "super().__init__(graph)\nself.op_to_module_dict = dict()\nself._num_products_made = 0\nself.starting_op_names = starting_op_names\nself._valid_ops = valid_ops\nself.processed_ops = set()\nself._sub_graph_matcher = sub_graph_matcher.SubGraphMatcher(self._graph, self.op_to_module_dict, self._valid_ops)", "default_...
<|body_start_0|> super().__init__(graph) self.op_to_module_dict = dict() self._num_products_made = 0 self.starting_op_names = starting_op_names self._valid_ops = valid_ops self.processed_ops = set() self._sub_graph_matcher = sub_graph_matcher.SubGraphMatcher(self....
Module identifier using graph structures
StructureModuleIdentifier
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StructureModuleIdentifier: """Module identifier using graph structures""" def __init__(self, graph: tf.Graph, starting_op_names: List[str], valid_ops: Set[tf.Operation]): """Initializer for ModuleIdentifier :param graph: Tensorflow graph to represent using connected graph. :param sta...
stack_v2_sparse_classes_36k_train_002981
4,653
permissive
[ { "docstring": "Initializer for ModuleIdentifier :param graph: Tensorflow graph to represent using connected graph. :param starting_op_names: Names of the starting ops of the model. :param valid_ops: Set of tf operations that are valid", "name": "__init__", "signature": "def __init__(self, graph: tf.Gra...
2
null
Implement the Python class `StructureModuleIdentifier` described below. Class description: Module identifier using graph structures Method signatures and docstrings: - def __init__(self, graph: tf.Graph, starting_op_names: List[str], valid_ops: Set[tf.Operation]): Initializer for ModuleIdentifier :param graph: Tensor...
Implement the Python class `StructureModuleIdentifier` described below. Class description: Module identifier using graph structures Method signatures and docstrings: - def __init__(self, graph: tf.Graph, starting_op_names: List[str], valid_ops: Set[tf.Operation]): Initializer for ModuleIdentifier :param graph: Tensor...
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
<|skeleton|> class StructureModuleIdentifier: """Module identifier using graph structures""" def __init__(self, graph: tf.Graph, starting_op_names: List[str], valid_ops: Set[tf.Operation]): """Initializer for ModuleIdentifier :param graph: Tensorflow graph to represent using connected graph. :param sta...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StructureModuleIdentifier: """Module identifier using graph structures""" def __init__(self, graph: tf.Graph, starting_op_names: List[str], valid_ops: Set[tf.Operation]): """Initializer for ModuleIdentifier :param graph: Tensorflow graph to represent using connected graph. :param starting_op_name...
the_stack_v2_python_sparse
TrainingExtensions/tensorflow/src/python/aimet_tensorflow/common/module_identifier.py
quic/aimet
train
1,676
372bfd1ed69120e9870b44c6a7b0104164ce7e9a
[ "self._descriptors = 'descriptors'\nself._db = 'world_model'\nself.conn = psycopg2.connect(database=self._db, user=user, password=pwd, host=host)\nself.lock = thread.allocate_lock()", "if 'descriptor_id' in entity.keys():\n del entity['descriptor_id']\nwith self.lock:\n if 'data' in entity.keys():\n ...
<|body_start_0|> self._descriptors = 'descriptors' self._db = 'world_model' self.conn = psycopg2.connect(database=self._db, user=user, password=pwd, host=host) self.lock = thread.allocate_lock() <|end_body_0|> <|body_start_1|> if 'descriptor_id' in entity.keys(): del...
The main DescriptorConnection object which communicates with the PostgreSQL World Model database.
DescriptorConnection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DescriptorConnection: """The main DescriptorConnection object which communicates with the PostgreSQL World Model database.""" def __init__(self, user, pwd, host='localhost'): """Creates the DescriptorConnection object and connects to the descriptors table. @param user: the database u...
stack_v2_sparse_classes_36k_train_002982
7,245
no_license
[ { "docstring": "Creates the DescriptorConnection object and connects to the descriptors table. @param user: the database username @type user: string @param pwd: the database password @type pwd: string @param host: the database hostname @type host: string", "name": "__init__", "signature": "def __init__(...
5
stack_v2_sparse_classes_30k_train_008493
Implement the Python class `DescriptorConnection` described below. Class description: The main DescriptorConnection object which communicates with the PostgreSQL World Model database. Method signatures and docstrings: - def __init__(self, user, pwd, host='localhost'): Creates the DescriptorConnection object and conne...
Implement the Python class `DescriptorConnection` described below. Class description: The main DescriptorConnection object which communicates with the PostgreSQL World Model database. Method signatures and docstrings: - def __init__(self, user, pwd, host='localhost'): Creates the DescriptorConnection object and conne...
4a835a04b469360b11243405d4d1f19b706c510d
<|skeleton|> class DescriptorConnection: """The main DescriptorConnection object which communicates with the PostgreSQL World Model database.""" def __init__(self, user, pwd, host='localhost'): """Creates the DescriptorConnection object and connects to the descriptors table. @param user: the database u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DescriptorConnection: """The main DescriptorConnection object which communicates with the PostgreSQL World Model database.""" def __init__(self, user, pwd, host='localhost'): """Creates the DescriptorConnection object and connects to the descriptors table. @param user: the database username @type...
the_stack_v2_python_sparse
spatial_world_model/worldlib/src/worldlib/descriptor_connection.py
Playfish/cafe_demo
train
0
30bad695936ec14a8c0f5a485e113d947c47b60f
[ "config_filename = '%s-slave-config.json' % socket.gethostname()\nconfig_path = os.path.join('config', config_filename)\nsuper().__init__(config_path=config_path)\nself.task_q = []\nself.master_nodes = []\nself.config['port'] = port\nmessenger_type = messenger.ZMQMessenger.TYPE_CLIENT\nself.messenger = messenger.ZM...
<|body_start_0|> config_filename = '%s-slave-config.json' % socket.gethostname() config_path = os.path.join('config', config_filename) super().__init__(config_path=config_path) self.task_q = [] self.master_nodes = [] self.config['port'] = port messenger_type = mes...
An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back.
Slave
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Slave: """An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back.""" def __init__(self, port, ip=None): """:param port: port number to run this slave on.""" <|body_0|> def associate(self):...
stack_v2_sparse_classes_36k_train_002983
3,136
permissive
[ { "docstring": ":param port: port number to run this slave on.", "name": "__init__", "signature": "def __init__(self, port, ip=None)" }, { "docstring": "Associate with the master(s). This involves sending a status update to the master.", "name": "associate", "signature": "def associate(s...
3
stack_v2_sparse_classes_30k_train_003586
Implement the Python class `Slave` described below. Class description: An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back. Method signatures and docstrings: - def __init__(self, port, ip=None): :param port: port number to run this ...
Implement the Python class `Slave` described below. Class description: An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back. Method signatures and docstrings: - def __init__(self, port, ip=None): :param port: port number to run this ...
97a46f165475f71b1cd0b10626232cd586e102b3
<|skeleton|> class Slave: """An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back.""" def __init__(self, port, ip=None): """:param port: port number to run this slave on.""" <|body_0|> def associate(self):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Slave: """An instance of this class represents a slave node. A slave node can accept work units from a master and process and send the results back.""" def __init__(self, port, ip=None): """:param port: port number to run this slave on.""" config_filename = '%s-slave-config.json' % socket...
the_stack_v2_python_sparse
slave.py
mtahmed/antnest
train
1
5868c972ff8320e9830c2658436fc8e247b3b7f9
[ "if self.df.empty:\n return self.df._default_to_pandas(lambda df: df.iloc[key])\nif isinstance(key, tuple):\n key = self._validate_key_length(key)\nrow_loc, col_loc, ndim = self._parse_row_and_column_locators(key)\nrow_scalar = is_scalar(row_loc)\ncol_scalar = is_scalar(col_loc)\nself._check_dtypes(row_loc)\n...
<|body_start_0|> if self.df.empty: return self.df._default_to_pandas(lambda df: df.iloc[key]) if isinstance(key, tuple): key = self._validate_key_length(key) row_loc, col_loc, ndim = self._parse_row_and_column_locators(key) row_scalar = is_scalar(row_loc) ...
An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on.
_iLocIndexer
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _iLocIndexer: """An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on.""" def __getitem__(self, key): """Retrieve dataset according to `key`. Parameters ---------- key : callable or tuple The global row numbers ...
stack_v2_sparse_classes_36k_train_002984
41,072
permissive
[ { "docstring": "Retrieve dataset according to `key`. Parameters ---------- key : callable or tuple The global row numbers to retrieve data from. Returns ------- DataFrame or Series Located dataset. See Also -------- pandas.DataFrame.iloc", "name": "__getitem__", "signature": "def __getitem__(self, key)"...
4
stack_v2_sparse_classes_30k_train_011661
Implement the Python class `_iLocIndexer` described below. Class description: An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on. Method signatures and docstrings: - def __getitem__(self, key): Retrieve dataset according to `key`. Parameters -...
Implement the Python class `_iLocIndexer` described below. Class description: An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on. Method signatures and docstrings: - def __getitem__(self, key): Retrieve dataset according to `key`. Parameters -...
8f6e00378e095817deccd25f4140406c5ee6c992
<|skeleton|> class _iLocIndexer: """An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on.""" def __getitem__(self, key): """Retrieve dataset according to `key`. Parameters ---------- key : callable or tuple The global row numbers ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _iLocIndexer: """An indexer for modin_df.iloc[] functionality. Parameters ---------- modin_df : modin.pandas.DataFrame DataFrame to operate on.""" def __getitem__(self, key): """Retrieve dataset according to `key`. Parameters ---------- key : callable or tuple The global row numbers to retrieve d...
the_stack_v2_python_sparse
modin/pandas/indexing.py
modin-project/modin
train
9,241
3c620b699ecff95c27f0ba5ee4a73f770fb45089
[ "check_cluster_name(cluster_name, application_name)\nvalidate_fields(instance_schema, {'application': application_name, 'cluster': cluster_name, 'key': key})\nim = InstanceManagement(huskar_client, application_name, SERVICE_SUBDOMAIN)\ninstance, _ = im.get_instance(cluster_name, key, resolve=False)\nif instance.sta...
<|body_start_0|> check_cluster_name(cluster_name, application_name) validate_fields(instance_schema, {'application': application_name, 'cluster': cluster_name, 'key': key}) im = InstanceManagement(huskar_client, application_name, SERVICE_SUBDOMAIN) instance, _ = im.get_instance(cluster_n...
ServiceInstanceWeightView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceInstanceWeightView: def get(self, application_name, cluster_name, key): """Gets the weight of specified service instance. :param application_name: The name of application. :param cluster_name: The name of cluster. :param key: The key of service instance. :<header Authorization: Hu...
stack_v2_sparse_classes_36k_train_002985
17,926
permissive
[ { "docstring": "Gets the weight of specified service instance. :param application_name: The name of application. :param cluster_name: The name of cluster. :param key: The key of service instance. :<header Authorization: Huskar Token (See :ref:`token`) :status 404: The instance is not found. :status 200: The res...
2
null
Implement the Python class `ServiceInstanceWeightView` described below. Class description: Implement the ServiceInstanceWeightView class. Method signatures and docstrings: - def get(self, application_name, cluster_name, key): Gets the weight of specified service instance. :param application_name: The name of applicat...
Implement the Python class `ServiceInstanceWeightView` described below. Class description: Implement the ServiceInstanceWeightView class. Method signatures and docstrings: - def get(self, application_name, cluster_name, key): Gets the weight of specified service instance. :param application_name: The name of applicat...
395775c59c7da97c46efe9756365cad028b7c95a
<|skeleton|> class ServiceInstanceWeightView: def get(self, application_name, cluster_name, key): """Gets the weight of specified service instance. :param application_name: The name of application. :param cluster_name: The name of cluster. :param key: The key of service instance. :<header Authorization: Hu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServiceInstanceWeightView: def get(self, application_name, cluster_name, key): """Gets the weight of specified service instance. :param application_name: The name of application. :param cluster_name: The name of cluster. :param key: The key of service instance. :<header Authorization: Huskar Token (Se...
the_stack_v2_python_sparse
huskar_api/api/service_instance.py
Zheaoli/huskar
train
0
604443f0b21640cb0eca42c8ed532957bdc0e9a4
[ "ng = self.get_object_or_404(self.single, group_id)\ncheck_if_network_configuration_locked(ng.nodegroup)\ndata = self.checked_data(self.validator.validate_update, instance=ng)\nself.single.update(ng, data)\nreturn self.single.to_dict(ng)", "ng = self.get_object_or_404(self.single, group_id)\ncheck_if_network_conf...
<|body_start_0|> ng = self.get_object_or_404(self.single, group_id) check_if_network_configuration_locked(ng.nodegroup) data = self.checked_data(self.validator.validate_update, instance=ng) self.single.update(ng, data) return self.single.to_dict(ng) <|end_body_0|> <|body_start_1...
Network group handler
NetworkGroupHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkGroupHandler: """Network group handler""" def PUT(self, group_id): """:returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden) * 404 (Network group was not found in db)""" <|b...
stack_v2_sparse_classes_36k_train_002986
3,725
permissive
[ { "docstring": ":returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden) * 404 (Network group was not found in db)", "name": "PUT", "signature": "def PUT(self, group_id)" }, { "docstring": "Remove Netwo...
2
null
Implement the Python class `NetworkGroupHandler` described below. Class description: Network group handler Method signatures and docstrings: - def PUT(self, group_id): :returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden)...
Implement the Python class `NetworkGroupHandler` described below. Class description: Network group handler Method signatures and docstrings: - def PUT(self, group_id): :returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden)...
768ac74a420f822261c4eb8da72f1d8af3c6bbff
<|skeleton|> class NetworkGroupHandler: """Network group handler""" def PUT(self, group_id): """:returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden) * 404 (Network group was not found in db)""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkGroupHandler: """Network group handler""" def PUT(self, group_id): """:returns: JSONized Network Group object. :http: * 200 (OK) * 400 (error occured while processing of data) * 403 (change of configuration is forbidden) * 404 (Network group was not found in db)""" ng = self.get_ob...
the_stack_v2_python_sparse
nailgun/nailgun/extensions/network_manager/handlers/network_group.py
dis-xcom/fuel-web
train
0
6c1ca1685c9d8a58203ee228e2cd73ec2af6c954
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong')\nrepo.dropPermanent('aggpublicschools')\nrepo.createPermanent('aggpublicschools')\npublicschools = list(repo.ashleyyu_bzwtong.publicschools.find())\nzipCount = []\n...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong') repo.dropPermanent('aggpublicschools') repo.createPermanent('aggpublicschools') publicschools = lis...
aggpublicschools
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class aggpublicschools: def execute(trial=False): """Find number of public schools within each zipcode""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in this scrip...
stack_v2_sparse_classes_36k_train_002987
3,932
no_license
[ { "docstring": "Find number of public schools within each zipcode", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that inv...
2
stack_v2_sparse_classes_30k_train_019458
Implement the Python class `aggpublicschools` described below. Class description: Implement the aggpublicschools class. Method signatures and docstrings: - def execute(trial=False): Find number of public schools within each zipcode - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ...
Implement the Python class `aggpublicschools` described below. Class description: Implement the aggpublicschools class. Method signatures and docstrings: - def execute(trial=False): Find number of public schools within each zipcode - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ...
b5ccaad97f6e35f9580e645ca764f36eb3406f43
<|skeleton|> class aggpublicschools: def execute(trial=False): """Find number of public schools within each zipcode""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening in this scrip...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class aggpublicschools: def execute(trial=False): """Find number of public schools within each zipcode""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong') repo.dropPerma...
the_stack_v2_python_sparse
ashleyyu_bzwtong/aggpublicschools.py
dwang1995/course-2018-spr-proj
train
1
325e0d89af4778dd574ee997c3c67b58a1a5b2c0
[ "if len(parts) < 3:\n self.client.sendServerMessage('You must provide a username and a message.')\nelse:\n try:\n from_user = self.client.username.lower()\n to_user = parts[1].lower()\n mess = ' '.join(parts[2:])\n file = open('config/data/inbox.dat', 'r')\n messages = cPick...
<|body_start_0|> if len(parts) < 3: self.client.sendServerMessage('You must provide a username and a message.') else: try: from_user = self.client.username.lower() to_user = parts[1].lower() mess = ' '.join(parts[2:]) ...
OfflineMessPlugin
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OfflineMessPlugin: def commandSendMessage(self, parts, fromloc, overriderank): """/s username message - Guest Aliases: sendmessage Sends an message to the users Inbox.""" <|body_0|> def commandCheckMessages(self, parts, fromloc, overriderank): """/inbox - Guest Check...
stack_v2_sparse_classes_36k_train_002988
3,110
permissive
[ { "docstring": "/s username message - Guest Aliases: sendmessage Sends an message to the users Inbox.", "name": "commandSendMessage", "signature": "def commandSendMessage(self, parts, fromloc, overriderank)" }, { "docstring": "/inbox - Guest Checks your Inbox of messages", "name": "commandCh...
3
stack_v2_sparse_classes_30k_train_013810
Implement the Python class `OfflineMessPlugin` described below. Class description: Implement the OfflineMessPlugin class. Method signatures and docstrings: - def commandSendMessage(self, parts, fromloc, overriderank): /s username message - Guest Aliases: sendmessage Sends an message to the users Inbox. - def commandC...
Implement the Python class `OfflineMessPlugin` described below. Class description: Implement the OfflineMessPlugin class. Method signatures and docstrings: - def commandSendMessage(self, parts, fromloc, overriderank): /s username message - Guest Aliases: sendmessage Sends an message to the users Inbox. - def commandC...
5482def8b50562fdbae980cda9b1708bfad8bffb
<|skeleton|> class OfflineMessPlugin: def commandSendMessage(self, parts, fromloc, overriderank): """/s username message - Guest Aliases: sendmessage Sends an message to the users Inbox.""" <|body_0|> def commandCheckMessages(self, parts, fromloc, overriderank): """/inbox - Guest Check...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OfflineMessPlugin: def commandSendMessage(self, parts, fromloc, overriderank): """/s username message - Guest Aliases: sendmessage Sends an message to the users Inbox.""" if len(parts) < 3: self.client.sendServerMessage('You must provide a username and a message.') else: ...
the_stack_v2_python_sparse
core/plugins/inbox.py
TheArchives/Nexus
train
1
d400bcf196f4f6b36e4df115035cb6f3253ed76c
[ "pivotedData = projectedData.dissolve(by=['severity', angleColumn], aggfunc='sum').reset_index().pivot(angleColumn, 'severity', 'effectedPopulation').reset_index().fillna(0)\nif ax is None:\n fig = plt.gcf()\n ax = fig.add_subplot(111, polar=True)\nelif isinstance(ax, list):\n fig = plt.gcf()\n ax = fig...
<|body_start_0|> pivotedData = projectedData.dissolve(by=['severity', angleColumn], aggfunc='sum').reset_index().pivot(angleColumn, 'severity', 'effectedPopulation').reset_index().fillna(0) if ax is None: fig = plt.gcf() ax = fig.add_subplot(111, polar=True) elif isinstan...
A class for plotting the different plots related to the casualties.
casualtiesPlot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class casualtiesPlot: """A class for plotting the different plots related to the casualties.""" def plotCasualtiesRose(self, projectedData, severityList, ax=None, angleColumn='mathematical_angle_rad', legend=True, weights=None, cycler=None, coordsTickConvertor=toAzimuthAngle): """plots the...
stack_v2_sparse_classes_36k_train_002989
4,815
no_license
[ { "docstring": "plots the total valueColumn in a radial bars according to the severity. *param: :data: a pandas like with the columns :severity and [valueColumn],[angleColumn]. :severityList: The list of severity values to plot. :valueColumn: the value to plot. :angleColumn: the column that holds the angle. the...
2
stack_v2_sparse_classes_30k_val_000440
Implement the Python class `casualtiesPlot` described below. Class description: A class for plotting the different plots related to the casualties. Method signatures and docstrings: - def plotCasualtiesRose(self, projectedData, severityList, ax=None, angleColumn='mathematical_angle_rad', legend=True, weights=None, cy...
Implement the Python class `casualtiesPlot` described below. Class description: A class for plotting the different plots related to the casualties. Method signatures and docstrings: - def plotCasualtiesRose(self, projectedData, severityList, ax=None, angleColumn='mathematical_angle_rad', legend=True, weights=None, cy...
7fbf20536c81c54cd69d1745f88bbcb264158e82
<|skeleton|> class casualtiesPlot: """A class for plotting the different plots related to the casualties.""" def plotCasualtiesRose(self, projectedData, severityList, ax=None, angleColumn='mathematical_angle_rad', legend=True, weights=None, cycler=None, coordsTickConvertor=toAzimuthAngle): """plots the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class casualtiesPlot: """A class for plotting the different plots related to the casualties.""" def plotCasualtiesRose(self, projectedData, severityList, ax=None, angleColumn='mathematical_angle_rad', legend=True, weights=None, cycler=None, coordsTickConvertor=toAzimuthAngle): """plots the total valueC...
the_stack_v2_python_sparse
hera/riskassessment/presentation/casualtiesFigs.py
swipswaps/Hera
train
0
c7c2034df9959505cd524084a5ea0dd0364fc8e6
[ "self.attempt_differential_restore = attempt_differential_restore\nself.datastore_folder_id = datastore_folder_id\nself.detach_network = detach_network\nself.disable_network = disable_network\nself.network_id = network_id\nself.network_mappings = network_mappings\nself.org_vdc_network = org_vdc_network\nself.overwr...
<|body_start_0|> self.attempt_differential_restore = attempt_differential_restore self.datastore_folder_id = datastore_folder_id self.detach_network = detach_network self.disable_network = disable_network self.network_id = network_id self.network_mappings = network_mappin...
Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datastore_folder_id (long|int): Specifies the folder where the restore datastore should be cre...
VmwareCloneParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VmwareCloneParameters: """Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datastore_folder_id (long|int): Specifies the...
stack_v2_sparse_classes_36k_train_002990
11,797
permissive
[ { "docstring": "Constructor for the VmwareCloneParameters class", "name": "__init__", "signature": "def __init__(self, attempt_differential_restore=None, datastore_folder_id=None, detach_network=None, disable_network=None, network_id=None, network_mappings=None, org_vdc_network=None, overwrite_existing_...
2
null
Implement the Python class `VmwareCloneParameters` described below. Class description: Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datast...
Implement the Python class `VmwareCloneParameters` described below. Class description: Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datast...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class VmwareCloneParameters: """Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datastore_folder_id (long|int): Specifies the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VmwareCloneParameters: """Implementation of the 'VmwareCloneParameters' model. Specifies the information required for recovering or cloning VmWare VMs. Attributes: attempt_differential_restore (bool): Specifies whether to attempt differential restore. datastore_folder_id (long|int): Specifies the folder where...
the_stack_v2_python_sparse
cohesity_management_sdk/models/vmware_clone_parameters.py
cohesity/management-sdk-python
train
24
d47028bd18f41970e469e42016adc01a88b4596f
[ "mol = np.zeros(natoms, dtype=int)\nnmol = natoms / npol\nk = 0\nfor i in range(nmol):\n for j in range(npol):\n mol[k] = i\n k = k + 1\nreturn (mol, nmol)", "line = line.split()\nself.nbins = int(line[1])\nself.vmin = float(line[2])\nself.vmax = float(line[3])\nself.mol, self.nmol = self.gen_mol...
<|body_start_0|> mol = np.zeros(natoms, dtype=int) nmol = natoms / npol k = 0 for i in range(nmol): for j in range(npol): mol[k] = i k = k + 1 return (mol, nmol) <|end_body_0|> <|body_start_1|> line = line.split() self....
VoronoiDensity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VoronoiDensity: def gen_mol_info(self, natoms, npol): """generate information on molecules""" <|body_0|> def __init__(self, nsteps, natoms, npol, line): """initialize, allocate required arrays and precompute misc required information""" <|body_1|> def co...
stack_v2_sparse_classes_36k_train_002991
2,417
no_license
[ { "docstring": "generate information on molecules", "name": "gen_mol_info", "signature": "def gen_mol_info(self, natoms, npol)" }, { "docstring": "initialize, allocate required arrays and precompute misc required information", "name": "__init__", "signature": "def __init__(self, nsteps, ...
3
null
Implement the Python class `VoronoiDensity` described below. Class description: Implement the VoronoiDensity class. Method signatures and docstrings: - def gen_mol_info(self, natoms, npol): generate information on molecules - def __init__(self, nsteps, natoms, npol, line): initialize, allocate required arrays and pre...
Implement the Python class `VoronoiDensity` described below. Class description: Implement the VoronoiDensity class. Method signatures and docstrings: - def gen_mol_info(self, natoms, npol): generate information on molecules - def __init__(self, nsteps, natoms, npol, line): initialize, allocate required arrays and pre...
7d2659bee85c955c680eda019cbff6e2b93ecff2
<|skeleton|> class VoronoiDensity: def gen_mol_info(self, natoms, npol): """generate information on molecules""" <|body_0|> def __init__(self, nsteps, natoms, npol, line): """initialize, allocate required arrays and precompute misc required information""" <|body_1|> def co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VoronoiDensity: def gen_mol_info(self, natoms, npol): """generate information on molecules""" mol = np.zeros(natoms, dtype=int) nmol = natoms / npol k = 0 for i in range(nmol): for j in range(npol): mol[k] = i k = k + 1 ...
the_stack_v2_python_sparse
analyse_collective/voronoidensity.py
melampyge/CollectiveFilament
train
0
65309477df33f56a86553c74184ed3d757a11e45
[ "Thread.__init__(self)\nwith open('text.txt', 'r') as file:\n self.text = file.read()\nself.character = character", "lock = Lock()\nwith lock:\n counter = 0\n for char in self.text:\n if char == self.character:\n counter += 1\n print('The character {0} appeared in the text {1} times'...
<|body_start_0|> Thread.__init__(self) with open('text.txt', 'r') as file: self.text = file.read() self.character = character <|end_body_0|> <|body_start_1|> lock = Lock() with lock: counter = 0 for char in self.text: if char =...
Class which handles searching in a text for a character.
CharThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CharThread: """Class which handles searching in a text for a character.""" def __init__(self, character): """Constructor of the CharThread class. :param character: The desired character.""" <|body_0|> def run(self): """Method which searches for a character in a t...
stack_v2_sparse_classes_36k_train_002992
868
no_license
[ { "docstring": "Constructor of the CharThread class. :param character: The desired character.", "name": "__init__", "signature": "def __init__(self, character)" }, { "docstring": "Method which searches for a character in a text.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_val_000680
Implement the Python class `CharThread` described below. Class description: Class which handles searching in a text for a character. Method signatures and docstrings: - def __init__(self, character): Constructor of the CharThread class. :param character: The desired character. - def run(self): Method which searches f...
Implement the Python class `CharThread` described below. Class description: Class which handles searching in a text for a character. Method signatures and docstrings: - def __init__(self, character): Constructor of the CharThread class. :param character: The desired character. - def run(self): Method which searches f...
7b3c92c151266cd3ccdd63e7dc0a37f7a60476fa
<|skeleton|> class CharThread: """Class which handles searching in a text for a character.""" def __init__(self, character): """Constructor of the CharThread class. :param character: The desired character.""" <|body_0|> def run(self): """Method which searches for a character in a t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CharThread: """Class which handles searching in a text for a character.""" def __init__(self, character): """Constructor of the CharThread class. :param character: The desired character.""" Thread.__init__(self) with open('text.txt', 'r') as file: self.text = file.read...
the_stack_v2_python_sparse
Laboratory 8/problem3/thread.py
BabyCakes13/Python-Treasure
train
0
37870f4d81c034edb2ab33232d9d10a12b2fb07a
[ "super().__init__(name, bases, attributes, **kwds)\nif not namespace:\n package = self.pyre_package()\n if package:\n namespace = package.name\nself.pyre_namespace = namespace\nreturn", "if name is not None:\n loc = pyre.tracking.simple(f\"while initializing application '{name}'\")\n locator = ...
<|body_start_0|> super().__init__(name, bases, attributes, **kwds) if not namespace: package = self.pyre_package() if package: namespace = package.name self.pyre_namespace = namespace return <|end_body_0|> <|body_start_1|> if name is not N...
The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework
Director
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Director: """The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework""" def __init__(self, name, bases, attributes, namespace=None, **kwds): """Initialization of application class records""" <|body_0|...
stack_v2_sparse_classes_36k_train_002993
1,873
permissive
[ { "docstring": "Initialization of application class records", "name": "__init__", "signature": "def __init__(self, name, bases, attributes, namespace=None, **kwds)" }, { "docstring": "Build an application instance", "name": "__call__", "signature": "def __call__(self, name=None, globalAl...
2
null
Implement the Python class `Director` described below. Class description: The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework Method signatures and docstrings: - def __init__(self, name, bases, attributes, namespace=None, **kwds): Initial...
Implement the Python class `Director` described below. Class description: The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework Method signatures and docstrings: - def __init__(self, name, bases, attributes, namespace=None, **kwds): Initial...
d741c44ffb3e9e1f726bf492202ac8738bb4aa1c
<|skeleton|> class Director: """The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework""" def __init__(self, name, bases, attributes, namespace=None, **kwds): """Initialization of application class records""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Director: """The metaclass of applications {Director} takes care of all the tasks necessary to register an application family with the framework""" def __init__(self, name, bases, attributes, namespace=None, **kwds): """Initialization of application class records""" super().__init__(name,...
the_stack_v2_python_sparse
packages/pyre/shells/Director.py
pyre/pyre
train
27
ceab5716b0cdfeae3a9c4efeeb00dfd45738efed
[ "if not s:\n return 0\nt, c = min(((s.count(c), c) for c in s))\nif t >= k:\n return len(s)\nreturn max((self.longestSubstring(x, k) for x in s.split(c)))", "stack = []\nstack.append(s)\nans = 0\nwhile stack:\n s = stack.pop()\n for c in set(s):\n if s.count(c) < k:\n stack.extend([z...
<|body_start_0|> if not s: return 0 t, c = min(((s.count(c), c) for c in s)) if t >= k: return len(s) return max((self.longestSubstring(x, k) for x in s.split(c))) <|end_body_0|> <|body_start_1|> stack = [] stack.append(s) ans = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestSubstring(self, s, k): """分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return:""" <|body_0|> def longestSubstring2(self, s, k): """迭代 模拟函数栈 for ... else ... 语句: 当for循环正常执行完后会执行else语句,如果for循环被break中断,则不会执行else语句 :type s: str :type k: in...
stack_v2_sparse_classes_36k_train_002994
9,679
no_license
[ { "docstring": "分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return:", "name": "longestSubstring", "signature": "def longestSubstring(self, s, k)" }, { "docstring": "迭代 模拟函数栈 for ... else ... 语句: 当for循环正常执行完后会执行else语句,如果for循环被break中断,则不会执行else语句 :type s: str :type k: int :rtype: int",...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestSubstring(self, s, k): 分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return: - def longestSubstring2(self, s, k): 迭代 模拟函数栈 for ... else ... 语句: 当for循环正常执行完后会...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestSubstring(self, s, k): 分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return: - def longestSubstring2(self, s, k): 迭代 模拟函数栈 for ... else ... 语句: 当for循环正常执行完后会...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def longestSubstring(self, s, k): """分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return:""" <|body_0|> def longestSubstring2(self, s, k): """迭代 模拟函数栈 for ... else ... 语句: 当for循环正常执行完后会执行else语句,如果for循环被break中断,则不会执行else语句 :type s: str :type k: in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestSubstring(self, s, k): """分治 从出现次数最小的字母开始分隔字符串,依次递归分隔后的所有字符串 :param s: :param k: :return:""" if not s: return 0 t, c = min(((s.count(c), c) for c in s)) if t >= k: return len(s) return max((self.longestSubstring(x, k) for x i...
the_stack_v2_python_sparse
395_至少有K个重复字符的最长子串.py
lovehhf/LeetCode
train
0
2259e2431ace6d5cb0e49a13846306c652976c4c
[ "global channel_list_page, admin_page\nchannel_list_page = ChannelListPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道业务管理')", "admin_page.select_menu('渠道列表')\nchannel_list_page.simple_query_channel(channel_name='三沙市')\nassert '三沙市' in channe...
<|body_start_0|> global channel_list_page, admin_page channel_list_page = ChannelListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道业务管理') <|end_body_0|> <|body_start_1|> admin_page.select_menu('渠道列表')...
TestChannelList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestChannelList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_channel(self, set_up): """渠道查询 :return:""" <|body_1|> def test_reset_channel_query(self): """重置渠道列表查询 :return:""" <|body_2|> def test_click_more_channel...
stack_v2_sparse_classes_36k_train_002995
2,199
no_license
[ { "docstring": "前置操作 :return:", "name": "set_up", "signature": "def set_up(self)" }, { "docstring": "渠道查询 :return:", "name": "test_query_channel", "signature": "def test_query_channel(self, set_up)" }, { "docstring": "重置渠道列表查询 :return:", "name": "test_reset_channel_query", ...
5
null
Implement the Python class `TestChannelList` described below. Class description: Implement the TestChannelList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_channel(self, set_up): 渠道查询 :return: - def test_reset_channel_query(self): 重置渠道列表查询 :return: - def test_click_more_...
Implement the Python class `TestChannelList` described below. Class description: Implement the TestChannelList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_channel(self, set_up): 渠道查询 :return: - def test_reset_channel_query(self): 重置渠道列表查询 :return: - def test_click_more_...
86d1b085af2d3808ac8472d541f4bf26d26591e0
<|skeleton|> class TestChannelList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_channel(self, set_up): """渠道查询 :return:""" <|body_1|> def test_reset_channel_query(self): """重置渠道列表查询 :return:""" <|body_2|> def test_click_more_channel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestChannelList: def set_up(self): """前置操作 :return:""" global channel_list_page, admin_page channel_list_page = ChannelListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道业务管理') def test_q...
the_stack_v2_python_sparse
src/cases/business_manage/channel_business_manage/test_channel_list_page_140.py
102244653/SeleniumByPython
train
2
62faaccf74199d4800fa9dd50b65ab42be2e855f
[ "self.num_parallel_calls = tf.convert_to_tensor(num_parallel_calls, tf.int32)\nself.event_size = tf.convert_to_tensor(event_size, tf.int32)\nself.data = [tf.cast(c, float_type) if c.dtype is not float_type else c for c in data]\nself.index_feed = index_feed\nself.slice_size = self.index_feed.step\nwith tf.control_d...
<|body_start_0|> self.num_parallel_calls = tf.convert_to_tensor(num_parallel_calls, tf.int32) self.event_size = tf.convert_to_tensor(event_size, tf.int32) self.data = [tf.cast(c, float_type) if c.dtype is not float_type else c for c in data] self.index_feed = index_feed self.slic...
DataFeed
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFeed: def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_calls=10): """Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of float_type, Tensor, [Nt, ..., D] Data to grab unflattened :param num_parallel_calls:""" <|bo...
stack_v2_sparse_classes_36k_train_002996
18,860
permissive
[ { "docstring": "Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of float_type, Tensor, [Nt, ..., D] Data to grab unflattened :param num_parallel_calls:", "name": "__init__", "signature": "def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_cal...
2
stack_v2_sparse_classes_30k_train_016004
Implement the Python class `DataFeed` described below. Class description: Implement the DataFeed class. Method signatures and docstrings: - def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_calls=10): Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of flo...
Implement the Python class `DataFeed` described below. Class description: Implement the DataFeed class. Method signatures and docstrings: - def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_calls=10): Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of flo...
2997d60d8cf07f875e42c0b5f07944e9ab7e9d33
<|skeleton|> class DataFeed: def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_calls=10): """Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of float_type, Tensor, [Nt, ..., D] Data to grab unflattened :param num_parallel_calls:""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataFeed: def __init__(self, index_feed: IndexFeed, *data, event_size=1, num_parallel_calls=10): """Create a time feed :param index_feed: IndexFeed Pulse of this feed :param data: list of float_type, Tensor, [Nt, ..., D] Data to grab unflattened :param num_parallel_calls:""" self.num_parallel_...
the_stack_v2_python_sparse
bayes_filter/feeds.py
Joshuaalbert/bayes_filter
train
0
49b30b7fe93956329bc1fc8ffe663f976f1ba00b
[ "ans = 0\nfor item in S:\n if item in J:\n ans += 1\nreturn ans", "mydict = {}\nfor item in J:\n if item in mydict.keys():\n mydict[item] += 1\n else:\n mydict[item] = 1\nans = 0\nfor item in S:\n if item in mydict.keys():\n ans += 1\nreturn ans" ]
<|body_start_0|> ans = 0 for item in S: if item in J: ans += 1 return ans <|end_body_0|> <|body_start_1|> mydict = {} for item in J: if item in mydict.keys(): mydict[item] += 1 else: mydict[item]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numJewelsInStones(self, J, S): """:type J: str :type S: str :rtype: int""" <|body_0|> def numJewelsInStones2(self, J, S): """:type J: str :type S: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ans = 0 for item...
stack_v2_sparse_classes_36k_train_002997
1,186
no_license
[ { "docstring": ":type J: str :type S: str :rtype: int", "name": "numJewelsInStones", "signature": "def numJewelsInStones(self, J, S)" }, { "docstring": ":type J: str :type S: str :rtype: int", "name": "numJewelsInStones2", "signature": "def numJewelsInStones2(self, J, S)" } ]
2
stack_v2_sparse_classes_30k_train_010882
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numJewelsInStones(self, J, S): :type J: str :type S: str :rtype: int - def numJewelsInStones2(self, J, S): :type J: str :type S: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numJewelsInStones(self, J, S): :type J: str :type S: str :rtype: int - def numJewelsInStones2(self, J, S): :type J: str :type S: str :rtype: int <|skeleton|> class Solution:...
690b685048c8e89d26047b6bc48b5f9af7d59cbb
<|skeleton|> class Solution: def numJewelsInStones(self, J, S): """:type J: str :type S: str :rtype: int""" <|body_0|> def numJewelsInStones2(self, J, S): """:type J: str :type S: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numJewelsInStones(self, J, S): """:type J: str :type S: str :rtype: int""" ans = 0 for item in S: if item in J: ans += 1 return ans def numJewelsInStones2(self, J, S): """:type J: str :type S: str :rtype: int""" myd...
the_stack_v2_python_sparse
哈希表/771. 宝石与石头.py
SimmonsChen/LeetCode
train
0
ac2b79ed7726626b548e71e2fee40a984ad157a5
[ "def cal(s):\n sum_1 = 0\n for char in s:\n if char == '1':\n sum_1 += 1\n return sum_1\nprime = {2, 3, 5, 7, 11, 13, 17, 19, 23}\nans = 0\nfor i in range(L, R + 1):\n if cal(bin(i)[2:]) in prime:\n ans += 1\nreturn ans", "count = 0\nfor x in range(L, R + 1):\n num = bin(x)...
<|body_start_0|> def cal(s): sum_1 = 0 for char in s: if char == '1': sum_1 += 1 return sum_1 prime = {2, 3, 5, 7, 11, 13, 17, 19, 23} ans = 0 for i in range(L, R + 1): if cal(bin(i)[2:]) in prime: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int 1138ms""" <|body_0|> def countPrimeSetBits_1(self, L, R): """1488ms :param L: :param R: :return:""" <|body_1|> def countPrimeSetBits_2(self, L, R): """63ms :par...
stack_v2_sparse_classes_36k_train_002998
2,525
no_license
[ { "docstring": ":type L: int :type R: int :rtype: int 1138ms", "name": "countPrimeSetBits", "signature": "def countPrimeSetBits(self, L, R)" }, { "docstring": "1488ms :param L: :param R: :return:", "name": "countPrimeSetBits_1", "signature": "def countPrimeSetBits_1(self, L, R)" }, {...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int 1138ms - def countPrimeSetBits_1(self, L, R): 1488ms :param L: :param R: :return: - def countPrimeSetBits...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int 1138ms - def countPrimeSetBits_1(self, L, R): 1488ms :param L: :param R: :return: - def countPrimeSetBits...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int 1138ms""" <|body_0|> def countPrimeSetBits_1(self, L, R): """1488ms :param L: :param R: :return:""" <|body_1|> def countPrimeSetBits_2(self, L, R): """63ms :par...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int 1138ms""" def cal(s): sum_1 = 0 for char in s: if char == '1': sum_1 += 1 return sum_1 prime = {2, 3, 5, 7, 11, 13, 17, 19, 23} ...
the_stack_v2_python_sparse
PrimeNumberOfSetBitsInBinaryRepresentation_762.py
953250587/leetcode-python
train
2
8d3fbc72f95891fe45b86724380600c7616d8be8
[ "low = self.action_space.low\nhigh = self.action_space.high\nscale_factor = (high - low) / 2\nreloc_factor = high - scale_factor\naction = action * scale_factor + reloc_factor\naction = np.clip(action, low, high)\nreturn action", "low = self.action_space.low\nhigh = self.action_space.high\nscale_factor = (high - ...
<|body_start_0|> low = self.action_space.low high = self.action_space.high scale_factor = (high - low) / 2 reloc_factor = high - scale_factor action = action * scale_factor + reloc_factor action = np.clip(action, low, high) return action <|end_body_0|> <|body_sta...
Rescale and relocate the actions.
ActionNormalizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActionNormalizer: """Rescale and relocate the actions.""" def action(self, action: np.ndarray) -> np.ndarray: """Change the range (-1, 1) to (low, high).""" <|body_0|> def reverse_action(self, action: np.ndarray) -> np.ndarray: """Change the range (low, high) to ...
stack_v2_sparse_classes_36k_train_002999
13,315
no_license
[ { "docstring": "Change the range (-1, 1) to (low, high).", "name": "action", "signature": "def action(self, action: np.ndarray) -> np.ndarray" }, { "docstring": "Change the range (low, high) to (-1, 1).", "name": "reverse_action", "signature": "def reverse_action(self, action: np.ndarray...
2
stack_v2_sparse_classes_30k_train_002631
Implement the Python class `ActionNormalizer` described below. Class description: Rescale and relocate the actions. Method signatures and docstrings: - def action(self, action: np.ndarray) -> np.ndarray: Change the range (-1, 1) to (low, high). - def reverse_action(self, action: np.ndarray) -> np.ndarray: Change the ...
Implement the Python class `ActionNormalizer` described below. Class description: Rescale and relocate the actions. Method signatures and docstrings: - def action(self, action: np.ndarray) -> np.ndarray: Change the range (-1, 1) to (low, high). - def reverse_action(self, action: np.ndarray) -> np.ndarray: Change the ...
14ddfb81295c349acc2ede7588ebc73c235246c0
<|skeleton|> class ActionNormalizer: """Rescale and relocate the actions.""" def action(self, action: np.ndarray) -> np.ndarray: """Change the range (-1, 1) to (low, high).""" <|body_0|> def reverse_action(self, action: np.ndarray) -> np.ndarray: """Change the range (low, high) to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ActionNormalizer: """Rescale and relocate the actions.""" def action(self, action: np.ndarray) -> np.ndarray: """Change the range (-1, 1) to (low, high).""" low = self.action_space.low high = self.action_space.high scale_factor = (high - low) / 2 reloc_factor = hig...
the_stack_v2_python_sparse
PPO_GAE_TEST/PPO_gae_test2.py
namjiwon1023/Reinforcement_learning
train
2