blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dab5075d356e6e99e81f0510720027b5b7d7a5b9 | [
"self.resource = resource\nself.inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=[])\nself.gen_inventory()",
"my_group = Group(name=groupname)\nif groupvars:\n for key, value in groupvars.iteritems():\n my_group.set_variable(key, value)\nfor host in hosts:\n hostname ... | <|body_start_0|>
self.resource = resource
self.inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=[])
self.gen_inventory()
<|end_body_0|>
<|body_start_1|>
my_group = Group(name=groupname)
if groupvars:
for key, value in groupvars.iterit... | this is my ansible inventory object. | MyInventory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": va... | stack_v2_sparse_classes_10k_train_002800 | 8,816 | permissive | [
{
"docstring": "resource的数据格式是一个列表字典,比如 { \"group1\": { \"hosts\": [{\"hostname\": \"10.0.0.0\", \"port\": \"22\", \"username\": \"test\", \"password\": \"pass\"}, ...], \"vars\": {\"var1\": value1, \"var2\": value2, ...} } } 如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如 [{\"hostname\": \"10.0.0.0\", \"port\": \"22\", ... | 3 | stack_v2_sparse_classes_30k_train_000656 | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "pass... | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "pass... | eb9373434d1ca069fd37ae6688d140d99a319294 | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": va... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": value2, ...} } ... | the_stack_v2_python_sparse | apps/myapp/ansible_api.py.bak | chenhuxy/myweb | train | 14 |
dcaee25ef2eae840730946cde9009cf88a030689 | [
"def isCompleteSubTree(root):\n if not root:\n return (0, 0)\n if root:\n left_deep = isCompleteSubTree(root.left)\n right_deep = isCompleteSubTree(root.right)\n print(root.val, left_deep, right_deep)\n if not left_deep or not right_deep:\n return None\n if... | <|body_start_0|>
def isCompleteSubTree(root):
if not root:
return (0, 0)
if root:
left_deep = isCompleteSubTree(root.left)
right_deep = isCompleteSubTree(root.right)
print(root.val, left_deep, right_deep)
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool 44 ms"""
<|body_0|>
def isCompleteTree_1(self, root):
""":type root: TreeNode :rtype: bool 24ms 排序输出查看情况"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def isCompleteSub... | stack_v2_sparse_classes_10k_train_002801 | 3,277 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool 44 ms",
"name": "isCompleteTree",
"signature": "def isCompleteTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool 24ms 排序输出查看情况",
"name": "isCompleteTree_1",
"signature": "def isCompleteTree_1(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCompleteTree(self, root): :type root: TreeNode :rtype: bool 44 ms
- def isCompleteTree_1(self, root): :type root: TreeNode :rtype: bool 24ms 排序输出查看情况 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCompleteTree(self, root): :type root: TreeNode :rtype: bool 44 ms
- def isCompleteTree_1(self, root): :type root: TreeNode :rtype: bool 24ms 排序输出查看情况
<|skeleton|>
class So... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool 44 ms"""
<|body_0|>
def isCompleteTree_1(self, root):
""":type root: TreeNode :rtype: bool 24ms 排序输出查看情况"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool 44 ms"""
def isCompleteSubTree(root):
if not root:
return (0, 0)
if root:
left_deep = isCompleteSubTree(root.left)
right_deep = isCompleteSubTr... | the_stack_v2_python_sparse | CheckCompletenessOfABinaryTree_MID_958.py | 953250587/leetcode-python | train | 2 | |
5c4a99d14f7f70f4f3b18bd3de95055468f7c09e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.deviceAndAppManagementRoleAssignment'.casef... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles. | RoleAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleAssignment:
"""The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None... | stack_v2_sparse_classes_10k_train_002802 | 3,985 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: RoleAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `RoleAssignment` described below.
Class description:
The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.
Method signatures and docstrings:
- def ... | Implement the Python class `RoleAssignment` described below.
Class description:
The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles.
Method signatures and docstrings:
- def ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RoleAssignment:
"""The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoleAssignment:
"""The Role Assignment resource. Role assignments tie together a role definition with members and scopes. There can be one or more role assignments per role. This applies to custom and built-in roles."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RoleAssi... | the_stack_v2_python_sparse | msgraph/generated/models/role_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 |
5966fc65dc15b01fd857b743e91d49e4559a6bc3 | [
"self.method = method\nself.uri = uri\nself.propstats = []\nself.success_response = success_response",
"if type(what) is int:\n code = what\n error = None\n message = responsecode.RESPONSES[code]\nelif isinstance(what, Failure):\n code = statusForFailure(what)\n error = errorForFailure(what)\n m... | <|body_start_0|>
self.method = method
self.uri = uri
self.propstats = []
self.success_response = success_response
<|end_body_0|>
<|body_start_1|>
if type(what) is int:
code = what
error = None
message = responsecode.RESPONSES[code]
eli... | Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}. | PropertyStatusResponseQueue | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param s... | stack_v2_sparse_classes_10k_train_002803 | 13,040 | permissive | [
{
"docstring": "@param method: the name of the method generating the queue. @param uri: the URI for the response. @param success_response: the status to return if no L{PropertyStatus} are added to this queue.",
"name": "__init__",
"signature": "def __init__(self, method, uri, success_response)"
},
{... | 4 | null | Implement the Python class `PropertyStatusResponseQueue` described below.
Class description:
Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, method, uri, success_response): @param method: the name of the method generating ... | Implement the Python class `PropertyStatusResponseQueue` described below.
Class description:
Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, method, uri, success_response): @param method: the name of the method generating ... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PropertyStatusResponseQueue:
"""Stores a list of propstat elements for use in a L{Response} in a L{MultiStatusResponse}."""
def __init__(self, method, uri, success_response):
"""@param method: the name of the method generating the queue. @param uri: the URI for the response. @param success_respon... | the_stack_v2_python_sparse | txweb2/dav/http.py | ass-a2s/ccs-calendarserver | train | 2 |
394b10ed158286c957616e271e7903476e876a31 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"tantum_match = re.search('_(s[ei])$', tnode.t_lemma)\nif tantum_match:\n refl_form = tantum_match.group(1)\n afun = 'AuxT'\nelif tnode.voice == 'reflexive_diathesis' or tnode.gram_dia... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
tantum_match = re.search('_(s[ei])$', tnode.t_lemma)
if tantum_match:
refl_form = tantum_match.grou... | Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree | AddReflexiveParticles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_10k_train_002804 | 1,857 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add reflexive particle to a node, if applicable.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000292 | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Blo... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addreflexiveparticles.py | oplatek/alex | train | 0 |
3dd3575ebec635de76b5e99550f7e1160b7cd75e | [
"commit_datetime = git_metadata_utils.get_head_commit_datetime(git_repo=_CHROMIUM_SRC_ROOT)\nself.assertIsNotNone(commit_datetime.tzinfo)\nself.assertIsNotNone(commit_datetime.utcoffset())\nself.assertEqual(timezone.utc, commit_datetime.tzinfo)\nself.assertGreater(commit_datetime, datetime(2021, 10, 5, tzinfo=timez... | <|body_start_0|>
commit_datetime = git_metadata_utils.get_head_commit_datetime(git_repo=_CHROMIUM_SRC_ROOT)
self.assertIsNotNone(commit_datetime.tzinfo)
self.assertIsNotNone(commit_datetime.utcoffset())
self.assertEqual(timezone.utc, commit_datetime.tzinfo)
self.assertGreater(com... | Tests for the get_head_commit_datetime function. | TestHeadCommitDatetime | [
"LGPL-2.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"LGPL-2.0-only",
"LicenseRef-scancode-unknown",
"LGPL-2.1-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"APSL-2.0",
"MPL-1.1",
"Zlib"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHeadCommitDatetime:
"""Tests for the get_head_commit_datetime function."""
def test_get_head_commit_datetime_chromium_repo(self):
"""Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is not naive (has a timezone, specifically UTC) and that th... | stack_v2_sparse_classes_10k_train_002805 | 7,599 | permissive | [
{
"docstring": "Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is not naive (has a timezone, specifically UTC) and that the datetime is sane.",
"name": "test_get_head_commit_datetime_chromium_repo",
"signature": "def test_get_head_commit_datetime_chromium_repo(se... | 6 | null | Implement the Python class `TestHeadCommitDatetime` described below.
Class description:
Tests for the get_head_commit_datetime function.
Method signatures and docstrings:
- def test_get_head_commit_datetime_chromium_repo(self): Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is... | Implement the Python class `TestHeadCommitDatetime` described below.
Class description:
Tests for the get_head_commit_datetime function.
Method signatures and docstrings:
- def test_get_head_commit_datetime_chromium_repo(self): Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is... | 87244f4ee50062e59667bf8b9ca4d5291b6818d7 | <|skeleton|>
class TestHeadCommitDatetime:
"""Tests for the get_head_commit_datetime function."""
def test_get_head_commit_datetime_chromium_repo(self):
"""Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is not naive (has a timezone, specifically UTC) and that th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestHeadCommitDatetime:
"""Tests for the get_head_commit_datetime function."""
def test_get_head_commit_datetime_chromium_repo(self):
"""Tests that get_head_commit_datetime returns a commit datetime. Checks that the datetime is not naive (has a timezone, specifically UTC) and that the datetime is... | the_stack_v2_python_sparse | chromium/tools/android/python_utils/git_metadata_utils_unittest.py | ric2b/Vivaldi-browser | train | 166 |
3b3e1b114ca0a4c4562e4d28b4a5aa6f586c7431 | [
"if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)):\n for anchor in anchor_list:\n pprint('%s is the achor of %s' % (anchor.name, [feature.name for feature in anchor.features]))\nelse:\n raise TypeError('anchor_list must be FeatureAnchor or List[FeatureAnchor]')",
"if isinstance(f... | <|body_start_0|>
if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)):
for anchor in anchor_list:
pprint('%s is the achor of %s' % (anchor.name, [feature.name for feature in anchor.features]))
else:
raise TypeError('anchor_list must be FeatureAnch... | The class for pretty-printing features | FeaturePrinter | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeaturePrinter:
"""The class for pretty-printing features"""
def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None:
"""Pretty print features Args: feature_list: FeatureAnchor"""
<|body_0|>
def pretty_print_feature_query(feature_query: FeatureQuery) -> None:
... | stack_v2_sparse_classes_10k_train_002806 | 1,725 | permissive | [
{
"docstring": "Pretty print features Args: feature_list: FeatureAnchor",
"name": "pretty_print_anchors",
"signature": "def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None"
},
{
"docstring": "Pretty print feature query Args: feature_query: feature query",
"name": "pretty_print... | 3 | null | Implement the Python class `FeaturePrinter` described below.
Class description:
The class for pretty-printing features
Method signatures and docstrings:
- def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: Pretty print features Args: feature_list: FeatureAnchor
- def pretty_print_feature_query(featur... | Implement the Python class `FeaturePrinter` described below.
Class description:
The class for pretty-printing features
Method signatures and docstrings:
- def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: Pretty print features Args: feature_list: FeatureAnchor
- def pretty_print_feature_query(featur... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class FeaturePrinter:
"""The class for pretty-printing features"""
def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None:
"""Pretty print features Args: feature_list: FeatureAnchor"""
<|body_0|>
def pretty_print_feature_query(feature_query: FeatureQuery) -> None:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeaturePrinter:
"""The class for pretty-printing features"""
def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None:
"""Pretty print features Args: feature_list: FeatureAnchor"""
if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)):
for anchor in a... | the_stack_v2_python_sparse | ai/feathr/feathr_project/feathr/utils/feature_printer.py | alldatacenter/alldata | train | 774 |
c110498e102aebfbc90fba86602a541e5d5ceb29 | [
"self.p = p\nfrom sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\nself.ring = PolynomialRing(FiniteField(p), 'x')\nif use_database:\n C = sage.databases.conway.ConwayPolynomials()\n self.nodes = {n: self.ring(C.polynomial(p, n)) for n in C.degrees(p)}\nelse:\n self.nodes = {}",
"... | <|body_start_0|>
self.p = p
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
self.ring = PolynomialRing(FiniteField(p), 'x')
if use_database:
C = sage.databases.conway.ConwayPolynomials()
self.nodes = {n: self.ring(C.polynomial(p, n)) f... | A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`, the element `x\\bmod f_n` generates the multiplicative group. - The minimal polynomia... | PseudoConwayLattice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PseudoConwayLattice:
"""A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`, the element `x\\bmod f_n` generates th... | stack_v2_sparse_classes_10k_train_002807 | 18,867 | no_license | [
{
"docstring": "TESTS:: sage: from sage.rings.finite_rings.conway_polynomials import PseudoConwayLattice sage: PCL = PseudoConwayLattice(3) sage: PCL.polynomial(3) x^3 + 2*x + 1 sage: PCL = PseudoConwayLattice(5, use_database=False) sage: PCL.polynomial(12) x^12 + 4*x^11 + 2*x^10 + 4*x^9 + 2*x^8 + 2*x^7 + 4*x^6... | 3 | null | Implement the Python class `PseudoConwayLattice` described below.
Class description:
A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`,... | Implement the Python class `PseudoConwayLattice` described below.
Class description:
A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`,... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class PseudoConwayLattice:
"""A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`, the element `x\\bmod f_n` generates th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PseudoConwayLattice:
"""A pseudo-Conway lattice over a given finite prime field. The Conway polynomial `f_n` of degree `n` over `\\Bold{F}_p` is defined by the following four conditions: - `f_n` is irreducible. - In the quotient field `\\Bold{F}_p[x]/(f_n)`, the element `x\\bmod f_n` generates the multiplicat... | the_stack_v2_python_sparse | sage/src/sage/rings/finite_rings/conway_polynomials.py | bopopescu/geosci | train | 0 |
0828fb0729244f70b2d9b4837b53781fa9ba93aa | [
"super(RegExEdge, self).__init__(label)\nself.from_regex = from_regex\nself.to_regex = to_regex\nself.weight = weight",
"res_id_strct = IDStruct()\nfor left, right in id_strct:\n res_id_strct.add(left, re.sub(self.from_regex, self.to_regex, right))\nreturn res_id_strct"
] | <|body_start_0|>
super(RegExEdge, self).__init__(label)
self.from_regex = from_regex
self.to_regex = to_regex
self.weight = weight
<|end_body_0|>
<|body_start_1|>
res_id_strct = IDStruct()
for left, right in id_strct:
res_id_strct.add(left, re.sub(self.from_r... | The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported. | RegExEdge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution.... | stack_v2_sparse_classes_10k_train_002808 | 22,080 | permissive | [
{
"docstring": ":param from_regex: The first parameter of the regular expression substitution. :type from_regex: str :param to_regex: The second parameter of the regular expression substitution. :type to_regex: str :param weight: Weights are used to prefer one path over another. The path with the lowest weight ... | 2 | stack_v2_sparse_classes_30k_train_000032 | Implement the Python class `RegExEdge` described below.
Class description:
The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported.
Method signatures and docstrings:
- def __init__(self, from_regex, to_regex, weight=1, label=None): :param from_regex: Th... | Implement the Python class `RegExEdge` described below.
Class description:
The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported.
Method signatures and docstrings:
- def __init__(self, from_regex, to_regex, weight=1, label=None): :param from_regex: Th... | 2c23e0da57b7c64b0a19e534b9f75da70f140159 | <|skeleton|>
class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution. :type from_r... | the_stack_v2_python_sparse | biothings/hub/datatransform/datatransform.py | biothings/biothings.api | train | 36 |
54cbe225c4d9de7369dd4e457804faee0020c705 | [
"super().__init__()\nself.queries = queries\nself.query_labels: IntTensor = tf.cast(tf.convert_to_tensor(query_labels), dtype='int32')\nself.targets = targets\nself.target_labels = target_labels\nself.distance = distance\nself.evaluator = MemoryEvaluator()\nself.metrics: List[ClassificationMetric] = [make_classific... | <|body_start_0|>
super().__init__()
self.queries = queries
self.query_labels: IntTensor = tf.cast(tf.convert_to_tensor(query_labels), dtype='int32')
self.targets = targets
self.target_labels = target_labels
self.distance = distance
self.evaluator = MemoryEvaluator... | Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive. | EvalCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvalCallback:
"""Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive."""
def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequ... | stack_v2_sparse_classes_10k_train_002809 | 15,886 | permissive | [
{
"docstring": "Evaluate model matching quality against a validation dataset at epoch end. Args: queries: Test examples that will be tested against the built index. query_labels: Queries nearest neighbors expected labels. targets: Examples that are indexed. target_labels: Target examples labels. distance: Dista... | 2 | stack_v2_sparse_classes_30k_test_000400 | Implement the Python class `EvalCallback` described below.
Class description:
Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.
Method signatures and docstrings:
- def __init__(self, queries: Tenso... | Implement the Python class `EvalCallback` described below.
Class description:
Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive.
Method signatures and docstrings:
- def __init__(self, queries: Tenso... | 99642bcd33c3e54dfef01a0f9d82823418c0e918 | <|skeleton|>
class EvalCallback:
"""Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive."""
def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EvalCallback:
"""Epoch end evaluation callback that build a test index and evaluate model performance on it. This evaluation only run at epoch_end as it is computationally very expensive."""
def __init__(self, queries: Tensor, query_labels: Sequence[int], targets: Tensor, target_labels: Sequence[int], di... | the_stack_v2_python_sparse | tensorflow_similarity/callbacks.py | aditigarg2810/similarity | train | 0 |
8f9826e7d97a95917e39842cb642baf24cc5eaac | [
"def partition(nums, left, right):\n pivot = nums[left]\n while left < right:\n while left < right and nums[right] >= pivot:\n right -= 1\n nums[left] = nums[right]\n while left < right and nums[left] <= pivot:\n left += 1\n nums[right] = nums[left]\n nums[... | <|body_start_0|>
def partition(nums, left, right):
pivot = nums[left]
while left < right:
while left < right and nums[right] >= pivot:
right -= 1
nums[left] = nums[right]
while left < right and nums[left] <= pivot:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
<|body_0|>
def min_k_num1(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_002810 | 2,555 | no_license | [
{
"docstring": "给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。",
"name": "min_k_num",
"signature": "def min_k_num(self, nums, k)"
},
{
"docstring": "给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。",
"name": "min_k_num1",
"signature": "def min_k_num1(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_k_num(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。
- def min_k_num1(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_k_num(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。
- def min_k_num1(self, nums, k): 给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间... | ca4dacda39dc12d53ed8d4448b3356a3f2936603 | <|skeleton|>
class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
<|body_0|>
def min_k_num1(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 此处可以使用大顶堆来做,时间复杂度为O(nlogk)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def min_k_num(self, nums, k):
"""给定一个无序数组,输出其中最小的k个数值。 借鉴快速排序中的partition操作,直到当前的pivot的位置为数组的第k个位置即可。时间复杂度为O(n)。"""
def partition(nums, left, right):
pivot = nums[left]
while left < right:
while left < right and nums[right] >= pivot:
... | the_stack_v2_python_sparse | book/面试题40-最小的k个数.py | lcqbit11/algorithms | train | 0 | |
6de916fb17caf7136b22033461b2ececfa2bfcdf | [
"data = super()._from_dict_transform(data)\nif 'verified' in data:\n data['is_verified'] = data.pop('verified')\nif 'verification_code' in data:\n del data['verification_code']\nreturn data",
"if 'is_verified' in data:\n data['verified'] = data.pop('is_verified')\ndata = super()._to_dict_transform(data)\... | <|body_start_0|>
data = super()._from_dict_transform(data)
if 'verified' in data:
data['is_verified'] = data.pop('verified')
if 'verification_code' in data:
del data['verification_code']
return data
<|end_body_0|>
<|body_start_1|>
if 'is_verified' in data... | Elements that can be verified or not. | VerifiedElement | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifiedElement:
"""Elements that can be verified or not."""
def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]:
"""Transform data received in eduid format into pythonic format."""
<|body_0|>
def _to_dict_transform(self,... | stack_v2_sparse_classes_10k_train_002811 | 18,109 | permissive | [
{
"docstring": "Transform data received in eduid format into pythonic format.",
"name": "_from_dict_transform",
"signature": "def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]"
},
{
"docstring": "Transform data kept in pythonic format into edui... | 2 | stack_v2_sparse_classes_30k_train_004202 | Implement the Python class `VerifiedElement` described below.
Class description:
Elements that can be verified or not.
Method signatures and docstrings:
- def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]: Transform data received in eduid format into pythonic format... | Implement the Python class `VerifiedElement` described below.
Class description:
Elements that can be verified or not.
Method signatures and docstrings:
- def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]: Transform data received in eduid format into pythonic format... | 5970880caf0b0e2bdee6c23869ef287acc87af2a | <|skeleton|>
class VerifiedElement:
"""Elements that can be verified or not."""
def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]:
"""Transform data received in eduid format into pythonic format."""
<|body_0|>
def _to_dict_transform(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VerifiedElement:
"""Elements that can be verified or not."""
def _from_dict_transform(cls: Type[TVerifiedElementSubclass], data: Dict[str, Any]) -> Dict[str, Any]:
"""Transform data received in eduid format into pythonic format."""
data = super()._from_dict_transform(data)
if 'ver... | the_stack_v2_python_sparse | src/eduid_userdb/element.py | SUNET/eduid-userdb | train | 0 |
42305a3a50c3af039dce76843791a38f88c54719 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the FeedMapping service. Service to manage feed mappings. | FeedMappingServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
<|body_0|>
def MutateFeedMappings(self, request, context... | stack_v2_sparse_classes_10k_train_002812 | 3,358 | permissive | [
{
"docstring": "Returns the requested feed mapping in full detail.",
"name": "GetFeedMapping",
"signature": "def GetFeedMapping(self, request, context)"
},
{
"docstring": "Creates or removes feed mappings. Operation statuses are returned.",
"name": "MutateFeedMappings",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_002190 | Implement the Python class `FeedMappingServiceServicer` described below.
Class description:
Proto file describing the FeedMapping service. Service to manage feed mappings.
Method signatures and docstrings:
- def GetFeedMapping(self, request, context): Returns the requested feed mapping in full detail.
- def MutateFee... | Implement the Python class `FeedMappingServiceServicer` described below.
Class description:
Proto file describing the FeedMapping service. Service to manage feed mappings.
Method signatures and docstrings:
- def GetFeedMapping(self, request, context): Returns the requested feed mapping in full detail.
- def MutateFee... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
<|body_0|>
def MutateFeedMappings(self, request, context... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detail... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/feed_mapping_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
16a8c6bfb0d1cb58f70f1415d4760111ed9da2c6 | [
"mediator = UnattendedVolumeScannerMediator()\ntype(mock_volumesystem.return_value).number_of_volumes = 1\nvolume_system = dfvfs_volume_system.VolumeSystem()\nvolume_identifiers = ['apfs1']\nresult = mediator.GetAPFSVolumeIdentifiers(volume_system, volume_identifiers)\nself.assertEqual(result, volume_identifiers)",... | <|body_start_0|>
mediator = UnattendedVolumeScannerMediator()
type(mock_volumesystem.return_value).number_of_volumes = 1
volume_system = dfvfs_volume_system.VolumeSystem()
volume_identifiers = ['apfs1']
result = mediator.GetAPFSVolumeIdentifiers(volume_system, volume_identifiers)... | Test the UnattendedVolumeScannerMediator class. | TestUnattendedVolumeScannerMediator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUnattendedVolumeScannerMediator:
"""Test the UnattendedVolumeScannerMediator class."""
def testGetAPFSVolumeIdentifiers(self, mock_volumesystem):
"""Test the GetAPFSVolumeIdentifiers function."""
<|body_0|>
def testGetPartitionIdentifiers(self, mock_volumesystem):
... | stack_v2_sparse_classes_10k_train_002813 | 3,628 | permissive | [
{
"docstring": "Test the GetAPFSVolumeIdentifiers function.",
"name": "testGetAPFSVolumeIdentifiers",
"signature": "def testGetAPFSVolumeIdentifiers(self, mock_volumesystem)"
},
{
"docstring": "Test the GetPartitionIdentifiers function.",
"name": "testGetPartitionIdentifiers",
"signature... | 4 | stack_v2_sparse_classes_30k_val_000363 | Implement the Python class `TestUnattendedVolumeScannerMediator` described below.
Class description:
Test the UnattendedVolumeScannerMediator class.
Method signatures and docstrings:
- def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): Test the GetAPFSVolumeIdentifiers function.
- def testGetPartitionIdentifi... | Implement the Python class `TestUnattendedVolumeScannerMediator` described below.
Class description:
Test the UnattendedVolumeScannerMediator class.
Method signatures and docstrings:
- def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): Test the GetAPFSVolumeIdentifiers function.
- def testGetPartitionIdentifi... | e73717549c6919e869ce4963449c36f227e3ccd6 | <|skeleton|>
class TestUnattendedVolumeScannerMediator:
"""Test the UnattendedVolumeScannerMediator class."""
def testGetAPFSVolumeIdentifiers(self, mock_volumesystem):
"""Test the GetAPFSVolumeIdentifiers function."""
<|body_0|>
def testGetPartitionIdentifiers(self, mock_volumesystem):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestUnattendedVolumeScannerMediator:
"""Test the UnattendedVolumeScannerMediator class."""
def testGetAPFSVolumeIdentifiers(self, mock_volumesystem):
"""Test the GetAPFSVolumeIdentifiers function."""
mediator = UnattendedVolumeScannerMediator()
type(mock_volumesystem.return_value)... | the_stack_v2_python_sparse | turbinia/lib/dfvfs_classes_test.py | Ash515/turbinia | train | 6 |
7bba5445d50a0c8a8f23d5c74fb3669761addd0c | [
"self.name = name\nself.light = light\nif self.light:\n self.d = common_light.copy()\nelse:\n self.d = common_dark.copy()\nself.d.update(extra)",
"if self.light:\n self.d.update({k: common_light[k] for k in common_light if k not in self.d})\nelse:\n self.d.update({k: common_dark[k] for k in common_dar... | <|body_start_0|>
self.name = name
self.light = light
if self.light:
self.d = common_light.copy()
else:
self.d = common_dark.copy()
self.d.update(extra)
<|end_body_0|>
<|body_start_1|>
if self.light:
self.d.update({k: common_light[k] fo... | Abstract class that represents a theme | Theme | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_pref... | stack_v2_sparse_classes_10k_train_002814 | 18,193 | no_license | [
{
"docstring": "Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_prefs': value => a Color some keys in 'variant_prefs': value => a tuple (weight, fg, bg) where weight is \"DEFAULT\", \"N... | 3 | stack_v2_sparse_classes_30k_train_002806 | Implement the Python class `Theme` described below.
Class description:
Abstract class that represents a theme
Method signatures and docstrings:
- def __init__(self, name, light=True, extra=None): Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys... | Implement the Python class `Theme` described below.
Class description:
Abstract class that represents a theme
Method signatures and docstrings:
- def __init__(self, name, light=True, extra=None): Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys... | 5b91c1816aadfa3a08bba730b8dfd3f6a0785463 | <|skeleton|>
class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_pref... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Theme:
"""Abstract class that represents a theme"""
def __init__(self, name, light=True, extra=None):
"""Initialise. light indicates whether to initialize with the light theme color values. Extra is a dict containing: some keys in 'css_colors': value => a Color some keys in 'rgb_prefs': value => ... | the_stack_v2_python_sparse | Code/share/gps/support/ui/theme_handling.py | AaronC98/PlaneSystem | train | 0 |
545fed3f1a27a00c8da8f7b56d5a0ab5ff200dce | [
"self.headers = headers or {}\nself.cookies = cookies or {}\nif request:\n token = request.QUERY.get(settings.SESSION_COOKIE_NAME) or request.META.get('HTTP_TBKT_TOKEN') or request.COOKIES.get('tbkt_token')\n self.cookies['tbkt_token'] = token",
"assert alias in settings.API_URLROOT, alias\nurlroot = settin... | <|body_start_0|>
self.headers = headers or {}
self.cookies = cookies or {}
if request:
token = request.QUERY.get(settings.SESSION_COOKIE_NAME) or request.META.get('HTTP_TBKT_TOKEN') or request.COOKIES.get('tbkt_token')
self.cookies['tbkt_token'] = token
<|end_body_0|>
<|... | Hub | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hub:
def __init__(self, request=None, headers=None, cookies=None):
""":param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典"""
<|body_0|>
def __getattr__(self, alias):
""":param alias: 接口服务器别名 公... | stack_v2_sparse_classes_10k_train_002815 | 4,472 | no_license | [
{
"docstring": ":param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典",
"name": "__init__",
"signature": "def __init__(self, request=None, headers=None, cookies=None)"
},
{
"docstring": ":param alias: 接口服务器别名 公共接口: com 银行接口... | 2 | stack_v2_sparse_classes_30k_train_006987 | Implement the Python class `Hub` described below.
Class description:
Implement the Hub class.
Method signatures and docstrings:
- def __init__(self, request=None, headers=None, cookies=None): :param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典... | Implement the Python class `Hub` described below.
Class description:
Implement the Hub class.
Method signatures and docstrings:
- def __init__(self, request=None, headers=None, cookies=None): :param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典... | 1f08cbfccc1ae2123d92670c0afed9b59ae645b8 | <|skeleton|>
class Hub:
def __init__(self, request=None, headers=None, cookies=None):
""":param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典"""
<|body_0|>
def __getattr__(self, alias):
""":param alias: 接口服务器别名 公... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Hub:
def __init__(self, request=None, headers=None, cookies=None):
""":param request: django.http.HttpRequest对象 如果request不为空, 意味着每次调用都携带登录状态 :param headers: 自定义公共头部字典 :param cookies: 自定义公共cookie字典"""
self.headers = headers or {}
self.cookies = cookies or {}
if request:
... | the_stack_v2_python_sparse | tbkt/libs/utils/tbktapi.py | GUAN-YE/hd_api_djs | train | 1 | |
e50d4668751b33b8d5505a300d5236347070edc0 | [
"if arg in cls.types_dict:\n raise RuntimeError('%s already registered' % arg)\n\nclass _Wrapper(arg):\n 'Wrapper for builtin %s\\n%s' % (arg, cls.__doc__)\n_Wrapper.__name__ = '_%sWrapper' % arg.__name__\ncls.types_dict[arg] = _Wrapper",
"for k, v in cls.types_dict.iteritems():\n what = Any.serialmap.ge... | <|body_start_0|>
if arg in cls.types_dict:
raise RuntimeError('%s already registered' % arg)
class _Wrapper(arg):
'Wrapper for builtin %s\n%s' % (arg, cls.__doc__)
_Wrapper.__name__ = '_%sWrapper' % arg.__name__
cls.types_dict[arg] = _Wrapper
<|end_body_0|>
<|bo... | Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized. | _GetPyobjWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _GetPyobjWrapper:
"""Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized."""
def RegisterBuiltin(cls, arg):
"""register a builtin, crea... | stack_v2_sparse_classes_10k_train_002816 | 14,557 | permissive | [
{
"docstring": "register a builtin, create a new wrapper.",
"name": "RegisterBuiltin",
"signature": "def RegisterBuiltin(cls, arg)"
},
{
"docstring": "If find registered TypeCode instance, add Wrapper class to TypeCode class serialmap and Re-RegisterType. Provides Any serialzation of any instanc... | 3 | stack_v2_sparse_classes_30k_test_000185 | Implement the Python class `_GetPyobjWrapper` described below.
Class description:
Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized.
Method signatures and docstrings:
... | Implement the Python class `_GetPyobjWrapper` described below.
Class description:
Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized.
Method signatures and docstrings:
... | 9b890e6a25471037b7485e4999b480de7c86b656 | <|skeleton|>
class _GetPyobjWrapper:
"""Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized."""
def RegisterBuiltin(cls, arg):
"""register a builtin, crea... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _GetPyobjWrapper:
"""Get a python object that wraps data and typecode. Used by <any> parse routine, so that typecode information discovered during parsing is retained in the pyobj representation and thus can be serialized."""
def RegisterBuiltin(cls, arg):
"""register a builtin, create a new wrap... | the_stack_v2_python_sparse | Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py | Spirent/iTest-assets | train | 10 |
dce5a55cac443f3df30378f99e8f7a4789e40c2a | [
"hostname = 'nosuchname'\ntimedgethostbyname(hostname, 5)\nckey = '%s_lookup' % hostname\nip = cache.get(ckey)\nself.assertEqual(ip, None)",
"hostname = 'localhost'\ntimedgethostbyname(hostname, 5)\nckey = '%s_lookup' % hostname\nip = cache.get(ckey)\nself.assertEqual(ip, '127.0.0.1')"
] | <|body_start_0|>
hostname = 'nosuchname'
timedgethostbyname(hostname, 5)
ckey = '%s_lookup' % hostname
ip = cache.get(ckey)
self.assertEqual(ip, None)
<|end_body_0|>
<|body_start_1|>
hostname = 'localhost'
timedgethostbyname(hostname, 5)
ckey = '%s_lookup... | UtilsTests | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsTests:
def test_timedgethostbyname_nosuchname(self):
"""timedgethostbyname() stores IP's in Django cache. A none existing key should return None."""
<|body_0|>
def test_timedgethostbyname_localhost(self):
"""timedgethostbyname() should cache an IP for a hostname... | stack_v2_sparse_classes_10k_train_002817 | 840 | permissive | [
{
"docstring": "timedgethostbyname() stores IP's in Django cache. A none existing key should return None.",
"name": "test_timedgethostbyname_nosuchname",
"signature": "def test_timedgethostbyname_nosuchname(self)"
},
{
"docstring": "timedgethostbyname() should cache an IP for a hostname passed t... | 2 | stack_v2_sparse_classes_30k_train_001266 | Implement the Python class `UtilsTests` described below.
Class description:
Implement the UtilsTests class.
Method signatures and docstrings:
- def test_timedgethostbyname_nosuchname(self): timedgethostbyname() stores IP's in Django cache. A none existing key should return None.
- def test_timedgethostbyname_localhos... | Implement the Python class `UtilsTests` described below.
Class description:
Implement the UtilsTests class.
Method signatures and docstrings:
- def test_timedgethostbyname_nosuchname(self): timedgethostbyname() stores IP's in Django cache. A none existing key should return None.
- def test_timedgethostbyname_localhos... | 64d9f42fc4298f6d0854441f0e514ecb042bfd9d | <|skeleton|>
class UtilsTests:
def test_timedgethostbyname_nosuchname(self):
"""timedgethostbyname() stores IP's in Django cache. A none existing key should return None."""
<|body_0|>
def test_timedgethostbyname_localhost(self):
"""timedgethostbyname() should cache an IP for a hostname... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UtilsTests:
def test_timedgethostbyname_nosuchname(self):
"""timedgethostbyname() stores IP's in Django cache. A none existing key should return None."""
hostname = 'nosuchname'
timedgethostbyname(hostname, 5)
ckey = '%s_lookup' % hostname
ip = cache.get(ckey)
s... | the_stack_v2_python_sparse | assets/tests.py | continual-delivery/stratahq | train | 1 | |
872c2603067cdb8c282ff11a387b7666c1b4f0b0 | [
"assert type(ensemble_weights) == list or type(ensemble_weights) == np.ndarray\nself.weights = ensemble_weights\nself.sum_weights = np.sum(self.weights) if ensemble_weights else None",
"assert type(scores) == list or type(scores) == np.ndarray, 'Unsupport score types, it should be list or numpy.ndarray'\nassert l... | <|body_start_0|>
assert type(ensemble_weights) == list or type(ensemble_weights) == np.ndarray
self.weights = ensemble_weights
self.sum_weights = np.sum(self.weights) if ensemble_weights else None
<|end_body_0|>
<|body_start_1|>
assert type(scores) == list or type(scores) == np.ndarray,... | WeightEnsemble | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightEnsemble:
def __init__(self, ensemble_weights: list=None):
"""Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with orders, we use equal weights/mean to recalculate the scores when it is None. Defaults to None."""
<|... | stack_v2_sparse_classes_10k_train_002818 | 1,511 | permissive | [
{
"docstring": "Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with orders, we use equal weights/mean to recalculate the scores when it is None. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, ensemble_weights: list=Non... | 2 | stack_v2_sparse_classes_30k_train_001575 | Implement the Python class `WeightEnsemble` described below.
Class description:
Implement the WeightEnsemble class.
Method signatures and docstrings:
- def __init__(self, ensemble_weights: list=None): Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with order... | Implement the Python class `WeightEnsemble` described below.
Class description:
Implement the WeightEnsemble class.
Method signatures and docstrings:
- def __init__(self, ensemble_weights: list=None): Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with order... | d2e38f4c35349b05c9bbd3ac753efc9a96e0ab05 | <|skeleton|>
class WeightEnsemble:
def __init__(self, ensemble_weights: list=None):
"""Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with orders, we use equal weights/mean to recalculate the scores when it is None. Defaults to None."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WeightEnsemble:
def __init__(self, ensemble_weights: list=None):
"""Anomaly scores ensemble with weighted average. Args: ensemble_weights (list, optional): Weights for scores with orders, we use equal weights/mean to recalculate the scores when it is None. Defaults to None."""
assert type(ense... | the_stack_v2_python_sparse | streamad/process/weight_ensemble.py | Fengrui-Liu/StreamAD | train | 73 | |
6bf00dcef6bb9cca25219a2bcd0ccad0008d24f1 | [
"super().__init__(model_config)\nself.pipelines = pipelines\nself.aggregation_type = ensemble_aggregation_type",
"inference_pipelines = []\nfor pipeline_id, path in enumerate(paths_to_checkpoint):\n pipeline = ScalarInferencePipeline.create_from_checkpoint(path, config, pipeline_id)\n if pipeline:\n ... | <|body_start_0|>
super().__init__(model_config)
self.pipelines = pipelines
self.aggregation_type = ensemble_aggregation_type
<|end_body_0|>
<|body_start_1|>
inference_pipelines = []
for pipeline_id, path in enumerate(paths_to_checkpoint):
pipeline = ScalarInferencePi... | Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models. | ScalarEnsemblePipeline | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase... | stack_v2_sparse_classes_10k_train_002819 | 10,504 | permissive | [
{
"docstring": ":param pipelines: A set of inference pipelines, one for each recovered checkpoint. :param model_config: Model configuration information. :param ensemble_aggregation_type: Type of aggregation to perform on the model outputs. :return:",
"name": "__init__",
"signature": "def __init__(self, ... | 4 | stack_v2_sparse_classes_30k_train_002263 | Implement the Python class `ScalarEnsemblePipeline` described below.
Class description:
Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models.
Method signatures and docstrings:
- def __init__(self, pip... | Implement the Python class `ScalarEnsemblePipeline` described below.
Class description:
Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models.
Method signatures and docstrings:
- def __init__(self, pip... | 12b496093097ef48d5ac8880985c04918d7f76fe | <|skeleton|>
class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScalarEnsemblePipeline:
"""Pipeline for inference from an ensemble model on classification tasks. This pipeline creates models from multiple checkpoints and aggregates the predictions across models."""
def __init__(self, pipelines: List[ScalarInferencePipeline], model_config: ScalarModelBase, ensemble_ag... | the_stack_v2_python_sparse | InnerEye/ML/pipelines/scalar_inference.py | MaxCodeXTC/InnerEye-DeepLearning | train | 1 |
1827159197cf616b96bf28aaf9dde7d297e21408 | [
"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)
... | [summary] Args: tf ([type]): [description] | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_10k_train_002820 | 1,702 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | stack_v2_sparse_classes_30k_train_006681 | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Enc... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
595ac2335a12fea6bebd10d78e7365622c61beb4 | [
"if not value:\n return []\nreturn [v.strip() for v in value.split() if v != '']",
"super().validate(value)\ntry:\n for email in value:\n validate_email(email)\nexcept ValidationError:\n raise ValidationError(self.message, code=self.code)"
] | <|body_start_0|>
if not value:
return []
return [v.strip() for v in value.split() if v != '']
<|end_body_0|>
<|body_start_1|>
super().validate(value)
try:
for email in value:
validate_email(email)
except ValidationError:
raise ... | MultiEmailField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not value:
... | stack_v2_sparse_classes_10k_train_002821 | 1,497 | permissive | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007320 | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails. | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails.
<|skeleton|>
class Mult... | de532aee33b03f9b580404dbf273713b12bd6275 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
if not value:
return []
return [v.strip() for v in value.split() if v != '']
def validate(self, value):
"""Check if value consists only of valid emails."""
super().v... | the_stack_v2_python_sparse | src/easydmp/invitation/forms.py | hmpf/easydmp | train | 8 | |
8584923d499efa0ce0587feddebfeda7232c416b | [
"if self.backend is None:\n raise QiskitError('backend not set. Cannot determine the center frequency.')\nreturn self._backend_data.drive_freqs[self.physical_qubits[0]]",
"circuit = QuantumCircuit(1)\ncircuit.append(Gate(name=self.__spec_gate_name__, num_qubits=1, params=[freq_param]), (0,))\ncircuit.measure_a... | <|body_start_0|>
if self.backend is None:
raise QiskitError('backend not set. Cannot determine the center frequency.')
return self._backend_data.drive_freqs[self.physical_qubits[0]]
<|end_body_0|>
<|body_start_1|>
circuit = QuantumCircuit(1)
circuit.append(Gate(name=self.__s... | A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule embedded in a spectroscopy gate... | QubitSpectroscopy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_10k_train_002822 | 4,798 | permissive | [
{
"docstring": "Returns the center frequency of the experiment. Returns: The center frequency of the experiment. Raises: QiskitError: If the experiment does not have a backend set.",
"name": "_backend_center_frequency",
"signature": "def _backend_center_frequency(self) -> float"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_002963 | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule... | the_stack_v2_python_sparse | qiskit_experiments/library/characterization/qubit_spectroscopy.py | oliverdial/qiskit-experiments | train | 0 |
fd67da1e95fbe7106e90a39d05ba8f4a82987c25 | [
"def dfs(root, res):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n dfs(root.left, res)\n dfs(root.right, res)\nres = []\ndfs(root, res)\nwhile res and res[-1] == '#':\n res.pop()\nreturn '.'.join(res)",
"def helper(values):\n nonlocal index\n if index >... | <|body_start_0|>
def dfs(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left, res)
dfs(root.right, res)
res = []
dfs(root, res)
while res and res[-1] == '#':
re... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(root, ... | stack_v2_sparse_classes_10k_train_002823 | 1,279 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 0250c3764b6e68dfe339afe8ee047e16c45db4e0 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def dfs(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left, res)
dfs(root.right, res)... | the_stack_v2_python_sparse | Python/LC449_SerializeAndDesrializeBST.py | wondershow/CodingTraining | train | 0 | |
14048504ec0bfa41af6dc6a8c20fcb6ac1f03952 | [
"self.state_manager = state_manager\nself.orchestrator = orchestrator\nself.extended = extended",
"health_check = HealthCheck()\ntry:\n now = self.state_manager.get_now()\n if now is None:\n raise Exception('None received from database for now()')\nexcept Exception:\n hcm = HealthCheckMessage(msg=... | <|body_start_0|>
self.state_manager = state_manager
self.orchestrator = orchestrator
self.extended = extended
<|end_body_0|>
<|body_start_1|>
health_check = HealthCheck()
try:
now = self.state_manager.get_now()
if now is None:
raise Except... | Returns Drydock health check status. | HealthCheckCombined | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthCheckCombined:
"""Returns Drydock health check status."""
def __init__(self, state_manager=None, orchestrator=None, extended=False):
"""Object initializer. :param orchestrator: instance of Drydock orchestrator"""
<|body_0|>
def get(self, req, resp):
"""Retu... | stack_v2_sparse_classes_10k_train_002824 | 4,455 | permissive | [
{
"docstring": "Object initializer. :param orchestrator: instance of Drydock orchestrator",
"name": "__init__",
"signature": "def __init__(self, state_manager=None, orchestrator=None, extended=False)"
},
{
"docstring": "Returns updated response with body if extended.",
"name": "get",
"si... | 2 | stack_v2_sparse_classes_30k_train_004848 | Implement the Python class `HealthCheckCombined` described below.
Class description:
Returns Drydock health check status.
Method signatures and docstrings:
- def __init__(self, state_manager=None, orchestrator=None, extended=False): Object initializer. :param orchestrator: instance of Drydock orchestrator
- def get(s... | Implement the Python class `HealthCheckCombined` described below.
Class description:
Returns Drydock health check status.
Method signatures and docstrings:
- def __init__(self, state_manager=None, orchestrator=None, extended=False): Object initializer. :param orchestrator: instance of Drydock orchestrator
- def get(s... | f99abfa4337f8cbb591513aac404b11208d4187c | <|skeleton|>
class HealthCheckCombined:
"""Returns Drydock health check status."""
def __init__(self, state_manager=None, orchestrator=None, extended=False):
"""Object initializer. :param orchestrator: instance of Drydock orchestrator"""
<|body_0|>
def get(self, req, resp):
"""Retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HealthCheckCombined:
"""Returns Drydock health check status."""
def __init__(self, state_manager=None, orchestrator=None, extended=False):
"""Object initializer. :param orchestrator: instance of Drydock orchestrator"""
self.state_manager = state_manager
self.orchestrator = orchest... | the_stack_v2_python_sparse | python/drydock_provisioner/control/health.py | airshipit/drydock | train | 13 |
4615cf2c86a7030a971ff4d1032e513b92d588c1 | [
"super(SCPCheckOKResponse, self).__init__()\nself._operation = operation\nself._command = command",
"result = self.scp_response_header.result\nif result != SCPResult.RC_OK:\n raise SpinnmanUnexpectedResponseCodeException(self._operation, self._command, result.name)"
] | <|body_start_0|>
super(SCPCheckOKResponse, self).__init__()
self._operation = operation
self._command = command
<|end_body_0|>
<|body_start_1|>
result = self.scp_response_header.result
if result != SCPResult.RC_OK:
raise SpinnmanUnexpectedResponseCodeException(self._... | An SCP response to a request which returns nothing other than OK | SCPCheckOKResponse | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCPCheckOKResponse:
"""An SCP response to a request which returns nothing other than OK"""
def __init__(self, operation, command):
""":param operation: The operation being performed :type operation: str :param command: The command that was sent :type command: str"""
<|body_0|... | stack_v2_sparse_classes_10k_train_002825 | 1,103 | permissive | [
{
"docstring": ":param operation: The operation being performed :type operation: str :param command: The command that was sent :type command: str",
"name": "__init__",
"signature": "def __init__(self, operation, command)"
},
{
"docstring": "See :py:meth:`spinnman.messages.scp.abstract_scp_respon... | 2 | stack_v2_sparse_classes_30k_train_003687 | Implement the Python class `SCPCheckOKResponse` described below.
Class description:
An SCP response to a request which returns nothing other than OK
Method signatures and docstrings:
- def __init__(self, operation, command): :param operation: The operation being performed :type operation: str :param command: The comm... | Implement the Python class `SCPCheckOKResponse` described below.
Class description:
An SCP response to a request which returns nothing other than OK
Method signatures and docstrings:
- def __init__(self, operation, command): :param operation: The operation being performed :type operation: str :param command: The comm... | 04fa1eaf78778edea3ba3afa4c527d20c491718e | <|skeleton|>
class SCPCheckOKResponse:
"""An SCP response to a request which returns nothing other than OK"""
def __init__(self, operation, command):
""":param operation: The operation being performed :type operation: str :param command: The command that was sent :type command: str"""
<|body_0|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SCPCheckOKResponse:
"""An SCP response to a request which returns nothing other than OK"""
def __init__(self, operation, command):
""":param operation: The operation being performed :type operation: str :param command: The command that was sent :type command: str"""
super(SCPCheckOKRespon... | the_stack_v2_python_sparse | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spinnman/messages/scp/impl/scp_check_ok_response.py | Roboy/LSM_SpiNNaker_MyoArm | train | 2 |
14f229d21cf6ef1b3df5017db0273fd6874a0179 | [
"result = []\nif not root:\n return result\nqueue = collections.deque([root])\nwhile queue:\n root = queue.pop()\n result.append('#')\n if root:\n result.append(str(root.val))\n queue.appendleft(root.left)\n queue.appendleft(root.right)\nreturn ''.join(result[1:])",
"index = 0\nif... | <|body_start_0|>
result = []
if not root:
return result
queue = collections.deque([root])
while queue:
root = queue.pop()
result.append('#')
if root:
result.append(str(root.val))
queue.appendleft(root.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002826 | 3,899 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
if not root:
return result
queue = collections.deque([root])
while queue:
root = queue.pop()
result.append('#')
... | the_stack_v2_python_sparse | Python_leetcode/297_serialize_and_deserialize.py | xiangcao/Leetcode | train | 0 | |
bb13fec6ce0926c6021ab9b3adfaa5ecd3266142 | [
"if 'AVALON_TASK' in session:\n return True\nreturn False",
"with pype.modified_environ(**session):\n app = lib.get_application(self.name)\n executable = lib.which(app['executable'])\n arguments = []\n tools_env = acre.get_tools([self.name])\n env = acre.compute(tools_env)\n env = acre.merge(... | <|body_start_0|>
if 'AVALON_TASK' in session:
return True
return False
<|end_body_0|>
<|body_start_1|>
with pype.modified_environ(**session):
app = lib.get_application(self.name)
executable = lib.which(app['executable'])
arguments = []
... | PremierePro | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
<|body_0|>
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Retu... | stack_v2_sparse_classes_10k_train_002827 | 2,565 | permissive | [
{
"docstring": "Return whether the action is compatible with the session",
"name": "is_compatible",
"signature": "def is_compatible(self, session)"
},
{
"docstring": "Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Returns: Popen instance of n... | 2 | stack_v2_sparse_classes_30k_train_002643 | Implement the Python class `PremierePro` described below.
Class description:
Implement the PremierePro class.
Method signatures and docstrings:
- def is_compatible(self, session): Return whether the action is compatible with the session
- def process(self, session, **kwargs): Implement the behavior for when the actio... | Implement the Python class `PremierePro` described below.
Class description:
Implement the PremierePro class.
Method signatures and docstrings:
- def is_compatible(self, session): Return whether the action is compatible with the session
- def process(self, session, **kwargs): Implement the behavior for when the actio... | 47ef4b64f297186c6d929a8f56ecfb93dd0f44e8 | <|skeleton|>
class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
<|body_0|>
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered Args: session (dict): environment dictionary Retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PremierePro:
def is_compatible(self, session):
"""Return whether the action is compatible with the session"""
if 'AVALON_TASK' in session:
return True
return False
def process(self, session, **kwargs):
"""Implement the behavior for when the action is triggered ... | the_stack_v2_python_sparse | pype/plugins/launcher/actions/unused/PremierePro.py | jrsndl/pype | train | 1 | |
47510d7029e8af23795e38e0ae5da4674fff0773 | [
"session = await get_session(self.request)\nif session.get('user'):\n redirect(self.request, 'account')\nreturn {}",
"data = await self.request.post()\nuser = User(self.request.app.db, data)\nresult = await user.check_user()\nif isinstance(result, dict):\n session = await get_session(self.request)\n set_... | <|body_start_0|>
session = await get_session(self.request)
if session.get('user'):
redirect(self.request, 'account')
return {}
<|end_body_0|>
<|body_start_1|>
data = await self.request.post()
user = User(self.request.app.db, data)
result = await user.check_us... | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
async def get(self):
"""Страница входа пользователя"""
<|body_0|>
async def post(self):
"""Обработка входа пользователя, проверка данных"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
session = await get_session(self.request)
if sess... | stack_v2_sparse_classes_10k_train_002828 | 3,877 | no_license | [
{
"docstring": "Страница входа пользователя",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "Обработка входа пользователя, проверка данных",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004810 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- async def get(self): Страница входа пользователя
- async def post(self): Обработка входа пользователя, проверка данных | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- async def get(self): Страница входа пользователя
- async def post(self): Обработка входа пользователя, проверка данных
<|skeleton|>
class Login:
async def get(self):
"""С... | c8726ad77079b981453c11d5c7fc39bc838eec67 | <|skeleton|>
class Login:
async def get(self):
"""Страница входа пользователя"""
<|body_0|>
async def post(self):
"""Обработка входа пользователя, проверка данных"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Login:
async def get(self):
"""Страница входа пользователя"""
session = await get_session(self.request)
if session.get('user'):
redirect(self.request, 'account')
return {}
async def post(self):
"""Обработка входа пользователя, проверка данных"""
... | the_stack_v2_python_sparse | auth/views.py | ArtemZaitsev1994/chat | train | 0 | |
153bef56d0717e41310e1905c7aaf33bb9835eb1 | [
"self.libm = libm\nself.gen_src = []\nself.clml_modules = None\nself.clml_builds = {}\nself.codegen = None\nself.nodes = None\nself.MakeFileHeader = Template('/*\\n * Licensed to the Apache Software Foundation (ASF) under one\\n * or more contributor license agreements. See the NOTICE file\\n ... | <|body_start_0|>
self.libm = libm
self.gen_src = []
self.clml_modules = None
self.clml_builds = {}
self.codegen = None
self.nodes = None
self.MakeFileHeader = Template('/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more con... | Generates CLML API source given a TVM compiled mod | CLMLGenSrc | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"LLVM-exception",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
<|body_0|>
def get_clml_params(self):
"""Returns parameters from the TVM module"""
<|... | stack_v2_sparse_classes_10k_train_002829 | 49,674 | permissive | [
{
"docstring": "Initialize Parameters ---------- libm : Module Compiled relay module",
"name": "__init__",
"signature": "def __init__(self, libm)"
},
{
"docstring": "Returns parameters from the TVM module",
"name": "get_clml_params",
"signature": "def get_clml_params(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004385 | Implement the Python class `CLMLGenSrc` described below.
Class description:
Generates CLML API source given a TVM compiled mod
Method signatures and docstrings:
- def __init__(self, libm): Initialize Parameters ---------- libm : Module Compiled relay module
- def get_clml_params(self): Returns parameters from the TVM... | Implement the Python class `CLMLGenSrc` described below.
Class description:
Generates CLML API source given a TVM compiled mod
Method signatures and docstrings:
- def __init__(self, libm): Initialize Parameters ---------- libm : Module Compiled relay module
- def get_clml_params(self): Returns parameters from the TVM... | d75083cd97ede706338ab413dbc964009456d01b | <|skeleton|>
class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
<|body_0|>
def get_clml_params(self):
"""Returns parameters from the TVM module"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CLMLGenSrc:
"""Generates CLML API source given a TVM compiled mod"""
def __init__(self, libm):
"""Initialize Parameters ---------- libm : Module Compiled relay module"""
self.libm = libm
self.gen_src = []
self.clml_modules = None
self.clml_builds = {}
self.... | the_stack_v2_python_sparse | python/tvm/relay/op/contrib/clml.py | apache/tvm | train | 4,575 |
bbd805c106c412cf5e124b5ba0b85fa21a782357 | [
"pointer_a, pointer_b = (headA, headB)\nwhile pointer_a is not pointer_b:\n pointer_a = headB if pointer_a is None else pointer_a.next\n pointer_b = headA if pointer_b is None else pointer_b.next\nreturn pointer_a",
"if headA is None or headB is None:\n return None\na, b = (headA, headB)\ncntA, cntB = (1... | <|body_start_0|>
pointer_a, pointer_b = (headA, headB)
while pointer_a is not pointer_b:
pointer_a = headB if pointer_a is None else pointer_a.next
pointer_b = headA if pointer_b is None else pointer_b.next
return pointer_a
<|end_body_0|>
<|body_start_1|>
if head... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_002830 | 2,275 | no_license | [
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNod... | 2 | stack_v2_sparse_classes_30k_val_000376 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: Lis... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
pointer_a, pointer_b = (headA, headB)
while pointer_a is not pointer_b:
pointer_a = headB if pointer_a is None else pointer_a.next
pointer_b = headA if poi... | the_stack_v2_python_sparse | code160IntersectionOfTwoLinkedLists.py | cybelewang/leetcode-python | train | 0 | |
95381f61022132a181a0b5399a1854c8f40fbb40 | [
"AssessmentResults.__init__(self, controller, **kwargs)\nself._lst_labels.append(u'π<sub>C</sub>:')\nself._lblModel.set_tooltip_markup(_(u\"The assessment model used to calculate the inductive device's failure rate.\"))\nself.txtPiC = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'The construc... | <|body_start_0|>
AssessmentResults.__init__(self, controller, **kwargs)
self._lst_labels.append(u'π<sub>C</sub>:')
self._lblModel.set_tooltip_markup(_(u"The assessment model used to calculate the inductive device's failure rate."))
self.txtPiC = ramstk.RAMSTKEntry(width=125, editable=Fal... | Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes of an Inductor assessment result view a... | InductorAssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T... | stack_v2_sparse_classes_10k_train_002831 | 20,499 | permissive | [
{
"docstring": "Initialize an instance of the Inductor assessment result view. :param controller: the hardware data controller instance. :type controller: :class:`ramstk.hardware.Controller.HardwareBoMDataController` :param int hardware_id: the hardware ID of the currently selected inductor. :param int subcateg... | 5 | stack_v2_sparse_classes_30k_train_004103 | Implement the Python class `InductorAssessmentResults` described below.
Class description:
Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2... | Implement the Python class `InductorAssessmentResults` described below.
Class description:
Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. T... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InductorAssessmentResults:
"""Display Inductor assessment results attribute data in the RAMSTK Work Book. The Inductor assessment result view displays all the assessment results for the selected inductor. This includes, currently, results for MIL-HDBK-217FN2 parts count and part stress methods. The attributes... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/components/Inductor.py | JmiXIII/ramstk | train | 0 |
84c8d220ac0c976eb936d2ff40d63525d790c683 | [
"_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)\nif return_cost_matrix is True:\n\n @njit(cache=True)\n def numba_twe_distance_alignment_path(_x: np.ndarray, _y: np.ndarray) -> Tuple[List, float, np.ndarray]:\n cost_matrix = _twe_cost_matrix(_x, _y, _boundi... | <|body_start_0|>
_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)
if return_cost_matrix is True:
@njit(cache=True)
def numba_twe_distance_alignment_path(_x: np.ndarray, _y: np.ndarray) -> Tuple[List, float, np.ndarray]:
... | Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE is a metric. Its computati... | _TweDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_10k_train_002832 | 11,583 | permissive | [
{
"docstring": "Create a no_python compiled twe distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array of shape (d,m2)). Second time series. return_cost... | 2 | stack_v2_sparse_classes_30k_train_001486 | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | fbe4af4d8419a01ada1e82da1aa63c0218d13edb | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE... | the_stack_v2_python_sparse | sktime/distances/_twe.py | jattenberg/sktime | train | 0 |
a27b072d5191688c078d2212b471471eaceba064 | [
"n = len(stones)\npre = [0] * (n + 1)\nfor i in range(n):\n pre[i + 1] = pre[i] + stones[i]\ndp = [[0] * (n + 1) for _ in range(n + 1)]\nfor length in range(1, n + 1):\n for i in range(1, n - length + 1):\n j = i + length\n dp[i][j] = max(pre[j] - pre[i] - dp[i + 1][j], pre[j - 1] - pre[i - 1] -... | <|body_start_0|>
n = len(stones)
pre = [0] * (n + 1)
for i in range(n):
pre[i + 1] = pre[i] + stones[i]
dp = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(1, n + 1):
for i in range(1, n - length + 1):
j = i + length
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def stoneGameVII1(self, stones: List[int]) -> int:
"""思路:动态规划法 @param stones: @return:"""
<|body_0|>
def stoneGameVII2(self, stones: List[int]) -> int:
"""思路:记忆化递归 @param stones: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n =... | stack_v2_sparse_classes_10k_train_002833 | 3,087 | no_license | [
{
"docstring": "思路:动态规划法 @param stones: @return:",
"name": "stoneGameVII1",
"signature": "def stoneGameVII1(self, stones: List[int]) -> int"
},
{
"docstring": "思路:记忆化递归 @param stones: @return:",
"name": "stoneGameVII2",
"signature": "def stoneGameVII2(self, stones: List[int]) -> int"
}... | 2 | stack_v2_sparse_classes_30k_train_004048 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGameVII1(self, stones: List[int]) -> int: 思路:动态规划法 @param stones: @return:
- def stoneGameVII2(self, stones: List[int]) -> int: 思路:记忆化递归 @param stones: @return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGameVII1(self, stones: List[int]) -> int: 思路:动态规划法 @param stones: @return:
- def stoneGameVII2(self, stones: List[int]) -> int: 思路:记忆化递归 @param stones: @return:
<|skele... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def stoneGameVII1(self, stones: List[int]) -> int:
"""思路:动态规划法 @param stones: @return:"""
<|body_0|>
def stoneGameVII2(self, stones: List[int]) -> int:
"""思路:记忆化递归 @param stones: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def stoneGameVII1(self, stones: List[int]) -> int:
"""思路:动态规划法 @param stones: @return:"""
n = len(stones)
pre = [0] * (n + 1)
for i in range(n):
pre[i + 1] = pre[i] + stones[i]
dp = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(... | the_stack_v2_python_sparse | LeetCode/石子游戏/5627. 石子游戏 VII.py | yiming1012/MyLeetCode | train | 2 | |
85e097bf77eb7059717f5b98b090a6f8797cb239 | [
"if not data.get('email'):\n raise ValueError('{\"detail\":\"' + str(_('The mail field can not be empty')) + '\"}')\ntry:\n user = accounts_models.User.objects.get(email=data.get('email'))\nexcept accounts_models.User.DoesNotExist:\n raise ValueError('{\"detail\":\"' + str(_('The mail is not registered in ... | <|body_start_0|>
if not data.get('email'):
raise ValueError('{"detail":"' + str(_('The mail field can not be empty')) + '"}')
try:
user = accounts_models.User.objects.get(email=data.get('email'))
except accounts_models.User.DoesNotExist:
raise ValueError('{"de... | this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request. | RecoverPasswordService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method ve... | stack_v2_sparse_classes_10k_train_002834 | 42,606 | no_license | [
{
"docstring": "this method verifies that the email sent by the user exists in the database, raise a exception if the email does not exist :param data: user's email :type data: dict :return: Model User :raises: ValueError",
"name": "check_email",
"signature": "def check_email(self, data: dict) -> accoun... | 2 | stack_v2_sparse_classes_30k_train_002897 | Implement the Python class `RecoverPasswordService` described below.
Class description:
this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request.
Method signatures and docstrings:
- def check_email(... | Implement the Python class `RecoverPasswordService` described below.
Class description:
this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request.
Method signatures and docstrings:
- def check_email(... | 497b8724d6e02582f28bc9c5a19f93ec21db84d8 | <|skeleton|>
class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method ve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method verifies that t... | the_stack_v2_python_sparse | accounts/services.py | carlos-o/weedmatchheroku | train | 0 |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"self.last_obs = -1.0\nself.last_timestamp = -1.0\nself._fitted = False",
"if X.size != y.size:\n raise ValueError(\"'X' and 'y' size must match.\")\nself.last_obs = y[-1]\nself.last_timestamp = X[-1]\nself._fitted = True\nreturn self",
"if not self._fitted:\n raise ValueError('Model is not fitted.')\nif ... | <|body_start_0|>
self.last_obs = -1.0
self.last_timestamp = -1.0
self._fitted = False
<|end_body_0|>
<|body_start_1|>
if X.size != y.size:
raise ValueError("'X' and 'y' size must match.")
self.last_obs = y[-1]
self.last_timestamp = X[-1]
self._fitted ... | Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation. | TSNaive | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSNaive:
"""Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation."""
def __init__(self):
"""Init a Naive model."""
<|body_0|>
def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaive':
... | stack_v2_sparse_classes_10k_train_002835 | 12,299 | permissive | [
{
"docstring": "Init a Naive model.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fit a Naive model. It stores the value of the last observation of ``y``, and its timestamp.",
"name": "fit",
"signature": "def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) ... | 3 | stack_v2_sparse_classes_30k_train_006466 | Implement the Python class `TSNaive` described below.
Class description:
Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation.
Method signatures and docstrings:
- def __init__(self): Init a Naive model.
- def fit(self, X: np.ndarray, y: np.ndarray,... | Implement the Python class `TSNaive` described below.
Class description:
Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation.
Method signatures and docstrings:
- def __init__(self): Init a Naive model.
- def fit(self, X: np.ndarray, y: np.ndarray,... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class TSNaive:
"""Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation."""
def __init__(self):
"""Init a Naive model."""
<|body_0|>
def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaive':
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TSNaive:
"""Naive model for time-series forecasting. In the Naive model, all forecasted values are equal to the last known observation."""
def __init__(self):
"""Init a Naive model."""
self.last_obs = -1.0
self.last_timestamp = -1.0
self._fitted = False
def fit(self, ... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
6a017a38ccaf36d39fc34f09adf897d7efa3215c | [
"solutions = []\nnums.sort()\nlength = len(nums)\nlist1 = [-x for x in nums]\nfor sum_id in range(length):\n dict = {}\n temp_num = nums[:]\n temp_num.pop(-(length - sum_id))\n for i in temp_num:\n if list1[sum_id] - i not in dict:\n dict[i] = i\n else:\n temp_sol = s... | <|body_start_0|>
solutions = []
nums.sort()
length = len(nums)
list1 = [-x for x in nums]
for sum_id in range(length):
dict = {}
temp_num = nums[:]
temp_num.pop(-(length - sum_id))
for i in temp_num:
if list1[sum_id]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
solutions = []
num... | stack_v2_sparse_classes_10k_train_002836 | 1,992 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004764 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 391328c7c601b5c77ff250ad173600d4d1dd7f57 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
solutions = []
nums.sort()
length = len(nums)
list1 = [-x for x in nums]
for sum_id in range(length):
dict = {}
temp_num = nums[:]
temp_nu... | the_stack_v2_python_sparse | leetcode/algo/p15_3Sum.py | wduncan21/Challenges | train | 0 | |
09ceeff88db61da4ecf6a84878bedc5302bdf39a | [
"if request.version == 'v6':\n return self.post_impl_v6(request)\nelif request.version == 'v7':\n return self.post_impl_v6(request)\nraise Http404()",
"configuration = rest_util.parse_dict(request, 'configuration')\nvalidation = Strike.objects.validate_strike_v6(configuration=configuration)\nresp_dict = {'i... | <|body_start_0|>
if request.version == 'v6':
return self.post_impl_v6(request)
elif request.version == 'v7':
return self.post_impl_v6(request)
raise Http404()
<|end_body_0|>
<|body_start_1|>
configuration = rest_util.parse_dict(request, 'configuration')
v... | This view is the endpoint for validating a new Strike process before attempting to actually create it | StrikesValidationView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrikesValidationView:
"""This view is the endpoint for validating a new Strike process before attempting to actually create it"""
def post(self, request):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.re... | stack_v2_sparse_classes_10k_train_002837 | 30,689 | permissive | [
{
"docstring": "Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user",
"name": "post",
"signature": "def post(self... | 2 | null | Implement the Python class `StrikesValidationView` described below.
Class description:
This view is the endpoint for validating a new Strike process before attempting to actually create it
Method signatures and docstrings:
- def post(self, request): Determine api version and call specific method :param request: the H... | Implement the Python class `StrikesValidationView` described below.
Class description:
This view is the endpoint for validating a new Strike process before attempting to actually create it
Method signatures and docstrings:
- def post(self, request): Determine api version and call specific method :param request: the H... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class StrikesValidationView:
"""This view is the endpoint for validating a new Strike process before attempting to actually create it"""
def post(self, request):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StrikesValidationView:
"""This view is the endpoint for validating a new Strike process before attempting to actually create it"""
def post(self, request):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request... | the_stack_v2_python_sparse | scale/ingest/views.py | kfconsultant/scale | train | 0 |
2b8bdcd46f7909d32358a40057f236bd3520e852 | [
"self.certfile = filename\nwith open(self.certfile) as file:\n self.der = ssl.PEM_cert_to_DER_cert(file.read())",
"i = asn1_node_root(self.der)\ni = asn1_node_first_child(self.der, i)\ni = asn1_node_first_child(self.der, i)\ni = asn1_node_next(self.der, i)\ni = asn1_node_next(self.der, i)\ni = asn1_node_next(s... | <|body_start_0|>
self.certfile = filename
with open(self.certfile) as file:
self.der = ssl.PEM_cert_to_DER_cert(file.read())
<|end_body_0|>
<|body_start_1|>
i = asn1_node_root(self.der)
i = asn1_node_first_child(self.der, i)
i = asn1_node_first_child(self.der, i)
... | A simple class to represent a X509 certificate. The certificate is encoding according the DER format. | X509 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
<|body_0|>
def check_validity_period(self):
"""Control the validity period. Raise an e... | stack_v2_sparse_classes_10k_train_002838 | 5,920 | permissive | [
{
"docstring": "Initialize the X509 object",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Control the validity period. Raise an exception if the control fails.",
"name": "check_validity_period",
"signature": "def check_validity_period(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005137 | Implement the Python class `X509` described below.
Class description:
A simple class to represent a X509 certificate. The certificate is encoding according the DER format.
Method signatures and docstrings:
- def __init__(self, filename): Initialize the X509 object
- def check_validity_period(self): Control the validi... | Implement the Python class `X509` described below.
Class description:
A simple class to represent a X509 certificate. The certificate is encoding according the DER format.
Method signatures and docstrings:
- def __init__(self, filename): Initialize the X509 object
- def check_validity_period(self): Control the validi... | e3957e8f5b0ed9908e62badacace7e581761dd96 | <|skeleton|>
class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
<|body_0|>
def check_validity_period(self):
"""Control the validity period. Raise an e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
self.certfile = filename
with open(self.certfile) as file:
self.der = ssl.PEM_cert_to_DER_ce... | the_stack_v2_python_sparse | mnemopwd/common/util/X509.py | thethythy/Mnemopwd | train | 3 |
b963a97531d82a23abf230fccbda536070e0f719 | [
"self.__class__.__name__ = 'Contingency' + measures.__class__.__name__\nfor k in dir(measures):\n if k.startswith('__'):\n continue\n v = getattr(measures, k)\n if not k.startswith('_'):\n v = self._make_contingency_fn(measures, v)\n setattr(self, k, v)",
"def res(*contingency):\n ret... | <|body_start_0|>
self.__class__.__name__ = 'Contingency' + measures.__class__.__name__
for k in dir(measures):
if k.startswith('__'):
continue
v = getattr(measures, k)
if not k.startswith('_'):
v = self._make_contingency_fn(measures, v)... | Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals. | ContingencyMeasures | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContingencyMeasures:
"""Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals."""
def __init__(self, measures):
"""Constructs a ContingencyMeasures given a NgramAssocMeasures class"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002839 | 16,093 | permissive | [
{
"docstring": "Constructs a ContingencyMeasures given a NgramAssocMeasures class",
"name": "__init__",
"signature": "def __init__(self, measures)"
},
{
"docstring": "From an association measure function, produces a new function which accepts contingency table values as its arguments.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_002235 | Implement the Python class `ContingencyMeasures` described below.
Class description:
Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals.
Method signatures and docstrings:
- def __init__(self, measures): Constructs a ContingencyMeasures g... | Implement the Python class `ContingencyMeasures` described below.
Class description:
Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals.
Method signatures and docstrings:
- def __init__(self, measures): Constructs a ContingencyMeasures g... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class ContingencyMeasures:
"""Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals."""
def __init__(self, measures):
"""Constructs a ContingencyMeasures given a NgramAssocMeasures class"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContingencyMeasures:
"""Wraps NgramAssocMeasures classes such that the arguments of association measures are contingency table values rather than marginals."""
def __init__(self, measures):
"""Constructs a ContingencyMeasures given a NgramAssocMeasures class"""
self.__class__.__name__ = '... | the_stack_v2_python_sparse | nltk/metrics/association.py | nltk/nltk | train | 11,860 |
a8956c6aa972fc14b6b6f6c51bfd00d7af6d708a | [
"self.generic = config.get('generic', False)\nwrap = config.get('tex_inline_wrap', ['\\\\(', '\\\\)'])\nself.wrap = wrap[0] + '%s' + wrap[1]\nself.preview = config.get('preview', True)\nPattern.__init__(self, pattern)",
"if self.preview:\n el = md_util.etree.Element('span')\n preview = md_util.etree.SubElem... | <|body_start_0|>
self.generic = config.get('generic', False)
wrap = config.get('tex_inline_wrap', ['\\(', '\\)'])
self.wrap = wrap[0] + '%s' + wrap[1]
self.preview = config.get('preview', True)
Pattern.__init__(self, pattern)
<|end_body_0|>
<|body_start_1|>
if self.previ... | Arithmatex inline pattern handler. | InlineArithmatexPattern | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
<|body_0|>
def mathjax_output(self, math):
"""Default MathJax output."""
<|body_1|>
def generic_output(self, math):
"""Ge... | stack_v2_sparse_classes_10k_train_002840 | 9,236 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, pattern, config)"
},
{
"docstring": "Default MathJax output.",
"name": "mathjax_output",
"signature": "def mathjax_output(self, math)"
},
{
"docstring": "Generic output.",
"name": "generic_outp... | 4 | stack_v2_sparse_classes_30k_train_004396 | Implement the Python class `InlineArithmatexPattern` described below.
Class description:
Arithmatex inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config): Initialize.
- def mathjax_output(self, math): Default MathJax output.
- def generic_output(self, math): Generic output.
-... | Implement the Python class `InlineArithmatexPattern` described below.
Class description:
Arithmatex inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config): Initialize.
- def mathjax_output(self, math): Default MathJax output.
- def generic_output(self, math): Generic output.
-... | 0e7796a61d4391ba51e3a9e21d3cdcd64a0ba8a4 | <|skeleton|>
class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
<|body_0|>
def mathjax_output(self, math):
"""Default MathJax output."""
<|body_1|>
def generic_output(self, math):
"""Ge... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
self.generic = config.get('generic', False)
wrap = config.get('tex_inline_wrap', ['\\(', '\\)'])
self.wrap = wrap[0] + '%s' + wrap[1]
self.previ... | the_stack_v2_python_sparse | thirdparty/pymdownx/arithmatex.py | cxsjclassroom/webserver | train | 5 |
76c7a7762febd30711d20a0e87413d510c0a6a51 | [
"self._metric_name = metric_name\n\ndef _default_compare_fn(best_eval_result, current_eval_result):\n \"\"\"Returns True if the current metric is better than the best metric.\"\"\"\n if higher_is_better:\n return current_eval_result[metric_name] > best_eval_result[metric_name]\n else:\n retur... | <|body_start_0|>
self._metric_name = metric_name
def _default_compare_fn(best_eval_result, current_eval_result):
"""Returns True if the current metric is better than the best metric."""
if higher_is_better:
return current_eval_result[metric_name] > best_eval_resu... | Exporter that saves the best SavedModel and checkpoint. | BestSavedModelAndCheckpointExporter | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BestSavedModelAndCheckpointExporter:
"""Exporter that saves the best SavedModel and checkpoint."""
def __init__(self, eval_spec_name, serving_input_receiver_fn, compare_fn=None, metric_name=None, higher_is_better=True, assets_extra=None):
"""Creates an exporter that compares models o... | stack_v2_sparse_classes_10k_train_002841 | 8,285 | permissive | [
{
"docstring": "Creates an exporter that compares models on the given eval and metric. While the SavedModel is useful for inference, the checkpoint is useful for warm-starting another stage of training (e.g., fine-tuning). Args: eval_spec_name: Name of the EvalSpec to use to compare models. serving_input_receiv... | 2 | null | Implement the Python class `BestSavedModelAndCheckpointExporter` described below.
Class description:
Exporter that saves the best SavedModel and checkpoint.
Method signatures and docstrings:
- def __init__(self, eval_spec_name, serving_input_receiver_fn, compare_fn=None, metric_name=None, higher_is_better=True, asset... | Implement the Python class `BestSavedModelAndCheckpointExporter` described below.
Class description:
Exporter that saves the best SavedModel and checkpoint.
Method signatures and docstrings:
- def __init__(self, eval_spec_name, serving_input_receiver_fn, compare_fn=None, metric_name=None, higher_is_better=True, asset... | ac9447064195e06de48cc91ff642f7fffa28ffe8 | <|skeleton|>
class BestSavedModelAndCheckpointExporter:
"""Exporter that saves the best SavedModel and checkpoint."""
def __init__(self, eval_spec_name, serving_input_receiver_fn, compare_fn=None, metric_name=None, higher_is_better=True, assets_extra=None):
"""Creates an exporter that compares models o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BestSavedModelAndCheckpointExporter:
"""Exporter that saves the best SavedModel and checkpoint."""
def __init__(self, eval_spec_name, serving_input_receiver_fn, compare_fn=None, metric_name=None, higher_is_better=True, assets_extra=None):
"""Creates an exporter that compares models on the given e... | the_stack_v2_python_sparse | language/common/utils/exporters.py | google-research/language | train | 1,567 |
00f3b73a17f249a6cb3ac196ce9111290f2d5d1a | [
"data = {'igdb': request.data['game']['id'], 'name': request.data['game']['name'], 'slug': request.data['game']['slug'], 'cover_id': request.data['game']['coverId'], 'backdrop_id': request.data['game']['backdropId']}\ngame, _ = Game.objects.get_or_create(**data)\nuser = CustomUser.objects.get(id=request.user.id)\nr... | <|body_start_0|>
data = {'igdb': request.data['game']['id'], 'name': request.data['game']['name'], 'slug': request.data['game']['slug'], 'cover_id': request.data['game']['coverId'], 'backdrop_id': request.data['game']['backdropId']}
game, _ = Game.objects.get_or_create(**data)
user = CustomUser.... | Endpoint for the gaming journal. | JournalView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and ... | stack_v2_sparse_classes_10k_train_002842 | 15,728 | no_license | [
{
"docstring": "Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and a game. Args: game: game object with igdb id, name, slug, cover_id and backdrop_id date: the day you finished... | 2 | stack_v2_sparse_classes_30k_train_001534 | Implement the Python class `JournalView` described below.
Class description:
Endpoint for the gaming journal.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in the... | Implement the Python class `JournalView` described below.
Class description:
Endpoint for the gaming journal.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in the... | 7f7e44ca0dae3525394458c16b7093f90612524b | <|skeleton|>
class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and a game. Args:... | the_stack_v2_python_sparse | backend/actions/views.py | RMalmberg/overworld | train | 3 |
8cda23dd5618502792feb639b94515308ee66749 | [
"self.matomo_url = matomo_url\nself.matomo_api_key = matomo_api_key\nself.matomo_api_key = '&token_auth=' + self.matomo_api_key\nself.ssl_verify = ssl_verify\nself.cleanmatomo_url()",
"self.matomo_url = re.sub('/\\\\/$/', '', self.matomo_url)\nif re.match('^http://', self.matomo_url):\n self.matomo_url = re.su... | <|body_start_0|>
self.matomo_url = matomo_url
self.matomo_api_key = matomo_api_key
self.matomo_api_key = '&token_auth=' + self.matomo_api_key
self.ssl_verify = ssl_verify
self.cleanmatomo_url()
<|end_body_0|>
<|body_start_1|>
self.matomo_url = re.sub('/\\/$/', '', self.m... | This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore. | MatomoApiManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_10k_train_002843 | 4,420 | permissive | [
{
"docstring": "Constructor initialises matomo_url, matomo_api_key, ssl_verify :param matomo_url: :param matomo_api_key: :param ssl_verify:",
"name": "__init__",
"signature": "def __init__(self, matomo_url, matomo_api_key, ssl_verify)"
},
{
"docstring": "Cleans Matomo-URL for proper requests. Ch... | 4 | stack_v2_sparse_classes_30k_val_000330 | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | b769510570d5921e30876565263813c0362994e2 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl_verify):
... | the_stack_v2_python_sparse | src/cms/views/statistics/matomo_api_manager.py | digitalfabrik/coldaid-backend | train | 4 |
df0bfdd6f9c355d9108f078218804a9b15d25f2a | [
"query_builder = Configuration.BASE_URI\nquery_builder += '/ws/scatterplot'\nquery_builder = APIHelper.append_url_with_query_parameters(query_builder, {'q': options.get('q', None), 'x': options.get('x', None), 'y': options.get('y', None), 'fq': options.get('fq', None), 'height': options.get('height', None), 'pointc... | <|body_start_0|>
query_builder = Configuration.BASE_URI
query_builder += '/ws/scatterplot'
query_builder = APIHelper.append_url_with_query_parameters(query_builder, {'q': options.get('q', None), 'x': options.get('x', None), 'y': options.get('y', None), 'fq': options.get('fq', None), 'height': op... | A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API. | ScatterplotController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScatterplotController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_scatterplot_image(self, options=dict()):
"""Does a GET request to /ws/scatterplot. Return an image for occurrences and two environmental layers as a scatterplot. Arg... | stack_v2_sparse_classes_10k_train_002844 | 9,072 | no_license | [
{
"docstring": "Does a GET request to /ws/scatterplot. Return an image for occurrences and two environmental layers as a scatterplot. Args: options (dict, optional): Key-value pairs for any of the parameters to this API Endpoint. All parameters to the endpoint are supplied through the dictionary with their name... | 2 | stack_v2_sparse_classes_30k_train_005679 | Implement the Python class `ScatterplotController` described below.
Class description:
A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API.
Method signatures and docstrings:
- def get_scatterplot_image(self, options=dict()): Does a GET request to /ws/scatterplot. Return an image for occur... | Implement the Python class `ScatterplotController` described below.
Class description:
A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API.
Method signatures and docstrings:
- def get_scatterplot_image(self, options=dict()): Does a GET request to /ws/scatterplot. Return an image for occur... | a9f803ea42bef4eb3720d5dd92a53dc98e8f2678 | <|skeleton|>
class ScatterplotController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_scatterplot_image(self, options=dict()):
"""Does a GET request to /ws/scatterplot. Return an image for occurrences and two environmental layers as a scatterplot. Arg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScatterplotController:
"""A Controller to access Endpoints in the AtlasOfLivingAustraliaOccurrencesLib API."""
def get_scatterplot_image(self, options=dict()):
"""Does a GET request to /ws/scatterplot. Return an image for occurrences and two environmental layers as a scatterplot. Args: options (d... | the_stack_v2_python_sparse | AtlasOfLivingAustraliaOccurrencesLib/Controllers/ScatterplotController.py | chm052/naturehack | train | 2 |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super().__init__()\nself.beta = beta\nself.inplace = inplace",
"if inplace:\n return torch.log(F.relu_(x).mul_(self.beta).add_(1), out=x)\nelse:\n return torch.log(1 + self.beta * F.relu(x))"
] | <|body_start_0|>
super().__init__()
self.beta = beta
self.inplace = inplace
<|end_body_0|>
<|body_start_1|>
if inplace:
return torch.log(F.relu_(x).mul_(self.beta).add_(1), out=x)
else:
return torch.log(1 + self.beta * F.relu(x))
<|end_body_1|>
| NLReLU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.beta = beta
self.in... | stack_v2_sparse_classes_10k_train_002845 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, beta=1.0, inplace=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000386 | Implement the Python class `NLReLU` described below.
Class description:
Implement the NLReLU class.
Method signatures and docstrings:
- def __init__(self, beta=1.0, inplace=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `NLReLU` described below.
Class description:
Implement the NLReLU class.
Method signatures and docstrings:
- def __init__(self, beta=1.0, inplace=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inpl... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
super().__init__()
self.beta = beta
self.inplace = inplace
def forward(self, input):
"""Forward pass of the function."""
if inplace:
return torch.log(F.relu_(x).mul_(self.be... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
08178f8b7e1a278bf325f70ab253568839dd2e9b | [
"path = self.request.get('path', None)\nif path is None:\n return []\nclassModule = getUtility(IDocumentationModule, 'Code')\nresults = []\nfor p in classRegistry.keys():\n if p.find(path) >= 0:\n klass = traverse(classModule, p.replace('.', '/'))\n results.append({'path': p, 'url': absoluteURL(... | <|body_start_0|>
path = self.request.get('path', None)
if path is None:
return []
classModule = getUtility(IDocumentationModule, 'Code')
results = []
for p in classRegistry.keys():
if p.find(path) >= 0:
klass = traverse(classModule, p.repla... | Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation. | Menu | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodul... | stack_v2_sparse_classes_10k_train_002846 | 5,400 | permissive | [
{
"docstring": "Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodule.class_ import Class >>> cm = apidoc.get('Code') >>> mod = cm['zope']['app']['apidoc']['codemodule']['browser'] Setup a couple of classes and register them. >>> class Foo(object): ... pass >>> mod._children... | 2 | stack_v2_sparse_classes_30k_train_003280 | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | 539d418fb28322e27fea252ceccc42192dd0d63d | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodule.class_ impo... | the_stack_v2_python_sparse | src/zope/app/apidoc/codemodule/browser/menu.py | jean/zope.app.apidoc | train | 0 |
bdf1de4f1ecb4b5c462a43a6b684a320d8a9db32 | [
"def dp(s, i, p, j):\n m = len(s)\n n = len(p)\n if j == n:\n return i == m\n if i == m:\n if (n - j) % 2 == 1:\n return False\n for j in range(0, n - 1, 2):\n if p[j + 1] != '*':\n return False\n return True\n if s[i] == p[j] or p[j] =... | <|body_start_0|>
def dp(s, i, p, j):
m = len(s)
n = len(p)
if j == n:
return i == m
if i == m:
if (n - j) % 2 == 1:
return False
for j in range(0, n - 1, 2):
if p[j + 1] != '*'... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
... | stack_v2_sparse_classes_10k_train_002847 | 2,919 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :r... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p:... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
def dp(s, i, p, j):
m = len(s)
n = len(p)
if j == n:
return i == m
if i == m:
if (n - j) % 2 == 1:
return False
... | the_stack_v2_python_sparse | 0010_Regular_Expression_Matching.py | bingli8802/leetcode | train | 0 | |
fe8af5173828e5f2ba3eec3accdcd3de4d5ac61f | [
"self.filename = filename\nself.__outputFieldsCsv = copy.deepcopy(outputFieldsCsv)\nself.__headerFiedlNames = None\nself.__boolAddShapeFields = boolAddShapeFields\nself.__userFieldShapeMap = userFieldShapeMap\ntry:\n self.__log = log\n if self.__outputFieldsCsv is not None:\n with open(self.filename, '... | <|body_start_0|>
self.filename = filename
self.__outputFieldsCsv = copy.deepcopy(outputFieldsCsv)
self.__headerFiedlNames = None
self.__boolAddShapeFields = boolAddShapeFields
self.__userFieldShapeMap = userFieldShapeMap
try:
self.__log = log
if se... | API for write output CSV files write data output files | CSV_Writer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSV_Writer:
"""API for write output CSV files write data output files"""
def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None):
"""Constructor :param log: logger object :param filename: Work file name :param inputFields: Column header na... | stack_v2_sparse_classes_10k_train_002848 | 8,314 | permissive | [
{
"docstring": "Constructor :param log: logger object :param filename: Work file name :param inputFields: Column header names list for output file",
"name": "__init__",
"signature": "def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_001672 | Implement the Python class `CSV_Writer` described below.
Class description:
API for write output CSV files write data output files
Method signatures and docstrings:
- def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None): Constructor :param log: logger object :param file... | Implement the Python class `CSV_Writer` described below.
Class description:
API for write output CSV files write data output files
Method signatures and docstrings:
- def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None): Constructor :param log: logger object :param file... | 9764fcb86d3898b232c4cc333dab75ebe41cd421 | <|skeleton|>
class CSV_Writer:
"""API for write output CSV files write data output files"""
def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None):
"""Constructor :param log: logger object :param filename: Work file name :param inputFields: Column header na... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CSV_Writer:
"""API for write output CSV files write data output files"""
def __init__(self, log, filename, outputFieldsCsv, boolAddShapeFields=False, userFieldShapeMap=None):
"""Constructor :param log: logger object :param filename: Work file name :param inputFields: Column header names list for ... | the_stack_v2_python_sparse | PlanheatMappingModule/PlanHeatDMM/manageCsv/csv_writer.py | Planheat/Planheat-Tool | train | 2 |
ceefcb20fdac0bf9b157b2cea0a7bf0dff2f8a92 | [
"l1, l2 = (len(word1), len(word2))\ndp = [[0] * (l2 + 1) for _ in range(l1 + 1)]\nfor i in range(l1 + 1):\n for j in range(l2 + 1):\n if i == 0 or j == 0:\n dp[i][j] = max(i, j)\n continue\n if word1[i - 1:i] == word2[j - 1:j]:\n dp[i][j] = dp[i - 1][j - 1]\n ... | <|body_start_0|>
l1, l2 = (len(word1), len(word2))
dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
for i in range(l1 + 1):
for j in range(l2 + 1):
if i == 0 or j == 0:
dp[i][j] = max(i, j)
continue
if word1[i - 1:i]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l1, l... | stack_v2_sparse_classes_10k_train_002849 | 1,478 | no_license | [
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance",
"signature": "def minDistance(self, word1, word2)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "minDistance",
"signature": "def minDistance(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007059 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleto... | 2a29426be1d690b6f90bc45b437900deee46d832 | <|skeleton|>
class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_0|>
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
l1, l2 = (len(word1), len(word2))
dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
for i in range(l1 + 1):
for j in range(l2 + 1):
if i == 0 or j == 0:
... | the_stack_v2_python_sparse | src/leet/72-edit-distance.py | sevenseablue/leetcode | train | 0 | |
96bd0c9246a0692c905e7b20da948804fe63c2d8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuditResource()",
"from .audit_property import AuditProperty\nfrom .audit_property import AuditProperty\nfields: Dict[str, Callable[[Any], None]] = {'auditResourceType': lambda n: setattr(self, 'audit_resource_type', n.get_str_value())... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AuditResource()
<|end_body_0|>
<|body_start_1|>
from .audit_property import AuditProperty
from .audit_property import AuditProperty
fields: Dict[str, Callable[[Any], None]] = {'a... | A class containing the properties for Audit Resource. | AuditResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditResource:
"""A class containing the properties for Audit Resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to u... | stack_v2_sparse_classes_10k_train_002850 | 3,477 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AuditResource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `AuditResource` described below.
Class description:
A class containing the properties for Audit Resource.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditResource: Creates a new instance of the appropriate class based on ... | Implement the Python class `AuditResource` described below.
Class description:
A class containing the properties for Audit Resource.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditResource: Creates a new instance of the appropriate class based on ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AuditResource:
"""A class containing the properties for Audit Resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AuditResource:
"""A class containing the properties for Audit Resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditResource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read th... | the_stack_v2_python_sparse | msgraph/generated/models/audit_resource.py | microsoftgraph/msgraph-sdk-python | train | 135 |
82d5c2a41a0f626df3341e8d0fa2b5d2afbc6233 | [
"for i in range(1, len(nums)):\n nums[i] = max(nums[i - 1] + nums[i], nums[i])\nreturn max(nums)",
"dp = [0] * len(nums)\ndp[0] = nums[0]\nfor i in range(1, len(nums)):\n dp[i] = max(dp[i - 1] + nums[i], nums[i])\nreturn max(dp)"
] | <|body_start_0|>
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nums)
<|end_body_0|>
<|body_start_1|>
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_10k_train_002851 | 1,087 | no_license | [
{
"docstring": "Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums: list) -> int"
},
{
"docstring": "动态规划",
"name": "maxSubArray2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_003478 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nu... | the_stack_v2_python_sparse | 053_maximum-subarray.py | helloocc/algorithm | train | 1 | |
2f02667ac30e668eeb111658d80a89dbe04d37af | [
"self._df_ = df_\nself._history = history\nself._future = future",
"scaler = MinMaxScaler()\nfeatures = len(self._df_.columns)\ndf_ = pd.DataFrame(scaler.fit_transform(self._df_), columns=self._df_.columns, index=self._df_.index)\nprint(type(df_))\nprint(df_.tail())\nx_train, y_train = create_features(list(df_.cl... | <|body_start_0|>
self._df_ = df_
self._history = history
self._future = future
<|end_body_0|>
<|body_start_1|>
scaler = MinMaxScaler()
features = len(self._df_.columns)
df_ = pd.DataFrame(scaler.fit_transform(self._df_), columns=self._df_.columns, index=self._df_.index)
... | Preprocess the data for models. | PreProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. fu... | stack_v2_sparse_classes_10k_train_002852 | 11,672 | no_license | [
{
"docstring": "Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. future: Number of future entries to predict. features: Number of features in Dataframe. Returns: None",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_005142 | Implement the Python class `PreProcessing` described below.
Class description:
Preprocess the data for models.
Method signatures and docstrings:
- def __init__(self, df_, history=50, future=50): Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is ... | Implement the Python class `PreProcessing` described below.
Class description:
Preprocess the data for models.
Method signatures and docstrings:
- def __init__(self, df_, history=50, future=50): Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is ... | 36a7996b140cccb9003cba8367364645e2d65d85 | <|skeleton|>
class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. fu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. future: Number ... | the_stack_v2_python_sparse | timeseries/obya/bin/forecast-x-period.py | palisadoes/AI | train | 1 |
deaa8d0108b929185bc6bd5b5139f3e426eeb503 | [
"node = root\nqueue = [node]\nresult = list()\nwhile queue:\n nodes = list()\n nodesvalue = list()\n for node in queue:\n nodesvalue.append(node.val)\n if node.left:\n nodes.append(node.left)\n if node.right:\n nodes.append(node.right)\n result.append(nodesvalu... | <|body_start_0|>
node = root
queue = [node]
result = list()
while queue:
nodes = list()
nodesvalue = list()
for node in queue:
nodesvalue.append(node.val)
if node.left:
nodes.append(node.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findBottomLeftValue_function2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def findBottomLeftValue_function3(self, root):
""":t... | stack_v2_sparse_classes_10k_train_002853 | 2,293 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findBottomLeftValue",
"signature": "def findBottomLeftValue(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findBottomLeftValue_function2",
"signature": "def findBottomLeftValue_function2(self, root)"... | 3 | stack_v2_sparse_classes_30k_train_000437 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue_function2(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue_function2(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue_... | 3f2de917df20de2d84446902fd6404ce1f15dd3d | <|skeleton|>
class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findBottomLeftValue_function2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def findBottomLeftValue_function3(self, root):
""":t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
node = root
queue = [node]
result = list()
while queue:
nodes = list()
nodesvalue = list()
for node in queue:
nodesvalue.append(node... | the_stack_v2_python_sparse | leetcode/找树左下角的值.py | YimingXue/leetcode-sword2offer | train | 1 | |
f95a8f37625b9e45cdc81de925493852f2715915 | [
"if base_path == '/v1/reflect/me':\n return self._reflect_request(base_path, url_args, body_args)\nmatch = self.SRV_QUERY_REGEXP.search(base_path)\nif match:\n return self.__srv_permissions_request_handler(match.group(1))\nraise EndpointException(code=500, content='Path `{}` is not supported yet'.format(base_... | <|body_start_0|>
if base_path == '/v1/reflect/me':
return self._reflect_request(base_path, url_args, body_args)
match = self.SRV_QUERY_REGEXP.search(base_path)
if match:
return self.__srv_permissions_request_handler(match.group(1))
raise EndpointException(code=500... | Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services. | MesosDnsHTTPRequestHandler | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-oracle-bcl-javase-javafx-2012",
"ErlPL-1.1",
"MPL-2.0",
"ISC",
"BSL-1.0",
"Python-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for gi... | stack_v2_sparse_classes_10k_train_002854 | 5,228 | permissive | [
{
"docstring": "Reply with the currently set mock-reply for given SRV record query. Please refer to the description of the BaseHTTPRequestHandler class for details on the arguments and return value of this method. Raises: EndpointException: request URL path is unsupported",
"name": "_calculate_response",
... | 2 | stack_v2_sparse_classes_30k_train_004197 | Implement the Python class `MesosDnsHTTPRequestHandler` described below.
Class description:
Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services.
Method signatures and docstrings:
- def _calculate_response(self, base_path, url_args, body_a... | Implement the Python class `MesosDnsHTTPRequestHandler` described below.
Class description:
Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services.
Method signatures and docstrings:
- def _calculate_response(self, base_path, url_args, body_a... | 79b9a39b4e639dc2c9435a869918399b50bfaf24 | <|skeleton|>
class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for gi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for given SRV recor... | the_stack_v2_python_sparse | packages/adminrouter/extra/src/test-harness/modules/mocker/endpoints/mesos_dns.py | dcos/dcos | train | 2,613 |
8347b3e71ca8e903e681e95d23b340607289e06b | [
"self.index_to_result = []\nself.hashable_to_index = dict()\nfor i, result in enumerate(generator):\n self.index_to_result.append(result)\n hashable = to_hashable(result)\n if hashable in self.hashable_to_index:\n break\n else:\n self.hashable_to_index[hashable] = i\nelse:\n raise Excep... | <|body_start_0|>
self.index_to_result = []
self.hashable_to_index = dict()
for i, result in enumerate(generator):
self.index_to_result.append(result)
hashable = to_hashable(result)
if hashable in self.hashable_to_index:
break
else:
... | RepeatingSequence | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
<|body_0|>
def cycle_number(self, index):
"""Returns which 0-indexed cycle... | stack_v2_sparse_classes_10k_train_002855 | 24,260 | permissive | [
{
"docstring": "generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable.",
"name": "__init__",
"signature": "def __init__(self, generator, to_hashable=lambda x: x)"
},
{
"docstring": "Returns which 0-indexed cycle index appears in. cycle_num... | 3 | stack_v2_sparse_classes_30k_train_005242 | Implement the Python class `RepeatingSequence` described below.
Class description:
Implement the RepeatingSequence class.
Method signatures and docstrings:
- def __init__(self, generator, to_hashable=lambda x: x): generator should yield the things in the sequence. to_hashable should be used if things aren't nicely ha... | Implement the Python class `RepeatingSequence` described below.
Class description:
Implement the RepeatingSequence class.
Method signatures and docstrings:
- def __init__(self, generator, to_hashable=lambda x: x): generator should yield the things in the sequence. to_hashable should be used if things aren't nicely ha... | 42ded86513cac25272a880983746f261336fee96 | <|skeleton|>
class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
<|body_0|>
def cycle_number(self, index):
"""Returns which 0-indexed cycle... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
self.index_to_result = []
self.hashable_to_index = dict()
for i, result in enumerate(... | the_stack_v2_python_sparse | dojo/adventofcode.com/2021/catchup/mcpower_utils.py | saramic/learning | train | 4 | |
5928d867f9dcaec1bec5798217cd30f325263229 | [
"for k, v in phenotypes.items():\n assert type(k) is str, 'phenotype keys must be strings'\n assert v[1] > v[0], 'upper bound of ' + k + ' must be greater than the lower bound'\n assert type(v[1]) is int and type(v[0]) is int, ' (!) recent change means bounds need to be in ints now: https://github.com/zafa... | <|body_start_0|>
for k, v in phenotypes.items():
assert type(k) is str, 'phenotype keys must be strings'
assert v[1] > v[0], 'upper bound of ' + k + ' must be greater than the lower bound'
assert type(v[1]) is int and type(v[0]) is int, ' (!) recent change means bounds need t... | PhenotypeEvaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dicti... | stack_v2_sparse_classes_10k_train_002856 | 3,310 | no_license | [
{
"docstring": "PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dictionary [mandatory] must contain entries akin to { 'phenotype-nam... | 2 | stack_v2_sparse_classes_30k_train_005662 | Implement the Python class `PhenotypeEvaluator` described below.
Class description:
Implement the PhenotypeEvaluator class.
Method signatures and docstrings:
- def __init__(self, phenotypes): PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. I... | Implement the Python class `PhenotypeEvaluator` described below.
Class description:
Implement the PhenotypeEvaluator class.
Method signatures and docstrings:
- def __init__(self, phenotypes): PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. I... | a01c36ddaaf72d04608ad1a848a24864b73e95bf | <|skeleton|>
class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dicti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PhenotypeEvaluator:
def __init__(self, phenotypes):
"""PhenotypeEvaluator This class allows us to create a phenotype evaluator that accepts a dict of phenotypes on initialization. It can then evaluate individual Genome objects and return the phenotypes that it exhibits phenotypes / dictionary [mandato... | the_stack_v2_python_sparse | cc3dtools/Phenotype.py | ibrahim85/metastasis | train | 0 | |
7812eb8c0f6546df0c3d1dbe24514bfa1077fe0c | [
"\"\"\" Init inherited thread \"\"\"\nThread.__init__(self)\n' Use gui interface to start the feed '\nscreenWidth, screenHeight = pyautogui.size()\npyautogui.moveTo(screenWidth / 2, screenHeight / 2)\npyautogui.moveTo(160, 750)\npyautogui.click()\ntime.sleep(2)\npyautogui.click(400, 50)\npyautogui.keyDown('ctrl')\n... | <|body_start_0|>
""" Init inherited thread """
Thread.__init__(self)
' Use gui interface to start the feed '
screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
pyautogui.moveTo(160, 750)
pyautogui.click()
time.... | Access television feed and enable stills capture | feed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class feed:
"""Access television feed and enable stills capture"""
def __init__(self):
"""Initalise the thread"""
<|body_0|>
def take_still(self):
"""Grab a still image from the threaded feed"""
<|body_1|>
def run(self):
"""Feed threaded"""
... | stack_v2_sparse_classes_10k_train_002857 | 1,906 | no_license | [
{
"docstring": "Initalise the thread",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Grab a still image from the threaded feed",
"name": "take_still",
"signature": "def take_still(self)"
},
{
"docstring": "Feed threaded",
"name": "run",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_003398 | Implement the Python class `feed` described below.
Class description:
Access television feed and enable stills capture
Method signatures and docstrings:
- def __init__(self): Initalise the thread
- def take_still(self): Grab a still image from the threaded feed
- def run(self): Feed threaded | Implement the Python class `feed` described below.
Class description:
Access television feed and enable stills capture
Method signatures and docstrings:
- def __init__(self): Initalise the thread
- def take_still(self): Grab a still image from the threaded feed
- def run(self): Feed threaded
<|skeleton|>
class feed:... | 86b06394b7567179a496d2a0eee76922e2c3c1f6 | <|skeleton|>
class feed:
"""Access television feed and enable stills capture"""
def __init__(self):
"""Initalise the thread"""
<|body_0|>
def take_still(self):
"""Grab a still image from the threaded feed"""
<|body_1|>
def run(self):
"""Feed threaded"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class feed:
"""Access television feed and enable stills capture"""
def __init__(self):
"""Initalise the thread"""
""" Init inherited thread """
Thread.__init__(self)
' Use gui interface to start the feed '
screenWidth, screenHeight = pyautogui.size()
pyautogui.mo... | the_stack_v2_python_sparse | feed.py | ashleyjr/Countdown | train | 0 |
982229c702b0bc02857703c4a9f44661336f7a54 | [
"self.num_p = num_particles\nself.num_d = num_dimensions\nself.alpha = alpha\nself.alpha4 = alpha ** 4\nself.alpha5 = alpha ** 5\nself.s = system",
"term = 0.0\nself.s.positions_distances_PBC(positions)\nfor i in range(self.num_p):\n for j in range(i, self.num_p - 1):\n distance = self.s.distances[i, j ... | <|body_start_0|>
self.num_p = num_particles
self.num_d = num_dimensions
self.alpha = alpha
self.alpha4 = alpha ** 4
self.alpha5 = alpha ** 5
self.s = system
<|end_body_0|>
<|body_start_1|>
term = 0.0
self.s.positions_distances_PBC(positions)
for i... | Contains parameters of wavefunction and wave equation. | McMillian_Wavefunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
<|body_0|>
def wavefunction(self, positions):
"""Return wave equation."""
<|bod... | stack_v2_sparse_classes_10k_train_002858 | 4,374 | no_license | [
{
"docstring": "Instance of class.",
"name": "__init__",
"signature": "def __init__(self, num_particles, num_dimensions, alpha, system)"
},
{
"docstring": "Return wave equation.",
"name": "wavefunction",
"signature": "def wavefunction(self, positions)"
},
{
"docstring": "Calculat... | 6 | stack_v2_sparse_classes_30k_train_001597 | Implement the Python class `McMillian_Wavefunction` described below.
Class description:
Contains parameters of wavefunction and wave equation.
Method signatures and docstrings:
- def __init__(self, num_particles, num_dimensions, alpha, system): Instance of class.
- def wavefunction(self, positions): Return wave equat... | Implement the Python class `McMillian_Wavefunction` described below.
Class description:
Contains parameters of wavefunction and wave equation.
Method signatures and docstrings:
- def __init__(self, num_particles, num_dimensions, alpha, system): Instance of class.
- def wavefunction(self, positions): Return wave equat... | bed19421ceef6203d089b67a657ca3290740300a | <|skeleton|>
class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
<|body_0|>
def wavefunction(self, positions):
"""Return wave equation."""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class McMillian_Wavefunction:
"""Contains parameters of wavefunction and wave equation."""
def __init__(self, num_particles, num_dimensions, alpha, system):
"""Instance of class."""
self.num_p = num_particles
self.num_d = num_dimensions
self.alpha = alpha
self.alpha4 = a... | the_stack_v2_python_sparse | src/Wavefunction/mcmillian.py | KariEriksen/VMC | train | 6 |
738520414003b38a39ee6f782bec02851a6f7f6d | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.bttn1 = Button(self, text='Я ничего не делаю!')\nself.bttn1.grid()\nself.bttn2 = Button(self)\nself.bttn2.grid()\nself.bttn2.configure(text='И я тоже!')\nself.bttn3 = Button(self)\nself.bttn3.grid()\nself.bttn3['text'] = 'И я!'... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.bttn1 = Button(self, text='Я ничего не делаю!')
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.conf... | GUI - приложение с тремя кнопками | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
<|body_0|>
def create_widgets(self):
"""Создает три бесполезные кнопки."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Applicatio... | stack_v2_sparse_classes_10k_train_002859 | 1,163 | no_license | [
{
"docstring": "Инициализирует рамку.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Создает три бесполезные кнопки.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002393 | Implement the Python class `Application` described below.
Class description:
GUI - приложение с тремя кнопками
Method signatures and docstrings:
- def __init__(self, master): Инициализирует рамку.
- def create_widgets(self): Создает три бесполезные кнопки. | Implement the Python class `Application` described below.
Class description:
GUI - приложение с тремя кнопками
Method signatures and docstrings:
- def __init__(self, master): Инициализирует рамку.
- def create_widgets(self): Создает три бесполезные кнопки.
<|skeleton|>
class Application:
"""GUI - приложение с тр... | 0192a5a936aac4ebec18e6f6bb4988e1865942f0 | <|skeleton|>
class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
<|body_0|>
def create_widgets(self):
"""Создает три бесполезные кнопки."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Создает три бесполезные кнопки."""
sel... | the_stack_v2_python_sparse | lessons/Chapter 10/10_02.py | a-abramow/MDawsonlessons | train | 0 |
6a8d51385bc02d017f1e248dc33e066d50abc2d2 | [
"self.nodes_count = n\nself.graph = [[] for _ in range(n)]\nfor rib, rib_weight in pairs:\n self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))",
"cur_node = [np.inf, 0]\nfor i in range(self.nodes_count):\n if d[i] < cur_node[0] and (not used[i]):\n cur_node = [d[i], i]\nreturn (cur_node, d, used... | <|body_start_0|>
self.nodes_count = n
self.graph = [[] for _ in range(n)]
for rib, rib_weight in pairs:
self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))
<|end_body_0|>
<|body_start_1|>
cur_node = [np.inf, 0]
for i in range(self.nodes_count):
if d[i... | Dijkstra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
<|body_0|>
def __find_next_node(self, d, used):
"""Find next node with min weight :param d: :param used: :return:"""
<|body_1|>
def solve(self, start... | stack_v2_sparse_classes_10k_train_002860 | 2,687 | no_license | [
{
"docstring": "Create graph for dijkstra algorithm :param pairs: :return:",
"name": "__init__",
"signature": "def __init__(self, pairs, n)"
},
{
"docstring": "Find next node with min weight :param d: :param used: :return:",
"name": "__find_next_node",
"signature": "def __find_next_node(... | 3 | stack_v2_sparse_classes_30k_train_001348 | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def __init__(self, pairs, n): Create graph for dijkstra algorithm :param pairs: :return:
- def __find_next_node(self, d, used): Find next node with min weight :param d: :param us... | Implement the Python class `Dijkstra` described below.
Class description:
Implement the Dijkstra class.
Method signatures and docstrings:
- def __init__(self, pairs, n): Create graph for dijkstra algorithm :param pairs: :return:
- def __find_next_node(self, d, used): Find next node with min weight :param d: :param us... | e672e0232ba7978107ab9fac2624e5bccf5f6a46 | <|skeleton|>
class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
<|body_0|>
def __find_next_node(self, d, used):
"""Find next node with min weight :param d: :param used: :return:"""
<|body_1|>
def solve(self, start... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dijkstra:
def __init__(self, pairs, n):
"""Create graph for dijkstra algorithm :param pairs: :return:"""
self.nodes_count = n
self.graph = [[] for _ in range(n)]
for rib, rib_weight in pairs:
self.graph[rib[0] - 1].append((rib[1] - 1, rib_weight))
def __find_ne... | the_stack_v2_python_sparse | SAiIO/src/dijkstra.py | qqpoltergeist/BSUIR-IITP-2016-2020 | train | 0 | |
2bc532086adf661bb286f7ea080cf6021e120ad0 | [
"if not self.versions:\n return ''\nif language is None:\n try:\n language = c.lang\n except AttributeError:\n pass\nversion = self.get_version(language)\nif version is not None:\n return version.text\nversion = self.get_version(fallback)\nif version is not None:\n return version.text\n... | <|body_start_0|>
if not self.versions:
return ''
if language is None:
try:
language = c.lang
except AttributeError:
pass
version = self.get_version(language)
if version is not None:
return version.text
... | I18nText | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I18nText:
def get_text(self, language=None, fallback='en'):
"""Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language or any other version. Returns empty string if no text is found."""
<|body_0|>
def se... | stack_v2_sparse_classes_10k_train_002861 | 5,283 | no_license | [
{
"docstring": "Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language or any other version. Returns empty string if no text is found.",
"name": "get_text",
"signature": "def get_text(self, language=None, fallback='en')"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003288 | Implement the Python class `I18nText` described below.
Class description:
Implement the I18nText class.
Method signatures and docstrings:
- def get_text(self, language=None, fallback='en'): Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language ... | Implement the Python class `I18nText` described below.
Class description:
Implement the I18nText class.
Method signatures and docstrings:
- def get_text(self, language=None, fallback='en'): Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language ... | e1f55f155761d7b350893fc0badb70c9c51c4b2f | <|skeleton|>
class I18nText:
def get_text(self, language=None, fallback='en'):
"""Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language or any other version. Returns empty string if no text is found."""
<|body_0|>
def se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class I18nText:
def get_text(self, language=None, fallback='en'):
"""Get a text for a given language. If no language is specified, attempts to get it from context. Falls back to the given language or any other version. Returns empty string if no text is found."""
if not self.versions:
re... | the_stack_v2_python_sparse | src/ututi/model/i18n.py | Ututi/ututi | train | 0 | |
6acd4eb5b0fd9558732acbb70f7169e23fb68b38 | [
"config_help = super(MemoryLxcCollector, self).get_default_config_help()\nconfig_help.update({'sys_path': \"Defaults to '/sys/fs/cgroup/lxc'\"})\nreturn config_help",
"config = super(MemoryLxcCollector, self).get_default_config()\nconfig.update({'path': 'lxc', 'sys_path': '/sys/fs/cgroup/lxc'})\nreturn config",
... | <|body_start_0|>
config_help = super(MemoryLxcCollector, self).get_default_config_help()
config_help.update({'sys_path': "Defaults to '/sys/fs/cgroup/lxc'"})
return config_help
<|end_body_0|>
<|body_start_1|>
config = super(MemoryLxcCollector, self).get_default_config()
config.u... | MemoryLxcCollector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoryLxcCollector:
def get_default_config_help(self):
"""Return help text for collector configuration."""
<|body_0|>
def get_default_config(self):
"""Returns default settings for collector."""
<|body_1|>
def collect(self):
"""Collect memory stat... | stack_v2_sparse_classes_10k_train_002862 | 2,599 | permissive | [
{
"docstring": "Return help text for collector configuration.",
"name": "get_default_config_help",
"signature": "def get_default_config_help(self)"
},
{
"docstring": "Returns default settings for collector.",
"name": "get_default_config",
"signature": "def get_default_config(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_004995 | Implement the Python class `MemoryLxcCollector` described below.
Class description:
Implement the MemoryLxcCollector class.
Method signatures and docstrings:
- def get_default_config_help(self): Return help text for collector configuration.
- def get_default_config(self): Returns default settings for collector.
- def... | Implement the Python class `MemoryLxcCollector` described below.
Class description:
Implement the MemoryLxcCollector class.
Method signatures and docstrings:
- def get_default_config_help(self): Return help text for collector configuration.
- def get_default_config(self): Returns default settings for collector.
- def... | 461caf29e84db8cbf46f9fc4c895f56353e10c61 | <|skeleton|>
class MemoryLxcCollector:
def get_default_config_help(self):
"""Return help text for collector configuration."""
<|body_0|>
def get_default_config(self):
"""Returns default settings for collector."""
<|body_1|>
def collect(self):
"""Collect memory stat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MemoryLxcCollector:
def get_default_config_help(self):
"""Return help text for collector configuration."""
config_help = super(MemoryLxcCollector, self).get_default_config_help()
config_help.update({'sys_path': "Defaults to '/sys/fs/cgroup/lxc'"})
return config_help
def ge... | the_stack_v2_python_sparse | src/collectors/memory_lxc/memory_lxc.py | python-diamond/Diamond | train | 1,874 | |
e54d32824889b45846a506ca7cdecd0cffd5913e | [
"signature = 'hfppnetwork.partner.httpservices.PartnerHTTPServices.data_request'\nmethod_enter(signature, {'self': self})\nrequest_body = cherrypy.request.body.read().decode('utf-8')\nlogging.debug('%s:%s', 'request_body', request_body)\nif len(request_body) == 0:\n raise PartnerClientError('request body can not... | <|body_start_0|>
signature = 'hfppnetwork.partner.httpservices.PartnerHTTPServices.data_request'
method_enter(signature, {'self': self})
request_body = cherrypy.request.body.read().decode('utf-8')
logging.debug('%s:%s', 'request_body', request_body)
if len(request_body) == 0:
... | PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request/response data, hence the use of CherryPy modul... | PartnerHTTPServices | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request... | stack_v2_sparse_classes_10k_train_002863 | 20,090 | permissive | [
{
"docstring": "This method is used to serve data request partner client http service. @param self the PartnerHTTPServices itself, it should be PartnerHTTPServices @throws PartnerClientError throws if request body is empty @throws Exception any error should be raised to caller. CherryPy will handle the error an... | 2 | stack_v2_sparse_classes_30k_train_002456 | Implement the Python class `PartnerHTTPServices` described below.
Class description:
PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes us... | Implement the Python class `PartnerHTTPServices` described below.
Class description:
PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes us... | 4facd935920e77239c25323ca7e233cb899ba9f5 | <|skeleton|>
class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PartnerHTTPServices:
"""PartnerHTTPServices class defines the CherryPy handler to serve Partner Client HTTP services. This class resides in Python source file httpservices.py Thread Safety: This class is thread safe because it is immutable. CherryPy makes use of thread local data for HTTP request/response dat... | the_stack_v2_python_sparse | partnerclient/hfppnetwork/partner/httpservices.py | joshuaeveleth/CoECI-CMS-Healthcare-Fraud-Prevention | train | 0 |
2a75b94e95bab6a40f675beb210a45e024bbb728 | [
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n n1 = pre.next\n n2 = n1.next\n tmp = n2.next\n pre.next = n2\n n2.next = n1\n n1.next = tmp\n pre = n1",
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n first... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
n2.next = n1
n1.next = tmp
pre = n1
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy = ListNode(0)
dummy.next ... | stack_v2_sparse_classes_10k_train_002864 | 1,460 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_2",
"signature": "def swapPairs_2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006058 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def swapP... | a42098599bac4188eccb447de146434bc236a70a | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
... | the_stack_v2_python_sparse | 力扣/z_03_两两交换链表中的节点.py | Pysuper/LetCODE | train | 1 | |
4c7151c381244afa91b1678239a2103fb64725fa | [
"super().__init__()\nself.cnn_layers = nn.Sequential()\nself.fc_layers = nn.Sequential()\nself.loss_criterion = None\nself.cnn_layers = nn.Sequential(nn.Conv2d(1, 10, kernel_size=5), nn.MaxPool2d(kernel_size=3), nn.ReLU(), nn.Conv2d(10, 20, kernel_size=5), nn.MaxPool2d(kernel_size=3), nn.ReLU())\nself.fc_layers = n... | <|body_start_0|>
super().__init__()
self.cnn_layers = nn.Sequential()
self.fc_layers = nn.Sequential()
self.loss_criterion = None
self.cnn_layers = nn.Sequential(nn.Conv2d(1, 10, kernel_size=5), nn.MaxPool2d(kernel_size=3), nn.ReLU(), nn.Conv2d(10, 20, kernel_size=5), nn.MaxPool2... | SimpleNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleNet:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
<|body_0|>
def forward(self, x: torch.tensor) -> torch.tensor:
"""Perform t... | stack_v2_sparse_classes_10k_train_002865 | 2,085 | no_license | [
{
"docstring": "Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform the forward pass with the net Args: - x: t... | 2 | stack_v2_sparse_classes_30k_train_004324 | Implement the Python class `SimpleNet` described below.
Class description:
Implement the SimpleNet class.
Method signatures and docstrings:
- def __init__(self): Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means
-... | Implement the Python class `SimpleNet` described below.
Class description:
Implement the SimpleNet class.
Method signatures and docstrings:
- def __init__(self): Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means
-... | 79efc17404225c9d5f9845d6e7d8beea6a714a57 | <|skeleton|>
class SimpleNet:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
<|body_0|>
def forward(self, x: torch.tensor) -> torch.tensor:
"""Perform t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleNet:
def __init__(self):
"""Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means"""
super().__init__()
self.cnn_layers = nn.Sequential()
self.fc_layers = nn.Sequential()
... | the_stack_v2_python_sparse | Project6/simple_net.py | echen67/Computer-Vision | train | 1 | |
f25c4ca8f74cd3079a0809aba38c573067e943f0 | [
"t_min, t_max, t_increment = (200.15, 220.15, 10.0)\nresult = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=t_increment).process()\nself.assertEqual(result.attributes['minimum_temperature'], t_min)\nself.assertEqual(result.attributes['maximum_temperature'], t_max)\nself.assertEqual(result.attri... | <|body_start_0|>
t_min, t_max, t_increment = (200.15, 220.15, 10.0)
result = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=t_increment).process()
self.assertEqual(result.attributes['minimum_temperature'], t_min)
self.assertEqual(result.attributes['maximum_temperature... | Test that the plugin functions as expected. | Test_process | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
<|body_0|>
def test_cube_values(self):
"""Test that returned cube has expected values."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_002866 | 4,810 | permissive | [
{
"docstring": "Test that returned cube has appropriate attributes.",
"name": "test_cube_attributes",
"signature": "def test_cube_attributes(self)"
},
{
"docstring": "Test that returned cube has expected values.",
"name": "test_cube_values",
"signature": "def test_cube_values(self)"
},... | 3 | stack_v2_sparse_classes_30k_train_005915 | Implement the Python class `Test_process` described below.
Class description:
Test that the plugin functions as expected.
Method signatures and docstrings:
- def test_cube_attributes(self): Test that returned cube has appropriate attributes.
- def test_cube_values(self): Test that returned cube has expected values.
-... | Implement the Python class `Test_process` described below.
Class description:
Test that the plugin functions as expected.
Method signatures and docstrings:
- def test_cube_attributes(self): Test that returned cube has appropriate attributes.
- def test_cube_values(self): Test that returned cube has expected values.
-... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
<|body_0|>
def test_cube_values(self):
"""Test that returned cube has expected values."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_process:
"""Test that the plugin functions as expected."""
def test_cube_attributes(self):
"""Test that returned cube has appropriate attributes."""
t_min, t_max, t_increment = (200.15, 220.15, 10.0)
result = SaturatedVapourPressureTable(t_min=t_min, t_max=t_max, t_increment=... | the_stack_v2_python_sparse | improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py | metoppv/improver | train | 101 |
d8674da0d7b90507cca013d3d5df134e02f9bedd | [
"tk = Track()\ntk.add(0.0, self.head_mot.pantilt(0.8, 0.6, 0.5))\ntk.add(0.01, self.head_mot.moveeyes(0.0, 0.5))\ntk.add(0.5, self.head_mot.pantilt(-0.8, -0.6, 0.5))\ntk.add(0.51, self.head_mot.moveeyes(0.4, 0.5))\ntk.add(3.0, self.lights_mot.white_glow(255, 0.1, float('inf')))\nreturn tk",
"tk = Track()\ntk.add(... | <|body_start_0|>
tk = Track()
tk.add(0.0, self.head_mot.pantilt(0.8, 0.6, 0.5))
tk.add(0.01, self.head_mot.moveeyes(0.0, 0.5))
tk.add(0.5, self.head_mot.pantilt(-0.8, -0.6, 0.5))
tk.add(0.51, self.head_mot.moveeyes(0.4, 0.5))
tk.add(3.0, self.lights_mot.white_glow(255, 0.... | TestAnimations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnimations:
def seizure(self):
"""Actuate joints through range of motions"""
<|body_0|>
def test_pan(self):
"""Move pan axis independently."""
<|body_1|>
def test_tilt(self):
"""Move tilt axis independently."""
<|body_2|>
def tes... | stack_v2_sparse_classes_10k_train_002867 | 1,605 | no_license | [
{
"docstring": "Actuate joints through range of motions",
"name": "seizure",
"signature": "def seizure(self)"
},
{
"docstring": "Move pan axis independently.",
"name": "test_pan",
"signature": "def test_pan(self)"
},
{
"docstring": "Move tilt axis independently.",
"name": "te... | 4 | stack_v2_sparse_classes_30k_train_001031 | Implement the Python class `TestAnimations` described below.
Class description:
Implement the TestAnimations class.
Method signatures and docstrings:
- def seizure(self): Actuate joints through range of motions
- def test_pan(self): Move pan axis independently.
- def test_tilt(self): Move tilt axis independently.
- d... | Implement the Python class `TestAnimations` described below.
Class description:
Implement the TestAnimations class.
Method signatures and docstrings:
- def seizure(self): Actuate joints through range of motions
- def test_pan(self): Move pan axis independently.
- def test_tilt(self): Move tilt axis independently.
- d... | e28512b63c599995ef8153549c2bae0b92097246 | <|skeleton|>
class TestAnimations:
def seizure(self):
"""Actuate joints through range of motions"""
<|body_0|>
def test_pan(self):
"""Move pan axis independently."""
<|body_1|>
def test_tilt(self):
"""Move tilt axis independently."""
<|body_2|>
def tes... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAnimations:
def seizure(self):
"""Actuate joints through range of motions"""
tk = Track()
tk.add(0.0, self.head_mot.pantilt(0.8, 0.6, 0.5))
tk.add(0.01, self.head_mot.moveeyes(0.0, 0.5))
tk.add(0.5, self.head_mot.pantilt(-0.8, -0.6, 0.5))
tk.add(0.51, self.h... | the_stack_v2_python_sparse | kuri_api/src/kuri_api/anim/library/test_animations.py | hcrlab/kuri | train | 11 | |
4cd41b1ecae528006805dd0c1a03e641ab5d8d14 | [
"self.post_parser = reqparse.RequestParser()\nself.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')\nself.post_parser.add_argument('Name', type=str, required=True, help='No object Name provided', location='json')\nsuper(Objects, self).__init__()",
"try:\n A... | <|body_start_0|>
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')
self.post_parser.add_argument('Name', type=str, required=True, help='No object Name provided', location='json')
super(O... | Objects | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche tous les objects de la base d'authorization ainsi que les regles associees"""
<|body_1|>
def post(self):
"""ajoute ... | stack_v2_sparse_classes_10k_train_002868 | 1,595 | no_license | [
{
"docstring": "Constructeur: liste les champs attendus dans le corps HTML",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "affiche tous les objects de la base d'authorization ainsi que les regles associees",
"name": "get",
"signature": "def get(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003558 | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche tous les objects de la base d'authorization ainsi que les regles associees
-... | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche tous les objects de la base d'authorization ainsi que les regles associees
-... | 8f107644a74fe46827ec5ed53d0457022bd1608b | <|skeleton|>
class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche tous les objects de la base d'authorization ainsi que les regles associees"""
<|body_1|>
def post(self):
"""ajoute ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')
self.post_parser.add_argument('N... | the_stack_v2_python_sparse | authapp/view_objects.py | ldurandadomia/Flask-Restful | train | 0 | |
5b9818a598ab106f3ecb355efacb3e99c5cf1a75 | [
"row = g.db.query(MachineGroup).get(machinegroup_id)\nif not row:\n log.warning('Requested a non-existant machine group %s', machinegroup_id)\n abort(http_client.NOT_FOUND, description='Machine Group not found')\nrecord = row.as_dict()\nrecord['url'] = url_for('machinegroups.entry', machinegroup_id=machinegro... | <|body_start_0|>
row = g.db.query(MachineGroup).get(machinegroup_id)
if not row:
log.warning('Requested a non-existant machine group %s', machinegroup_id)
abort(http_client.NOT_FOUND, description='Machine Group not found')
record = row.as_dict()
record['url'] = ur... | Information about specific machines | MachineGroupAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachineGroupAPI:
"""Information about specific machines"""
def get(self, machinegroup_id):
"""Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def patch(self, args, machinegroup_id):
""... | stack_v2_sparse_classes_10k_train_002869 | 4,597 | permissive | [
{
"docstring": "Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json",
"name": "get",
"signature": "def get(self, machinegroup_id)"
},
{
"docstring": "Update machine group",
"name": "patch",
"signature": "def patch(self, args, m... | 2 | stack_v2_sparse_classes_30k_train_002377 | Implement the Python class `MachineGroupAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machinegroup_id): Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def patch(self, ar... | Implement the Python class `MachineGroupAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machinegroup_id): Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def patch(self, ar... | 2771bb46db7fd331448f9db3cfb257fab7f89bcc | <|skeleton|>
class MachineGroupAPI:
"""Information about specific machines"""
def get(self, machinegroup_id):
"""Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def patch(self, args, machinegroup_id):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MachineGroupAPI:
"""Information about specific machines"""
def get(self, machinegroup_id):
"""Find machine group by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
row = g.db.query(MachineGroup).get(machinegroup_id)
if not row:
... | the_stack_v2_python_sparse | driftbase/api/machinegroups.py | directivegames/drift-base | train | 1 |
32d3587dc126ae25fc211702f8d941c95f111010 | [
"if not root:\n return []\nq = deque()\nq.append(root)\nans = []\nwhile q:\n cur = q.popleft()\n if not cur:\n ans.append(None)\n continue\n ans.append(cur.val)\n q.append(cur.left)\n q.append(cur.right)\nreturn ans",
"if not data:\n return None\nroot = TreeNode(data.pop(0))\nq ... | <|body_start_0|>
if not root:
return []
q = deque()
q.append(root)
ans = []
while q:
cur = q.popleft()
if not cur:
ans.append(None)
continue
ans.append(cur.val)
q.append(cur.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002870 | 1,530 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002720 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0ab632adefa18ba8c5a0ca50738f4cb092e37b92 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
q = deque()
q.append(root)
ans = []
while q:
cur = q.popleft()
if not cur:
ans.... | the_stack_v2_python_sparse | offer/37.py | xychen1015/leetcode | train | 0 | |
e0f8954cac756eec29f1296797de34f8e8f65155 | [
"self.variable = variable\nvalue = str(ServerVar(variable))\ntry:\n value = float(value)\nexcept:\n pass\nself.default = value",
"if not addon in self:\n return\nsuper(_RegisteredAddons, self).remove(addon)\nif not self:\n del VariableBackups[self.variable]"
] | <|body_start_0|>
self.variable = variable
value = str(ServerVar(variable))
try:
value = float(value)
except:
pass
self.default = value
<|end_body_0|>
<|body_start_1|>
if not addon in self:
return
super(_RegisteredAddons, self).... | Class used to register addons to the variable and store its default value | _RegisteredAddons | [
"Artistic-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
<|body_0|>
def remove(self, addon):
"""Unregis... | stack_v2_sparse_classes_10k_train_002871 | 2,938 | permissive | [
{
"docstring": "Stores the variable, its default value, and addons that register for the variable",
"name": "__init__",
"signature": "def __init__(self, variable)"
},
{
"docstring": "Unregisters an addon for the variable and removes the variable from the dictionary if it is no longer registered"... | 2 | stack_v2_sparse_classes_30k_train_004929 | Implement the Python class `_RegisteredAddons` described below.
Class description:
Class used to register addons to the variable and store its default value
Method signatures and docstrings:
- def __init__(self, variable): Stores the variable, its default value, and addons that register for the variable
- def remove(... | Implement the Python class `_RegisteredAddons` described below.
Class description:
Class used to register addons to the variable and store its default value
Method signatures and docstrings:
- def __init__(self, variable): Stores the variable, its default value, and addons that register for the variable
- def remove(... | ebf4624626266f552189a32612b8d09cd5b4c5a3 | <|skeleton|>
class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
<|body_0|>
def remove(self, addon):
"""Unregis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
self.variable = variable
value = str(ServerVar(variable))
... | the_stack_v2_python_sparse | cstrike/addons/eventscripts/gungame51/modules/backups.py | GunGame-Dev-Team/GunGame51 | train | 0 |
1738ed8d4580f1107dfbee9373698fe766ade0ac | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, user_id=user_id))\ninherited = self._check_if_inherited()\nPROVIDERS.assignment_api.get_grant(role_id=role_id, user_id=user_id, project_id=project_id, inh... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, user_id=user_id))
inherited = self._check_if_inherited()
PROVIDERS.assignment_api.get_grant(role_id=role_id, user_id=u... | ProjectUserGrantResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, user_id, role_id):
"""Grant role for user on proje... | stack_v2_sparse_classes_10k_train_002872 | 22,149 | permissive | [
{
"docstring": "Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, project_id, user_id, role_id)"
},
{
"docstring": "Grant role for user on project. PUT /v3/projects/{project_id}/users/{user_id}/role... | 3 | stack_v2_sparse_classes_30k_train_000494 | Implement the Python class `ProjectUserGrantResource` described below.
Class description:
Implement the ProjectUserGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id... | Implement the Python class `ProjectUserGrantResource` described below.
Class description:
Implement the ProjectUserGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, user_id, role_id):
"""Grant role for user on proje... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target... | the_stack_v2_python_sparse | keystone/api/projects.py | sapcc/keystone | train | 0 | |
fe6f208cddc84bea8d5bca52e0bc3c6d2764cfcc | [
"tests = ['test.1', 'test.2']\nexpected = 'test.1:test.2'\nself.assertEqual(test_runner.get_gtest_filter(tests), expected)",
"tests = ['test.1', 'test.2']\nexpected = '-test.1:test.2'\nself.assertEqual(test_runner.get_gtest_filter(tests, invert=True), expected)"
] | <|body_start_0|>
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter(tests), expected)
<|end_body_0|>
<|body_start_1|>
tests = ['test.1', 'test.2']
expected = '-test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter... | Tests for test_runner.get_gtest_filter. | GetGTestFilterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_002873 | 19,298 | permissive | [
{
"docstring": "Ensures correctness of filter.",
"name": "test_correct",
"signature": "def test_correct(self)"
},
{
"docstring": "Ensures correctness of inverted filter.",
"name": "test_correct_inverted",
"signature": "def test_correct_inverted(self)"
}
] | 2 | null | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter. | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter.
<|skeleton|>
class GetGTest... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_runner.get_gtest_filter(tests), expected)
def test_correct_inve... | the_stack_v2_python_sparse | ios/build/bots/scripts/test_runner_test.py | Samsung/Castanets | train | 58 |
f0b8145f2a2b37538ad9cf83f8ae97f99cfc452d | [
"if entity_embedding is not None and relation_embedding is not None:\n config['dim'] = entity_embedding.shape[1]\n config['e_num'] = entity_embedding.shape[0]\n config['r_num'] = relation_embedding.shape[0]\nsuper().__init__(config, device)\nself.e_embedding = nn.Embedding(self.e_num, self.dim)\nself.r_emb... | <|body_start_0|>
if entity_embedding is not None and relation_embedding is not None:
config['dim'] = entity_embedding.shape[1]
config['e_num'] = entity_embedding.shape[0]
config['r_num'] = relation_embedding.shape[0]
super().__init__(config, device)
self.e_emb... | TransE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes ... | stack_v2_sparse_classes_10k_train_002874 | 3,883 | no_license | [
{
"docstring": "Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes :param device: the torch device on which the model is executed :param entity_embedding: an optional pre... | 3 | stack_v2_sparse_classes_30k_train_002338 | Implement the Python class `TransE` described below.
Class description:
Implement the TransE class.
Method signatures and docstrings:
- def __init__(self, config, device, entity_embedding=None, relation_embedding=None): Initialize model and assign parameters in parent class based on the chosen configurations. Use pre... | Implement the Python class `TransE` described below.
Class description:
Implement the TransE class.
Method signatures and docstrings:
- def __init__(self, config, device, entity_embedding=None, relation_embedding=None): Initialize model and assign parameters in parent class based on the chosen configurations. Use pre... | f8d43e8bfa6131ed6926fce516df6bec699450af | <|skeleton|>
class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransE:
def __init__(self, config, device, entity_embedding=None, relation_embedding=None):
"""Initialize model and assign parameters in parent class based on the chosen configurations. Use pre-trained embeddings if provided. :param config: a dictionary that defines the model attributes :param device:... | the_stack_v2_python_sparse | src/kg_embedding/transE.py | jusch25/mt_kg-fusion | train | 0 | |
e09f1eee9a266cab57aaa4b880ec242aa9755aa5 | [
"interval = self.bot.configuration.prestige_wait_when_ready_interval\nif interval > 0:\n self.logger.info('Scheduling prestige to take place in %(interval)s second(s)...' % {'interval': interval})\n self.bot.cancel_scheduled_plugin(tags=['prestige', 'prestige_close_to_max'])\n self.bot.schedule_plugin(plug... | <|body_start_0|>
interval = self.bot.configuration.prestige_wait_when_ready_interval
if interval > 0:
self.logger.info('Scheduling prestige to take place in %(interval)s second(s)...' % {'interval': interval})
self.bot.cancel_scheduled_plugin(tags=['prestige', 'prestige_close_to_... | Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of these are met, the close to max has been reac... | PrestigeCloseToMax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of... | stack_v2_sparse_classes_10k_train_002875 | 7,177 | no_license | [
{
"docstring": "Execute, or schedule a prestige based on the current configured interval.",
"name": "_prestige_execute_or_schedule",
"signature": "def _prestige_execute_or_schedule(self)"
},
{
"docstring": "Perform a prestige in game when the user has reached the stage required that represents t... | 2 | stack_v2_sparse_classes_30k_train_003784 | Implement the Python class `PrestigeCloseToMax` described below.
Class description:
Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" ic... | Implement the Python class `PrestigeCloseToMax` described below.
Class description:
Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" ic... | b8695acead575228c281459ba1397557f9a47149 | <|skeleton|>
class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrestigeCloseToMax:
"""Perform a prestige in game if the "close to max" threshold has been reached. Close to max can be determined two ways: 1. The "event" icon is available for the event that is currently running. 2. The "skills" page "Prestige To Reset" icon is available in game. Once either of these are me... | the_stack_v2_python_sparse | bot/plugins/prestige/prestige_close_to_max.py | DevonJerothe/tap-titans-bot | train | 0 |
50fa60b10976f3693c1c4b7d8fb71238856a3b9d | [
"res = []\nfor i in range(len(words)):\n for j in range(len(words)):\n if i != j:\n temp = words[i] + words[j]\n if temp == temp[::-1]:\n res.append([i, j])\nreturn res",
"def isPalindrome(temp):\n return temp == temp[::-1]\ndict, res = ({}, [])\nfor i in range(le... | <|body_start_0|>
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == temp[::-1]:
res.append([i, j])
return res
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r... | stack_v2_sparse_classes_10k_train_002876 | 2,198 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol1",
"signature": "def palindromePairsSol1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol2",
"signature": "def palindromePairsSol2(sel... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]]
<|ske... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == tem... | the_stack_v2_python_sparse | google/hard/palindrome_pairs.py | gerrycfchang/leetcode-python | train | 2 | |
7e2c2b446199a82141470cc9a5b4c74c3b0e2ae2 | [
"keys = {key: value for key, value in cls.__dict__.items() if not isinstance(value, classmethod) and (not isinstance(value, staticmethod)) and (not callable(value)) and (not key.startswith('__'))}\nrequired = [v for k, v in keys.items() if not k.endswith('_')]\noptional = [v for k, v in keys.items() if k.endswith('... | <|body_start_0|>
keys = {key: value for key, value in cls.__dict__.items() if not isinstance(value, classmethod) and (not isinstance(value, staticmethod)) and (not callable(value)) and (not key.startswith('__'))}
required = [v for k, v in keys.items() if not k.endswith('_')]
optional = [v for k,... | Class to validate dictionary configurations. | ConfigKeys | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigKeys:
"""Class to validate dictionary configurations."""
def get_keys(cls) -> Tuple[List[str], List[str]]:
"""Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class."""
... | stack_v2_sparse_classes_10k_train_002877 | 3,020 | permissive | [
{
"docstring": "Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class.",
"name": "get_keys",
"signature": "def get_keys(cls) -> Tuple[List[str], List[str]]"
},
{
"docstring": "Checks wheth... | 2 | stack_v2_sparse_classes_30k_train_000575 | Implement the Python class `ConfigKeys` described below.
Class description:
Class to validate dictionary configurations.
Method signatures and docstrings:
- def get_keys(cls) -> Tuple[List[str], List[str]]: Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are ... | Implement the Python class `ConfigKeys` described below.
Class description:
Class to validate dictionary configurations.
Method signatures and docstrings:
- def get_keys(cls) -> Tuple[List[str], List[str]]: Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are ... | f1499e9c3fee00fd1d66de14cab66c4472c0085d | <|skeleton|>
class ConfigKeys:
"""Class to validate dictionary configurations."""
def get_keys(cls) -> Tuple[List[str], List[str]]:
"""Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigKeys:
"""Class to validate dictionary configurations."""
def get_keys(cls) -> Tuple[List[str], List[str]]:
"""Gets all the required and optional config keys for this class. Returns: A tuple (required, optional) which are lists of the required/optional keys for this class."""
keys = ... | the_stack_v2_python_sparse | src/zenml/config/config_keys.py | stefannica/zenml | train | 0 |
e0ba47514b3cccba60ebcbaeca3639a3b21353e9 | [
"batch_node_features = np.vstack([graph.node_features for graph in graph_list])\nif graph_list[0].edge_features is not None:\n batch_edge_features: Optional[np.ndarray] = np.vstack([graph.edge_features for graph in graph_list])\nelse:\n batch_edge_features = None\nif graph_list[0].node_pos_features is not Non... | <|body_start_0|>
batch_node_features = np.vstack([graph.node_features for graph in graph_list])
if graph_list[0].edge_features is not None:
batch_edge_features: Optional[np.ndarray] = np.vstack([graph.edge_features for graph in graph_list])
else:
batch_edge_features = Non... | Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO format with shape [2, num_edges]. `num_edges... | BatchGraphData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO fo... | stack_v2_sparse_classes_10k_train_002878 | 22,111 | permissive | [
{
"docstring": "Parameters ---------- graph_list: Sequence[GraphData] List of GraphData",
"name": "__init__",
"signature": "def __init__(self, graph_list: Sequence[GraphData])"
},
{
"docstring": "A GraphData object can have user defined attributes but the attribute name of those are unknown sinc... | 3 | null | Implement the Python class `BatchGraphData` described below.
Class description:
Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Co... | Implement the Python class `BatchGraphData` described below.
Class description:
Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Co... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO format with sha... | the_stack_v2_python_sparse | deepchem/feat/graph_data.py | deepchem/deepchem | train | 4,876 |
f02f6712d7c06880d738c68cb2b288e3f480bdc7 | [
"self.job_uids = job_uids\nself.cluster_id = cluster_id\nself.cluster_match_string = cluster_match_string\nself.encryption_keys = encryption_keys\nself.end_time_usecs = end_time_usecs\nself.job_match_string = job_match_string\nself.search_job_name = search_job_name\nself.start_time_usecs = start_time_usecs\nself.va... | <|body_start_0|>
self.job_uids = job_uids
self.cluster_id = cluster_id
self.cluster_match_string = cluster_match_string
self.encryption_keys = encryption_keys
self.end_time_usecs = end_time_usecs
self.job_match_string = job_match_string
self.search_job_name = sear... | Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of remote job uids in form of clusterId:clusterIncarnationId:jobId.... | CreateRemoteVaultSearchJobParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of ... | stack_v2_sparse_classes_10k_train_002879 | 5,599 | permissive | [
{
"docstring": "Constructor for the CreateRemoteVaultSearchJobParameters class",
"name": "__init__",
"signature": "def __init__(self, job_uids=None, cluster_id=None, cluster_match_string=None, encryption_keys=None, end_time_usecs=None, job_match_string=None, search_job_name=None, start_time_usecs=None, ... | 2 | stack_v2_sparse_classes_30k_train_000369 | Implement the Python class `CreateRemoteVaultSearchJobParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of s... | Implement the Python class `CreateRemoteVaultSearchJobParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of s... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateRemoteVaultSearchJobParameters:
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model. Specifies settings required to create a search of a remote Vault for data that has been archived from other Clusters. Attributes: job_uids (list of string): Filter by specifying a list of remote job ui... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_remote_vault_search_job_parameters.py | cohesity/management-sdk-python | train | 24 |
ed3c19e8a0e20d19710c4849df0b73d38bef42cf | [
"units = Unit.objects.all()\nserializer = UnitSerializer(units, many=True)\nreturn Response(serializer.data)",
"serializer = UnitSerializer(request.data)\nserializer.save()\nreturn Response(serializer.data)"
] | <|body_start_0|>
units = Unit.objects.all()
serializer = UnitSerializer(units, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = UnitSerializer(request.data)
serializer.save()
return Response(serializer.data)
<|end_body_1|>
| View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. | ListUnits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
<|body_0|>
def post(self, request):
"""Creates a new complex."""
... | stack_v2_sparse_classes_10k_train_002880 | 9,992 | no_license | [
{
"docstring": "Return a list of all units.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Creates a new complex.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007072 | Implement the Python class `ListUnits` described below.
Class description:
View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view.
Method signatures and docstrings:
- def get(self, request): Return a list of all units.
- def post(self, request): Creates ... | Implement the Python class `ListUnits` described below.
Class description:
View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view.
Method signatures and docstrings:
- def get(self, request): Return a list of all units.
- def post(self, request): Creates ... | f887d41800541e058b2d350ded6f02759d174815 | <|skeleton|>
class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
<|body_0|>
def post(self, request):
"""Creates a new complex."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListUnits:
"""View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view."""
def get(self, request):
"""Return a list of all units."""
units = Unit.objects.all()
serializer = UnitSerializer(units, many=True)
retur... | the_stack_v2_python_sparse | api/govrent/views.py | kamal94/hacka22019 | train | 0 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('compile_results', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Results To Compile'\ncontext['detail_text'] = 'Please ... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('compile_results', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['... | View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid. | CompileResultView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call sup... | stack_v2_sparse_classes_10k_train_002881 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_002751 | Implement the Python class `CompileResultView` described below.
Class description:
View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid.
Method signatures and docstrings:
- def for... | Implement the Python class `CompileResultView` described below.
Class description:
View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid.
Method signatures and docstrings:
- def for... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call sup... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
c5bd9d3daefb2e3eb81f01cca16a7c066ada767c | [
"screenSlot = None\nScreenSlot._slotsCondition.acquire()\ntry:\n while len(ScreenSlot._slotsList) == 0:\n ScreenSlot._slotsCondition.wait(WAIT_TIMEOUT)\n screenSlot = ScreenSlot._slotsList.pop(0)\nexcept Exception:\n pass\nScreenSlot._slotsCondition.release()\nreturn screenSlot",
"if screenSlot ==... | <|body_start_0|>
screenSlot = None
ScreenSlot._slotsCondition.acquire()
try:
while len(ScreenSlot._slotsList) == 0:
ScreenSlot._slotsCondition.wait(WAIT_TIMEOUT)
screenSlot = ScreenSlot._slotsList.pop(0)
except Exception:
pass
S... | Слот для вывода на экран | ScreenSlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScreenSlot:
"""Слот для вывода на экран"""
def Acquire(self):
"""Захватываем слот"""
<|body_0|>
def Release(self, screenSlot):
"""Освобождаем захваченный слот"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
screenSlot = None
ScreenSlot._... | stack_v2_sparse_classes_10k_train_002882 | 2,990 | no_license | [
{
"docstring": "Захватываем слот",
"name": "Acquire",
"signature": "def Acquire(self)"
},
{
"docstring": "Освобождаем захваченный слот",
"name": "Release",
"signature": "def Release(self, screenSlot)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003009 | Implement the Python class `ScreenSlot` described below.
Class description:
Слот для вывода на экран
Method signatures and docstrings:
- def Acquire(self): Захватываем слот
- def Release(self, screenSlot): Освобождаем захваченный слот | Implement the Python class `ScreenSlot` described below.
Class description:
Слот для вывода на экран
Method signatures and docstrings:
- def Acquire(self): Захватываем слот
- def Release(self, screenSlot): Освобождаем захваченный слот
<|skeleton|>
class ScreenSlot:
"""Слот для вывода на экран"""
def Acquire... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class ScreenSlot:
"""Слот для вывода на экран"""
def Acquire(self):
"""Захватываем слот"""
<|body_0|>
def Release(self, screenSlot):
"""Освобождаем захваченный слот"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScreenSlot:
"""Слот для вывода на экран"""
def Acquire(self):
"""Захватываем слот"""
screenSlot = None
ScreenSlot._slotsCondition.acquire()
try:
while len(ScreenSlot._slotsList) == 0:
ScreenSlot._slotsCondition.wait(WAIT_TIMEOUT)
scr... | the_stack_v2_python_sparse | stumbleupon/common.py | cash2one/doorscenter | train | 0 |
515d16b24900962ac4e292d3fe86f9e48481ba01 | [
"self.filtering_policy = filtering_policy\nself.group_backup_params = group_backup_params\nself.onedrive_backup_params = onedrive_backup_params\nself.outlook_backup_params = outlook_backup_params\nself.public_folders_backup_params = public_folders_backup_params\nself.site_backup_params = site_backup_params\nself.te... | <|body_start_0|>
self.filtering_policy = filtering_policy
self.group_backup_params = group_backup_params
self.onedrive_backup_params = onedrive_backup_params
self.outlook_backup_params = outlook_backup_params
self.public_folders_backup_params = public_folders_backup_params
... | Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. Use 'filtering_policy' specified within 'outlook... | O365BackupEnvParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class O365BackupEnvParams:
"""Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. U... | stack_v2_sparse_classes_10k_train_002883 | 5,762 | permissive | [
{
"docstring": "Constructor for the O365BackupEnvParams class",
"name": "__init__",
"signature": "def __init__(self, filtering_policy=None, group_backup_params=None, onedrive_backup_params=None, outlook_backup_params=None, public_folders_backup_params=None, site_backup_params=None, teams_backup_params=N... | 2 | null | Implement the Python class `O365BackupEnvParams` described below.
Class description:
Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyPr... | Implement the Python class `O365BackupEnvParams` described below.
Class description:
Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyPr... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class O365BackupEnvParams:
"""Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. U... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class O365BackupEnvParams:
"""Implementation of the 'O365BackupEnvParams' model. Message to capture any additional backup params for Office365 environment. This encapsulates both Outlook & OneDrive backup parameters. Attributes: filtering_policy (FilteringPolicyProto): This field has been deprecated. Use 'filtering... | the_stack_v2_python_sparse | cohesity_management_sdk/models/o_365_backup_env_params.py | cohesity/management-sdk-python | train | 24 |
f2bd0590aefc85d347cb33fb308221e2b72ce902 | [
"self._business_one = business_one\nself._business_two = business_two\nself._business_three = business_three",
"report_list = [self._business_one, self._business_two, self._business_three]\nrandom.shuffle(report_list)\nreport_list = report_list[0:random.randint(0, len(report_list))]\nreturn report_list"
] | <|body_start_0|>
self._business_one = business_one
self._business_two = business_two
self._business_three = business_three
<|end_body_0|>
<|body_start_1|>
report_list = [self._business_one, self._business_two, self._business_three]
random.shuffle(report_list)
report_list... | Assemble | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Assemble:
def __init__(self, business_one, business_two, business_three):
"""接受修改好的数据 :param business_one: :param business_two: :param business_three:"""
<|body_0|>
def single_element(self):
"""生成最终的上报数据 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_002884 | 785 | no_license | [
{
"docstring": "接受修改好的数据 :param business_one: :param business_two: :param business_three:",
"name": "__init__",
"signature": "def __init__(self, business_one, business_two, business_three)"
},
{
"docstring": "生成最终的上报数据 :return:",
"name": "single_element",
"signature": "def single_element... | 2 | null | Implement the Python class `Assemble` described below.
Class description:
Implement the Assemble class.
Method signatures and docstrings:
- def __init__(self, business_one, business_two, business_three): 接受修改好的数据 :param business_one: :param business_two: :param business_three:
- def single_element(self): 生成最终的上报数据 :r... | Implement the Python class `Assemble` described below.
Class description:
Implement the Assemble class.
Method signatures and docstrings:
- def __init__(self, business_one, business_two, business_three): 接受修改好的数据 :param business_one: :param business_two: :param business_three:
- def single_element(self): 生成最终的上报数据 :r... | 9dc610c68a2c6e3026725c1bb98c017edb51e2b9 | <|skeleton|>
class Assemble:
def __init__(self, business_one, business_two, business_three):
"""接受修改好的数据 :param business_one: :param business_two: :param business_three:"""
<|body_0|>
def single_element(self):
"""生成最终的上报数据 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Assemble:
def __init__(self, business_one, business_two, business_three):
"""接受修改好的数据 :param business_one: :param business_two: :param business_three:"""
self._business_one = business_one
self._business_two = business_two
self._business_three = business_three
def single_el... | the_stack_v2_python_sparse | hugh/simulat_probe/report_data/data_assemble/assemble.py | windorchidwarm/py_test_project | train | 0 | |
86d69c3485cf4306cdf942f421fa0c90b9c464a9 | [
"data = super().get_context_data(*args, **kwargs)\ndata['project'] = get_object_or_404(Project, pk=self.kwargs['pk'])\nreturn data",
"pk = self.kwargs['pk']\nfilesource = form.save(commit=False)\nfilesource.project = get_object_or_404(Project, pk=pk)\nfilesource.save()\nreturn HttpResponseRedirect(reverse('projec... | <|body_start_0|>
data = super().get_context_data(*args, **kwargs)
data['project'] = get_object_or_404(Project, pk=self.kwargs['pk'])
return data
<|end_body_0|>
<|body_start_1|>
pk = self.kwargs['pk']
filesource = form.save(commit=False)
filesource.project = get_object_or... | A base class for view for creating new project sources | SourceCreateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
<|body_0|>
def form_valid(self, form):
"""Override to set the project for the `Source... | stack_v2_sparse_classes_10k_train_002885 | 3,269 | permissive | [
{
"docstring": "Override to add project to the template context",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Override to set the project for the `Source` and redirect back to that project",
"name": "form_valid",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_004430 | Implement the Python class `SourceCreateView` described below.
Class description:
A base class for view for creating new project sources
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Override to add project to the template context
- def form_valid(self, form): Override to set the pr... | Implement the Python class `SourceCreateView` described below.
Class description:
A base class for view for creating new project sources
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Override to add project to the template context
- def form_valid(self, form): Override to set the pr... | ce5d86343e340ff0bd734e49a48d0745ae88144d | <|skeleton|>
class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
<|body_0|>
def form_valid(self, form):
"""Override to set the project for the `Source... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
data = super().get_context_data(*args, **kwargs)
data['project'] = get_object_or_404(Project, pk=self.k... | the_stack_v2_python_sparse | director/projects/source_views.py | paulolimac/hub | train | 0 |
c0f07234bf121bb26bbe7e1a043d32e1e5edcae7 | [
"super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes, mode=mode)\nself.zero_division = zero_division\nself.reset()",
"kv_metrics = {}\nfor aggregation_name, aggregated_metrics in zip(('_micro', '_macro', '_weighted'), (micro, macro, weighted)):\n metrics = {f... | <|body_start_0|>
super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes, mode=mode)
self.zero_division = zero_division
self.reset()
<|end_body_0|>
<|body_start_1|>
kv_metrics = {}
for aggregation_name, aggregated_metrics in zip(('... | Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one o... | PrecisionRecallF1SupportMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division durin... | stack_v2_sparse_classes_10k_train_002886 | 30,124 | permissive | [
{
"docstring": "Init PrecisionRecallF1SupportMetric instance",
"name": "__init__",
"signature": "def __init__(self, mode: str, num_classes: int=None, zero_division: int=0, compute_on_call: bool=True, prefix: str=None, suffix: str=None) -> None"
},
{
"docstring": "Convert metrics aggregation to k... | 6 | stack_v2_sparse_classes_30k_train_003325 | Implement the Python class `PrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: valu... | Implement the Python class `PrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: valu... | ac8567dc389fb7a265e3104e8a743497aa903165 | <|skeleton|>
class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division durin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division during metrics (pr... | the_stack_v2_python_sparse | catalyst/metrics/_classification.py | Podidiving/catalyst | train | 2 |
99a588fd1b3c8e7defae24d01c4ae7e08c5fb5c1 | [
"if not callable(trafo):\n raise ValueError('trafo is not callable, but of type {}'.format(type(trafo)))\nsuper(WithThresh, self).__init__()\nself.batch_wise: bool = batch_wise\n'Whether to assume a batch of masks is given (``True``) or a\\n single mask (``False``).'\nself.trafo: Callable[[torch.Tensor], ... | <|body_start_0|>
if not callable(trafo):
raise ValueError('trafo is not callable, but of type {}'.format(type(trafo)))
super(WithThresh, self).__init__()
self.batch_wise: bool = batch_wise
'Whether to assume a batch of masks is given (``True``) or a\n single mask (``Fa... | Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThresh.batch_wise` is ``True``) and return a transformed batch. If given, ``pre_... | WithThresh | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithThresh:
"""Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThresh.batch_wise` is ``True``) and return... | stack_v2_sparse_classes_10k_train_002887 | 14,707 | permissive | [
{
"docstring": "Init. :param trafo: the transformation instance to wrap :param pre_thresh: if not ``None``, the tensors to be modified are binarized to 0 and 1 values with threshold ``pre_thresh`` before modification :param post_thresh: if not ``None``, the tensors to be modified are binarized to 0 and 1 values... | 3 | stack_v2_sparse_classes_30k_train_006974 | Implement the Python class `WithThresh` described below.
Class description:
Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThr... | Implement the Python class `WithThresh` described below.
Class description:
Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThr... | 37b9fc83d7b14902dfe92e0c45071c150bcf3779 | <|skeleton|>
class WithThresh:
"""Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThresh.batch_wise` is ``True``) and return... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WithThresh:
"""Wrap a batch transformation with binarizing (and unsqueezing) before and after. The transformation should accept a tensor holding a masks (respectively a batch of masks if :py:attr:`~hybrid_learning.datasets.transforms.image_transforms.WithThresh.batch_wise` is ``True``) and return a transforme... | the_stack_v2_python_sparse | hybrid_learning/datasets/transforms/image_transforms.py | JohnnyZhang917/hybrid_learning | train | 0 |
89fda9895a6eca166b978d46ec7ff15cc158b24b | [
"self.shards = shards\nself.id_col = schema['id_col']\nself.dt_col = schema['dt_col']\nself.feature_col = schema['feature_col'].copy()\nself.target_col = schema['target_col'].copy()\nself.numpy_shards = None\nself._id_list = list(shards[self.id_col].unique())",
"_check_type(shards, 'shards', SparkXShards)\ntarget... | <|body_start_0|>
self.shards = shards
self.id_col = schema['id_col']
self.dt_col = schema['dt_col']
self.feature_col = schema['feature_col'].copy()
self.target_col = schema['target_col'].copy()
self.numpy_shards = None
self._id_list = list(shards[self.id_col].uniq... | XShardsTSDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
... | stack_v2_sparse_classes_10k_train_002888 | 8,833 | permissive | [
{
"docstring": "XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental.",
"name": "__init__",
"signature": "def __init__(self, shards, **schem... | 4 | stack_v2_sparse_classes_30k_train_000343 | Implement the Python class `XShardsTSDataset` described below.
Class description:
Implement the XShardsTSDataset class.
Method signatures and docstrings:
- def __init__(self, shards, **schema): XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the tr... | Implement the Python class `XShardsTSDataset` described below.
Class description:
Implement the XShardsTSDataset class.
Method signatures and docstrings:
- def __init__(self, shards, **schema): XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the tr... | 7cc3e2849057d6429d03b1af0db13caae57960a5 | <|skeleton|>
class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XShardsTSDataset:
def __init__(self, shards, **schema):
"""XShardTSDataset is an abstract of time series dataset with distributed fashion. Cascade call is supported for most of the transform methods. XShardTSDataset will partition the dataset by id_col, which is experimental."""
self.shards = ... | the_stack_v2_python_sparse | pyzoo/zoo/chronos/data/experimental/xshards_tsdataset.py | intel-analytics/analytics-zoo | train | 3,104 | |
09bda41fa073c3e9ecdc3e92343d94b8c2a3172b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center. | MerchantCenterLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for th... | stack_v2_sparse_classes_10k_train_002889 | 4,994 | permissive | [
{
"docstring": "Returns Merchant Center links available for this customer.",
"name": "ListMerchantCenterLinks",
"signature": "def ListMerchantCenterLinks(self, request, context)"
},
{
"docstring": "Returns the Merchant Center link in full detail.",
"name": "GetMerchantCenterLink",
"signa... | 3 | stack_v2_sparse_classes_30k_train_000226 | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available for this customer."... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/merchant_center_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
27e81e336fa7b33e2e4dff6c3eb0598e261850e7 | [
"async for batch in self.batches(in_q):\n content_q_by_type = defaultdict(lambda: Q(pk=None))\n for declarative_content in batch:\n model_type = type(declarative_content.content)\n unit_key = declarative_content.content.natural_key_dict()\n content_q_by_type[model_type] = content_q_by_typ... | <|body_start_0|>
async for batch in self.batches(in_q):
content_q_by_type = defaultdict(lambda: Q(pk=None))
for declarative_content in batch:
model_type = type(declarative_content.content)
unit_key = declarative_content.content.natural_key_dict()
... | A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects :class:`~pulpcore.plugin.stages.DeclarativeContent` units from `in_q` and inspects their ass... | QueryExistingContentUnits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryExistingContentUnits:
"""A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects :class:`~pulpcore.plugin.stages.Declara... | stack_v2_sparse_classes_10k_train_002890 | 6,533 | no_license | [
{
"docstring": "The coroutine for this stage. Args: in_q (:class:`asyncio.Queue`): The queue to receive :class:`~pulpcore.plugin.stages.DeclarativeContent` objects from. out_q (:class:`asyncio.Queue`): The queue to put :class:`~pulpcore.plugin.stages.DeclarativeContent` into. Returns: The coroutine for this sta... | 2 | stack_v2_sparse_classes_30k_train_000081 | Implement the Python class `QueryExistingContentUnits` described below.
Class description:
A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects ... | Implement the Python class `QueryExistingContentUnits` described below.
Class description:
A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects ... | f667ec77eb5325ae68d091eac7dbd1d22b0b33f0 | <|skeleton|>
class QueryExistingContentUnits:
"""A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects :class:`~pulpcore.plugin.stages.Declara... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QueryExistingContentUnits:
"""A Stages API stage that saves :attr:`DeclarativeContent.content` objects and saves its related :class:`~pulpcore.plugin.models.ContentArtifact` and :class:`~pulpcore.plugin.models.RemoteArtifact` objects too. This stage expects :class:`~pulpcore.plugin.stages.DeclarativeContent` ... | the_stack_v2_python_sparse | synchronize_refactor/trashbin/queryandsavecontent.py | asmacdo/sandbox | train | 0 |
814cfc5a34effc2a440c60d5aa43db239f6266bb | [
"category = classifier.classify(key)\nif category in container:\n container[category].append(value)\nelse:\n container.update({category: subCollectionFactory(value)})",
"elapsedTscGroup = {}\nfor txn in txnSubCollection:\n if txn.hasProbes([beginProbe, endProbe]):\n beginCounter = txn.getCounterFo... | <|body_start_0|>
category = classifier.classify(key)
if category in container:
container[category].append(value)
else:
container.update({category: subCollectionFactory(value)})
<|end_body_0|>
<|body_start_1|>
elapsedTscGroup = {}
for txn in txnSubCollecti... | Aggregates transaction by categories | TxnAggregator | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_10k_train_002891 | 5,883 | permissive | [
{
"docstring": "Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subCollectionFactory: Callable used to build an instance of subcollection :param classifier: Predicate to classify transactions into different categ... | 4 | stack_v2_sparse_classes_30k_train_001990 | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subC... | the_stack_v2_python_sparse | scripts/lib/xpedite/analytics/aggregator.py | dendisuhubdy/Xpedite | train | 1 |
74cd87827d18a9e0e2cb2f999a894ca92ee3fe42 | [
"self.num_vms_in_cluster = num_vms_in_cluster\nself.scaler_logic_called = False\nScale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)",
"servers_to_stop = 0\nif self.scaler_logic_called is False:\n servers_to_start = self.num_vms_in_cluster\... | <|body_start_0|>
self.num_vms_in_cluster = num_vms_in_cluster
self.scaler_logic_called = False
Scale.__init__(self, sim=sim, scale_rate=scale_rate, startup_delay_func=startup_delay_func, shutdown_delay=shutdown_delay)
<|end_body_0|>
<|body_start_1|>
servers_to_stop = 0
if self.s... | Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request. | FixedSizePolicy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_dela... | stack_v2_sparse_classes_10k_train_002892 | 1,645 | no_license | [
{
"docstring": "Initializes a FixedSizePolicy object parameters: sim -- The Simulation containing a cluster cluster object this scale function is managing scale_rate -- The interarrival time between scale events in seconds startup_delay_func -- A callable that returns the time a server spends in the booting sta... | 2 | stack_v2_sparse_classes_30k_train_004277 | Implement the Python class `FixedSizePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request.
Method signatures and docstrings:
- d... | Implement the Python class `FixedSizePolicy` described below.
Class description:
Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request.
Method signatures and docstrings:
- d... | 30dc0702f6189307ff776525a2f3006ec471de47 | <|skeleton|>
class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_dela... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FixedSizePolicy:
"""Wake up periodically and Scale the cluster This policy requests self.num_vms_in_cluster number of virtual machines, and makes no further requests to modify the cluster size after the initial request."""
def __init__(self, sim, scale_rate, startup_delay_func, shutdown_delay, num_vms_in... | the_stack_v2_python_sparse | appsim/scaler/fixed_size_policy.py | bmbouter/vcl_simulation | train | 0 |
5e7b52ecb441c4972fd4855ac4edcc1747d8f79f | [
"super(SegNet_1, self).__init__()\nself.layer_1 = SegnetLayer_Encoder(in_channels, 64, 2)\nself.layer_2 = SegnetLayer_Encoder(64, 128, 2)\nself.layer_3 = SegnetLayer_Encoder(128, 256, 3)\nself.layer_4 = SegnetLayer_Encoder(256, 512, 3)\nself.layer_5 = SegnetLayer_Encoder(512, 1024, 3)\nself.layer_6 = SegnetLayer_En... | <|body_start_0|>
super(SegNet_1, self).__init__()
self.layer_1 = SegnetLayer_Encoder(in_channels, 64, 2)
self.layer_2 = SegnetLayer_Encoder(64, 128, 2)
self.layer_3 = SegnetLayer_Encoder(128, 256, 3)
self.layer_4 = SegnetLayer_Encoder(256, 512, 3)
self.layer_5 = SegnetLay... | Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badrinarayanan, Alex Kendall, Roberto Ci... | SegNet_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegNet_1:
"""Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badr... | stack_v2_sparse_classes_10k_train_002893 | 20,094 | no_license | [
{
"docstring": "Sequential Instanciation of the different Layers",
"name": "__init__",
"signature": "def __init__(self, in_channels=3, n_classes=21)"
},
{
"docstring": "Sequential Computation, see nn.Module.forward methods PyTorch",
"name": "forward",
"signature": "def forward(self, inpu... | 2 | stack_v2_sparse_classes_30k_train_007258 | Implement the Python class `SegNet_1` described below.
Class description:
Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Archite... | Implement the Python class `SegNet_1` described below.
Class description:
Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Archite... | 3b63f360e67013d5962082e57fb36ebfb37d8920 | <|skeleton|>
class SegNet_1:
"""Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SegNet_1:
"""Derived Class to define a Segnet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation Vijay Badrinarayanan, A... | the_stack_v2_python_sparse | segmentation/models/nn.py | Kivo0/vibotorch | train | 0 |
59d39fdcc2b24b90dceb996c889af5de25eb65da | [
"\"\"\"\n Thoughts:\n 这个方法没有left和right子树为None的情况进行对比会出现问题.\n \"\"\"\nif not self.isEqualNode(root1, root2):\n return False\nif not self.isEqualNode(root1.left, root2.left):\n root1.left, root1.right = (root1.right, root1.left)\nreturn self.flipEquiv(root1.left, root2.left) and self.flipEq... | <|body_start_0|>
"""
Thoughts:
这个方法没有left和right子树为None的情况进行对比会出现问题.
"""
if not self.isEqualNode(root1, root2):
return False
if not self.isEqualNode(root1.left, root2.left):
root1.left, root1.right = (root1.right, root1.left)... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def isEqualNode(self, root1, root2):
"""return True if root1.val == root2.val"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
""... | stack_v2_sparse_classes_10k_train_002894 | 3,565 | no_license | [
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool",
"name": "flipEquiv",
"signature": "def flipEquiv(self, root1, root2)"
},
{
"docstring": "return True if root1.val == root2.val",
"name": "isEqualNode",
"signature": "def isEqualNode(self, root1, root2)"
}
] | 2 | null | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def isEqualNode(self, root1, root2): return True if root1.val == root2.val | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def isEqualNode(self, root1, root2): return True if root1.val == root2.val
<|sk... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def isEqualNode(self, root1, root2):
"""return True if root1.val == root2.val"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
"""
Thoughts:
这个方法没有left和right子树为None的情况进行对比会出现问题.
"""
if not self.isEqualNode(root1, root2):
return False
i... | the_stack_v2_python_sparse | Python/FlipEquivalentBinaryTrees.py | here0009/LeetCode | train | 1 | |
63986f0297d48db3861456e49677712f25618874 | [
"self._august_gateway = None\nself.user_auth_details = {}\nself._needs_reset = False\nsuper().__init__()",
"if self._august_gateway is None:\n self._august_gateway = AugustGateway(self.hass)\nerrors = {}\nif user_input is not None:\n combined_inputs = {**self.user_auth_details, **user_input}\n await self... | <|body_start_0|>
self._august_gateway = None
self.user_auth_details = {}
self._needs_reset = False
super().__init__()
<|end_body_0|>
<|body_start_1|>
if self._august_gateway is None:
self._august_gateway = AugustGateway(self.hass)
errors = {}
if user_... | Handle a config flow for August. | AugustConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_step_validation(self, ... | stack_v2_sparse_classes_10k_train_002895 | 5,668 | permissive | [
{
"docstring": "Store an AugustGateway().",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Handle validation (2fa) st... | 6 | null | Implement the Python class `AugustConfigFlow` described below.
Class description:
Handle a config flow for August.
Method signatures and docstrings:
- def __init__(self): Store an AugustGateway().
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_validation(self, user... | Implement the Python class `AugustConfigFlow` described below.
Class description:
Handle a config flow for August.
Method signatures and docstrings:
- def __init__(self): Store an AugustGateway().
- async def async_step_user(self, user_input=None): Handle the initial step.
- async def async_step_validation(self, user... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
<|body_1|>
async def async_step_validation(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AugustConfigFlow:
"""Handle a config flow for August."""
def __init__(self):
"""Store an AugustGateway()."""
self._august_gateway = None
self.user_auth_details = {}
self._needs_reset = False
super().__init__()
async def async_step_user(self, user_input=None):
... | the_stack_v2_python_sparse | homeassistant/components/august/config_flow.py | tchellomello/home-assistant | train | 8 |
5c6d7f7c7e57052b691e8802dc6d166583c75f53 | [
"super().__init__(env, name, seed)\nself.buffer_processing_matrix = self.env.job_generator.buffer_processing_matrix\nnum_resources, _ = self.env.constituency_matrix.shape\nself.priorities = {}\nfor resource in np.arange(num_resources):\n priority_activity = priorities.get(resource, None)\n if priority_activit... | <|body_start_0|>
super().__init__(env, name, seed)
self.buffer_processing_matrix = self.env.job_generator.buffer_processing_matrix
num_resources, _ = self.env.constituency_matrix.shape
self.priorities = {}
for resource in np.arange(num_resources):
priority_activity = ... | CustomActivityPriorityAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomActivityPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, priorities: Dict, name: str='CustomActivityPriorityAgent', seed: Optional[int]=None) -> None:
"""Priority policy such that some activities have priority over others. For resources where no priorities are given... | stack_v2_sparse_classes_10k_train_002896 | 4,341 | permissive | [
{
"docstring": "Priority policy such that some activities have priority over others. For resources where no priorities are given, activities are chosen randomly. :param env: the environment to stepped through. :param priorities: a dictionary where the keys are the resources and the values are the activity with ... | 3 | stack_v2_sparse_classes_30k_train_004926 | Implement the Python class `CustomActivityPriorityAgent` described below.
Class description:
Implement the CustomActivityPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, priorities: Dict, name: str='CustomActivityPriorityAgent', seed: Optional[int]=None) -> No... | Implement the Python class `CustomActivityPriorityAgent` described below.
Class description:
Implement the CustomActivityPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, priorities: Dict, name: str='CustomActivityPriorityAgent', seed: Optional[int]=None) -> No... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class CustomActivityPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, priorities: Dict, name: str='CustomActivityPriorityAgent', seed: Optional[int]=None) -> None:
"""Priority policy such that some activities have priority over others. For resources where no priorities are given... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomActivityPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, priorities: Dict, name: str='CustomActivityPriorityAgent', seed: Optional[int]=None) -> None:
"""Priority policy such that some activities have priority over others. For resources where no priorities are given, activities a... | the_stack_v2_python_sparse | src/snc/agents/general_heuristics/custom_activity_priority_agent.py | stochasticnetworkcontrol/snc | train | 9 | |
4946060df9f7e5dc7b361b123be906f849bc574c | [
"if isinstance(value, str) and value.replace(' ', '') == '':\n raise InvalidEmptyValue(field_name=field.name)\nreturn value",
"if value.lower() not in [i.lower() for i in cls.case_management_types]:\n raise InvalidEntityType(field_name=field.name, entity_type=str(cls.case_management_types), value=value)\nre... | <|body_start_0|>
if isinstance(value, str) and value.replace(' ', '') == '':
raise InvalidEmptyValue(field_name=field.name)
return value
<|end_body_0|>
<|body_start_1|>
if value.lower() not in [i.lower() for i in cls.case_management_types]:
raise InvalidEntityType(field_... | Case Management Entity Field (Model) Type | CaseManagementEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseManagementEntity:
"""Case Management Entity Field (Model) Type"""
def is_empty(cls, value: str, field: ModelField) -> str:
"""Validate that the value is a non-empty string."""
<|body_0|>
def is_type(cls, value: str, field: ModelField) -> str:
"""Validate that... | stack_v2_sparse_classes_10k_train_002897 | 2,334 | permissive | [
{
"docstring": "Validate that the value is a non-empty string.",
"name": "is_empty",
"signature": "def is_empty(cls, value: str, field: ModelField) -> str"
},
{
"docstring": "Validate that the entity is of Indicator type.",
"name": "is_type",
"signature": "def is_type(cls, value: str, fi... | 2 | null | Implement the Python class `CaseManagementEntity` described below.
Class description:
Case Management Entity Field (Model) Type
Method signatures and docstrings:
- def is_empty(cls, value: str, field: ModelField) -> str: Validate that the value is a non-empty string.
- def is_type(cls, value: str, field: ModelField) ... | Implement the Python class `CaseManagementEntity` described below.
Class description:
Case Management Entity Field (Model) Type
Method signatures and docstrings:
- def is_empty(cls, value: str, field: ModelField) -> str: Validate that the value is a non-empty string.
- def is_type(cls, value: str, field: ModelField) ... | 30dc147e40d63d1082ec2a5e6c62005b60c29c37 | <|skeleton|>
class CaseManagementEntity:
"""Case Management Entity Field (Model) Type"""
def is_empty(cls, value: str, field: ModelField) -> str:
"""Validate that the value is a non-empty string."""
<|body_0|>
def is_type(cls, value: str, field: ModelField) -> str:
"""Validate that... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CaseManagementEntity:
"""Case Management Entity Field (Model) Type"""
def is_empty(cls, value: str, field: ModelField) -> str:
"""Validate that the value is a non-empty string."""
if isinstance(value, str) and value.replace(' ', '') == '':
raise InvalidEmptyValue(field_name=fi... | the_stack_v2_python_sparse | tcex/input/field_type/case_management_entity.py | ThreatConnect-Inc/tcex | train | 24 |
a9a0185ab6c07e59d5434aa273cbb2c48d948c50 | [
"import tables\nself.h5 = tables.open_file(filename)\nself.min_points = min_points\ntable_names = list(self.h5.root.events._v_children.keys())\nstart_times = [datetime(*getattr(self.h5.root.events, the_table).attrs['start_time']) for the_table in table_names]\nst, tn = zip(*sorted(zip(start_times, table_names)))\ns... | <|body_start_0|>
import tables
self.h5 = tables.open_file(filename)
self.min_points = min_points
table_names = list(self.h5.root.events._v_children.keys())
start_times = [datetime(*getattr(self.h5.root.events, the_table).attrs['start_time']) for the_table in table_names]
... | LMAh5File | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. s... | stack_v2_sparse_classes_10k_train_002898 | 10,049 | permissive | [
{
"docstring": "Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. self.base_date provides the base_date against which time in seconds... | 3 | stack_v2_sparse_classes_30k_train_001058 | Implement the Python class `LMAh5File` described below.
Class description:
Implement the LMAh5File class.
Method signatures and docstrings:
- def __init__(self, filename, min_points=1): Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the l... | Implement the Python class `LMAh5File` described below.
Class description:
Implement the LMAh5File class.
Method signatures and docstrings:
- def __init__(self, filename, min_points=1): Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the l... | 392eff5f15735be7b7f5ccc20d2835a617000117 | <|skeleton|>
class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LMAh5File:
def __init__(self, filename, min_points=1):
"""Open an HDF5 LMA file so as to read LMA event/flash tables. The events and flashes groups may contain more than one table, and the list of self.table_names corresponds to self.start_times and are sorted in increasing time order. self.base_date ... | the_stack_v2_python_sparse | lmatools/io/LMA_h5_file.py | deeplycloudy/lmatools | train | 16 | |
52d5bcbf55130f1cc0b4c5eb2c62768eae307ff6 | [
"ret = list()\nif not root:\n return json.dumps(ret)\nlevel = [root]\nwhile any(level):\n for node in level:\n if node:\n ret.append(node.val)\n else:\n ret.append(None)\n tmp = list()\n for node in level:\n if node:\n tmp.extend([node.left, node.rig... | <|body_start_0|>
ret = list()
if not root:
return json.dumps(ret)
level = [root]
while any(level):
for node in level:
if node:
ret.append(node.val)
else:
ret.append(None)
tmp = lis... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002899 | 1,940 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | aea2630be6ca2c60186593d6e66b0a59e56dc848 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
ret = list()
if not root:
return json.dumps(ret)
level = [root]
while any(level):
for node in level:
if node:
... | the_stack_v2_python_sparse | 十二、剑指offer-Python/面试题37.序列化二叉树.py | Lcoderfit/Introduction-to-algotithms | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.