blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82bcf6f3e4e0aa2c11e809dc982b412cccaa331f | [
"def helper(i):\n if i == 1:\n return '0'\n s = helper(i - 1)\n t = ''\n for c in s:\n if c == '0':\n t += '01'\n else:\n t += '10'\n print(t)\n return t\ns = helper(n)\nreturn int(s[k - 1])",
"if n == 1:\n return 0\nif n == 2:\n if k == 1:\n ... | <|body_start_0|>
def helper(i):
if i == 1:
return '0'
s = helper(i - 1)
t = ''
for c in s:
if c == '0':
t += '01'
else:
t += '10'
print(t)
return t
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kthGrammar(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(i):
if i == 1... | stack_v2_sparse_classes_75kplus_train_005300 | 1,902 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kthGrammarTLE",
"signature": "def kthGrammarTLE(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kthGrammar",
"signature": "def kthGrammar(self, n, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048112 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammarTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kthGrammar(self, n, k): :type n: int :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammarTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kthGrammar(self, n, k): :type n: int :type k: int :rtype: int
<|skeleton|>
class Solution:
def kt... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kthGrammar(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
def helper(i):
if i == 1:
return '0'
s = helper(i - 1)
t = ''
for c in s:
if c == '0':
t += '01'
... | the_stack_v2_python_sparse | K/K-thSymbolinGrammar.py | bssrdf/pyleet | train | 2 | |
2ed01bf5948a2a365581c7ace3b38c9689652a8f | [
"super(ParallelCategoricalNet, self).__init__()\nself.sizes = sizes\nself.max_size = sizes.max()\nself.n_args = n_arguments\nself.sizes_mask = torch.tensor(self.sizes).view(-1, 1) <= torch.arange(self.max_size).repeat(self.n_args, 1)\nlayers = []\nlayers.append(nn.Linear(n_features, hiddens[0]))\nlayers.append(nn.R... | <|body_start_0|>
super(ParallelCategoricalNet, self).__init__()
self.sizes = sizes
self.max_size = sizes.max()
self.n_args = n_arguments
self.sizes_mask = torch.tensor(self.sizes).view(-1, 1) <= torch.arange(self.max_size).repeat(self.n_args, 1)
layers = []
layers... | ParallelCategoricalNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelCategoricalNet:
def __init__(self, n_features, sizes, n_arguments, hiddens=[256]):
"""Parameters ---------- n_features: int, last dimension of input tensor used in forward sizes: shape (n_arguments,), contains the number of values ranging from 0 to sizes[i] that each argument i c... | stack_v2_sparse_classes_75kplus_train_005301 | 34,424 | no_license | [
{
"docstring": "Parameters ---------- n_features: int, last dimension of input tensor used in forward sizes: shape (n_arguments,), contains the number of values ranging from 0 to sizes[i] that each argument i can assume. Used for masking out impossible values while sampling all of them together. n_arguments: in... | 2 | null | Implement the Python class `ParallelCategoricalNet` described below.
Class description:
Implement the ParallelCategoricalNet class.
Method signatures and docstrings:
- def __init__(self, n_features, sizes, n_arguments, hiddens=[256]): Parameters ---------- n_features: int, last dimension of input tensor used in forwa... | Implement the Python class `ParallelCategoricalNet` described below.
Class description:
Implement the ParallelCategoricalNet class.
Method signatures and docstrings:
- def __init__(self, n_features, sizes, n_arguments, hiddens=[256]): Parameters ---------- n_features: int, last dimension of input tensor used in forwa... | 20eaff007473c74c284263735c2fa96491b642bd | <|skeleton|>
class ParallelCategoricalNet:
def __init__(self, n_features, sizes, n_arguments, hiddens=[256]):
"""Parameters ---------- n_features: int, last dimension of input tensor used in forward sizes: shape (n_arguments,), contains the number of values ranging from 0 to sizes[i] that each argument i c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParallelCategoricalNet:
def __init__(self, n_features, sizes, n_arguments, hiddens=[256]):
"""Parameters ---------- n_features: int, last dimension of input tensor used in forward sizes: shape (n_arguments,), contains the number of values ranging from 0 to sizes[i] that each argument i can assume. Use... | the_stack_v2_python_sparse | AC_modules/Networks.py | owenpanqiufeng/SC2-RL | train | 0 | |
341075ed6ab45d3f9d6c97152fb9dbfde86673b3 | [
"self.project_name = project_name\nself.wf = wf\nself.bridge_order_id = None\nself.order_name = None\nself.partner_name = None\nself.industry = None\nself.html_link = None\nself.banner_link = None\nself.start_date = None\nself.target_volume = None\nself.overage = None\nself.geo_target = None\nself.geo_target_state ... | <|body_start_0|>
self.project_name = project_name
self.wf = wf
self.bridge_order_id = None
self.order_name = None
self.partner_name = None
self.industry = None
self.html_link = None
self.banner_link = None
self.start_date = None
self.target... | @summary: Project builder for CW Push projects. | CWPushProjectBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CWPushProjectBuilder:
"""@summary: Project builder for CW Push projects."""
def __init__(self, wf, project_name):
"""@param wf: Workfront service object @param project_name: that the created will have."""
<|body_0|>
def build(self):
"""@summary: Build the WF proj... | stack_v2_sparse_classes_75kplus_train_005302 | 2,851 | no_license | [
{
"docstring": "@param wf: Workfront service object @param project_name: that the created will have.",
"name": "__init__",
"signature": "def __init__(self, wf, project_name)"
},
{
"docstring": "@summary: Build the WF project. @raise WFBridgeException: if the combination of parameters set in the ... | 2 | stack_v2_sparse_classes_30k_train_014570 | Implement the Python class `CWPushProjectBuilder` described below.
Class description:
@summary: Project builder for CW Push projects.
Method signatures and docstrings:
- def __init__(self, wf, project_name): @param wf: Workfront service object @param project_name: that the created will have.
- def build(self): @summa... | Implement the Python class `CWPushProjectBuilder` described below.
Class description:
@summary: Project builder for CW Push projects.
Method signatures and docstrings:
- def __init__(self, wf, project_name): @param wf: Workfront service object @param project_name: that the created will have.
- def build(self): @summa... | c1ee2b252029d9188f247bc884fcc940f34eec06 | <|skeleton|>
class CWPushProjectBuilder:
"""@summary: Project builder for CW Push projects."""
def __init__(self, wf, project_name):
"""@param wf: Workfront service object @param project_name: that the created will have."""
<|body_0|>
def build(self):
"""@summary: Build the WF proj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CWPushProjectBuilder:
"""@summary: Project builder for CW Push projects."""
def __init__(self, wf, project_name):
"""@param wf: Workfront service object @param project_name: that the created will have."""
self.project_name = project_name
self.wf = wf
self.bridge_order_id =... | the_stack_v2_python_sparse | workfront_bridge/projects/cwpush_builder.py | BridgeMarketing/workfront-bridge | train | 1 |
50445b724da404260d4bc95417a2bdfedbac2f9c | [
"set_seed(10)\nimg = get_img('images/TX1_polarised_cropped.tif')\nobj = kmeans_img(img, 10)\nobj.update_clusters()\nassert all([len(o) for o in obj.clusters.values()]), 'no cluster should be empty intially'\nobj.update_centroids()\nobj.update_clusters()\nassert all([len(o) for o in obj.clusters.values()]), 'no clus... | <|body_start_0|>
set_seed(10)
img = get_img('images/TX1_polarised_cropped.tif')
obj = kmeans_img(img, 10)
obj.update_clusters()
assert all([len(o) for o in obj.clusters.values()]), 'no cluster should be empty intially'
obj.update_centroids()
obj.update_clusters()
... | Test_kmeans_img | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_kmeans_img:
def test_clusters(self):
"""test clusters are initalised and iterate without any empty clusters"""
<|body_0|>
def test_vector_initalisation(self):
"""test the convergence from 2d rgb image to 5d vectors is correct"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_005303 | 1,508 | permissive | [
{
"docstring": "test clusters are initalised and iterate without any empty clusters",
"name": "test_clusters",
"signature": "def test_clusters(self)"
},
{
"docstring": "test the convergence from 2d rgb image to 5d vectors is correct",
"name": "test_vector_initalisation",
"signature": "de... | 2 | null | Implement the Python class `Test_kmeans_img` described below.
Class description:
Implement the Test_kmeans_img class.
Method signatures and docstrings:
- def test_clusters(self): test clusters are initalised and iterate without any empty clusters
- def test_vector_initalisation(self): test the convergence from 2d rgb... | Implement the Python class `Test_kmeans_img` described below.
Class description:
Implement the Test_kmeans_img class.
Method signatures and docstrings:
- def test_clusters(self): test clusters are initalised and iterate without any empty clusters
- def test_vector_initalisation(self): test the convergence from 2d rgb... | b6f52a189dbb1cfb53325793966e32ee39155e9e | <|skeleton|>
class Test_kmeans_img:
def test_clusters(self):
"""test clusters are initalised and iterate without any empty clusters"""
<|body_0|>
def test_vector_initalisation(self):
"""test the convergence from 2d rgb image to 5d vectors is correct"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_kmeans_img:
def test_clusters(self):
"""test clusters are initalised and iterate without any empty clusters"""
set_seed(10)
img = get_img('images/TX1_polarised_cropped.tif')
obj = kmeans_img(img, 10)
obj.update_clusters()
assert all([len(o) for o in obj.clu... | the_stack_v2_python_sparse | notebooks/older_code/tst_kmeans_img.py | msc-acse/acse-9-independent-research-project-Boyne272 | train | 2 | |
8b132c2e94fbb59c32a2f6ee9d8f424dce93b12e | [
"ImageProcessor.__init__(self, **kwargs)\nself.sigma = sigma\nself.box_size = box_size\nself.filter_size = filter_size",
"from photutils.background import Background2D, MedianBackground\nsigma_clip = SigmaClip(sigma=self.sigma)\nbkg_estimator = MedianBackground()\nbkg = Background2D(image.data, self.box_size, fil... | <|body_start_0|>
ImageProcessor.__init__(self, **kwargs)
self.sigma = sigma
self.box_size = box_size
self.filter_size = filter_size
<|end_body_0|>
<|body_start_1|>
from photutils.background import Background2D, MedianBackground
sigma_clip = SigmaClip(sigma=self.sigma)
... | Remove background from image. | RemoveBackground | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveBackground:
"""Remove background from image."""
def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[int, int]=(3, 3), **kwargs: Any):
"""Init an image processor that removes background from image. Args: sigma: Sigma for clipping box_size:... | stack_v2_sparse_classes_75kplus_train_005304 | 1,681 | permissive | [
{
"docstring": "Init an image processor that removes background from image. Args: sigma: Sigma for clipping box_size: Box size for bkg estimation. filter_size: Size of filter.",
"name": "__init__",
"signature": "def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[... | 2 | stack_v2_sparse_classes_30k_train_033998 | Implement the Python class `RemoveBackground` described below.
Class description:
Remove background from image.
Method signatures and docstrings:
- def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[int, int]=(3, 3), **kwargs: Any): Init an image processor that removes backgro... | Implement the Python class `RemoveBackground` described below.
Class description:
Remove background from image.
Method signatures and docstrings:
- def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[int, int]=(3, 3), **kwargs: Any): Init an image processor that removes backgro... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class RemoveBackground:
"""Remove background from image."""
def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[int, int]=(3, 3), **kwargs: Any):
"""Init an image processor that removes background from image. Args: sigma: Sigma for clipping box_size:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoveBackground:
"""Remove background from image."""
def __init__(self, sigma: float=3.0, box_size: Tuple[int, int]=(50, 50), filter_size: Tuple[int, int]=(3, 3), **kwargs: Any):
"""Init an image processor that removes background from image. Args: sigma: Sigma for clipping box_size: Box size for... | the_stack_v2_python_sparse | pyobs/images/processors/misc/removebackground.py | pyobs/pyobs-core | train | 9 |
342977e676c209abdb3246d7e40f89db1bf177e3 | [
"if self.__class__.all is None:\n self.__class__.all = set()\nself.__class__.all.add(self)\nself.identifier = identifier",
"for instance in cls.all:\n if instance.identifier == identifier:\n return instance\nreturn None"
] | <|body_start_0|>
if self.__class__.all is None:
self.__class__.all = set()
self.__class__.all.add(self)
self.identifier = identifier
<|end_body_0|>
<|body_start_1|>
for instance in cls.all:
if instance.identifier == identifier:
return instance
... | base class for domain classes | Base | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
<|body_0|>
def find_instance(cls, identifier):
"""find instance with given identifier :param identifier: instance to look for :return: instan... | stack_v2_sparse_classes_75kplus_train_005305 | 804 | permissive | [
{
"docstring": "create domain object and self-register it",
"name": "__init__",
"signature": "def __init__(self, identifier)"
},
{
"docstring": "find instance with given identifier :param identifier: instance to look for :return: instance or None",
"name": "find_instance",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_035340 | Implement the Python class `Base` described below.
Class description:
base class for domain classes
Method signatures and docstrings:
- def __init__(self, identifier): create domain object and self-register it
- def find_instance(cls, identifier): find instance with given identifier :param identifier: instance to loo... | Implement the Python class `Base` described below.
Class description:
base class for domain classes
Method signatures and docstrings:
- def __init__(self, identifier): create domain object and self-register it
- def find_instance(cls, identifier): find instance with given identifier :param identifier: instance to loo... | e65fddb94513e7c2f54f248b4ce69e9e10ce42f5 | <|skeleton|>
class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
<|body_0|>
def find_instance(cls, identifier):
"""find instance with given identifier :param identifier: instance to look for :return: instan... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
if self.__class__.all is None:
self.__class__.all = set()
self.__class__.all.add(self)
self.identifier = identifier
def find_instance(... | the_stack_v2_python_sparse | python/domain/base.py | jeroenpeeters/document-as-code | train | 0 |
0d5c616df16683eb0cf1c6cdfd1569980a81ae8f | [
"try:\n return self._list(self._PROJECTS_URL, 'projects', obj_class=Project)\nexcept exceptions.EndpointNotFound:\n endpoint_filter = {'interface': plugin.AUTH_INTERFACE}\n return self._list(self._PROJECTS_URL, 'projects', obj_class=Project, endpoint_filter=endpoint_filter)",
"try:\n return self._list... | <|body_start_0|>
try:
return self._list(self._PROJECTS_URL, 'projects', obj_class=Project)
except exceptions.EndpointNotFound:
endpoint_filter = {'interface': plugin.AUTH_INTERFACE}
return self._list(self._PROJECTS_URL, 'projects', obj_class=Project, endpoint_filter=e... | Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user. | AuthManager | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthManager:
"""Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user."""
def projects(self):
"""List projects that the specified token can be rescoped to. :returns: a list ... | stack_v2_sparse_classes_75kplus_train_005306 | 3,252 | permissive | [
{
"docstring": "List projects that the specified token can be rescoped to. :returns: a list of projects. :rtype: list of :class:`keystoneclient.v3.projects.Project`",
"name": "projects",
"signature": "def projects(self)"
},
{
"docstring": "List Domains that the specified token can be rescoped to... | 3 | stack_v2_sparse_classes_30k_train_048881 | Implement the Python class `AuthManager` described below.
Class description:
Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.
Method signatures and docstrings:
- def projects(self): List projects that ... | Implement the Python class `AuthManager` described below.
Class description:
Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.
Method signatures and docstrings:
- def projects(self): List projects that ... | 141787ae8b0db7ac4dffce915e033a78d145d54e | <|skeleton|>
class AuthManager:
"""Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user."""
def projects(self):
"""List projects that the specified token can be rescoped to. :returns: a list ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthManager:
"""Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user."""
def projects(self):
"""List projects that the specified token can be rescoped to. :returns: a list of projects. ... | the_stack_v2_python_sparse | keystoneclient/v3/auth.py | openstack/python-keystoneclient | train | 118 |
bf2f9dabaef386cfb111b6cf0ed56d5f13d1b638 | [
"if maxdate and (not isinstance(maxdate, datetime)):\n raise ValueError('Expected a datetime object')\nreturn self.filter(id__in=self.get_interaction_per_client_ids(maxdate, active_only))",
"from django.db import connection\ncursor = connection.cursor()\ncfilter = 'expiration is null'\nsql = 'select reports_in... | <|body_start_0|>
if maxdate and (not isinstance(maxdate, datetime)):
raise ValueError('Expected a datetime object')
return self.filter(id__in=self.get_interaction_per_client_ids(maxdate, active_only))
<|end_body_0|>
<|body_start_1|>
from django.db import connection
cursor = ... | Manages interactions objects. | InteractiveManager | [
"LicenseRef-scancode-unknown-license-reference",
"mpich2",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractiveManager:
"""Manages interactions objects."""
def interaction_per_client(self, maxdate=None, active_only=True):
"""Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. Most recent date to pull. (dafault None) active_only -- In... | stack_v2_sparse_classes_75kplus_train_005307 | 14,270 | permissive | [
{
"docstring": "Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. Most recent date to pull. (dafault None) active_only -- Include only active clients (default True)",
"name": "interaction_per_client",
"signature": "def interaction_per_client(self, maxda... | 2 | stack_v2_sparse_classes_30k_train_038520 | Implement the Python class `InteractiveManager` described below.
Class description:
Manages interactions objects.
Method signatures and docstrings:
- def interaction_per_client(self, maxdate=None, active_only=True): Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. M... | Implement the Python class `InteractiveManager` described below.
Class description:
Manages interactions objects.
Method signatures and docstrings:
- def interaction_per_client(self, maxdate=None, active_only=True): Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. M... | 8605cd3d0cb4d549cb8b43de945d447f6d82892a | <|skeleton|>
class InteractiveManager:
"""Manages interactions objects."""
def interaction_per_client(self, maxdate=None, active_only=True):
"""Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. Most recent date to pull. (dafault None) active_only -- In... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InteractiveManager:
"""Manages interactions objects."""
def interaction_per_client(self, maxdate=None, active_only=True):
"""Returns the most recent interactions for clients as of a date Arguments: maxdate -- datetime object. Most recent date to pull. (dafault None) active_only -- Include only ac... | the_stack_v2_python_sparse | src/lib/Bcfg2/Server/Reports/reports/models.py | Bcfg2/bcfg2 | train | 56 |
210a6d83544d63a25c490efce28c310842cca5fd | [
"self.asteroids = []\nfor _ in range(1, Controller.NO_OF_ASTEROIDS + 1):\n radius = random.randint(1, Controller.MAX_RADIUS + 1)\n circum = 2 * math.pi * radius\n pos = Controller.init_pos()\n vel = Controller.init_vel()\n self.asteroids.append(Asteroid(circum, pos, vel))",
"for i in range(seconds)... | <|body_start_0|>
self.asteroids = []
for _ in range(1, Controller.NO_OF_ASTEROIDS + 1):
radius = random.randint(1, Controller.MAX_RADIUS + 1)
circum = 2 * math.pi * radius
pos = Controller.init_pos()
vel = Controller.init_vel()
self.asteroids.a... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def __init__(self):
"""Initializes a controller object. It contains a list of 100 asteroids."""
<|body_0|>
def simulate(self, seconds):
"""Simulate movement of all asteroids. :param seconds: :return:"""
<|body_1|>
def init_pos():
"""H... | stack_v2_sparse_classes_75kplus_train_005308 | 2,270 | no_license | [
{
"docstring": "Initializes a controller object. It contains a list of 100 asteroids.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Simulate movement of all asteroids. :param seconds: :return:",
"name": "simulate",
"signature": "def simulate(self, seconds)"
... | 4 | stack_v2_sparse_classes_30k_train_039057 | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self): Initializes a controller object. It contains a list of 100 asteroids.
- def simulate(self, seconds): Simulate movement of all asteroids. :param seconds: :... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self): Initializes a controller object. It contains a list of 100 asteroids.
- def simulate(self, seconds): Simulate movement of all asteroids. :param seconds: :... | e8007377b57537b4d054419c84049d745e1b8acd | <|skeleton|>
class Controller:
def __init__(self):
"""Initializes a controller object. It contains a list of 100 asteroids."""
<|body_0|>
def simulate(self, seconds):
"""Simulate movement of all asteroids. :param seconds: :return:"""
<|body_1|>
def init_pos():
"""H... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def __init__(self):
"""Initializes a controller object. It contains a list of 100 asteroids."""
self.asteroids = []
for _ in range(1, Controller.NO_OF_ASTEROIDS + 1):
radius = random.randint(1, Controller.MAX_RADIUS + 1)
circum = 2 * math.pi * radius... | the_stack_v2_python_sparse | Labs/Lab1/controller.py | dhruvparekh01/3552_A01157984 | train | 0 | |
f734c3ff4cc1270cdc06e3af5cc13768b9399530 | [
"self.width = width\nself.height = height\nself.food = food\nself.body = [[0, 0]]\nself.score = 0",
"head = self.body[0]\nx, y = (head[0], head[1])\nif direction == 'U':\n nx, ny = (x - 1, y)\nelif direction == 'D':\n nx, ny = (x + 1, y)\nelif direction == 'L':\n nx, ny = (x, y - 1)\nelse:\n nx, ny = ... | <|body_start_0|>
self.width = width
self.height = height
self.food = food
self.body = [[0, 0]]
self.score = 0
<|end_body_0|>
<|body_start_1|>
head = self.body[0]
x, y = (head[0], head[1])
if direction == 'U':
nx, ny = (x - 1, y)
elif d... | SnakeGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus_train_005309 | 2,054 | permissive | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_025885 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 64018a9ead8731ef98d48ab3bbd9d1dd6410c6e7 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | 353_DesignSnakeGame/SnakeGame.py | excaliburnan/SolutionsOnLeetcodeForZZW | train | 0 | |
6020c3f6d71c7685417a2b3493419b6c3a5f7197 | [
"left, right = (0, len(nums) - 1)\nwhile right > left:\n if nums[right] > nums[left]:\n return nums[left]\n else:\n mid = (right + left) // 2\n if nums[mid] >= nums[left]:\n left = mid + 1\n else:\n right = mid\nreturn nums[left]",
"left, right = (0, len(num... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while right > left:
if nums[right] > nums[left]:
return nums[left]
else:
mid = (right + left) // 2
if nums[mid] >= nums[left]:
left = mid + 1
else... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
<|body_0|>
def findMin1(self, nums):
"""may have duplicates :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, l... | stack_v2_sparse_classes_75kplus_train_005310 | 1,244 | no_license | [
{
"docstring": "no duplicate :type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": "may have duplicates :type nums: List[int] :rtype: int",
"name": "findMin1",
"signature": "def findMin1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000811 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): no duplicate :type nums: List[int] :rtype: int
- def findMin1(self, nums): may have duplicates :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): no duplicate :type nums: List[int] :rtype: int
- def findMin1(self, nums): may have duplicates :type nums: List[int] :rtype: int
<|skeleton|>
class Solu... | c9fb0b623501b3746444b05da55405e3a6c42bbf | <|skeleton|>
class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
<|body_0|>
def findMin1(self, nums):
"""may have duplicates :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
left, right = (0, len(nums) - 1)
while right > left:
if nums[right] > nums[left]:
return nums[left]
else:
mid = (right + left) // 2
... | the_stack_v2_python_sparse | Archive-1/FindMinimuminRotatedSortedArray.py | smsxgz/my-leetcode | train | 0 | |
5b12e5b78c4d631a9b34ab4ce02471abbef2f73a | [
"print('運行has_permission()')\nrole_list = request.user.roles.all()\nfor role in role_list:\n for perm in role.permissions.all():\n print(role, perm)\n if perm.resource == view.basename and perm.method == view.action:\n return True\nif request.user.is_superuser:\n return True\nelse:\n ... | <|body_start_0|>
print('運行has_permission()')
role_list = request.user.roles.all()
for role in role_list:
for perm in role.permissions.all():
print(role, perm)
if perm.resource == view.basename and perm.method == view.action:
return ... | MyPermission | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentica... | stack_v2_sparse_classes_75kplus_train_005311 | 3,035 | no_license | [
{
"docstring": "Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentication)後,自動將當前用戶封裝到request中 view: 可通過它調用視圖相關參數 - view.basename: 在url... | 2 | stack_v2_sparse_classes_30k_train_016872 | Implement the Python class `MyPermission` described below.
Class description:
Implement the MyPermission class.
Method signatures and docstrings:
- def has_permission(self, request, view): Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permi... | Implement the Python class `MyPermission` described below.
Class description:
Implement the MyPermission class.
Method signatures and docstrings:
- def has_permission(self, request, view): Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permi... | f9cb1670fb84b9eb8aaaf7cd5cf9139ab4ef4053 | <|skeleton|>
class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentica... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyPermission:
def has_permission(self, request, view):
"""Description: 一、對於「表」級別的權限設置 二、先執行has_permission(),再執行has_object_permission() 三、當在has_permission()中有return的話,就不會運行has_object_permission() Parameters: request: 經過DRF再包裝的request,包含Django原本的request功能 - request.user: 這是在通過認證(Authentication)後,自動將當前用戶... | the_stack_v2_python_sparse | Web網頁框架/框架(Django Rest Framework)/200725_權限設計/mysite/api/utils/permission.py | narru888/PythonWork-py37- | train | 0 | |
b043e7584717115ee985a695177d1cc9d4f43027 | [
"self.assertEqual('both/delims', asset_paths.as_key(BOTH_DELIMS))\nself.assertEqual('end/delim', asset_paths.as_key(END_DELIM))\nself.assertEqual('start/delim', asset_paths.as_key(START_DELIM))\nself.assertEqual('assets/img/abs_img_path.jpg', asset_paths.as_key(ABS_KEY))\nself.assertEqual('assets/img/rel_img_path.j... | <|body_start_0|>
self.assertEqual('both/delims', asset_paths.as_key(BOTH_DELIMS))
self.assertEqual('end/delim', asset_paths.as_key(END_DELIM))
self.assertEqual('start/delim', asset_paths.as_key(START_DELIM))
self.assertEqual('assets/img/abs_img_path.jpg', asset_paths.as_key(ABS_KEY))
... | Unit tests for modules.dashboard.asset_paths functions. | AssetPathsTests | [
"Apache-2.0",
"CC-BY-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssetPathsTests:
"""Unit tests for modules.dashboard.asset_paths functions."""
def test_asset_paths_as_key(self):
"""Tests the asset_paths.as_key function."""
<|body_0|>
def test_asset_paths_as_base(self):
"""Tests the asset_paths.as_base function."""
<|b... | stack_v2_sparse_classes_75kplus_train_005312 | 13,333 | permissive | [
{
"docstring": "Tests the asset_paths.as_key function.",
"name": "test_asset_paths_as_key",
"signature": "def test_asset_paths_as_key(self)"
},
{
"docstring": "Tests the asset_paths.as_base function.",
"name": "test_asset_paths_as_base",
"signature": "def test_asset_paths_as_base(self)"
... | 5 | null | Implement the Python class `AssetPathsTests` described below.
Class description:
Unit tests for modules.dashboard.asset_paths functions.
Method signatures and docstrings:
- def test_asset_paths_as_key(self): Tests the asset_paths.as_key function.
- def test_asset_paths_as_base(self): Tests the asset_paths.as_base fun... | Implement the Python class `AssetPathsTests` described below.
Class description:
Unit tests for modules.dashboard.asset_paths functions.
Method signatures and docstrings:
- def test_asset_paths_as_key(self): Tests the asset_paths.as_key function.
- def test_asset_paths_as_base(self): Tests the asset_paths.as_base fun... | 64f5ea13a8d85b9ef057dddae888a427b1396df6 | <|skeleton|>
class AssetPathsTests:
"""Unit tests for modules.dashboard.asset_paths functions."""
def test_asset_paths_as_key(self):
"""Tests the asset_paths.as_key function."""
<|body_0|>
def test_asset_paths_as_base(self):
"""Tests the asset_paths.as_base function."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssetPathsTests:
"""Unit tests for modules.dashboard.asset_paths functions."""
def test_asset_paths_as_key(self):
"""Tests the asset_paths.as_key function."""
self.assertEqual('both/delims', asset_paths.as_key(BOTH_DELIMS))
self.assertEqual('end/delim', asset_paths.as_key(END_DELI... | the_stack_v2_python_sparse | coursebuilder/modules/dashboard/dashboard_unit_tests.py | ram8647/gcb-clone-v111 | train | 1 |
816619fe3e5697345aabdad5642b18aaf7d9bc94 | [
"book_list = get_object_or_404(models.List, id=list_id)\nbook_list.raise_not_editable(request.user)\ndata = {'list': book_list, 'pending': book_list.listitem_set.filter(approved=False), 'list_form': forms.ListForm(instance=book_list)}\nreturn TemplateResponse(request, 'lists/curate.html', data)",
"book_list = get... | <|body_start_0|>
book_list = get_object_or_404(models.List, id=list_id)
book_list.raise_not_editable(request.user)
data = {'list': book_list, 'pending': book_list.listitem_set.filter(approved=False), 'list_form': forms.ListForm(instance=book_list)}
return TemplateResponse(request, 'lists... | approve or discard list suggestions | Curate | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
<|body_0|>
def post(self, request, list_id):
"""edit a book_list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book_list = get_obje... | stack_v2_sparse_classes_75kplus_train_005313 | 2,106 | no_license | [
{
"docstring": "display a pending list",
"name": "get",
"signature": "def get(self, request, list_id)"
},
{
"docstring": "edit a book_list",
"name": "post",
"signature": "def post(self, request, list_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003976 | Implement the Python class `Curate` described below.
Class description:
approve or discard list suggestions
Method signatures and docstrings:
- def get(self, request, list_id): display a pending list
- def post(self, request, list_id): edit a book_list | Implement the Python class `Curate` described below.
Class description:
approve or discard list suggestions
Method signatures and docstrings:
- def get(self, request, list_id): display a pending list
- def post(self, request, list_id): edit a book_list
<|skeleton|>
class Curate:
"""approve or discard list sugges... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
<|body_0|>
def post(self, request, list_id):
"""edit a book_list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
book_list = get_object_or_404(models.List, id=list_id)
book_list.raise_not_editable(request.user)
data = {'list': book_list, 'pending': book_list.listitem_set.fi... | the_stack_v2_python_sparse | bookwyrm/views/list/curate.py | bookwyrm-social/bookwyrm | train | 1,398 |
447f5b04de5b3b0eb3204f9c86f10d609ea98244 | [
"dummy = ListNode(0)\ndummy.next = head\nfirst = head\nlength = 0\nwhile first:\n first = first.next\n length += 1\nlength -= n\nfirst = dummy\nwhile length:\n length -= 1\n first = first.next\nfirst.next = first.next.next\nreturn dummy.next",
"first = head\nsecond = first\nwhile n:\n n -= 1\n f... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
first = head
length = 0
while first:
first = first.next
length += 1
length -= n
first = dummy
while length:
length -= 1
first = first.next
first.... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:"""
<|body_0|>
def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_75kplus_train_005314 | 1,555 | no_license | [
{
"docstring": "Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:",
"name": "remove_nth_node_",
"signature": "def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode'"
},
{
"docstring": "Approach: Single Pass Time Complexity: O(N) Space Com... | 2 | stack_v2_sparse_classes_30k_train_011984 | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:
- def remo... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:
- def remo... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:"""
<|body_0|>
def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkedList:
def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:"""
dummy = ListNode(0)
dummy.next = head
first = head
length = 0
while first:
... | the_stack_v2_python_sparse | revisited__2021/linked_list/remove_nth_node_from_end_of_list.py | Shiv2157k/leet_code | train | 1 | |
fc63e69a02c228ba2121691b51d8be44b8102992 | [
"EventHandler.__init__(self)\nself._win = win\nself._button = Rectangle(120, 100, (100, 630))\nself._button.setFillColor('lavender')\nself._text = Text('Done with Turn!', (100, 630), 16)\nself._button.addHandler(self)\nself._block = Rectangle(210, 30, (340, 645))\nself._block.setDepth(1)\nself._block.setFillColor('... | <|body_start_0|>
EventHandler.__init__(self)
self._win = win
self._button = Rectangle(120, 100, (100, 630))
self._button.setFillColor('lavender')
self._text = Text('Done with Turn!', (100, 630), 16)
self._button.addHandler(self)
self._block = Rectangle(210, 30, (3... | A class that is used to create a done button that will switch players' turns | Done | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Done:
"""A class that is used to create a done button that will switch players' turns"""
def __init__(self, win):
"""Creates the parts of the button and the rectangular block"""
<|body_0|>
def addTo(self, win):
"""Adds the button and block to the window"""
... | stack_v2_sparse_classes_75kplus_train_005315 | 23,085 | no_license | [
{
"docstring": "Creates the parts of the button and the rectangular block",
"name": "__init__",
"signature": "def __init__(self, win)"
},
{
"docstring": "Adds the button and block to the window",
"name": "addTo",
"signature": "def addTo(self, win)"
},
{
"docstring": "Changes the ... | 3 | stack_v2_sparse_classes_30k_train_010105 | Implement the Python class `Done` described below.
Class description:
A class that is used to create a done button that will switch players' turns
Method signatures and docstrings:
- def __init__(self, win): Creates the parts of the button and the rectangular block
- def addTo(self, win): Adds the button and block to... | Implement the Python class `Done` described below.
Class description:
A class that is used to create a done button that will switch players' turns
Method signatures and docstrings:
- def __init__(self, win): Creates the parts of the button and the rectangular block
- def addTo(self, win): Adds the button and block to... | e5d96a65fc84481b85072cfb55dea9a0666634b5 | <|skeleton|>
class Done:
"""A class that is used to create a done button that will switch players' turns"""
def __init__(self, win):
"""Creates the parts of the button and the rectangular block"""
<|body_0|>
def addTo(self, win):
"""Adds the button and block to the window"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Done:
"""A class that is used to create a done button that will switch players' turns"""
def __init__(self, win):
"""Creates the parts of the button and the rectangular block"""
EventHandler.__init__(self)
self._win = win
self._button = Rectangle(120, 100, (100, 630))
... | the_stack_v2_python_sparse | Games-2017/21/Game.py | paulmagnus/CSPy | train | 0 |
2fe58994e52c2caac72556dcdc9977e842393e6c | [
"l = len(A)\nif l < 3:\n return False\nflag = l - 1\nfor i in range(1, l):\n if A[i - 1] < A[i]:\n continue\n elif A[i - 1] == A[i]:\n return False\n else:\n flag = i - 1\n break\nif flag == l - 1 or flag == 0:\n return False\nreturn all([A[i] > A[i + 1] for i in range(fla... | <|body_start_0|>
l = len(A)
if l < 3:
return False
flag = l - 1
for i in range(1, l):
if A[i - 1] < A[i]:
continue
elif A[i - 1] == A[i]:
return False
else:
flag = i - 1
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool 36 ms"""
<|body_0|>
def validMountainArray_1(self, A):
""":type A: List[int] :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = len(A)
if l < 3:... | stack_v2_sparse_classes_75kplus_train_005316 | 2,021 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool 36 ms",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool 36ms",
"name": "validMountainArray_1",
"signature": "def validMountainArray_1(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035124 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool 36 ms
- def validMountainArray_1(self, A): :type A: List[int] :rtype: bool 36ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool 36 ms
- def validMountainArray_1(self, A): :type A: List[int] :rtype: bool 36ms
<|skeleton|>
class Solution:
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool 36 ms"""
<|body_0|>
def validMountainArray_1(self, A):
""":type A: List[int] :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool 36 ms"""
l = len(A)
if l < 3:
return False
flag = l - 1
for i in range(1, l):
if A[i - 1] < A[i]:
continue
elif A[i - 1] == A[i]:
... | the_stack_v2_python_sparse | ValidMountainArray_941.py | 953250587/leetcode-python | train | 2 | |
4ba9828912d435f72acff0143f05539f382ea80b | [
"sj_file = 'input_files/toy_sjs_mixed_chroms.txt'\nchroms = set(['chr1', 'chr2'])\ntmp_dir = 'scratch/sj_reading_test/'\nos.system('mkdir -p ' + tmp_dir)\ndonor_bt, accept_bt, annot = TC.processSpliceAnnotation(sj_file, tmp_dir, chroms, process='test')\nassert os.path.exists('scratch/sj_reading_test/splice_files/te... | <|body_start_0|>
sj_file = 'input_files/toy_sjs_mixed_chroms.txt'
chroms = set(['chr1', 'chr2'])
tmp_dir = 'scratch/sj_reading_test/'
os.system('mkdir -p ' + tmp_dir)
donor_bt, accept_bt, annot = TC.processSpliceAnnotation(sj_file, tmp_dir, chroms, process='test')
assert ... | TestProcessSpliceAnnot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProcessSpliceAnnot:
def test_tmp_files(self):
"""Check that the expected tmp files are created."""
<|body_0|>
def test_chrom_filtering(self):
"""Check that only chr1 and chr2 junctions get saved"""
<|body_1|>
def test_chrom_warning(self):
"""... | stack_v2_sparse_classes_75kplus_train_005317 | 4,026 | permissive | [
{
"docstring": "Check that the expected tmp files are created.",
"name": "test_tmp_files",
"signature": "def test_tmp_files(self)"
},
{
"docstring": "Check that only chr1 and chr2 junctions get saved",
"name": "test_chrom_filtering",
"signature": "def test_chrom_filtering(self)"
},
{... | 5 | null | Implement the Python class `TestProcessSpliceAnnot` described below.
Class description:
Implement the TestProcessSpliceAnnot class.
Method signatures and docstrings:
- def test_tmp_files(self): Check that the expected tmp files are created.
- def test_chrom_filtering(self): Check that only chr1 and chr2 junctions get... | Implement the Python class `TestProcessSpliceAnnot` described below.
Class description:
Implement the TestProcessSpliceAnnot class.
Method signatures and docstrings:
- def test_tmp_files(self): Check that the expected tmp files are created.
- def test_chrom_filtering(self): Check that only chr1 and chr2 junctions get... | ae9e71556a6b2e2c1fd80a9dca8fbab8d8196206 | <|skeleton|>
class TestProcessSpliceAnnot:
def test_tmp_files(self):
"""Check that the expected tmp files are created."""
<|body_0|>
def test_chrom_filtering(self):
"""Check that only chr1 and chr2 junctions get saved"""
<|body_1|>
def test_chrom_warning(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProcessSpliceAnnot:
def test_tmp_files(self):
"""Check that the expected tmp files are created."""
sj_file = 'input_files/toy_sjs_mixed_chroms.txt'
chroms = set(['chr1', 'chr2'])
tmp_dir = 'scratch/sj_reading_test/'
os.system('mkdir -p ' + tmp_dir)
donor_bt,... | the_stack_v2_python_sparse | testing_suite/test_process_splice_annotation.py | hzongyao/TranscriptClean | train | 0 | |
feb77b35af1dff64dce2c0a5a9701f4861715d0b | [
"super(FeedForwardGenerator, self).__init__()\nword_ids = sorted(word_ids)\nself.word_embedd = word_embedd\nself.word_ids = word_ids\nself.word_ids_set = set(word_ids)\nm_emb = word_embedd.weight.size(-1)\nweight = torch.index_select(word_embedd.weight, 0, torch.tensor(word_ids, device=cfg.device))\nself.obfenc = O... | <|body_start_0|>
super(FeedForwardGenerator, self).__init__()
word_ids = sorted(word_ids)
self.word_embedd = word_embedd
self.word_ids = word_ids
self.word_ids_set = set(word_ids)
m_emb = word_embedd.weight.size(-1)
weight = torch.index_select(word_embedd.weight, ... | FeedForwardGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedForwardGenerator:
def __init__(self, word_ids, word_embedd, word_alphabet, char_alphabet):
"""in the generator, we try to hijack the biaffine parser model provided by Max thanks for the dynamic feature of python, we want to substitute the embedd_word all the ablation study is done he... | stack_v2_sparse_classes_75kplus_train_005318 | 10,807 | no_license | [
{
"docstring": "in the generator, we try to hijack the biaffine parser model provided by Max thanks for the dynamic feature of python, we want to substitute the embedd_word all the ablation study is done here, notice that once done, we need the result from the final decoder. It seems impossible to this end. But... | 2 | stack_v2_sparse_classes_30k_train_013295 | Implement the Python class `FeedForwardGenerator` described below.
Class description:
Implement the FeedForwardGenerator class.
Method signatures and docstrings:
- def __init__(self, word_ids, word_embedd, word_alphabet, char_alphabet): in the generator, we try to hijack the biaffine parser model provided by Max than... | Implement the Python class `FeedForwardGenerator` described below.
Class description:
Implement the FeedForwardGenerator class.
Method signatures and docstrings:
- def __init__(self, word_ids, word_embedd, word_alphabet, char_alphabet): in the generator, we try to hijack the biaffine parser model provided by Max than... | aa1da79dea82c36bc1b8d4d83e1d8ad40871d330 | <|skeleton|>
class FeedForwardGenerator:
def __init__(self, word_ids, word_embedd, word_alphabet, char_alphabet):
"""in the generator, we try to hijack the biaffine parser model provided by Max thanks for the dynamic feature of python, we want to substitute the embedd_word all the ablation study is done he... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeedForwardGenerator:
def __init__(self, word_ids, word_embedd, word_alphabet, char_alphabet):
"""in the generator, we try to hijack the biaffine parser model provided by Max thanks for the dynamic feature of python, we want to substitute the embedd_word all the ablation study is done here, notice tha... | the_stack_v2_python_sparse | net/generator/ff.py | ichn-hu/Parsing-Obfuscation | train | 3 | |
763e8cab568f9fb88dc238ee0890739c23cc75c2 | [
"print(self.driver)\nprint(self.driver.dummy_parameter)\nprint('Do something before define')\nsuper(DummyVolume, self).define()\nprint('Do something after define')",
"print('Do something before erase')\nsuper(DummyVolume, self).erase()\nprint('Do something after erase')"
] | <|body_start_0|>
print(self.driver)
print(self.driver.dummy_parameter)
print('Do something before define')
super(DummyVolume, self).define()
print('Do something after define')
<|end_body_0|>
<|body_start_1|>
print('Do something before erase')
super(DummyVolume, s... | Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node | DummyVolume | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DummyVolume:
"""Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node"""
def define(self):
"""Define Define method is called one time after environment successfully saved from templat... | stack_v2_sparse_classes_75kplus_train_005319 | 7,586 | permissive | [
{
"docstring": "Define Define method is called one time after environment successfully saved from template to database. It should contain something to prepare an instance of Volume before usage in Node class",
"name": "define",
"signature": "def define(self)"
},
{
"docstring": "Erase Erase metho... | 2 | stack_v2_sparse_classes_30k_train_035817 | Implement the Python class `DummyVolume` described below.
Class description:
Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node
Method signatures and docstrings:
- def define(self): Define Define method is called o... | Implement the Python class `DummyVolume` described below.
Class description:
Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node
Method signatures and docstrings:
- def define(self): Define Define method is called o... | ceafbce11c86bf6af3d43d095153bc452d535828 | <|skeleton|>
class DummyVolume:
"""Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node"""
def define(self):
"""Define Define method is called one time after environment successfully saved from templat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DummyVolume:
"""Example implementation of volume Note: This class is imported as Volume at .__init__.py Volume is image or disk which should be mounted to a specific Node"""
def define(self):
"""Define Define method is called one time after environment successfully saved from template to database... | the_stack_v2_python_sparse | devops/driver/dummy/dummy_driver.py | bopopescu/fuel-devops-3.0.5 | train | 0 |
b72c5e1b96645ed86e5d883f9dd0fa2563131dce | [
"msg = KuduMsg(MsgType.VULNERABILITY.value)\nmsg.add_datetime(vuln.scan.start)\nmsg.add_short(vuln.port.number)\nmsg.add_ip(vuln.port.node.ip)\nmsg.add_int(vuln.port.node.id)\nmsg.add_str(vuln.port.protocol)\nmsg.add_str(str(vuln.port.service))\nmsg.add_str(vuln.port.banner)\nmsg.add_byte(vuln.port.transport_protoc... | <|body_start_0|>
msg = KuduMsg(MsgType.VULNERABILITY.value)
msg.add_datetime(vuln.scan.start)
msg.add_short(vuln.port.number)
msg.add_ip(vuln.port.node.ip)
msg.add_int(vuln.port.node.id)
msg.add_str(vuln.port.protocol)
msg.add_str(str(vuln.port.service))
m... | Class for serializing objects | Serializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializer:
"""Class for serializing objects"""
def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg:
"""Serializes Vulnerability"""
<|body_0|>
def serialize_exploit(cls, exploit: Exploit) -> KuduMsg:
"""Serializes Exploit"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_005320 | 5,657 | permissive | [
{
"docstring": "Serializes Vulnerability",
"name": "serialize_vulnerability",
"signature": "def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg"
},
{
"docstring": "Serializes Exploit",
"name": "serialize_exploit",
"signature": "def serialize_exploit(cls, exploit: Exploit) ->... | 3 | stack_v2_sparse_classes_30k_train_052971 | Implement the Python class `Serializer` described below.
Class description:
Class for serializing objects
Method signatures and docstrings:
- def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg: Serializes Vulnerability
- def serialize_exploit(cls, exploit: Exploit) -> KuduMsg: Serializes Exploit
- def s... | Implement the Python class `Serializer` described below.
Class description:
Class for serializing objects
Method signatures and docstrings:
- def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg: Serializes Vulnerability
- def serialize_exploit(cls, exploit: Exploit) -> KuduMsg: Serializes Exploit
- def s... | bb21ff02965ed0cca5a55ee559eae77856d9866c | <|skeleton|>
class Serializer:
"""Class for serializing objects"""
def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg:
"""Serializes Vulnerability"""
<|body_0|>
def serialize_exploit(cls, exploit: Exploit) -> KuduMsg:
"""Serializes Exploit"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serializer:
"""Class for serializing objects"""
def serialize_vulnerability(cls, vuln: Vulnerability) -> KuduMsg:
"""Serializes Vulnerability"""
msg = KuduMsg(MsgType.VULNERABILITY.value)
msg.add_datetime(vuln.scan.start)
msg.add_short(vuln.port.number)
msg.add_ip(... | the_stack_v2_python_sparse | database/serializer.py | collectivesense/aucote | train | 0 |
f9f10d7d8f806adbd887ce7c296b26eec1731156 | [
"self._min = _min\nself._max = _max\nself.integer = integer",
"value = random.uniform(self._min, self._max)\nif self.integer:\n return round(value)\nreturn value"
] | <|body_start_0|>
self._min = _min
self._max = _max
self.integer = integer
<|end_body_0|>
<|body_start_1|>
value = random.uniform(self._min, self._max)
if self.integer:
return round(value)
return value
<|end_body_1|>
| Uniform -f Random variable | Uniform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uniform:
"""Uniform -f Random variable"""
def __init__(self, _min, _max, integer=False):
"""Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers"""
<|body_0|>
def get_value(self):
"""... | stack_v2_sparse_classes_75kplus_train_005321 | 6,001 | no_license | [
{
"docstring": "Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers",
"name": "__init__",
"signature": "def __init__(self, _min, _max, integer=False)"
},
{
"docstring": "get_value Return a value from the uniform Dis... | 2 | stack_v2_sparse_classes_30k_train_007247 | Implement the Python class `Uniform` described below.
Class description:
Uniform -f Random variable
Method signatures and docstrings:
- def __init__(self, _min, _max, integer=False): Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers
- ... | Implement the Python class `Uniform` described below.
Class description:
Uniform -f Random variable
Method signatures and docstrings:
- def __init__(self, _min, _max, integer=False): Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers
- ... | 7f509d9b6c2aaf64ffc0bb1d97ba6344170242c7 | <|skeleton|>
class Uniform:
"""Uniform -f Random variable"""
def __init__(self, _min, _max, integer=False):
"""Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers"""
<|body_0|>
def get_value(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Uniform:
"""Uniform -f Random variable"""
def __init__(self, _min, _max, integer=False):
"""Constructor :param _min: _minimum value :param _max: _maximum value :param integer: whether to use integer or floating point numbers"""
self._min = _min
self._max = _max
self.intege... | the_stack_v2_python_sparse | src/util/distribution.py | tiamilani/BGPFSM | train | 1 |
bad60bdbda1acd4b76539698962a0856ff276141 | [
"super(TearingStats, self).__init__()\nself.fitsfile = fitsfile\nccd = MaskedCCD(fitsfile)\nfor amp in ccd:\n self[amp] = AmpTearingStats(ccd[amp], ccd.amp_geom, buf=buf)",
"ntear = 0\nfor amp in self:\n rstats1, rstats2 = self[amp].rstats\n if rstats1.diff - cut1 > nsig * rstats1.error and rstats2.diff ... | <|body_start_0|>
super(TearingStats, self).__init__()
self.fitsfile = fitsfile
ccd = MaskedCCD(fitsfile)
for amp in ccd:
self[amp] = AmpTearingStats(ccd[amp], ccd.amp_geom, buf=buf)
<|end_body_0|>
<|body_start_1|>
ntear = 0
for amp in self:
rstats... | Tearing statistics for a CCD, keyed by amp number, 1-17. | TearingStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TearingStats:
"""Tearing statistics for a CCD, keyed by amp number, 1-17."""
def __init__(self, fitsfile, buf=10):
"""Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leading and trailing edge of serial overscan to compute the bi... | stack_v2_sparse_classes_75kplus_train_005322 | 7,880 | no_license | [
{
"docstring": "Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leading and trailing edge of serial overscan to compute the bias level for each row.",
"name": "__init__",
"signature": "def __init__(self, fitsfile, buf=10)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_val_001463 | Implement the Python class `TearingStats` described below.
Class description:
Tearing statistics for a CCD, keyed by amp number, 1-17.
Method signatures and docstrings:
- def __init__(self, fitsfile, buf=10): Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leadi... | Implement the Python class `TearingStats` described below.
Class description:
Tearing statistics for a CCD, keyed by amp number, 1-17.
Method signatures and docstrings:
- def __init__(self, fitsfile, buf=10): Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leadi... | d0d094fc01b47480287ce009ed13286106c214bf | <|skeleton|>
class TearingStats:
"""Tearing statistics for a CCD, keyed by amp number, 1-17."""
def __init__(self, fitsfile, buf=10):
"""Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leading and trailing edge of serial overscan to compute the bi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TearingStats:
"""Tearing statistics for a CCD, keyed by amp number, 1-17."""
def __init__(self, fitsfile, buf=10):
"""Parameters ---------- fitsfile: str Single sensor FITS file. buf: int [10] Number of pixels to avoid on leading and trailing edge of serial overscan to compute the bias level for ... | the_stack_v2_python_sparse | python/lsst/cr_eotest/sensor/tearing_statistics.py | lsst-camera-dh/cr-eotest | train | 1 |
72fa46a74c5f57bdc4f3f2b89fb2ff302ca1f415 | [
"if self._mode == common.FULL_COMMS_MODE:\n if struct_tree.IsValidElement(args[arg_idx]):\n return args[arg_idx].flags.status\n else:\n return None\nelif self._mode == common.SPARSE_COMMS_MODE:\n return self._GetTetherValue(args[0], self._node_labels[arg_idx], 'state')\nelse:\n assert Fals... | <|body_start_0|>
if self._mode == common.FULL_COMMS_MODE:
if struct_tree.IsValidElement(args[arg_idx]):
return args[arg_idx].flags.status
else:
return None
elif self._mode == common.SPARSE_COMMS_MODE:
return self._GetTetherValue(args[0]... | Base indicator for servos' armed status. | BaseArmedIndicator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseArmedIndicator:
"""Base indicator for servos' armed status."""
def _GetSingleValue(self, arg_idx, *args):
"""Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicat... | stack_v2_sparse_classes_75kplus_train_005323 | 17,733 | permissive | [
{
"docstring": "Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicator. The attributes vary in different modes. For FULL_COMMS_MODE, it is the list of ServoStatus messages for each servo, so ar... | 2 | stack_v2_sparse_classes_30k_train_012150 | Implement the Python class `BaseArmedIndicator` described below.
Class description:
Base indicator for servos' armed status.
Method signatures and docstrings:
- def _GetSingleValue(self, arg_idx, *args): Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the... | Implement the Python class `BaseArmedIndicator` described below.
Class description:
Base indicator for servos' armed status.
Method signatures and docstrings:
- def _GetSingleValue(self, arg_idx, *args): Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the... | 818ae8b7119b200a28af6b3669a3045f30e0dc64 | <|skeleton|>
class BaseArmedIndicator:
"""Base indicator for servos' armed status."""
def _GetSingleValue(self, arg_idx, *args):
"""Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseArmedIndicator:
"""Base indicator for servos' armed status."""
def _GetSingleValue(self, arg_idx, *args):
"""Obtain a single value for one servo, invoked within _GetAvailableValues. Args: arg_idx: The index referring to the n-th servo. *args: The list of attributes to the indicator. The attri... | the_stack_v2_python_sparse | gs/monitor2/apps/plugins/indicators/servo.py | ghomsy/makani | train | 0 |
092db83682422d7066ba07882680bbdac7cb8da3 | [
"if request.session.get('login', None):\n return JsonResponse({'status': True, 'id': getUser(request.session.get('login')).id})\nelse:\n return JsonResponse({'status': False, 'errMsg': '你还未登录'}, status=401)",
"try:\n jsonParams = json.loads(request.body.decode('utf-8'))\n user = UserInfo.objects.filte... | <|body_start_0|>
if request.session.get('login', None):
return JsonResponse({'status': True, 'id': getUser(request.session.get('login')).id})
else:
return JsonResponse({'status': False, 'errMsg': '你还未登录'}, status=401)
<|end_body_0|>
<|body_start_1|>
try:
json... | AccountBaseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountBaseView:
def get(self, request):
"""用于检查是否登录 :param request: :return:"""
<|body_0|>
def post(self, request):
"""登录账户 :param request: :return:"""
<|body_1|>
def delete(self, request):
"""登出账户 :param request: :return:"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_005324 | 3,084 | no_license | [
{
"docstring": "用于检查是否登录 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "登录账户 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "登出账户 :param request: :return:",
"name": "delet... | 3 | stack_v2_sparse_classes_30k_train_001892 | Implement the Python class `AccountBaseView` described below.
Class description:
Implement the AccountBaseView class.
Method signatures and docstrings:
- def get(self, request): 用于检查是否登录 :param request: :return:
- def post(self, request): 登录账户 :param request: :return:
- def delete(self, request): 登出账户 :param request:... | Implement the Python class `AccountBaseView` described below.
Class description:
Implement the AccountBaseView class.
Method signatures and docstrings:
- def get(self, request): 用于检查是否登录 :param request: :return:
- def post(self, request): 登录账户 :param request: :return:
- def delete(self, request): 登出账户 :param request:... | bcfbfb71bac696695ec98ac7796fea8262e5af8a | <|skeleton|>
class AccountBaseView:
def get(self, request):
"""用于检查是否登录 :param request: :return:"""
<|body_0|>
def post(self, request):
"""登录账户 :param request: :return:"""
<|body_1|>
def delete(self, request):
"""登出账户 :param request: :return:"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountBaseView:
def get(self, request):
"""用于检查是否登录 :param request: :return:"""
if request.session.get('login', None):
return JsonResponse({'status': True, 'id': getUser(request.session.get('login')).id})
else:
return JsonResponse({'status': False, 'errMsg': '你... | the_stack_v2_python_sparse | App/Account/views/restFul/baseInfo/login_logout.py | DICKQI/UTime_BackEnd | train | 0 | |
d0c3500068fb3bd0c0ddffaaeaf7ec1c55878ed9 | [
"super(RNNDecoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(self.units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)",
"Self_Att... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(self.units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')
... | decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""Public instance method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005325 | 1,367 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "Public instance method",
"name": "call",
"signature": "def call(self, x, s_prev, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018651 | Implement the Python class `RNNDecoder` described below.
Class description:
decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor
- def call(self, x, s_prev, hidden_states): Public instance method | Implement the Python class `RNNDecoder` described below.
Class description:
decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor
- def call(self, x, s_prev, hidden_states): Public instance method
<|skeleton|>
class RNNDecoder:
""... | c23deee331a71a089197547fcae4c1eefb8d24ef | <|skeleton|>
class RNNDecoder:
"""decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""Public instance method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor"""
super(RNNDecoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | YosriGFX/holbertonschool-machine_learning | train | 0 |
634557e06961d354c8e3976c8083fd672ec1a7bd | [
"template = orm.ContentTemplate.objects.get(key='how_it_works')\ncontent = 'Vinely is a personality test<br />disguised as a wine tasting'\norm.Section.objects.create(category=4, content=content, template=template)\ncontent = \"Are you Whimsical? Serendipitous? Do you think you're Sensational? Exuberant? Full of Mo... | <|body_start_0|>
template = orm.ContentTemplate.objects.get(key='how_it_works')
content = 'Vinely is a personality test<br />disguised as a wine tasting'
orm.Section.objects.create(category=4, content=content, template=template)
content = "Are you Whimsical? Serendipitous? Do you think y... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
template = orm.ContentTemplate.objects.get(key='ho... | stack_v2_sparse_classes_75kplus_train_005326 | 3,586 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014135 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
template = orm.ContentTemplate.objects.get(key='how_it_works')
content = 'Vinely is a personality test<br />disguised as a wine tasting'
orm.Section.objects.create(category=4, content=content, template=... | the_stack_v2_python_sparse | cms/migrations/0006_add_header_sub_heading_sections.py | RSV3/nuvine | train | 0 | |
0277209510a43ad1f2e32c840aaef28016cd0d37 | [
"result = []\n\ndef bc(r, left, right):\n if len(r) == 2 * n:\n result.append(r)\n else:\n if left < n:\n bc(r + '(', left + 1, right)\n if right < left:\n bc(r + ')', left, right + 1)\nbc('', 0, 0)\nreturn result",
"result = []\n\ndef isValid(r):\n bal = 0\n ... | <|body_start_0|>
result = []
def bc(r, left, right):
if len(r) == 2 * n:
result.append(r)
else:
if left < n:
bc(r + '(', left + 1, right)
if right < left:
bc(r + ')', left, right + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesisBC(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesisBF(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
def bc(r, left, ... | stack_v2_sparse_classes_75kplus_train_005327 | 1,142 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesisBC",
"signature": "def generateParenthesisBC(self, n)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesisBF",
"signature": "def generateParenthesisBF(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001575 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesisBC(self, n): :type n: int :rtype: List[str]
- def generateParenthesisBF(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesisBC(self, n): :type n: int :rtype: List[str]
- def generateParenthesisBF(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Solution:
def gen... | 325519f6a729b4e6eb04fec5e69f46a84e727252 | <|skeleton|>
class Solution:
def generateParenthesisBC(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesisBF(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesisBC(self, n):
""":type n: int :rtype: List[str]"""
result = []
def bc(r, left, right):
if len(r) == 2 * n:
result.append(r)
else:
if left < n:
bc(r + '(', left + 1, right)
... | the_stack_v2_python_sparse | 22_Generate Parentheses.py | hahalaugh/LeetCode | train | 0 | |
1b198fb4280f326490a1dfb1b49303a94aa19f4c | [
"domish.Element.__init__(self, (None, 'iq'))\nself.addUniqueId()\nself['type'] = stanzaType\nself._xmlstream = xmlstream",
"if to is not None:\n self['to'] = to\nif not ijabber.IIQResponseTracker.providedBy(self._xmlstream):\n upgradeWithIQResponseTracker(self._xmlstream)\nd = defer.Deferred()\nself._xmlstr... | <|body_start_0|>
domish.Element.__init__(self, (None, 'iq'))
self.addUniqueId()
self['type'] = stanzaType
self._xmlstream = xmlstream
<|end_body_0|>
<|body_start_1|>
if to is not None:
self['to'] = to
if not ijabber.IIQResponseTracker.providedBy(self._xmlstre... | Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period after which the deferred returned by C{send} will have its errback call... | IQ | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IQ:
"""Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period after which the deferred returned by C{se... | stack_v2_sparse_classes_75kplus_train_005328 | 36,848 | permissive | [
{
"docstring": "@type xmlstream: L{xmlstream.XmlStream} @param xmlstream: XmlStream to use for transmission of this IQ @type stanzaType: C{str} @param stanzaType: IQ type identifier ('get' or 'set')",
"name": "__init__",
"signature": "def __init__(self, xmlstream, stanzaType='set')"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_006676 | Implement the Python class `IQ` described below.
Class description:
Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period af... | Implement the Python class `IQ` described below.
Class description:
Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period af... | 40861791ec4ed3bbd14b07875af25cc740f76920 | <|skeleton|>
class IQ:
"""Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period after which the deferred returned by C{se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IQ:
"""Wrapper for an iq stanza. Iq stanzas are used for communications with a request-response behaviour. Each iq request is associated with an XML stream and has its own unique id to be able to track the response. @ivar timeout: if set, a timeout period after which the deferred returned by C{send} will have... | the_stack_v2_python_sparse | stackoverflow/venv/lib/python3.6/site-packages/twisted/words/protocols/jabber/xmlstream.py | wistbean/learn_python3_spider | train | 14,403 |
5509f4de4b5eb3bac9a74a49b60da52eedf67321 | [
"height = 100\nmargin = 2\nself.decider = Decider(height, margin)\nself.pump = Pump('127.0.0.1', 8000)\nself.sensor = Sensor('127.0.0.1', 8001)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.decider.decide = MagicMock(return_value=self.pump.PUMP_IN)\nself.pump.get_state = MagicMock(return... | <|body_start_0|>
height = 100
margin = 2
self.decider = Decider(height, margin)
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.0.0.1', 8001)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.decider.decide = MagicMock(return_va... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""set up class variables"""
<|body_0|>
def test_controller(self):
"""test tick function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
height = 100
margin = 2
... | stack_v2_sparse_classes_75kplus_train_005329 | 2,651 | no_license | [
{
"docstring": "set up class variables",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test tick function",
"name": "test_controller",
"signature": "def test_controller(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024875 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): set up class variables
- def test_controller(self): test tick function | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): set up class variables
- def test_controller(self): test tick function
<|skeleton|>
class ControllerTests:
"""Unit tests for the Controller cla... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""set up class variables"""
<|body_0|>
def test_controller(self):
"""test tick function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""set up class variables"""
height = 100
margin = 2
self.decider = Decider(height, margin)
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.0.0.1', 8001)
self.... | the_stack_v2_python_sparse | students/rmart300/lesson06_testing/water-regulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
642f643e0f2a39fdb0d20044a92861bfec86bdcf | [
"contents = [doc.get_attributes(*fields) for doc in self]\nif len(fields) > 1:\n contents = list(map(list, zip(*contents)))\nreturn contents",
"contents = []\ndocs_pts = []\nfor doc in self:\n contents.append(doc.get_attributes(*fields))\n docs_pts.append(doc)\nif len(fields) > 1:\n contents = list(ma... | <|body_start_0|>
contents = [doc.get_attributes(*fields) for doc in self]
if len(fields) > 1:
contents = list(map(list, zip(*contents)))
return contents
<|end_body_0|>
<|body_start_1|>
contents = []
docs_pts = []
for doc in self:
contents.append(d... | Helpers that provide attributes getter in bulk | GetAttributeMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAttributeMixin:
"""Helpers that provide attributes getter in bulk"""
def get_attributes(self, *fields: str) -> Union[List, List[List]]:
"""Return all nonempty values of the fields from all docs this array contains :param fields: Variable length argument with the name of the fields... | stack_v2_sparse_classes_75kplus_train_005330 | 1,645 | permissive | [
{
"docstring": "Return all nonempty values of the fields from all docs this array contains :param fields: Variable length argument with the name of the fields to extract :return: Returns a list of the values for these fields. When `fields` has multiple values, then it returns a list of list.",
"name": "get_... | 2 | stack_v2_sparse_classes_30k_train_051971 | Implement the Python class `GetAttributeMixin` described below.
Class description:
Helpers that provide attributes getter in bulk
Method signatures and docstrings:
- def get_attributes(self, *fields: str) -> Union[List, List[List]]: Return all nonempty values of the fields from all docs this array contains :param fie... | Implement the Python class `GetAttributeMixin` described below.
Class description:
Helpers that provide attributes getter in bulk
Method signatures and docstrings:
- def get_attributes(self, *fields: str) -> Union[List, List[List]]: Return all nonempty values of the fields from all docs this array contains :param fie... | 34c34acfb0115ad2ec4cc8e2e9a86c521855612f | <|skeleton|>
class GetAttributeMixin:
"""Helpers that provide attributes getter in bulk"""
def get_attributes(self, *fields: str) -> Union[List, List[List]]:
"""Return all nonempty values of the fields from all docs this array contains :param fields: Variable length argument with the name of the fields... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetAttributeMixin:
"""Helpers that provide attributes getter in bulk"""
def get_attributes(self, *fields: str) -> Union[List, List[List]]:
"""Return all nonempty values of the fields from all docs this array contains :param fields: Variable length argument with the name of the fields to extract :... | the_stack_v2_python_sparse | jina/types/arrays/mixins/getattr.py | amitesh1as/jina | train | 0 |
409c93f2ab2049040c77216066f63f7cf366a191 | [
"from .models import VLANGroup\nq = Q()\nif device.site.region:\n q |= Q(scope_type=ContentType.objects.get_by_natural_key('dcim', 'region'), scope_id__in=device.site.region.get_ancestors(include_self=True))\nif device.site.group:\n q |= Q(scope_type=ContentType.objects.get_by_natural_key('dcim', 'sitegroup')... | <|body_start_0|>
from .models import VLANGroup
q = Q()
if device.site.region:
q |= Q(scope_type=ContentType.objects.get_by_natural_key('dcim', 'region'), scope_id__in=device.site.region.get_ancestors(include_self=True))
if device.site.group:
q |= Q(scope_type=Cont... | VLANQuerySet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VLANQuerySet:
def get_for_device(self, device):
"""Return all VLANs available to the specified Device."""
<|body_0|>
def get_for_virtualmachine(self, vm):
"""Return all VLANs available to the specified VirtualMachine."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_005331 | 5,753 | permissive | [
{
"docstring": "Return all VLANs available to the specified Device.",
"name": "get_for_device",
"signature": "def get_for_device(self, device)"
},
{
"docstring": "Return all VLANs available to the specified VirtualMachine.",
"name": "get_for_virtualmachine",
"signature": "def get_for_vir... | 2 | stack_v2_sparse_classes_30k_train_038782 | Implement the Python class `VLANQuerySet` described below.
Class description:
Implement the VLANQuerySet class.
Method signatures and docstrings:
- def get_for_device(self, device): Return all VLANs available to the specified Device.
- def get_for_virtualmachine(self, vm): Return all VLANs available to the specified ... | Implement the Python class `VLANQuerySet` described below.
Class description:
Implement the VLANQuerySet class.
Method signatures and docstrings:
- def get_for_device(self, device): Return all VLANs available to the specified Device.
- def get_for_virtualmachine(self, vm): Return all VLANs available to the specified ... | 506884bc4dc70299db3e2a7ad577dd7fd808065e | <|skeleton|>
class VLANQuerySet:
def get_for_device(self, device):
"""Return all VLANs available to the specified Device."""
<|body_0|>
def get_for_virtualmachine(self, vm):
"""Return all VLANs available to the specified VirtualMachine."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VLANQuerySet:
def get_for_device(self, device):
"""Return all VLANs available to the specified Device."""
from .models import VLANGroup
q = Q()
if device.site.region:
q |= Q(scope_type=ContentType.objects.get_by_natural_key('dcim', 'region'), scope_id__in=device.sit... | the_stack_v2_python_sparse | netbox/ipam/querysets.py | netbox-community/netbox | train | 8,122 | |
dd4907cce92d7e5aa897bda1fe5228bf6177b22c | [
"self.road_data_dict = road_data_dict\nself.reach_road = reach_road\nself.reach_lane = reach_lane",
"if target_road is None:\n return (None, None)\nelif target_road == self.reach_road:\n diff = int(self.reach_lane[2:]) - int(target_lane[2:])\n return (index, diff)\nelif target_road == ego_road:\n retu... | <|body_start_0|>
self.road_data_dict = road_data_dict
self.reach_road = reach_road
self.reach_lane = reach_lane
<|end_body_0|>
<|body_start_1|>
if target_road is None:
return (None, None)
elif target_road == self.reach_road:
diff = int(self.reach_lane[2:]... | Scanner | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
<|body_0|>
def successor(self, target_road, target_lane, ego_road=None, ego_lane=None, ... | stack_v2_sparse_classes_75kplus_train_005332 | 3,097 | permissive | [
{
"docstring": ":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane",
"name": "__init__",
"signature": "def __init__(self, road_data_dict, reach_road, reach_lane)"
},
{
"docstring": ":param target_road: :param target_lane: :param ego_r... | 3 | stack_v2_sparse_classes_30k_train_008813 | Implement the Python class `Scanner` described below.
Class description:
Implement the Scanner class.
Method signatures and docstrings:
- def __init__(self, road_data_dict, reach_road, reach_lane): :param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane
- def s... | Implement the Python class `Scanner` described below.
Class description:
Implement the Scanner class.
Method signatures and docstrings:
- def __init__(self, road_data_dict, reach_road, reach_lane): :param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane
- def s... | 588fc9d254b913548159bcd01c5b34bd1c5cbc73 | <|skeleton|>
class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
<|body_0|>
def successor(self, target_road, target_lane, ego_road=None, ego_lane=None, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scanner:
def __init__(self, road_data_dict, reach_road, reach_lane):
""":param road_data_dict: MongoDBから取得したRoad, Lane情報 :param reach_road: 他車両の走行するRoad :param reach_lane: 他車両の走行するLane"""
self.road_data_dict = road_data_dict
self.reach_road = reach_road
self.reach_lane = reach_... | the_stack_v2_python_sparse | Zipc_airflow/src/analyzer/utils/scanner.py | open-garden/garden | train | 16 | |
9adc96bd7b6fdb25b973a79394ce1289b5c0300d | [
"super(SimGNN, self).__init__()\nself.args = args\nself.number_labels = number_of_labels\nself.setup_layers()",
"if self.args.histogram == True:\n self.feature_count = self.args.tensor_neurons + self.args.bins\nelse:\n self.feature_count = self.args.tensor_neurons",
"self.calculate_bottleneck_features()\n... | <|body_start_0|>
super(SimGNN, self).__init__()
self.args = args
self.number_labels = number_of_labels
self.setup_layers()
<|end_body_0|>
<|body_start_1|>
if self.args.histogram == True:
self.feature_count = self.args.tensor_neurons + self.args.bins
else:
... | SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689 | SimGNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
<|body_0|>
def calculate... | stack_v2_sparse_classes_75kplus_train_005333 | 8,576 | no_license | [
{
"docstring": ":param args: Arguments object. :param number_of_labels: Number of node labels.",
"name": "__init__",
"signature": "def __init__(self, args, number_of_labels)"
},
{
"docstring": "Deciding the shape of the bottleneck layer.",
"name": "calculate_bottleneck_features",
"signat... | 6 | stack_v2_sparse_classes_30k_train_011533 | Implement the Python class `SimGNN` described below.
Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689
Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number... | Implement the Python class `SimGNN` described below.
Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689
Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
<|body_0|>
def calculate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
super(SimGNN, self).__init__()
sel... | the_stack_v2_python_sparse | generated/test_benedekrozemberczki_SimGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
4e24d5ac9f01c88edc528b55b9773936cea181b6 | [
"def is_palindrone(i, j):\n return s[i:j + 1] == s[i:j + 1][::-1]\nn = len(s)\nresult = 0\nfor i in range(n):\n for j in range(i, n):\n if is_palindrone(i, j):\n result += 1\nreturn result",
"@lru_cache(None)\ndef is_palindrone(i, j):\n if j <= i:\n return True\n return s[i] =... | <|body_start_0|>
def is_palindrone(i, j):
return s[i:j + 1] == s[i:j + 1][::-1]
n = len(s)
result = 0
for i in range(n):
for j in range(i, n):
if is_palindrone(i, j):
result += 1
return result
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubstrings(self, s: str) -> int:
"""Brute Force, Time: O(n^3), Space: O(1)"""
<|body_0|>
def countSubstrings(self, s: str) -> int:
"""Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)"""
<|body_1|>
def countSubstrings(self, s:... | stack_v2_sparse_classes_75kplus_train_005334 | 1,729 | no_license | [
{
"docstring": "Brute Force, Time: O(n^3), Space: O(1)",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s: str) -> int"
},
{
"docstring": "Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s... | 3 | stack_v2_sparse_classes_30k_train_016924 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s: str) -> int: Brute Force, Time: O(n^3), Space: O(1)
- def countSubstrings(self, s: str) -> int: Top-Down DP for is_palindrone, Time: O(n^2), Space: O... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s: str) -> int: Brute Force, Time: O(n^3), Space: O(1)
- def countSubstrings(self, s: str) -> int: Top-Down DP for is_palindrone, Time: O(n^2), Space: O... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def countSubstrings(self, s: str) -> int:
"""Brute Force, Time: O(n^3), Space: O(1)"""
<|body_0|>
def countSubstrings(self, s: str) -> int:
"""Top-Down DP for is_palindrone, Time: O(n^2), Space: O(n^2)"""
<|body_1|>
def countSubstrings(self, s:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countSubstrings(self, s: str) -> int:
"""Brute Force, Time: O(n^3), Space: O(1)"""
def is_palindrone(i, j):
return s[i:j + 1] == s[i:j + 1][::-1]
n = len(s)
result = 0
for i in range(n):
for j in range(i, n):
if is_p... | the_stack_v2_python_sparse | python/647-Palindromic Substrings.py | cwza/leetcode | train | 0 | |
18808924659768d24a74f4831c32441242f0c90c | [
"if node[u'type'] == NodeType.DUT:\n pci_address1 = Topology.get_interface_pci_addr(node, if1)\n pci_address2 = Topology.get_interface_pci_addr(node, if2)\n command = f'{Constants.REMOTE_FW_DIR}/{Constants.RESOURCES_LIB_SH}/entry/init_dpdk.sh {nic_driver} {pci_address1} {pci_address2}'\n message = u'Ini... | <|body_start_0|>
if node[u'type'] == NodeType.DUT:
pci_address1 = Topology.get_interface_pci_addr(node, if1)
pci_address2 = Topology.get_interface_pci_addr(node, if2)
command = f'{Constants.REMOTE_FW_DIR}/{Constants.RESOURCES_LIB_SH}/entry/init_dpdk.sh {nic_driver} {pci_addre... | This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment. | DPDKTools | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT ... | stack_v2_sparse_classes_75kplus_train_005335 | 4,823 | permissive | [
{
"docstring": "Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT first interface name. :param if2: DUT second interface name. :param nic_driver: Interface driver. :type node: dict :type if1: str :type if2: str :type nic_driver: str :raises RuntimeE... | 5 | stack_v2_sparse_classes_30k_train_010647 | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_framework(node, if1, if2, nic_driver): Initialize the DPDK framework on the DUT node. Bind inte... | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_framework(node, if1, if2, nic_driver): Initialize the DPDK framework on the DUT node. Bind inte... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT first interfa... | the_stack_v2_python_sparse | resources/libraries/python/DPDK/DPDKTools.py | FDio/csit | train | 28 |
6bf97f809190655ad4afd0e0c9d1bce222e9ae6d | [
"path = ''\nword = 'empires'\nself.assertRaises(IOError, find_anagrams, path, word)\npath = 'random/path/word.txt'\nword = 'empires'\nself.assertRaises(IOError, find_anagrams, path, word)\npath = './words.txt'\nword = ''\nresult = find_anagrams(path, word)\nself.assertEqual(result, None)",
"with open('./test_word... | <|body_start_0|>
path = ''
word = 'empires'
self.assertRaises(IOError, find_anagrams, path, word)
path = 'random/path/word.txt'
word = 'empires'
self.assertRaises(IOError, find_anagrams, path, word)
path = './words.txt'
word = ''
result = find_anag... | Unit test for function: find_anagram | FindAnagramsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindAnagramsTest:
"""Unit test for function: find_anagram"""
def test_find_anagrams_empty(self):
"""test for empty input"""
<|body_0|>
def test_find_anagrams_success(self):
"""testing for sucess"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pa... | stack_v2_sparse_classes_75kplus_train_005336 | 4,431 | no_license | [
{
"docstring": "test for empty input",
"name": "test_find_anagrams_empty",
"signature": "def test_find_anagrams_empty(self)"
},
{
"docstring": "testing for sucess",
"name": "test_find_anagrams_success",
"signature": "def test_find_anagrams_success(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023207 | Implement the Python class `FindAnagramsTest` described below.
Class description:
Unit test for function: find_anagram
Method signatures and docstrings:
- def test_find_anagrams_empty(self): test for empty input
- def test_find_anagrams_success(self): testing for sucess | Implement the Python class `FindAnagramsTest` described below.
Class description:
Unit test for function: find_anagram
Method signatures and docstrings:
- def test_find_anagrams_empty(self): test for empty input
- def test_find_anagrams_success(self): testing for sucess
<|skeleton|>
class FindAnagramsTest:
"""Un... | b27db09b577e992d5a5c28550ed796df768deb4d | <|skeleton|>
class FindAnagramsTest:
"""Unit test for function: find_anagram"""
def test_find_anagrams_empty(self):
"""test for empty input"""
<|body_0|>
def test_find_anagrams_success(self):
"""testing for sucess"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FindAnagramsTest:
"""Unit test for function: find_anagram"""
def test_find_anagrams_empty(self):
"""test for empty input"""
path = ''
word = 'empires'
self.assertRaises(IOError, find_anagrams, path, word)
path = 'random/path/word.txt'
word = 'empires'
... | the_stack_v2_python_sparse | codetest.py | Leo-Liu-us/Python | train | 0 |
9e11bc12f0bdeb4022bcf47764b79a59c74e0dd3 | [
"res = Object()\nfor name, value in d.items():\n n = string.normalize(name, 'alphanum_')\n setattr(res, n, klass.convertValue(value))\nreturn res",
"i = len(l) - 1\nwhile i >= 0:\n l[i] = klass.convertValue(l[i])\n i -= 1",
"if isinstance(val, list):\n klass.convertList(val)\n res = val\nelif ... | <|body_start_0|>
res = Object()
for name, value in d.items():
n = string.normalize(name, 'alphanum_')
setattr(res, n, klass.convertValue(value))
return res
<|end_body_0|>
<|body_start_1|>
i = len(l) - 1
while i >= 0:
l[i] = klass.convertValue(... | Converts JSON data into Pyton data structures | JsonDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonDecoder:
"""Converts JSON data into Pyton data structures"""
def convertDict(klass, d):
"""Returns a appy.Object instance representing dict p_d"""
<|body_0|>
def convertList(klass, l):
"""Every item being a dict in p_l is converted to an object"""
<|b... | stack_v2_sparse_classes_75kplus_train_005337 | 23,330 | no_license | [
{
"docstring": "Returns a appy.Object instance representing dict p_d",
"name": "convertDict",
"signature": "def convertDict(klass, d)"
},
{
"docstring": "Every item being a dict in p_l is converted to an object",
"name": "convertList",
"signature": "def convertList(klass, l)"
},
{
... | 4 | null | Implement the Python class `JsonDecoder` described below.
Class description:
Converts JSON data into Pyton data structures
Method signatures and docstrings:
- def convertDict(klass, d): Returns a appy.Object instance representing dict p_d
- def convertList(klass, l): Every item being a dict in p_l is converted to an ... | Implement the Python class `JsonDecoder` described below.
Class description:
Converts JSON data into Pyton data structures
Method signatures and docstrings:
- def convertDict(klass, d): Returns a appy.Object instance representing dict p_d
- def convertList(klass, l): Every item being a dict in p_l is converted to an ... | 0b32e429ceeb6c7adc6515baae3d3152679a89c5 | <|skeleton|>
class JsonDecoder:
"""Converts JSON data into Pyton data structures"""
def convertDict(klass, d):
"""Returns a appy.Object instance representing dict p_d"""
<|body_0|>
def convertList(klass, l):
"""Every item being a dict in p_l is converted to an object"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonDecoder:
"""Converts JSON data into Pyton data structures"""
def convertDict(klass, d):
"""Returns a appy.Object instance representing dict p_d"""
res = Object()
for name, value in d.items():
n = string.normalize(name, 'alphanum_')
setattr(res, n, klass... | the_stack_v2_python_sparse | appy/http/client.py | lino-framework/appypod | train | 1 |
8317fd229bdd4ada191c0d92434141c8bd655278 | [
"time.sleep(2)\nPcenterPage(login).click_addresss()\ntime.sleep(2)\nAddressPage(login).create_button()\ntime.sleep(2)\nAddressPage(login).input_address(data['input_name'], data['input_mobile'], data['detailaddress'])\ntime.sleep(2)\nlogging.info('开始断言')\ntry:\n assert AddressPage(login).get_addresstext() == data... | <|body_start_0|>
time.sleep(2)
PcenterPage(login).click_addresss()
time.sleep(2)
AddressPage(login).create_button()
time.sleep(2)
AddressPage(login).input_address(data['input_name'], data['input_mobile'], data['detailaddress'])
time.sleep(2)
logging.info('... | Testaddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Testaddress:
def test_addresssuccess(self, data, login):
"""成功新增管理地址"""
<|body_0|>
def test_updateaddress(self, login):
"""编辑地址"""
<|body_1|>
def test_deleteaddress(self, login):
"""删除地址"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005338 | 2,230 | no_license | [
{
"docstring": "成功新增管理地址",
"name": "test_addresssuccess",
"signature": "def test_addresssuccess(self, data, login)"
},
{
"docstring": "编辑地址",
"name": "test_updateaddress",
"signature": "def test_updateaddress(self, login)"
},
{
"docstring": "删除地址",
"name": "test_deleteaddress... | 3 | stack_v2_sparse_classes_30k_train_016461 | Implement the Python class `Testaddress` described below.
Class description:
Implement the Testaddress class.
Method signatures and docstrings:
- def test_addresssuccess(self, data, login): 成功新增管理地址
- def test_updateaddress(self, login): 编辑地址
- def test_deleteaddress(self, login): 删除地址 | Implement the Python class `Testaddress` described below.
Class description:
Implement the Testaddress class.
Method signatures and docstrings:
- def test_addresssuccess(self, data, login): 成功新增管理地址
- def test_updateaddress(self, login): 编辑地址
- def test_deleteaddress(self, login): 删除地址
<|skeleton|>
class Testaddress... | b262c13e55a6e9eae1d4fa11d50b71814028261c | <|skeleton|>
class Testaddress:
def test_addresssuccess(self, data, login):
"""成功新增管理地址"""
<|body_0|>
def test_updateaddress(self, login):
"""编辑地址"""
<|body_1|>
def test_deleteaddress(self, login):
"""删除地址"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Testaddress:
def test_addresssuccess(self, data, login):
"""成功新增管理地址"""
time.sleep(2)
PcenterPage(login).click_addresss()
time.sleep(2)
AddressPage(login).create_button()
time.sleep(2)
AddressPage(login).input_address(data['input_name'], data['input_mobi... | the_stack_v2_python_sparse | TestCase/test_C_phone/test_address.py | xjx985426946/Test_UI | train | 0 | |
fd007c6747771add99033addf0d3d6df22710ff8 | [
"problem = problems.simple()\noptimizer = meta.MetaOptimizer(net=dict(net='CoordinateWiseDeepLSTM', net_options={'layers': (), 'initializer': 'zeros'}))\nminimize_ops = optimizer.meta_minimize(problem, 5)\nwith self.test_session() as sess:\n sess.run(tf.global_variables_initializer())\n cost, final_x = train(... | <|body_start_0|>
problem = problems.simple()
optimizer = meta.MetaOptimizer(net=dict(net='CoordinateWiseDeepLSTM', net_options={'layers': (), 'initializer': 'zeros'}))
minimize_ops = optimizer.meta_minimize(problem, 5)
with self.test_session() as sess:
sess.run(tf.global_vari... | Tests L2L meta-optimizer. | L2LTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2LTest:
"""Tests L2L meta-optimizer."""
def testResults(self):
"""Tests reproducibility of Torch results."""
<|body_0|>
def testMultiOptimizer(self, net_assignments, net_config):
"""Tests different variable->net mappings in multi-optimizer problem."""
<|... | stack_v2_sparse_classes_75kplus_train_005339 | 7,641 | permissive | [
{
"docstring": "Tests reproducibility of Torch results.",
"name": "testResults",
"signature": "def testResults(self)"
},
{
"docstring": "Tests different variable->net mappings in multi-optimizer problem.",
"name": "testMultiOptimizer",
"signature": "def testMultiOptimizer(self, net_assig... | 6 | stack_v2_sparse_classes_30k_train_026473 | Implement the Python class `L2LTest` described below.
Class description:
Tests L2L meta-optimizer.
Method signatures and docstrings:
- def testResults(self): Tests reproducibility of Torch results.
- def testMultiOptimizer(self, net_assignments, net_config): Tests different variable->net mappings in multi-optimizer p... | Implement the Python class `L2LTest` described below.
Class description:
Tests L2L meta-optimizer.
Method signatures and docstrings:
- def testResults(self): Tests reproducibility of Torch results.
- def testMultiOptimizer(self, net_assignments, net_config): Tests different variable->net mappings in multi-optimizer p... | 4e28fdf2ffd0eaefc0d23049106609421c9290b0 | <|skeleton|>
class L2LTest:
"""Tests L2L meta-optimizer."""
def testResults(self):
"""Tests reproducibility of Torch results."""
<|body_0|>
def testMultiOptimizer(self, net_assignments, net_config):
"""Tests different variable->net mappings in multi-optimizer problem."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class L2LTest:
"""Tests L2L meta-optimizer."""
def testResults(self):
"""Tests reproducibility of Torch results."""
problem = problems.simple()
optimizer = meta.MetaOptimizer(net=dict(net='CoordinateWiseDeepLSTM', net_options={'layers': (), 'initializer': 'zeros'}))
minimize_ops... | the_stack_v2_python_sparse | learning-to-learn/meta_test.py | SynthAI/SynthAI | train | 3 |
37e34975531600fe64d024f41b8bcad9b167ed82 | [
"_len = len(nums)\nfor i in range(_len - 1):\n for j in range(i + 1, _len):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn []",
"_dict = {}\nfor k, v in enumerate(nums):\n val = target - v\n if val in _dict:\n return [_dict[val], k]\n _dict[v] = k\nreturn []"
] | <|body_start_0|>
_len = len(nums)
for i in range(_len - 1):
for j in range(i + 1, _len):
if nums[i] + nums[j] == target:
return [i, j]
return []
<|end_body_0|>
<|body_start_1|>
_dict = {}
for k, v in enumerate(nums):
va... | 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元素,所以i指针范围为0 ~ len(nums) - 2,指针j范围为i + 1 ~ len(nums) - 1。时间复杂度为O(n * n), 空间复... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元素,所以i指针范围为0 ~ len(nums) - 2,指针j范围为i + 1... | stack_v2_sparse_classes_75kplus_train_005340 | 1,998 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int] 时间复杂度:O(n * n) 空间复杂度:O(1)",
"name": "two_sum",
"signature": "def two_sum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int] 空间换时间 时间复杂度:O(n) 空间复杂度:O(n)",
"name": "two_sum2... | 2 | stack_v2_sparse_classes_30k_train_032984 | Implement the Python class `Solution` described below.
Class description:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元... | Implement the Python class `Solution` described below.
Class description:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元... | 2c534185854c1a6f5ffdb2698f9db9989f30a25b | <|skeleton|>
class Solution:
"""给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元素,所以i指针范围为0 ~ len(nums) - 2,指针j范围为i + 1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 分析:寻找数组中两个不同位置的元素的和等于target的唯一解。这里首先想到的是两层枚举方法,因为是不同位置 元素,所以i指针范围为0 ~ len(nums) - 2,指针j范围为i + 1 ~ len(nums) ... | the_stack_v2_python_sparse | Week 01/id_668/leetcode_1_668.py | Carryours/algorithm004-03 | train | 2 |
7df9ddfcfd485096e53a37bf21c443ffff5740ae | [
"log.debug('Composing bundle %s', subgraph_id)\nlinks_file = self.links[subgraph_id]\nmanifest = []\nmetadata = {'links.json': links_file.content}\nentity_ids_by_type = self._entity_ids_by_type(subgraph_id)\nfor entity_type, entity_ids in entity_ids_by_type.items():\n for i, entity_id in enumerate(sorted(entity_... | <|body_start_0|>
log.debug('Composing bundle %s', subgraph_id)
links_file = self.links[subgraph_id]
manifest = []
metadata = {'links.json': links_file.content}
entity_ids_by_type = self._entity_ids_by_type(subgraph_id)
for entity_type, entity_ids in entity_ids_by_type.ite... | StagingArea | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in ... | stack_v2_sparse_classes_75kplus_train_005341 | 13,088 | permissive | [
{
"docstring": "Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in the bundle to the JSON contents of that file.",
"name": "get_bundle",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_003273 | Implement the Python class `StagingArea` described below.
Class description:
Implement the StagingArea class.
Method signatures and docstrings:
- def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]: Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries fo... | Implement the Python class `StagingArea` described below.
Class description:
Implement the StagingArea class.
Method signatures and docstrings:
- def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]: Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries fo... | 3722323d4eed3089d25f6d6c9cbfb1672b7de939 | <|skeleton|>
class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StagingArea:
def get_bundle(self, subgraph_id: str) -> Tuple[str, List[JSON], JSON]:
"""Return a tuple consisting of the version of the downloaded bundle, a list of the manifest entries for all metadata files in the bundle, and a dictionary mapping the file name of each metadata file in the bundle to ... | the_stack_v2_python_sparse | src/humancellatlas/data/metadata/helpers/staging_area.py | DataBiosphere/azul | train | 23 | |
0d1c430853882a68b2558f8abb9a66d7f0ec2f22 | [
"try:\n id = int(id)\nexcept ValueError:\n return (None, 404)\nforum = db.session.query(Forum).filter(Forum.id == id).first()\nif forum is None:\n return (None, 404)\nreturn forum",
"data = request.json\nforum = Forum.query.filter(Forum.id == id).update(dict(name=data.get('name'), author_name=data.get('a... | <|body_start_0|>
try:
id = int(id)
except ValueError:
return (None, 404)
forum = db.session.query(Forum).filter(Forum.id == id).first()
if forum is None:
return (None, 404)
return forum
<|end_body_0|>
<|body_start_1|>
data = request.js... | ForumItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForumItem:
def get(self, id):
"""Returns a forum."""
<|body_0|>
def put(self, id):
"""Updates a forum"""
<|body_1|>
def delete(self, id):
"""Deletes a forum"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
id = i... | stack_v2_sparse_classes_75kplus_train_005342 | 3,425 | no_license | [
{
"docstring": "Returns a forum.",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Updates a forum",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Deletes a forum",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | null | Implement the Python class `ForumItem` described below.
Class description:
Implement the ForumItem class.
Method signatures and docstrings:
- def get(self, id): Returns a forum.
- def put(self, id): Updates a forum
- def delete(self, id): Deletes a forum | Implement the Python class `ForumItem` described below.
Class description:
Implement the ForumItem class.
Method signatures and docstrings:
- def get(self, id): Returns a forum.
- def put(self, id): Updates a forum
- def delete(self, id): Deletes a forum
<|skeleton|>
class ForumItem:
def get(self, id):
... | d427358dd52329438c4f42bed929bfa53d9ccfc5 | <|skeleton|>
class ForumItem:
def get(self, id):
"""Returns a forum."""
<|body_0|>
def put(self, id):
"""Updates a forum"""
<|body_1|>
def delete(self, id):
"""Deletes a forum"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForumItem:
def get(self, id):
"""Returns a forum."""
try:
id = int(id)
except ValueError:
return (None, 404)
forum = db.session.query(Forum).filter(Forum.id == id).first()
if forum is None:
return (None, 404)
return forum
... | the_stack_v2_python_sparse | api/forums/forum.py | jvazquez96/wt_test | train | 0 | |
059f6039c91304e330752a684b56e9cd88eeaebf | [
"super().__init__(kernel_size, erosion_iters=0)\nself.prob_threshold = prob_threshold\nself.__erosion_iters = erosion_iters",
"filter_mask = prob_filter(mask=mask, prob_threshold=self.prob_threshold)\ntrimap = super(TrimapGenerator, self).__call__(original_image, filter_mask)\nnew_trimap = prob_as_unknown_area(tr... | <|body_start_0|>
super().__init__(kernel_size, erosion_iters=0)
self.prob_threshold = prob_threshold
self.__erosion_iters = erosion_iters
<|end_body_0|>
<|body_start_1|>
filter_mask = prob_filter(mask=mask, prob_threshold=self.prob_threshold)
trimap = super(TrimapGenerator, self... | TrimapGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrimapGenerator:
def __init__(self, prob_threshold: int=231, kernel_size: int=30, erosion_iters: int=5):
"""Initialize a TrimapGenerator instance Args: prob_threshold: Probability threshold at which the prob_filter and prob_as_unknown_area operations will be applied kernel_size: The size... | stack_v2_sparse_classes_75kplus_train_005343 | 1,955 | permissive | [
{
"docstring": "Initialize a TrimapGenerator instance Args: prob_threshold: Probability threshold at which the prob_filter and prob_as_unknown_area operations will be applied kernel_size: The size of the offset from the object mask in pixels when an unknown area is detected in the trimap erosion_iters: The numb... | 2 | stack_v2_sparse_classes_30k_train_002520 | Implement the Python class `TrimapGenerator` described below.
Class description:
Implement the TrimapGenerator class.
Method signatures and docstrings:
- def __init__(self, prob_threshold: int=231, kernel_size: int=30, erosion_iters: int=5): Initialize a TrimapGenerator instance Args: prob_threshold: Probability thre... | Implement the Python class `TrimapGenerator` described below.
Class description:
Implement the TrimapGenerator class.
Method signatures and docstrings:
- def __init__(self, prob_threshold: int=231, kernel_size: int=30, erosion_iters: int=5): Initialize a TrimapGenerator instance Args: prob_threshold: Probability thre... | 2935e4655d2c0260195e22ac08af6c43b5969fdd | <|skeleton|>
class TrimapGenerator:
def __init__(self, prob_threshold: int=231, kernel_size: int=30, erosion_iters: int=5):
"""Initialize a TrimapGenerator instance Args: prob_threshold: Probability threshold at which the prob_filter and prob_as_unknown_area operations will be applied kernel_size: The size... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrimapGenerator:
def __init__(self, prob_threshold: int=231, kernel_size: int=30, erosion_iters: int=5):
"""Initialize a TrimapGenerator instance Args: prob_threshold: Probability threshold at which the prob_filter and prob_as_unknown_area operations will be applied kernel_size: The size of the offset... | the_stack_v2_python_sparse | carvekit/trimap/generator.py | OPHoperHPO/image-background-remove-tool | train | 1,029 | |
9f398bab65b7ee58b06728f4c6379e190761a6e9 | [
"assert_mysql_uri(server_url)\npayload = {'server_url': server_url, 'dbname': dbname, 'species': species, 'division': division, 'db_type': db_type, 'datacheck_names': [], 'datacheck_groups': [], 'datacheck_types': [], 'email': email, 'tag': tag}\nif target_url is not None:\n payload['target_url'] = target_url\ni... | <|body_start_0|>
assert_mysql_uri(server_url)
payload = {'server_url': server_url, 'dbname': dbname, 'species': species, 'division': division, 'db_type': db_type, 'datacheck_names': [], 'datacheck_groups': [], 'datacheck_types': [], 'email': email, 'tag': tag}
if target_url is not None:
... | Client for checking databases using the datacheck service | DatacheckClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatacheckClient:
"""Client for checking databases using the datacheck service"""
def submit_job(self, server_url, dbname, species, division, db_type, datacheck_names, datacheck_groups, datacheck_types, email, tag, target_url):
"""Run datachecks on a given server, for one or more spec... | stack_v2_sparse_classes_75kplus_train_005344 | 6,749 | permissive | [
{
"docstring": "Run datachecks on a given server, for one or more species. Parameter requirements are complicated, because only the server_url is absolutely required, for lots of other parameters you need one from a set, but it doesn't matter which one... Arguments: server_url - location of server, in URI forma... | 4 | stack_v2_sparse_classes_30k_train_049050 | Implement the Python class `DatacheckClient` described below.
Class description:
Client for checking databases using the datacheck service
Method signatures and docstrings:
- def submit_job(self, server_url, dbname, species, division, db_type, datacheck_names, datacheck_groups, datacheck_types, email, tag, target_url... | Implement the Python class `DatacheckClient` described below.
Class description:
Client for checking databases using the datacheck service
Method signatures and docstrings:
- def submit_job(self, server_url, dbname, species, division, db_type, datacheck_names, datacheck_groups, datacheck_types, email, tag, target_url... | db212300992cc238055f4d37f1fb39f3de099ce3 | <|skeleton|>
class DatacheckClient:
"""Client for checking databases using the datacheck service"""
def submit_job(self, server_url, dbname, species, division, db_type, datacheck_names, datacheck_groups, datacheck_types, email, tag, target_url):
"""Run datachecks on a given server, for one or more spec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatacheckClient:
"""Client for checking databases using the datacheck service"""
def submit_job(self, server_url, dbname, species, division, db_type, datacheck_names, datacheck_groups, datacheck_types, email, tag, target_url):
"""Run datachecks on a given server, for one or more species. Paramete... | the_stack_v2_python_sparse | src/ensembl/production/core/clients/datachecks.py | Ensembl/ensembl-prodinf-core | train | 1 |
12677c6c07c58539c280d64698a3d3df35eb7da9 | [
"self.is_training = is_training\nif not is_training:\n batch_size = 1\n min_dimension = params['min_dimension']\n assert min_dimension % DIVISOR == 0\n self.min_dimension = min_dimension\nelse:\n batch_size = params['batch_size']\n width, height = params['image_size']\n assert height % DIVISOR ... | <|body_start_0|>
self.is_training = is_training
if not is_training:
batch_size = 1
min_dimension = params['min_dimension']
assert min_dimension % DIVISOR == 0
self.min_dimension = min_dimension
else:
batch_size = params['batch_size']
... | Input pipeline for training or evaluating networks for heatmaps regression. | KeypointPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeypointPipeline:
"""Input pipeline for training or evaluating networks for heatmaps regression."""
def __init__(self, filenames, is_training, params):
"""During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. i... | stack_v2_sparse_classes_75kplus_train_005345 | 17,983 | permissive | [
{
"docstring": "During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. is_training: a boolean. params: a dict.",
"name": "__init__",
"signature": "def __init__(self, filenames, is_training, params)"
},
{
"docstring": "All h... | 3 | stack_v2_sparse_classes_30k_train_004198 | Implement the Python class `KeypointPipeline` described below.
Class description:
Input pipeline for training or evaluating networks for heatmaps regression.
Method signatures and docstrings:
- def __init__(self, filenames, is_training, params): During the evaluation we resize images keeping aspect ratio. Arguments: ... | Implement the Python class `KeypointPipeline` described below.
Class description:
Input pipeline for training or evaluating networks for heatmaps regression.
Method signatures and docstrings:
- def __init__(self, filenames, is_training, params): During the evaluation we resize images keeping aspect ratio. Arguments: ... | 0a509a6f217e84342e54219e0ca8d2e4052127e9 | <|skeleton|>
class KeypointPipeline:
"""Input pipeline for training or evaluating networks for heatmaps regression."""
def __init__(self, filenames, is_training, params):
"""During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeypointPipeline:
"""Input pipeline for training or evaluating networks for heatmaps regression."""
def __init__(self, filenames, is_training, params):
"""During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. is_training: a... | the_stack_v2_python_sparse | detector/input_pipeline/keypoints_detector_pipeline.py | TropComplique/MultiPoseNet | train | 12 |
b6b127a12458b5bdc8eb3c2c88c8381caa398427 | [
"try:\n s = remote(target['ip'], 21, timeout=0.25)\n banner = s.recvuntil('220 \\r\\n')\n if b'%E.' in banner:\n return None\n return s\nexcept:\n return None",
"payload = self.payload\ntry:\n detect_val.sendline(b'USER anonymousD8')\n detect_val.recvline()\n detect_val.sendline(b'P... | <|body_start_0|>
try:
s = remote(target['ip'], 21, timeout=0.25)
banner = s.recvuntil('220 \r\n')
if b'%E.' in banner:
return None
return s
except:
return None
<|end_body_0|>
<|body_start_1|>
payload = self.payload
... | Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module) | PatchedVSFTPdBackdoor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatchedVSFTPdBackdoor:
"""Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module)"""
def detect(self, target):
"""Detect a small change in the banner signifying compromise Also detect if there was already a shell running, if so close it."""
<|body_0|>
def compromis... | stack_v2_sparse_classes_75kplus_train_005346 | 5,456 | no_license | [
{
"docstring": "Detect a small change in the banner signifying compromise Also detect if there was already a shell running, if so close it.",
"name": "detect",
"signature": "def detect(self, target)"
},
{
"docstring": "Perform the exploitation",
"name": "compromise",
"signature": "def co... | 3 | stack_v2_sparse_classes_30k_train_023740 | Implement the Python class `PatchedVSFTPdBackdoor` described below.
Class description:
Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module)
Method signatures and docstrings:
- def detect(self, target): Detect a small change in the banner signifying compromise Also detect if there was already a shell running,... | Implement the Python class `PatchedVSFTPdBackdoor` described below.
Class description:
Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module)
Method signatures and docstrings:
- def detect(self, target): Detect a small change in the banner signifying compromise Also detect if there was already a shell running,... | f5898536dec77b9eed4aadb22f5945c37bd29cd1 | <|skeleton|>
class PatchedVSFTPdBackdoor:
"""Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module)"""
def detect(self, target):
"""Detect a small change in the banner signifying compromise Also detect if there was already a shell running, if so close it."""
<|body_0|>
def compromis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PatchedVSFTPdBackdoor:
"""Exploits the vsftpd 2.3.4 patched backdoor (Secondary Module)"""
def detect(self, target):
"""Detect a small change in the banner signifying compromise Also detect if there was already a shell running, if so close it."""
try:
s = remote(target['ip'], ... | the_stack_v2_python_sparse | framework/lib/modules/vsftpdbd.py | tellnol437/cinnapwn | train | 0 |
aa535cf73827caf07d6571a183251aab0b26f916 | [
"Log().info('======开始考前资料核查======')\nsleep(2)\nself.find_element(*self.Editer).click()\nsleep(2)\nself.switch_to_frame(self.find_element(*self.iframe1))\nself.implicity_wait(5)\nLog().info('======审核附件======')\nself.find_element(*self.AdoptOne).click()\nsleep(2)\nself.find_element(*self.AdoptTwo).click()\nsleep(2)\n... | <|body_start_0|>
Log().info('======开始考前资料核查======')
sleep(2)
self.find_element(*self.Editer).click()
sleep(2)
self.switch_to_frame(self.find_element(*self.iframe1))
self.implicity_wait(5)
Log().info('======审核附件======')
self.find_element(*self.AdoptOne).cli... | 考前资料核查页面 | AdultCheck | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdultCheck:
"""考前资料核查页面"""
def type_audit_data(self):
"""考前资料核查通过"""
<|body_0|>
def type_audit_pass(self):
"""审核通过断言"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Log().info('======开始考前资料核查======')
sleep(2)
self.find_element(*s... | stack_v2_sparse_classes_75kplus_train_005347 | 1,886 | no_license | [
{
"docstring": "考前资料核查通过",
"name": "type_audit_data",
"signature": "def type_audit_data(self)"
},
{
"docstring": "审核通过断言",
"name": "type_audit_pass",
"signature": "def type_audit_pass(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032729 | Implement the Python class `AdultCheck` described below.
Class description:
考前资料核查页面
Method signatures and docstrings:
- def type_audit_data(self): 考前资料核查通过
- def type_audit_pass(self): 审核通过断言 | Implement the Python class `AdultCheck` described below.
Class description:
考前资料核查页面
Method signatures and docstrings:
- def type_audit_data(self): 考前资料核查通过
- def type_audit_pass(self): 审核通过断言
<|skeleton|>
class AdultCheck:
"""考前资料核查页面"""
def type_audit_data(self):
"""考前资料核查通过"""
<|body_0|>
... | 08d7fab053f6797016d827396fc7b48a3eba9b6e | <|skeleton|>
class AdultCheck:
"""考前资料核查页面"""
def type_audit_data(self):
"""考前资料核查通过"""
<|body_0|>
def type_audit_pass(self):
"""审核通过断言"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdultCheck:
"""考前资料核查页面"""
def type_audit_data(self):
"""考前资料核查通过"""
Log().info('======开始考前资料核查======')
sleep(2)
self.find_element(*self.Editer).click()
sleep(2)
self.switch_to_frame(self.find_element(*self.iframe1))
self.implicity_wait(5)
L... | the_stack_v2_python_sparse | YZ_AutoTest_Project/Website/test_case/page_object/AdultCheckFilePage.py | MikeDarkCloud/YZ | train | 0 |
3eff43eed38a4e83a1778e2fc80af3adcf78b6bb | [
"if x < 0:\n return None\np = x\nwhile p * p - x >= 1:\n p = 0.5 * (p + x / p)\nreturn int(p)",
"if x < 0:\n return None\nleft = 0\nright = x\nwhile True:\n mid = (left + right) // 2\n if mid * mid > x:\n right = mid - 1\n else:\n if (mid + 1) ** 2 > x:\n return mid\n ... | <|body_start_0|>
if x < 0:
return None
p = x
while p * p - x >= 1:
p = 0.5 * (p + x / p)
return int(p)
<|end_body_0|>
<|body_start_1|>
if x < 0:
return None
left = 0
right = x
while True:
mid = (left + right... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return None
p = x
while p * p - x >= 1:
... | stack_v2_sparse_classes_75kplus_train_005348 | 795 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt2",
"signature": "def mySqrt2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040943 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rt... | 032016724564d0bee85f9e1b9d9d6c769d0eb667 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
if x < 0:
return None
p = x
while p * p - x >= 1:
p = 0.5 * (p + x / p)
return int(p)
def mySqrt2(self, x):
""":type x: int :rtype: int"""
if x < 0:
re... | the_stack_v2_python_sparse | q69.py | maples1993/LeetCode | train | 1 | |
2a3f07f2dfcd3104843fff89cc72443df8c4f22f | [
"if phase_name == 'ECalDigi':\n return 0\nelif phase_name == 'HCalDigi':\n return 1\nelif phase_name == 'MuonAndHCalOtherDigi':\n return 2\nelif phase_name == 'ElectroMagEnergy':\n return 3\nelif phase_name == 'HadronicEnergy':\n return 4\nelif phase_name == 'PhotonTraining':\n return 5\nelse:\n ... | <|body_start_0|>
if phase_name == 'ECalDigi':
return 0
elif phase_name == 'HCalDigi':
return 1
elif phase_name == 'MuonAndHCalOtherDigi':
return 2
elif phase_name == 'ElectroMagEnergy':
return 3
elif phase_name == 'HadronicEnergy':
... | Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementation from PyPi. | CalibrationPhase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalibrationPhase:
"""Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementatio... | stack_v2_sparse_classes_75kplus_train_005349 | 43,413 | no_license | [
{
"docstring": "Return the ID of the given CalibrationPhase, passed as a string. :param str phase_name: Name of the CalibrationPhase. Allowed are: ECalDigi, HCalDigi, MuonAndHCalOtherDigi, ElectroMagEnergy, HadronicEnergy, PhotonTraining :returns: ID of this phase :rtype: int",
"name": "phaseIDFromString",
... | 4 | stack_v2_sparse_classes_30k_train_030563 | Implement the Python class `CalibrationPhase` described below.
Class description:
Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install ... | Implement the Python class `CalibrationPhase` described below.
Class description:
Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install ... | 9c366957fdd680a284df675c318989cb88e5959c | <|skeleton|>
class CalibrationPhase:
"""Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalibrationPhase:
"""Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementation from PyPi."... | the_stack_v2_python_sparse | CalibrationSystem/Service/CalibrationRun.py | LCDsoft/ILCDIRAC | train | 1 |
878a79bfa100fcce35c90ca8d9ecbe8ebfcc8085 | [
"self.capacity = capacity\nself.cache = {}\nself.last_time_dic = {}\nself.used_size = 0\nself.last_time = 0\nself.lru = deque()",
"value = self.cache.get(key, -1)\nif value != -1:\n self.lru.append((key, self.last_time))\n self.last_time_dic[key] = self.last_time\n self.last_time += 1\nreturn value",
"... | <|body_start_0|>
self.capacity = capacity
self.cache = {}
self.last_time_dic = {}
self.used_size = 0
self.last_time = 0
self.lru = deque()
<|end_body_0|>
<|body_start_1|>
value = self.cache.get(key, -1)
if value != -1:
self.lru.append((key, se... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_005350 | 3,050 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_044682 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = {}
self.last_time_dic = {}
self.used_size = 0
self.last_time = 0
self.lru = deque()
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | 146-LRU_cache.py | WweiL/LeetCode | train | 0 | |
a9eab2ef4b94851019af2eb8818ad7dd47e983e0 | [
"try:\n jobs = Jobs.query.all()\nexcept:\n return make_response(jsonify({'error': 'Database Connection Problem'}), 500)\nif jobs is []:\n return make_response(jsonify({'error': 'Jobs not found'}), 404)\njobsList = []\nfor job in jobs:\n jobsList.append({'name': job.name, 'id': job.id})\nreturn make_resp... | <|body_start_0|>
try:
jobs = Jobs.query.all()
except:
return make_response(jsonify({'error': 'Database Connection Problem'}), 500)
if jobs is []:
return make_response(jsonify({'error': 'Jobs not found'}), 404)
jobsList = []
for job in jobs:
... | Get/Post/Put/Delete endpoints of Jobs are implemented in this class | JobsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobsAPI:
"""Get/Post/Put/Delete endpoints of Jobs are implemented in this class"""
def get(self):
"""Returns all job names"""
<|body_0|>
def post(self):
"""Creates a new job"""
<|body_1|>
def put(self):
"""Updates a job"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_005351 | 22,916 | no_license | [
{
"docstring": "Returns all job names",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates a new job",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Updates a job",
"name": "put",
"signature": "def put(self)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_040143 | Implement the Python class `JobsAPI` described below.
Class description:
Get/Post/Put/Delete endpoints of Jobs are implemented in this class
Method signatures and docstrings:
- def get(self): Returns all job names
- def post(self): Creates a new job
- def put(self): Updates a job
- def delete(self): Deletes a job | Implement the Python class `JobsAPI` described below.
Class description:
Get/Post/Put/Delete endpoints of Jobs are implemented in this class
Method signatures and docstrings:
- def get(self): Returns all job names
- def post(self): Creates a new job
- def put(self): Updates a job
- def delete(self): Deletes a job
<|... | f7aebee17a0a79e8d3c2927733bce8015b4a9da3 | <|skeleton|>
class JobsAPI:
"""Get/Post/Put/Delete endpoints of Jobs are implemented in this class"""
def get(self):
"""Returns all job names"""
<|body_0|>
def post(self):
"""Creates a new job"""
<|body_1|>
def put(self):
"""Updates a job"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobsAPI:
"""Get/Post/Put/Delete endpoints of Jobs are implemented in this class"""
def get(self):
"""Returns all job names"""
try:
jobs = Jobs.query.all()
except:
return make_response(jsonify({'error': 'Database Connection Problem'}), 500)
if jobs i... | the_stack_v2_python_sparse | platon/backend/app/profile_management/views.py | bounswe/bounswe2020group7 | train | 18 |
76e1b868c76e95e3a13fdc9917225694e22aaf87 | [
"coins = [1, 3, 5, 10]\namount = 10\nresult = change(amount, coins)\nself.assertEqual(result, 8)",
"coins = [1, 2, 4, 5, 6, 14, 15]\namount = 100\nresult = change(amount, coins)\nself.assertEqual(result, 93843)",
"def result():\n return change({}, [1, 2, 3])\nself.assertRaises(TypeError, result)",
"def res... | <|body_start_0|>
coins = [1, 3, 5, 10]
amount = 10
result = change(amount, coins)
self.assertEqual(result, 8)
<|end_body_0|>
<|body_start_1|>
coins = [1, 2, 4, 5, 6, 14, 15]
amount = 100
result = change(amount, coins)
self.assertEqual(result, 93843)
<|end... | TestChange | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChange:
def test_can_find_max_change_in_small_amount(self):
"""Can return correct total ways to get to a small amount"""
<|body_0|>
def test_can_find_max_change_in_large_amount(self):
"""Can return correct total ways to get to a large amount"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_005352 | 1,411 | permissive | [
{
"docstring": "Can return correct total ways to get to a small amount",
"name": "test_can_find_max_change_in_small_amount",
"signature": "def test_can_find_max_change_in_small_amount(self)"
},
{
"docstring": "Can return correct total ways to get to a large amount",
"name": "test_can_find_ma... | 5 | stack_v2_sparse_classes_30k_train_013975 | Implement the Python class `TestChange` described below.
Class description:
Implement the TestChange class.
Method signatures and docstrings:
- def test_can_find_max_change_in_small_amount(self): Can return correct total ways to get to a small amount
- def test_can_find_max_change_in_large_amount(self): Can return co... | Implement the Python class `TestChange` described below.
Class description:
Implement the TestChange class.
Method signatures and docstrings:
- def test_can_find_max_change_in_small_amount(self): Can return correct total ways to get to a small amount
- def test_can_find_max_change_in_large_amount(self): Can return co... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestChange:
def test_can_find_max_change_in_small_amount(self):
"""Can return correct total ways to get to a small amount"""
<|body_0|>
def test_can_find_max_change_in_large_amount(self):
"""Can return correct total ways to get to a large amount"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestChange:
def test_can_find_max_change_in_small_amount(self):
"""Can return correct total ways to get to a small amount"""
coins = [1, 3, 5, 10]
amount = 10
result = change(amount, coins)
self.assertEqual(result, 8)
def test_can_find_max_change_in_large_amount(se... | the_stack_v2_python_sparse | src/leetcode/medium/coin-change-ii/test_coin_change_ii.py | nwthomas/code-challenges | train | 2 | |
9540cbf473d2afa226f5d115561c26c9c9be2744 | [
"super().__init__()\nself.mlp_query = nn.Linear(query_dim, att_dim, bias=True)\nself.mlp_key = nn.Linear(key_dim, att_dim, bias=False)\nself.mlp_coverage = nn.Linear(1, att_dim, bias=False)\nself.mlp_out = nn.Linear(att_dim, 1, bias=False)",
"query = query.unsqueeze(1)\nquery = self.mlp_query(query)\nkeys = self.... | <|body_start_0|>
super().__init__()
self.mlp_query = nn.Linear(query_dim, att_dim, bias=True)
self.mlp_key = nn.Linear(key_dim, att_dim, bias=False)
self.mlp_coverage = nn.Linear(1, att_dim, bias=False)
self.mlp_out = nn.Linear(att_dim, 1, bias=False)
<|end_body_0|>
<|body_start... | dotAttn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, cover, key_len=None, scaling=1.0):
""":param query: ... | stack_v2_sparse_classes_75kplus_train_005353 | 22,870 | no_license | [
{
"docstring": "basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim",
"name": "__init__",
"signature": "def __init__(self, query_dim, key_dim, att_dim)"
},
{
"docstring": ":param query: previous hidden state of the decoder, in shape (batch, dec_d... | 2 | stack_v2_sparse_classes_30k_train_051501 | Implement the Python class `dotAttn` described below.
Class description:
Implement the dotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- def forward(self, query, ke... | Implement the Python class `dotAttn` described below.
Class description:
Implement the dotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- def forward(self, query, ke... | d354b06afbd8ae8172314af524f4f6cdeded363c | <|skeleton|>
class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, cover, key_len=None, scaling=1.0):
""":param query: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dotAttn:
def __init__(self, query_dim, key_dim, att_dim):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
super().__init__()
self.mlp_query = nn.Linear(query_dim, att_dim, bias=True)
self.mlp_key = nn.Linear(key_dim, a... | the_stack_v2_python_sparse | temp/model.py | ihungalexhsu/Text-style-tranfer | train | 1 | |
a1d20d62b14e63c0ebe0a7fe8e17f38e4a4834d6 | [
"self.stages = stages\nself.steps = np.cumsum([stage.steps for stage in self.stages])\nself.total_steps = self.steps[-1]\nself.stage_idx = -1\nself.min_steps = 0\nself.max_steps = 0\nself.stage = None",
"epoch = max(min(epoch, self.total_steps), 0)\nwhile epoch >= self.max_steps and self.max_steps < self.total_st... | <|body_start_0|>
self.stages = stages
self.steps = np.cumsum([stage.steps for stage in self.stages])
self.total_steps = self.steps[-1]
self.stage_idx = -1
self.min_steps = 0
self.max_steps = 0
self.stage = None
<|end_body_0|>
<|body_start_1|>
epoch = max(... | Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for the number of steps in each stage. | MultiLinearDecay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLinearDecay:
"""Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for the number of steps in each stage."""
... | stack_v2_sparse_classes_75kplus_train_005354 | 44,726 | permissive | [
{
"docstring": "Initializer. See class documentation for parameter definitions.",
"name": "__init__",
"signature": "def __init__(self, stages: Sequence[LinearDecay]) -> None"
},
{
"docstring": "Get the decayed value factor for `epoch` number of steps. # Parameters epoch : The number of steps. # ... | 2 | stack_v2_sparse_classes_30k_train_048660 | Implement the Python class `MultiLinearDecay` described below.
Class description:
Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for th... | Implement the Python class `MultiLinearDecay` described below.
Class description:
Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for th... | 9772eeeb7eacc1f9a83c90d1cf549a3f7e783c12 | <|skeleton|>
class MultiLinearDecay:
"""Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for the number of steps in each stage."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLinearDecay:
"""Container for multiple stages of LinearDecay. Obtain the value corresponding to the `i`-th step by calling an instance of this class with the value `i`. # Parameters stages: List of `LinearDecay` objects to be sequentially applied for the number of steps in each stage."""
def __init_... | the_stack_v2_python_sparse | allenact/utils/experiment_utils.py | allenai/allenact | train | 266 |
346bf7669f3f7b481170d8b104aaa3257d75e283 | [
"value = cls.validate_payload(payload)[0] + 1\nif not cls._test_boundaries(value):\n raise ConversionError(f'Could not parse {cls.__name__}', value=value, payload=payload)\nreturn value",
"try:\n knx_value = int(value) - 1\n if not cls._test_boundaries(knx_value + 1):\n raise ValueError\n retur... | <|body_start_0|>
value = cls.validate_payload(payload)[0] + 1
if not cls._test_boundaries(value):
raise ConversionError(f'Could not parse {cls.__name__}', value=value, payload=payload)
return value
<|end_body_0|>
<|body_start_1|>
try:
knx_value = int(value) - 1
... | Abstraction for KNX 1 Octet Scene Number. DPT 17.001 | DPTSceneNumber | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPTSceneNumber:
"""Abstraction for KNX 1 Octet Scene Number. DPT 17.001"""
def from_knx(cls, payload: DPTArray | DPTBinary) -> int:
"""Parse/deserialize from KNX/IP raw data."""
<|body_0|>
def to_knx(cls, value: int | float) -> DPTArray:
"""Serialize to KNX/IP ra... | stack_v2_sparse_classes_75kplus_train_005355 | 3,355 | permissive | [
{
"docstring": "Parse/deserialize from KNX/IP raw data.",
"name": "from_knx",
"signature": "def from_knx(cls, payload: DPTArray | DPTBinary) -> int"
},
{
"docstring": "Serialize to KNX/IP raw data.",
"name": "to_knx",
"signature": "def to_knx(cls, value: int | float) -> DPTArray"
}
] | 2 | stack_v2_sparse_classes_30k_train_011698 | Implement the Python class `DPTSceneNumber` described below.
Class description:
Abstraction for KNX 1 Octet Scene Number. DPT 17.001
Method signatures and docstrings:
- def from_knx(cls, payload: DPTArray | DPTBinary) -> int: Parse/deserialize from KNX/IP raw data.
- def to_knx(cls, value: int | float) -> DPTArray: S... | Implement the Python class `DPTSceneNumber` described below.
Class description:
Abstraction for KNX 1 Octet Scene Number. DPT 17.001
Method signatures and docstrings:
- def from_knx(cls, payload: DPTArray | DPTBinary) -> int: Parse/deserialize from KNX/IP raw data.
- def to_knx(cls, value: int | float) -> DPTArray: S... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class DPTSceneNumber:
"""Abstraction for KNX 1 Octet Scene Number. DPT 17.001"""
def from_knx(cls, payload: DPTArray | DPTBinary) -> int:
"""Parse/deserialize from KNX/IP raw data."""
<|body_0|>
def to_knx(cls, value: int | float) -> DPTArray:
"""Serialize to KNX/IP ra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPTSceneNumber:
"""Abstraction for KNX 1 Octet Scene Number. DPT 17.001"""
def from_knx(cls, payload: DPTArray | DPTBinary) -> int:
"""Parse/deserialize from KNX/IP raw data."""
value = cls.validate_payload(payload)[0] + 1
if not cls._test_boundaries(value):
raise Conv... | the_stack_v2_python_sparse | xknx/dpt/dpt_1byte_uint.py | XKNX/xknx | train | 248 |
86981b0936194db63401e5c598a612e9e8d85a7a | [
"res = []\n\ndef dfs(buffer, nums, start):\n if len(buffer) > 1:\n res.append(buffer[:])\n unique = set()\n for i in range(start, len(nums)):\n if i > 0 and nums[i] in unique:\n continue\n if not buffer or buffer[-1] <= nums[i]:\n unique.add(nums[i])\n ... | <|body_start_0|>
res = []
def dfs(buffer, nums, start):
if len(buffer) > 1:
res.append(buffer[:])
unique = set()
for i in range(start, len(nums)):
if i > 0 and nums[i] in unique:
continue
if not buff... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubsequences(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def findSubsequences_using_set(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r... | stack_v2_sparse_classes_75kplus_train_005356 | 1,670 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "findSubsequences",
"signature": "def findSubsequences(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "findSubsequences_using_set",
"signature": "def findSubsequences_using_se... | 2 | stack_v2_sparse_classes_30k_train_047359 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubsequences(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def findSubsequences_using_set(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 findSubsequences(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def findSubsequences_using_set(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|ske... | 6c640581a642fc1a1c43e4b9f9f397b4d67bb67b | <|skeleton|>
class Solution:
def findSubsequences(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def findSubsequences_using_set(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findSubsequences(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
res = []
def dfs(buffer, nums, start):
if len(buffer) > 1:
res.append(buffer[:])
unique = set()
for i in range(start, len(nums)):
... | the_stack_v2_python_sparse | python/491-increaseing-subsequences.py | whiledoing/leetcode | train | 0 | |
7cb2d1512bb7c52e1d58134d6f306f8df0812536 | [
"env_names = []\nfor env_name in external_environments.keys():\n env_data = external_environments[env_name]\n env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))\nreturn env_names",
"if not isinstance(name, basestring):\n raise TypeError('\"name\" argume... | <|body_start_0|>
env_names = []
for env_name in external_environments.keys():
env_data = external_environments[env_name]
env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))
return env_names
<|end_body_0|>
<|body_start_1|... | A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances. | ExternalEnvFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalEnvFactory:
"""A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of environment names which it is possible to create one environment. :param str name... | stack_v2_sparse_classes_75kplus_train_005357 | 11,040 | permissive | [
{
"docstring": "returns a list of environment names which it is possible to create one environment. :param str name_format: A string showing the format of the output variables: %n : the name of the Environment %e : the extension of the Environment :return list: list",
"name": "get_env_names",
"signature... | 2 | stack_v2_sparse_classes_30k_train_042577 | Implement the Python class `ExternalEnvFactory` described below.
Class description:
A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of environment names which ... | Implement the Python class `ExternalEnvFactory` described below.
Class description:
A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of environment names which ... | 70cd2655596446f2b5e7050ad477b5680a33911c | <|skeleton|>
class ExternalEnvFactory:
"""A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of environment names which it is possible to create one environment. :param str name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExternalEnvFactory:
"""A factory for External Environments. A Factory object for environments. Generates :class:`ExternalEnv` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of environment names which it is possible to create one environment. :param str name_format: A st... | the_stack_v2_python_sparse | anima/env/external.py | all-in-one-of/anima | train | 0 |
4818ccd6a12c8b838118a55bcbf41d4dcd6b713c | [
"self.image_pub = rospy.Publisher('image_topic_2', Image, queue_size=10)\nself.image_pub_b = rospy.Publisher('image_topic_3', Image, queue_size=10)\nself.bridge = CvBridge()\nself.image_sub_rgb = rospy.Subscriber('/camera/rgb/image_raw', Image, self.callback)",
"try:\n cv_image = self.bridge.imgmsg_to_cv2(data... | <|body_start_0|>
self.image_pub = rospy.Publisher('image_topic_2', Image, queue_size=10)
self.image_pub_b = rospy.Publisher('image_topic_3', Image, queue_size=10)
self.bridge = CvBridge()
self.image_sub_rgb = rospy.Subscriber('/camera/rgb/image_raw', Image, self.callback)
<|end_body_0|>
... | image_converter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class image_converter:
def __init__(self):
"""publishing to rostopic"""
<|body_0|>
def callback(self, data):
"""convert ROS image to OpenCV image"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.image_pub = rospy.Publisher('image_topic_2', Image, queu... | stack_v2_sparse_classes_75kplus_train_005358 | 6,011 | no_license | [
{
"docstring": "publishing to rostopic",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "convert ROS image to OpenCV image",
"name": "callback",
"signature": "def callback(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036836 | Implement the Python class `image_converter` described below.
Class description:
Implement the image_converter class.
Method signatures and docstrings:
- def __init__(self): publishing to rostopic
- def callback(self, data): convert ROS image to OpenCV image | Implement the Python class `image_converter` described below.
Class description:
Implement the image_converter class.
Method signatures and docstrings:
- def __init__(self): publishing to rostopic
- def callback(self, data): convert ROS image to OpenCV image
<|skeleton|>
class image_converter:
def __init__(self... | da6511ad2fbf10867af88eddb91ba1d43c82e327 | <|skeleton|>
class image_converter:
def __init__(self):
"""publishing to rostopic"""
<|body_0|>
def callback(self, data):
"""convert ROS image to OpenCV image"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class image_converter:
def __init__(self):
"""publishing to rostopic"""
self.image_pub = rospy.Publisher('image_topic_2', Image, queue_size=10)
self.image_pub_b = rospy.Publisher('image_topic_3', Image, queue_size=10)
self.bridge = CvBridge()
self.image_sub_rgb = rospy.Subscr... | the_stack_v2_python_sparse | final_demo/ROS_imgProcessing_subscribePublish.py | Antimony51122/Image_Processing | train | 1 | |
1ec5405d00ff4b75e2114e4a13e55cd42690fa26 | [
"self.function = function\nkwargs.setdefault('nopython', True)\nself.kwargs = kwargs",
"try:\n numba = importlib.import_module('numba')\n numba_fn = numba.jit(**self.kwargs)(self.function)\nexcept ImportError:\n numba_fn = self.function\nreturn numba_fn",
"if Numba.numba_flag:\n return self.numba_fn... | <|body_start_0|>
self.function = function
kwargs.setdefault('nopython', True)
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
try:
numba = importlib.import_module('numba')
numba_fn = numba.jit(**self.kwargs)(self.function)
except ImportError:
... | Wrap a function to (maybe) use a (lazy) jit-compiled version. | maybe_numba_fn | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class maybe_numba_fn:
"""Wrap a function to (maybe) use a (lazy) jit-compiled version."""
def __init__(self, function, **kwargs):
"""Wrap a function and save compilation keywords."""
<|body_0|>
def numba_fn(self):
"""Memoized compiled function."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_005359 | 25,845 | permissive | [
{
"docstring": "Wrap a function and save compilation keywords.",
"name": "__init__",
"signature": "def __init__(self, function, **kwargs)"
},
{
"docstring": "Memoized compiled function.",
"name": "numba_fn",
"signature": "def numba_fn(self)"
},
{
"docstring": "Call the jitted fun... | 3 | null | Implement the Python class `maybe_numba_fn` described below.
Class description:
Wrap a function to (maybe) use a (lazy) jit-compiled version.
Method signatures and docstrings:
- def __init__(self, function, **kwargs): Wrap a function and save compilation keywords.
- def numba_fn(self): Memoized compiled function.
- d... | Implement the Python class `maybe_numba_fn` described below.
Class description:
Wrap a function to (maybe) use a (lazy) jit-compiled version.
Method signatures and docstrings:
- def __init__(self, function, **kwargs): Wrap a function and save compilation keywords.
- def numba_fn(self): Memoized compiled function.
- d... | 24c260a0390d030e106943f21811652ea82aebc7 | <|skeleton|>
class maybe_numba_fn:
"""Wrap a function to (maybe) use a (lazy) jit-compiled version."""
def __init__(self, function, **kwargs):
"""Wrap a function and save compilation keywords."""
<|body_0|>
def numba_fn(self):
"""Memoized compiled function."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class maybe_numba_fn:
"""Wrap a function to (maybe) use a (lazy) jit-compiled version."""
def __init__(self, function, **kwargs):
"""Wrap a function and save compilation keywords."""
self.function = function
kwargs.setdefault('nopython', True)
self.kwargs = kwargs
def numba... | the_stack_v2_python_sparse | arviz/utils.py | arviz-devs/arviz | train | 1,421 |
34aa7b91b0f5d2cbaf2df9c3986ace0ec5603b41 | [
"self.fs_type = fs_type\nself.read_only = read_only\nself.secret_ref = secret_ref\nself.volume_name = volume_name\nself.volume_namespace = volume_namespace",
"if dictionary is None:\n return None\nfs_type = dictionary.get('fsType')\nread_only = dictionary.get('readOnly')\nsecret_ref = cohesity_management_sdk.m... | <|body_start_0|>
self.fs_type = fs_type
self.read_only = read_only
self.secret_ref = secret_ref
self.volume_name = volume_name
self.volume_namespace = volume_namespace
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
fs_type = dictio... | Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (ObjectReference): TODO: Type description here. volume_name (string): TODO: Type description here. volume_... | PodInfo_PodSpec_VolumeInfo_StorageOS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_StorageOS:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (ObjectReference): TODO: Type description ... | stack_v2_sparse_classes_75kplus_train_005360 | 2,532 | permissive | [
{
"docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_StorageOS class",
"name": "__init__",
"signature": "def __init__(self, fs_type=None, read_only=None, secret_ref=None, volume_name=None, volume_namespace=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Ar... | 2 | stack_v2_sparse_classes_30k_train_048771 | Implement the Python class `PodInfo_PodSpec_VolumeInfo_StorageOS` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (Ob... | Implement the Python class `PodInfo_PodSpec_VolumeInfo_StorageOS` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (Ob... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_StorageOS:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (ObjectReference): TODO: Type description ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PodInfo_PodSpec_VolumeInfo_StorageOS:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_StorageOS' model. TODO: type description here. Attributes: fs_type (string): TODO: Type description here. read_only (bool): TODO: Type description here. secret_ref (ObjectReference): TODO: Type description here. volume_... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pod_info_pod_spec_volume_info_storage_os.py | cohesity/management-sdk-python | train | 24 |
d42604b91af8198748e3d8106b1a880833bdb7fc | [
"dp = [['' for x in range(len(t2))] for y in range(len(t1))]\nfor i in range(len(t1)):\n for j in range(len(t2)):\n if t1[i] == t2[j]:\n if i == 0 or j == 0:\n dp[i][j] = t1[i]\n else:\n dp[i][j] = dp[i - 1][j - 1] + t1[i]\n else:\n dp[... | <|body_start_0|>
dp = [['' for x in range(len(t2))] for y in range(len(t1))]
for i in range(len(t1)):
for j in range(len(t2)):
if t1[i] == t2[j]:
if i == 0 or j == 0:
dp[i][j] = t1[i]
else:
... | LongestCommonSubsequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestCommonSubsequence:
def longestString(self, t1, t2):
"""Uses actual string in dp therefore to return answer you must use len(dp)"""
<|body_0|>
def stringLength(self, s1, s2):
"""Uses the length of the string in dp therefore no need for len(dp)"""
<|body... | stack_v2_sparse_classes_75kplus_train_005361 | 1,257 | no_license | [
{
"docstring": "Uses actual string in dp therefore to return answer you must use len(dp)",
"name": "longestString",
"signature": "def longestString(self, t1, t2)"
},
{
"docstring": "Uses the length of the string in dp therefore no need for len(dp)",
"name": "stringLength",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_049750 | Implement the Python class `LongestCommonSubsequence` described below.
Class description:
Implement the LongestCommonSubsequence class.
Method signatures and docstrings:
- def longestString(self, t1, t2): Uses actual string in dp therefore to return answer you must use len(dp)
- def stringLength(self, s1, s2): Uses t... | Implement the Python class `LongestCommonSubsequence` described below.
Class description:
Implement the LongestCommonSubsequence class.
Method signatures and docstrings:
- def longestString(self, t1, t2): Uses actual string in dp therefore to return answer you must use len(dp)
- def stringLength(self, s1, s2): Uses t... | acc4a53c3636265eec852761e019dc8928824826 | <|skeleton|>
class LongestCommonSubsequence:
def longestString(self, t1, t2):
"""Uses actual string in dp therefore to return answer you must use len(dp)"""
<|body_0|>
def stringLength(self, s1, s2):
"""Uses the length of the string in dp therefore no need for len(dp)"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LongestCommonSubsequence:
def longestString(self, t1, t2):
"""Uses actual string in dp therefore to return answer you must use len(dp)"""
dp = [['' for x in range(len(t2))] for y in range(len(t1))]
for i in range(len(t1)):
for j in range(len(t2)):
if t1[i] =... | the_stack_v2_python_sparse | longestCommonSubsequence.py | sp00ks-L/LeetCode-Problems | train | 0 | |
f8e8fc96c20017bdd9c6dd55aeb84705a3659cc0 | [
"from cms.models import GlobalPagePermission, Page\nif user.is_superuser or GlobalPagePermission.objects.with_can_change_permissions(user):\n return self.all()\nfrom cms.utils.permissions import get_user_permission_level\ntry:\n user_level = get_user_permission_level(user)\nexcept NoPermissionsException:\n ... | <|body_start_0|>
from cms.models import GlobalPagePermission, Page
if user.is_superuser or GlobalPagePermission.objects.with_can_change_permissions(user):
return self.all()
from cms.utils.permissions import get_user_permission_level
try:
user_level = get_user_perm... | Page permission manager accessible under objects. | PagePermissionManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagePermissionManager:
"""Page permission manager accessible under objects."""
def subordinate_to_user(self, user):
"""Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude obje... | stack_v2_sparse_classes_75kplus_train_005362 | 18,602 | permissive | [
{
"docstring": "Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude objects with given user, or any group containing this user - he can't be able to change his own permissions, because if he does, and re... | 2 | stack_v2_sparse_classes_30k_train_035266 | Implement the Python class `PagePermissionManager` described below.
Class description:
Page permission manager accessible under objects.
Method signatures and docstrings:
- def subordinate_to_user(self, user): Get all page permission objects on which user/group is lover in hierarchy then given user and given user can... | Implement the Python class `PagePermissionManager` described below.
Class description:
Page permission manager accessible under objects.
Method signatures and docstrings:
- def subordinate_to_user(self, user): Get all page permission objects on which user/group is lover in hierarchy then given user and given user can... | d563d912c99f0c138a66d99829d8d0133226894e | <|skeleton|>
class PagePermissionManager:
"""Page permission manager accessible under objects."""
def subordinate_to_user(self, user):
"""Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PagePermissionManager:
"""Page permission manager accessible under objects."""
def subordinate_to_user(self, user):
"""Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude objects with give... | the_stack_v2_python_sparse | cms/models/managers.py | DrMeers/django-cms-2.0 | train | 4 |
474494ce13b5e3f8aa507558a741d146df6d4982 | [
"urls = super().get_urls()\nnew_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('export-elastic/', ElasticActions.export_to_elastic)]\nreturn new_urls + urls",
"if request.method == 'POST':\n csv_file = request.FILES['importer_un_fichier']\n if not ... | <|body_start_0|>
urls = super().get_urls()
new_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('export-elastic/', ElasticActions.export_to_elastic)]
return new_urls + urls
<|end_body_0|>
<|body_start_1|>
if request.method == 'PO... | Modèle de l'administration des structures | StructureAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StructureAdmin:
"""Modèle de l'administration des structures"""
def get_urls(self):
"""Initialise les urls du modèle StructureAdmin"""
<|body_0|>
def upload_csv(request):
"""Permet de charger un fichier CSV dans la base de données du modèle Structure"""
<... | stack_v2_sparse_classes_75kplus_train_005363 | 12,279 | no_license | [
{
"docstring": "Initialise les urls du modèle StructureAdmin",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "Permet de charger un fichier CSV dans la base de données du modèle Structure",
"name": "upload_csv",
"signature": "def upload_csv(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027423 | Implement the Python class `StructureAdmin` described below.
Class description:
Modèle de l'administration des structures
Method signatures and docstrings:
- def get_urls(self): Initialise les urls du modèle StructureAdmin
- def upload_csv(request): Permet de charger un fichier CSV dans la base de données du modèle S... | Implement the Python class `StructureAdmin` described below.
Class description:
Modèle de l'administration des structures
Method signatures and docstrings:
- def get_urls(self): Initialise les urls du modèle StructureAdmin
- def upload_csv(request): Permet de charger un fichier CSV dans la base de données du modèle S... | 0471d2de17597d97f3209099aff3edc72d615fa2 | <|skeleton|>
class StructureAdmin:
"""Modèle de l'administration des structures"""
def get_urls(self):
"""Initialise les urls du modèle StructureAdmin"""
<|body_0|>
def upload_csv(request):
"""Permet de charger un fichier CSV dans la base de données du modèle Structure"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StructureAdmin:
"""Modèle de l'administration des structures"""
def get_urls(self):
"""Initialise les urls du modèle StructureAdmin"""
urls = super().get_urls()
new_urls = [path('upload-csv/', self.upload_csv), path('update_elastic/', ElasticActions.update_elastic), path('export-e... | the_stack_v2_python_sparse | elasticHal/admin.py | Patent2net/SoVisu | train | 1 |
f77f2ac55b6324b327ced40b73807265531f2a4f | [
"self.year = year\nself.dupersids = dupersids\nself.OB_LOOKUPS = {2018: {'model': OfficeBasedVisits18, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC_M18'}, 'see_doc': 'SEEDOC_M18'}, 2017: {'model': OfficeBasedVisits17, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC'}, 'see_doc... | <|body_start_0|>
self.year = year
self.dupersids = dupersids
self.OB_LOOKUPS = {2018: {'model': OfficeBasedVisits18, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR', 'OBDATEMM', 'SEEDOC_M18'}, 'see_doc': 'SEEDOC_M18'}, 2017: {'model': OfficeBasedVisits17, 'fields': {'DUPERSID', 'EVNTIDX', 'OBDATEYR... | Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types. | OfficeBasedVisitsEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively f... | stack_v2_sparse_classes_75kplus_train_005364 | 5,068 | permissive | [
{
"docstring": "Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively fetch data for",
"name": "__init__",
"signature": "def __init__(self, year, dupersids=None)"
},
{
"docstring": "Groups events by respondents. Classifies events th... | 2 | stack_v2_sparse_classes_30k_train_002026 | Implement the Python class `OfficeBasedVisitsEncoder` described below.
Class description:
Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types.
Method signatures and docstrings:
- def __init__(self, year, dupersids=None): Required_Inputs: year: Year to fetch data for Optional Inputs:... | Implement the Python class `OfficeBasedVisitsEncoder` described below.
Class description:
Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types.
Method signatures and docstrings:
- def __init__(self, year, dupersids=None): Required_Inputs: year: Year to fetch data for Optional Inputs:... | cd98ff6b484799fc0f2f447b3945621bd013bee6 | <|skeleton|>
class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficeBasedVisitsEncoder:
"""Queries the OfficeBasedVisits Tables. Encodes fields from strings to usable data types."""
def __init__(self, year, dupersids=None):
"""Required_Inputs: year: Year to fetch data for Optional Inputs: dupersids: list of respondent dupersids to exclusively fetch data for... | the_stack_v2_python_sparse | meps_db/processors/encoders/office_based_visits_encoder.py | explore-meps/meps_dev | train | 0 |
ec208e82b0797065f9f99741f30908ad1a6db397 | [
"NetStrucLner.__init__(self, False, states_df, vtx_to_states)\nself.tar_vtx = tar_vtx\nself.learn_net_struc()",
"nd_names = self.states_df.columns\nnd_names_sans_tar = list(set(nd_names) - {self.tar_vtx})\nnum_nds = len(nd_names)\ndf = self.states_df[nd_names_sans_tar]\nlnr = ChowLiuTreeLner(df)\nself.bnet = lnr.... | <|body_start_0|>
NetStrucLner.__init__(self, False, states_df, vtx_to_states)
self.tar_vtx = tar_vtx
self.learn_net_struc()
<|end_body_0|>
<|body_start_1|>
nd_names = self.states_df.columns
nd_names_sans_tar = list(set(nd_names) - {self.tar_vtx})
num_nds = len(nd_names)
... | TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target node to all other nodes, TAN Bayes first builds a CL tree from all nodes except the tar... | TreeAugNaiveBayesLner | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeAugNaiveBayesLner:
"""TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target node to all other nodes, TAN Bayes fir... | stack_v2_sparse_classes_75kplus_train_005365 | 2,781 | permissive | [
{
"docstring": "Constructor Parameters ---------- states_df : pandas.DataFrame tar_vtx : str vtx_to_states : dict[str, list[str]] A dictionary mapping each node name to a list of its state names. This information will be stored in self.bnet. If vtx_to_states=None, constructor will learn vtx_to_states from state... | 2 | stack_v2_sparse_classes_30k_train_033840 | Implement the Python class `TreeAugNaiveBayesLner` described below.
Class description:
TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target... | Implement the Python class `TreeAugNaiveBayesLner` described below.
Class description:
TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class TreeAugNaiveBayesLner:
"""TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target node to all other nodes, TAN Bayes fir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeAugNaiveBayesLner:
"""TreeAugNaiveBayesLner (Tree Augmented Naive Bayes Learner) is a simple improvement of the Naive Bayes algorithm that combines Naive Bayes with Chow Liu Trees. Whereas in Naive Bayes, the only arrows are those emanating from a target node to all other nodes, TAN Bayes first builds a C... | the_stack_v2_python_sparse | learning/TreeAugNaiveBayesLner.py | artiste-qb-net/quantum-fog | train | 95 |
5d2cae60f2f9be0840ac10e409f9914be4c80007 | [
"word_count = len(tmpwords)\nspace_count = max(1, word_count - 1)\ncharacter_num = sum([len(i) for i in tmpwords])\nbase_space = (maxWidth - character_num) / space_count\nextra_space = (maxWidth - character_num) % space_count\nret = ''\nfor i in range(space_count):\n ret = ret + tmpwords[i] + ''.join([' '] * bas... | <|body_start_0|>
word_count = len(tmpwords)
space_count = max(1, word_count - 1)
character_num = sum([len(i) for i in tmpwords])
base_space = (maxWidth - character_num) / space_count
extra_space = (maxWidth - character_num) % space_count
ret = ''
for i in range(sp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def modify(self, tmpwords, maxWidth):
""":type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int"""
<|body_0|>
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_005366 | 2,455 | no_license | [
{
"docstring": ":type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int",
"name": "modify",
"signature": "def modify(self, tmpwords, maxWidth)"
},
{
"docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]",
"name": "fullJustify",
"signature": "def fullJustif... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def modify(self, tmpwords, maxWidth): :type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int
- def fullJustify(self, words, maxWidth): :type words: List[str] :type ma... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def modify(self, tmpwords, maxWidth): :type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int
- def fullJustify(self, words, maxWidth): :type words: List[str] :type ma... | 1520e1e9bb0c428797a3e5234e5b328110472c20 | <|skeleton|>
class Solution:
def modify(self, tmpwords, maxWidth):
""":type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int"""
<|body_0|>
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def modify(self, tmpwords, maxWidth):
""":type tmpwords:List[str] eg:['This','is','an'] :type maxWidth: int"""
word_count = len(tmpwords)
space_count = max(1, word_count - 1)
character_num = sum([len(i) for i in tmpwords])
base_space = (maxWidth - character_nu... | the_stack_v2_python_sparse | String/68. Text Justification.py | tinkle1129/Leetcode_Solution | train | 0 | |
9ebcb1d6e46220659750a394d788ccd82910fef8 | [
"curl = self.get_client('curl-2')\nself.start_all_servers()\nself.start_tempesta()\ncurl.start()\nself.wait_while_busy(curl)\ncurl.stop()\nresponse = curl.response_msg\nself.assertIn('https', response, 'Expected `https` schema in response')\nself.assertIn('HTTP/2 302', response, 'Expected status `302` and sticky co... | <|body_start_0|>
curl = self.get_client('curl-2')
self.start_all_servers()
self.start_tempesta()
curl.start()
self.wait_while_busy(curl)
curl.stop()
response = curl.response_msg
self.assertIn('https', response, 'Expected `https` schema in response')
... | Test case to check cookies' behavior. | H2StickyCookieTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class H2StickyCookieTestCase:
"""Test case to check cookies' behavior."""
def test_h2_many_cookie_enforce(self):
"""Send request with many `Cookie` headers and enforced option."""
<|body_0|>
def test_h2_no_cookie_enforce(self):
"""Send request with no `Cookie` headers ... | stack_v2_sparse_classes_75kplus_train_005367 | 6,153 | no_license | [
{
"docstring": "Send request with many `Cookie` headers and enforced option.",
"name": "test_h2_many_cookie_enforce",
"signature": "def test_h2_many_cookie_enforce(self)"
},
{
"docstring": "Send request with no `Cookie` headers and enforced option.",
"name": "test_h2_no_cookie_enforce",
... | 2 | null | Implement the Python class `H2StickyCookieTestCase` described below.
Class description:
Test case to check cookies' behavior.
Method signatures and docstrings:
- def test_h2_many_cookie_enforce(self): Send request with many `Cookie` headers and enforced option.
- def test_h2_no_cookie_enforce(self): Send request with... | Implement the Python class `H2StickyCookieTestCase` described below.
Class description:
Test case to check cookies' behavior.
Method signatures and docstrings:
- def test_h2_many_cookie_enforce(self): Send request with many `Cookie` headers and enforced option.
- def test_h2_no_cookie_enforce(self): Send request with... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class H2StickyCookieTestCase:
"""Test case to check cookies' behavior."""
def test_h2_many_cookie_enforce(self):
"""Send request with many `Cookie` headers and enforced option."""
<|body_0|>
def test_h2_no_cookie_enforce(self):
"""Send request with no `Cookie` headers ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class H2StickyCookieTestCase:
"""Test case to check cookies' behavior."""
def test_h2_many_cookie_enforce(self):
"""Send request with many `Cookie` headers and enforced option."""
curl = self.get_client('curl-2')
self.start_all_servers()
self.start_tempesta()
curl.start(... | the_stack_v2_python_sparse | http2_general/test_h2_sticky_cookie.py | tempesta-tech/tempesta-test | train | 13 |
6deff823389c0ca35ab85656f1866504a94d2d3e | [
"from_user_info = UserTable.query.filter_by(id=from_user).first()\nto_user_info = UserTable.query.filter_by(id=to_user).first()\nprint(from_user_info)\nprint(to_user_info)\nif from_user_info is None or to_user_info is None:\n return {'code': 1, 'msg': ERROR.USER_NOT_EXISTS}\nprint('stream to sms {} send to {} co... | <|body_start_0|>
from_user_info = UserTable.query.filter_by(id=from_user).first()
to_user_info = UserTable.query.filter_by(id=to_user).first()
print(from_user_info)
print(to_user_info)
if from_user_info is None or to_user_info is None:
return {'code': 1, 'msg': ERROR.... | im business logic class | StreamChatController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChatController:
"""im business logic class"""
def stream_to_sms(self, from_user, to_user, content):
"""getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: message text content"""
<|body_0|>
def sms_to... | stack_v2_sparse_classes_75kplus_train_005368 | 2,257 | no_license | [
{
"docstring": "getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: message text content",
"name": "stream_to_sms",
"signature": "def stream_to_sms(self, from_user, to_user, content)"
},
{
"docstring": "twilio sms send to getStream... | 2 | stack_v2_sparse_classes_30k_train_002457 | Implement the Python class `StreamChatController` described below.
Class description:
im business logic class
Method signatures and docstrings:
- def stream_to_sms(self, from_user, to_user, content): getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: m... | Implement the Python class `StreamChatController` described below.
Class description:
im business logic class
Method signatures and docstrings:
- def stream_to_sms(self, from_user, to_user, content): getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: m... | 98dc95107d3080d7326a972f6ecdd2ba5970286a | <|skeleton|>
class StreamChatController:
"""im business logic class"""
def stream_to_sms(self, from_user, to_user, content):
"""getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: message text content"""
<|body_0|>
def sms_to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamChatController:
"""im business logic class"""
def stream_to_sms(self, from_user, to_user, content):
"""getStream message send to twilio sms :param from_user: sender user id :param to_user: resive user id :param content: message text content"""
from_user_info = UserTable.query.filter... | the_stack_v2_python_sparse | siyu/controller/stream_chat_controller.py | JamesJoe-C/house-api-test2 | train | 0 |
0d182a49ef4792f09733ea99b3b1e92bf39d2e5b | [
"if not root:\n return False\nif not root.left and (not root.right):\n return sum == root.val\nreturn self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)",
"def preOrder(node, path):\n if not node:\n return False\n path.append(node.val)\n if sum(path) ==... | <|body_start_0|>
if not root:
return False
if not root.left and (not root.right):
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
<|end_body_0|>
<|body_start_1|>
def preOrder(node, path):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""dfs"""
<|body_0|>
def hasPathSum1(self, root: TreeNode, targetSum: int) -> bool:
"""回溯"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return False
... | stack_v2_sparse_classes_75kplus_train_005369 | 2,099 | permissive | [
{
"docstring": "dfs",
"name": "hasPathSum",
"signature": "def hasPathSum(self, root: TreeNode, sum: int) -> bool"
},
{
"docstring": "回溯",
"name": "hasPathSum1",
"signature": "def hasPathSum1(self, root: TreeNode, targetSum: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_030101 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root: TreeNode, sum: int) -> bool: dfs
- def hasPathSum1(self, root: TreeNode, targetSum: int) -> bool: 回溯 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root: TreeNode, sum: int) -> bool: dfs
- def hasPathSum1(self, root: TreeNode, targetSum: int) -> bool: 回溯
<|skeleton|>
class Solution:
def hasPathSum(... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""dfs"""
<|body_0|>
def hasPathSum1(self, root: TreeNode, targetSum: int) -> bool:
"""回溯"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""dfs"""
if not root:
return False
if not root.left and (not root.right):
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - roo... | the_stack_v2_python_sparse | 112-path-sum.py | yuenliou/leetcode | train | 0 | |
a16b2567d5cbf5fb183b3a17a79289288fc81c5e | [
"super(ThreadLogHandler, self).__init__()\nif formatter is None:\n formatter = MessageFormatter()\nelif isinstance(formatter, str):\n formatter = MessageFormatter(formatter)\nself.setFormatter(formatter)\nself.thread_id = thread_id\nself.logs = []",
"if record.thread == self.thread_id:\n return super().h... | <|body_start_0|>
super(ThreadLogHandler, self).__init__()
if formatter is None:
formatter = MessageFormatter()
elif isinstance(formatter, str):
formatter = MessageFormatter(formatter)
self.setFormatter(formatter)
self.thread_id = thread_id
self.log... | Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread().ident) logger = logging.getLogger(__name__) logger.addHandler(log_handler) See Al... | ThreadLogHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadLogHandler:
"""Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread().ident) logger = logging.getLogger(__n... | stack_v2_sparse_classes_75kplus_train_005370 | 23,325 | permissive | [
{
"docstring": "Initialize the log handler for a particular thread. Args: thread_id: The ID of the thread.",
"name": "__init__",
"signature": "def __init__(self, thread_id, formatter=None)"
},
{
"docstring": "Determine whether to emit base on the thread ID.",
"name": "handle",
"signature... | 3 | stack_v2_sparse_classes_30k_train_045950 | Implement the Python class `ThreadLogHandler` described below.
Class description:
Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread(... | Implement the Python class `ThreadLogHandler` described below.
Class description:
Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread(... | 62f66d69ff00af37368a87f41dda8e7be042f119 | <|skeleton|>
class ThreadLogHandler:
"""Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread().ident) logger = logging.getLogger(__n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadLogHandler:
"""Captures the logs of a particular thread. Attributes: thread_id: The ID of the thread of which the logs are being captured. logs (list): A list of formatted log messages. Examples: log_handler = ThreadLogHandler(threading.current_thread().ident) logger = logging.getLogger(__name__) logger... | the_stack_v2_python_sparse | outputs.py | qiuosier/Aries | train | 5 |
d9adbdd34690f68ae968a5b462ef9fa420f53c4d | [
"super().__init__()\nself.msg_chars = MSG_CHARS_COLOR_SUBLIME\nself.msg_ready = MSG_READY_COLOR_SUBLIME",
"if not self.showing:\n return\nfrom random import sample\nmod = len(self.msg_chars)\nrands = [self.msg_chars[x % mod] for x in sample(range(100), 10)]\nBaseProgressStatus.set_status(BaseProgressStatus.FUL... | <|body_start_0|>
super().__init__()
self.msg_chars = MSG_CHARS_COLOR_SUBLIME
self.msg_ready = MSG_READY_COLOR_SUBLIME
<|end_body_0|>
<|body_start_1|>
if not self.showing:
return
from random import sample
mod = len(self.msg_chars)
rands = [self.msg_cha... | Progress status that shows phases of the moon. | ColorSublimeProgressStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorSublimeProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init color sublime like progress status."""
<|body_0|>
def update_progress(self, message):
"""Show next random progress indicator and a custom message."""
... | stack_v2_sparse_classes_75kplus_train_005371 | 3,576 | permissive | [
{
"docstring": "Init color sublime like progress status.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Show next random progress indicator and a custom message.",
"name": "update_progress",
"signature": "def update_progress(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038832 | Implement the Python class `ColorSublimeProgressStatus` described below.
Class description:
Progress status that shows phases of the moon.
Method signatures and docstrings:
- def __init__(self): Init color sublime like progress status.
- def update_progress(self, message): Show next random progress indicator and a cu... | Implement the Python class `ColorSublimeProgressStatus` described below.
Class description:
Progress status that shows phases of the moon.
Method signatures and docstrings:
- def __init__(self): Init color sublime like progress status.
- def update_progress(self, message): Show next random progress indicator and a cu... | c2e8913052f4c9f11433f0a421fbbc4b78699fd6 | <|skeleton|>
class ColorSublimeProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init color sublime like progress status."""
<|body_0|>
def update_progress(self, message):
"""Show next random progress indicator and a custom message."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColorSublimeProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init color sublime like progress status."""
super().__init__()
self.msg_chars = MSG_CHARS_COLOR_SUBLIME
self.msg_ready = MSG_READY_COLOR_SUBLIME
def update_progress... | the_stack_v2_python_sparse | plugin/utils/progress_status.py | niosus/EasyClangComplete | train | 677 |
0ebdb911f22c0005f594da04b78deeee50cc99bc | [
"super(Basic, self).__init__(name, **kwargs)\nself.data_type = data_type\nself.allow_fallback = allow_fallback",
"if isinstance(value, self.data_type):\n return value\ntry:\n return self.data_type(text_type(value))\nexcept ValueError:\n if not self.allow_fallback:\n self.report(value, context)"
] | <|body_start_0|>
super(Basic, self).__init__(name, **kwargs)
self.data_type = data_type
self.allow_fallback = allow_fallback
<|end_body_0|>
<|body_start_1|>
if isinstance(value, self.data_type):
return value
try:
return self.data_type(text_type(value))
... | Basic property to handle int, float and other basic types. | Basic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Basic:
"""Basic property to handle int, float and other basic types."""
def __init__(self, name, data_type, allow_fallback=False, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_005372 | 766 | permissive | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, name, data_type, allow_fallback=False, **kwargs)"
},
{
"docstring": "Handle value.",
"name": "handle",
"signature": "def handle(self, value, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054360 | Implement the Python class `Basic` described below.
Class description:
Basic property to handle int, float and other basic types.
Method signatures and docstrings:
- def __init__(self, name, data_type, allow_fallback=False, **kwargs): Init method.
- def handle(self, value, context): Handle value. | Implement the Python class `Basic` described below.
Class description:
Basic property to handle int, float and other basic types.
Method signatures and docstrings:
- def __init__(self, name, data_type, allow_fallback=False, **kwargs): Init method.
- def handle(self, value, context): Handle value.
<|skeleton|>
class ... | eea9ac18e38c930230cf81b5dca4a9af9fb10d4e | <|skeleton|>
class Basic:
"""Basic property to handle int, float and other basic types."""
def __init__(self, name, data_type, allow_fallback=False, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Basic:
"""Basic property to handle int, float and other basic types."""
def __init__(self, name, data_type, allow_fallback=False, **kwargs):
"""Init method."""
super(Basic, self).__init__(name, **kwargs)
self.data_type = data_type
self.allow_fallback = allow_fallback
... | the_stack_v2_python_sparse | knowit/properties/basic.py | labrys/knowit | train | 0 |
cdcf088e8b985d64fefc3cb3e2f823bc3f11c140 | [
"self.left_eye_percentage = left_eye_percentage\nself.desired_face_width = desired_face_width\nself.desired_face_height = desired_face_height\nself.predictor = LandmarkPredictor(predictor_type)\nif self.desired_face_height is None:\n self.desired_face_height = self.desired_face_width",
"shape = self.predictor.... | <|body_start_0|>
self.left_eye_percentage = left_eye_percentage
self.desired_face_width = desired_face_width
self.desired_face_height = desired_face_height
self.predictor = LandmarkPredictor(predictor_type)
if self.desired_face_height is None:
self.desired_face_height... | FaceAligner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye ... | stack_v2_sparse_classes_75kplus_train_005373 | 4,971 | no_license | [
{
"docstring": "Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye position. For this variable, it is common to see percentages within the range of 20-40%. These percentages control how much of the face is visible af... | 2 | stack_v2_sparse_classes_30k_train_038362 | Implement the Python class `FaceAligner` described below.
Class description:
Implement the FaceAligner class.
Method signatures and docstrings:
- def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'): Define aligner for all images. :param left_eye_... | Implement the Python class `FaceAligner` described below.
Class description:
Implement the FaceAligner class.
Method signatures and docstrings:
- def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'): Define aligner for all images. :param left_eye_... | 3d80158f3261ddff2bd455ce883f57d6fc9ede43 | <|skeleton|>
class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye position. For ... | the_stack_v2_python_sparse | image_alterations_detector/face_transform/face_alignment/face_aligner.py | Giulianini/image-alterations-detector | train | 1 | |
c18be3dafb6dbdcf95c0bccfd6d7f4488bcd0905 | [
"if kwargs.has_key('opac_url'):\n self.opac_url = kwargs.get('opac_url')\nelse:\n self.opac_url = None\nif kwargs.has_key('item_id'):\n self.item_id = kwargs.get('item_id')\n raw_xml_url = self.opac_url + self.item_id\n try:\n raw_xml = urllib2.urlopen(raw_xml_url).read()\n self.item_xm... | <|body_start_0|>
if kwargs.has_key('opac_url'):
self.opac_url = kwargs.get('opac_url')
else:
self.opac_url = None
if kwargs.has_key('item_id'):
self.item_id = kwargs.get('item_id')
raw_xml_url = self.opac_url + self.item_id
try:
... | `ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode. | ItemBot | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemBot:
"""`ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode."""
def __init__(self, **kwargs):
"""Initializes web OPAC address from passed in variable."""
<|body_0|>
def ca... | stack_v2_sparse_classes_75kplus_train_005374 | 8,869 | permissive | [
{
"docstring": "Initializes web OPAC address from passed in variable.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Retrieves call number from XML by first checking to see if there is a 090 and then tries 099 field. :rtype: string or None",
"name": "cal... | 5 | null | Implement the Python class `ItemBot` described below.
Class description:
`ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes web OPAC address f... | Implement the Python class `ItemBot` described below.
Class description:
`ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes web OPAC address f... | b5c44fa008f9afb4441988803921a93ffd615c30 | <|skeleton|>
class ItemBot:
"""`ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode."""
def __init__(self, **kwargs):
"""Initializes web OPAC address from passed in variable."""
<|body_0|>
def ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemBot:
"""`ItemBot` uses the eulxml module to capture specific information about an item in a III Millennium ILS from a method call to a web OPAC in XML mode."""
def __init__(self, **kwargs):
"""Initializes web OPAC address from passed in variable."""
if kwargs.has_key('opac_url'):
... | the_stack_v2_python_sparse | aristotle/apps/vendors/iii/bots/iiibots.py | jermnelson/Discover-Aristotle | train | 15 |
d8b6e65252235b67eab89ef70134e23cda6c83c1 | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units=units)\nself.U = tf.keras.layers.Dense(units=units)\nself.V = tf.keras.layers.Dense(units=1)",
"exp_s_prev = tf.expand_dims(s_prev, axis=1)\nscore = self.V(tf.nn.tanh(self.W(exp_s_prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(score, axis=1)\ncon... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
self.V = tf.keras.layers.Dense(units=1)
<|end_body_0|>
<|body_start_1|>
exp_s_prev = tf.expand_dims(s_prev, axis=1)
score = self.V(tf.nn.tanh(self.... | Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""* s_prev (batch, units) contains the previo... | stack_v2_sparse_classes_75kplus_train_005375 | 1,769 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "* s_prev (batch, units) contains the previous decoder hidden state. * hidden_states (batch, input_seq_len, units) contains the outputs of the encoder Returns: context, weights",
... | 2 | stack_v2_sparse_classes_30k_train_041707 | Implement the Python class `SelfAttention` described below.
Class description:
Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Class constructor
- def call(self, s_prev, hidden_states): * s_prev (batch, units... | Implement the Python class `SelfAttention` described below.
Class description:
Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Class constructor
- def call(self, s_prev, hidden_states): * s_prev (batch, units... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class SelfAttention:
"""Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""* s_prev (batch, units) contains the previo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""Inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor"""
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | felipeserna/holbertonschool-machine_learning | train | 0 |
699ee7c085ae75873aad30a4a81c344c6e758275 | [
"super().__init__()\nif nn_embedding is not None:\n self.embedding = nn.Embedding.from_pretrained(nn_embedding)\nelif sum(field_sizes) is not None and embed_size is not None:\n self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs)\nelse:\n raise ValueError('missing required arguments')\nsel... | <|body_start_0|>
super().__init__()
if nn_embedding is not None:
self.embedding = nn.Embedding.from_pretrained(nn_embedding)
elif sum(field_sizes) is not None and embed_size is not None:
self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs)
else:
... | Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding. | MultiIndicesEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par... | stack_v2_sparse_classes_75kplus_train_005376 | 4,009 | permissive | [
{
"docstring": "Initialize MultiIndicesEmbedding. Args: embed_size (int): size of embedding tensor. Defaults to None field_sizes (List[int]): list of inputs fields' sizes. Defaults to None nn_embedding (nn.Parameter, optional): pretrained embedding values. Defaults to None device (str): device of torch. Default... | 4 | stack_v2_sparse_classes_30k_train_053443 | Implement the Python class `MultiIndicesEmbedding` described below.
Class description:
Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, ... | Implement the Python class `MultiIndicesEmbedding` described below.
Class description:
Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, ... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Parameter]=None,... | the_stack_v2_python_sparse | torecsys/inputs/base/multi_indices_emb.py | p768lwy3/torecsys | train | 98 |
7c5f30360040696d6a96c9f862ed6feb90ff500c | [
"path = '/C.1/time series 1'\nfd = aff4.FACTORY.Create(path, 'GRRTimeSeries', token=self.token)\nnow = int(time.time() * 1000000)\ntimes = [random.randint(0, 1000) * 1000000 + now for _ in range(100)]\nfor t in times:\n event = rdfvalue.Event(timestamp=t)\n event.stat.st_mtime = t / 1000000\n event.stat.pa... | <|body_start_0|>
path = '/C.1/time series 1'
fd = aff4.FACTORY.Create(path, 'GRRTimeSeries', token=self.token)
now = int(time.time() * 1000000)
times = [random.randint(0, 1000) * 1000000 + now for _ in range(100)]
for t in times:
event = rdfvalue.Event(timestamp=t)
... | Test the timeline implementation. | TimelineTest | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimelineTest:
"""Test the timeline implementation."""
def testTimeSeries(self):
"""Check that timeseries sort events by timestamps."""
<|body_0|>
def testTimeSeriesQuery(self):
"""Check that we can filter by query string."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_005377 | 2,810 | permissive | [
{
"docstring": "Check that timeseries sort events by timestamps.",
"name": "testTimeSeries",
"signature": "def testTimeSeries(self)"
},
{
"docstring": "Check that we can filter by query string.",
"name": "testTimeSeriesQuery",
"signature": "def testTimeSeriesQuery(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054755 | Implement the Python class `TimelineTest` described below.
Class description:
Test the timeline implementation.
Method signatures and docstrings:
- def testTimeSeries(self): Check that timeseries sort events by timestamps.
- def testTimeSeriesQuery(self): Check that we can filter by query string. | Implement the Python class `TimelineTest` described below.
Class description:
Test the timeline implementation.
Method signatures and docstrings:
- def testTimeSeries(self): Check that timeseries sort events by timestamps.
- def testTimeSeriesQuery(self): Check that we can filter by query string.
<|skeleton|>
class ... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class TimelineTest:
"""Test the timeline implementation."""
def testTimeSeries(self):
"""Check that timeseries sort events by timestamps."""
<|body_0|>
def testTimeSeriesQuery(self):
"""Check that we can filter by query string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimelineTest:
"""Test the timeline implementation."""
def testTimeSeries(self):
"""Check that timeseries sort events by timestamps."""
path = '/C.1/time series 1'
fd = aff4.FACTORY.Create(path, 'GRRTimeSeries', token=self.token)
now = int(time.time() * 1000000)
tim... | the_stack_v2_python_sparse | lib/aff4_objects/timeline_test.py | defaultnamehere/grr | train | 3 |
d051c56739e63411295c24497eb538752b66894a | [
"print('Initializing.......')\ndataset = pd.read_csv('https://guneet-public-data.s3.ap-south-1.amazonaws.com/Salary_Data.csv')\nx = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0... | <|body_start_0|>
print('Initializing.......')
dataset = pd.read_csv('https://guneet-public-data.s3.ap-south-1.amazonaws.com/Salary_Data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
from sklearn.model_selection import train_test_split
x_train, x_tes... | Model template. You can load your model parameters in __init__ from a location accessible at runtime | MyModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyModel:
"""Model template. You can load your model parameters in __init__ from a location accessible at runtime"""
def __init__(self):
"""Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your seldondeployment kubernet... | stack_v2_sparse_classes_75kplus_train_005378 | 1,624 | no_license | [
{
"docstring": "Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your seldondeployment kubernetes resource manifest.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a prediction. Parameters ------... | 2 | stack_v2_sparse_classes_30k_train_049626 | Implement the Python class `MyModel` described below.
Class description:
Model template. You can load your model parameters in __init__ from a location accessible at runtime
Method signatures and docstrings:
- def __init__(self): Add any initialization parameters. These will be passed at runtime from the graph defini... | Implement the Python class `MyModel` described below.
Class description:
Model template. You can load your model parameters in __init__ from a location accessible at runtime
Method signatures and docstrings:
- def __init__(self): Add any initialization parameters. These will be passed at runtime from the graph defini... | f14e98441ac75a71042b37f4e2ff21467c1a06f8 | <|skeleton|>
class MyModel:
"""Model template. You can load your model parameters in __init__ from a location accessible at runtime"""
def __init__(self):
"""Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your seldondeployment kubernet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyModel:
"""Model template. You can load your model parameters in __init__ from a location accessible at runtime"""
def __init__(self):
"""Add any initialization parameters. These will be passed at runtime from the graph definition parameters defined in your seldondeployment kubernetes resource m... | the_stack_v2_python_sparse | Scikit-Learn/Regression/Simple-Linear-Regression/Seldon/src/MyModel.py | lakshikaparihar/Machine_Learning_Examples | train | 0 |
d9f8e75e72916e21299d82aeddbce18fd623817f | [
"super(Acer, self).__init__()\nself.runner = runner\nself.model = model\nself.buffer = buffer\nself.log_interval = log_interval\nself.t_start = None\nself.episode_stats = EpisodeStats(runner.n_steps, runner.n_env)\nself.steps = None",
"runner, model, buffer, steps = (self.runner, self.model, self.buffer, self.ste... | <|body_start_0|>
super(Acer, self).__init__()
self.runner = runner
self.model = model
self.buffer = buffer
self.log_interval = log_interval
self.t_start = None
self.episode_stats = EpisodeStats(runner.n_steps, runner.n_env)
self.steps = None
<|end_body_0|>... | Acer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Acer:
def __init__(self, runner, model, buffer, log_interval):
"""Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model :param model: (Model) The model to learn :param buffer: (Buffer) The observation buffer :par... | stack_v2_sparse_classes_75kplus_train_005379 | 22,723 | permissive | [
{
"docstring": "Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model :param model: (Model) The model to learn :param buffer: (Buffer) The observation buffer :param log_interval: (int) The number of timesteps before logging.",
"name... | 2 | null | Implement the Python class `Acer` described below.
Class description:
Implement the Acer class.
Method signatures and docstrings:
- def __init__(self, runner, model, buffer, log_interval): Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model... | Implement the Python class `Acer` described below.
Class description:
Implement the Acer class.
Method signatures and docstrings:
- def __init__(self, runner, model, buffer, log_interval): Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model... | 5f11927a4420b46bed873c4a8477a55153d37bcd | <|skeleton|>
class Acer:
def __init__(self, runner, model, buffer, log_interval):
"""Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model :param model: (Model) The model to learn :param buffer: (Buffer) The observation buffer :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Acer:
def __init__(self, runner, model, buffer, log_interval):
"""Wrapper for the ACER model object :param runner: (AbstractEnvRunner) The runner to learn the policy of an environment for a model :param model: (Model) The model to learn :param buffer: (Buffer) The observation buffer :param log_interva... | the_stack_v2_python_sparse | baselines/acer/acer_simple.py | northtiger/stable-baselines | train | 0 | |
a5e8edfbce3cb5030a8eba893d5506e4b7fec966 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_admin', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | Custom user model manager where email is the unique identifiers for authentication instead of usernames. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus_train_005380 | 8,138 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | stack_v2_sparse_classes_30k_train_000736 | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | 16175feffbee1c0cac4b4f11e9396a07fe0472f6 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueEr... | the_stack_v2_python_sparse | codeine_django/common/models.py | ptm108/codeine-django | train | 2 |
d0c65016615912c04cc74173b5490bb63f4c158f | [
"queryset = BookInfo.objects.all()\nbook_list = []\nfor book in queryset:\n book_list.append({'id': book.id, 'name': book.name, 'pub_date': book.pub_date})\nreturn JsonResponse(book_list, safe=False)",
"json_bytes = request.body\njson_str = json_bytes.decode()\nbook_dict = json.loads(json_str)\nbook = BookInfo... | <|body_start_0|>
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
book_list.append({'id': book.id, 'name': book.name, 'pub_date': book.pub_date})
return JsonResponse(book_list, safe=False)
<|end_body_0|>
<|body_start_1|>
json_bytes = request.bod... | 图书列表 | BookListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookListView:
"""图书列表"""
def get(self, request):
"""查询所有图书 路由:GET /books/"""
<|body_0|>
def post(self, request):
"""新增图书 路由:POST /books/"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = BookInfo.objects.all()
book_list = []
... | stack_v2_sparse_classes_75kplus_train_005381 | 4,877 | no_license | [
{
"docstring": "查询所有图书 路由:GET /books/",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增图书 路由:POST /books/",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044381 | Implement the Python class `BookListView` described below.
Class description:
图书列表
Method signatures and docstrings:
- def get(self, request): 查询所有图书 路由:GET /books/
- def post(self, request): 新增图书 路由:POST /books/ | Implement the Python class `BookListView` described below.
Class description:
图书列表
Method signatures and docstrings:
- def get(self, request): 查询所有图书 路由:GET /books/
- def post(self, request): 新增图书 路由:POST /books/
<|skeleton|>
class BookListView:
"""图书列表"""
def get(self, request):
"""查询所有图书 路由:GET /b... | 206592bb8464de40e8eaa992e040f05b69aab2c6 | <|skeleton|>
class BookListView:
"""图书列表"""
def get(self, request):
"""查询所有图书 路由:GET /books/"""
<|body_0|>
def post(self, request):
"""新增图书 路由:POST /books/"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookListView:
"""图书列表"""
def get(self, request):
"""查询所有图书 路由:GET /books/"""
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
book_list.append({'id': book.id, 'name': book.name, 'pub_date': book.pub_date})
return JsonResponse(book_... | the_stack_v2_python_sparse | django/bookmanager/book/views.py | maoqiansheng/python_interview | train | 1 |
b726e75289f280b1b11c95fda15fa67644cb97fb | [
"super().__init__(name=name)\nself.reference_grid = layer_util.get_reference_grid(image_size)\nself.transform_initial = tf.constant_initializer(value=list(np.eye(4, 3).reshape(-1)))\nself._flatten = tfkl.Flatten()\nself._dense = tfkl.Dense(units=12, bias_initializer=self.transform_initial)",
"if isinstance(inputs... | <|body_start_0|>
super().__init__(name=name)
self.reference_grid = layer_util.get_reference_grid(image_size)
self.transform_initial = tf.constant_initializer(value=list(np.eye(4, 3).reshape(-1)))
self._flatten = tfkl.Flatten()
self._dense = tfkl.Dense(units=12, bias_initializer=s... | AffineHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AffineHead:
def __init__(self, image_size: tuple, name: str='AffineHead'):
"""Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer"""
<|body_0|>
def call(self, inputs: Union[tf.Tensor, List], **kwargs) -> Tuple[tf.Tensor, tf.Tensor]:
"""... | stack_v2_sparse_classes_75kplus_train_005382 | 4,852 | permissive | [
{
"docstring": "Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer",
"name": "__init__",
"signature": "def __init__(self, image_size: tuple, name: str='AffineHead')"
},
{
"docstring": ":param inputs: a tensor or a list of tensor with length 1 :param kwargs: additi... | 3 | stack_v2_sparse_classes_30k_train_021010 | Implement the Python class `AffineHead` described below.
Class description:
Implement the AffineHead class.
Method signatures and docstrings:
- def __init__(self, image_size: tuple, name: str='AffineHead'): Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer
- def call(self, inputs: Uni... | Implement the Python class `AffineHead` described below.
Class description:
Implement the AffineHead class.
Method signatures and docstrings:
- def __init__(self, image_size: tuple, name: str='AffineHead'): Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer
- def call(self, inputs: Uni... | 650a2f1a88ad3c6932be305d6a98a36e26feedc6 | <|skeleton|>
class AffineHead:
def __init__(self, image_size: tuple, name: str='AffineHead'):
"""Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer"""
<|body_0|>
def call(self, inputs: Union[tf.Tensor, List], **kwargs) -> Tuple[tf.Tensor, tf.Tensor]:
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AffineHead:
def __init__(self, image_size: tuple, name: str='AffineHead'):
"""Init. :param image_size: such as (dim1, dim2, dim3) :param name: name of the layer"""
super().__init__(name=name)
self.reference_grid = layer_util.get_reference_grid(image_size)
self.transform_initial... | the_stack_v2_python_sparse | deepreg/model/backbone/global_net.py | DeepRegNet/DeepReg | train | 509 | |
60f48bb88b1b6772339b4020c90f26d9296be2b9 | [
"TaskManager.__init__(self)\nif task_assignment_timeout is None or task_assignment_timeout <= 0:\n task_assignment_timeout = 0\ntask.props[_KEY_ORDER] = send_order\ntask.props[_KEY_TASK_ASSIGN_TIMEOUT] = task_assignment_timeout",
"task = client_task.task\nif len(task.client_tasks) > 0:\n if client_task.task... | <|body_start_0|>
TaskManager.__init__(self)
if task_assignment_timeout is None or task_assignment_timeout <= 0:
task_assignment_timeout = 0
task.props[_KEY_ORDER] = send_order
task.props[_KEY_TASK_ASSIGN_TIMEOUT] = task_assignment_timeout
<|end_body_0|>
<|body_start_1|>
... | SendTaskManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a clie... | stack_v2_sparse_classes_75kplus_train_005383 | 4,727 | permissive | [
{
"docstring": "Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a client requesting its task",
"name": "__init__",
"signature": "def __init__(self, task: Task, send_order... | 3 | stack_v2_sparse_classes_30k_train_042521 | Implement the Python class `SendTaskManager` described below.
Class description:
Implement the SendTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout): Task manager for send controller. Args: task (Task): an instance of Task send_order ... | Implement the Python class `SendTaskManager` described below.
Class description:
Implement the SendTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout): Task manager for send controller. Args: task (Task): an instance of Task send_order ... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a clie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendTaskManager:
def __init__(self, task: Task, send_order: SendOrder, task_assignment_timeout):
"""Task manager for send controller. Args: task (Task): an instance of Task send_order (SendOrder): the order of clients to receive task task_assignment_timeout (int): timeout value on a client requesting ... | the_stack_v2_python_sparse | nvflare/apis/impl/send_manager.py | NVIDIA/NVFlare | train | 442 | |
3770ea0140cfe9eada6fd11913853ed890a687c9 | [
"res = []\nif not root:\n return res\nfrontier = [root]\nwhile frontier:\n expand = frontier.pop()\n res.append(expand.val)\n for child in [expand.left, expand.right]:\n if child:\n frontier.append(child)\nreturn res[::-1]",
"res = []\nif not root:\n return res\nfrontier = []\nwhi... | <|body_start_0|>
res = []
if not root:
return res
frontier = [root]
while frontier:
expand = frontier.pop()
res.append(expand.val)
for child in [expand.left, expand.right]:
if child:
frontier.append(child... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal(self, root):
""":type root: Tree... | stack_v2_sparse_classes_75kplus_train_005384 | 1,164 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "postorderTraversal",
"signature": "def postorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"d... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal(self, root):
""":type root: Tree... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
res = []
if not root:
return res
frontier = [root]
while frontier:
expand = frontier.pop()
res.append(expand.val)
for child in [exp... | the_stack_v2_python_sparse | LeetCodes/Trees/Binary Tree Postorder Traversal.py | chutianwen/LeetCodes | train | 0 | |
d765bd4196eb3ca05265a641e83201eae7c2af77 | [
"server = g.db.query(Server).get(server_id)\nif not server:\n log.warning('Requested a non-existant battleserver: %s', server_id)\n abort(http_client.NOT_FOUND, description='Server not found')\nmachine_id = server.machine_id\nrecord = server.as_dict()\nrecord['url'] = url_for('servers.entry', server_id=server... | <|body_start_0|>
server = g.db.query(Server).get(server_id)
if not server:
log.warning('Requested a non-existant battleserver: %s', server_id)
abort(http_client.NOT_FOUND, description='Server not found')
machine_id = server.machine_id
record = server.as_dict()
... | Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource. | ServerAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerAPI:
"""Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource."""
def get(self, server_id):
... | stack_v2_sparse_classes_75kplus_train_005385 | 16,872 | permissive | [
{
"docstring": "Get information about a single battle server instance. Returns information from the machine and the associated battle if found.",
"name": "get",
"signature": "def get(self, server_id)"
},
{
"docstring": "The battleserver management (celery) process calls this to update the status... | 2 | stack_v2_sparse_classes_30k_train_038087 | Implement the Python class `ServerAPI` described below.
Class description:
Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource.
... | Implement the Python class `ServerAPI` described below.
Class description:
Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource.
... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class ServerAPI:
"""Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource."""
def get(self, server_id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerAPI:
"""Interface to battle servers instances. A battleserver instance is a single run of a battleserver executable. The battleserver will have a single battle on it. You should never have a battle resource without an associated battleserver resource."""
def get(self, server_id):
"""Get inf... | the_stack_v2_python_sparse | driftbase/api/servers.py | dgnorth/drift-base | train | 1 |
dea229123ade83bac1738f51a9b8f20b249397f3 | [
"xlsx_file = BytesIO()\nwith cls._open_worksheet(xlsx_file) as worksheet:\n cls._populate_worksheet(worksheet, categories, series)\nreturn xlsx_file.getvalue()",
"workbook = Workbook(xlsx_file, {'in_memory': True})\nworksheet = workbook.add_worksheet()\nyield worksheet\nworkbook.close()",
"worksheet.write_co... | <|body_start_0|>
xlsx_file = BytesIO()
with cls._open_worksheet(xlsx_file) as worksheet:
cls._populate_worksheet(worksheet, categories, series)
return xlsx_file.getvalue()
<|end_body_0|>
<|body_start_1|>
workbook = Workbook(xlsx_file, {'in_memory': True})
worksheet =... | Service object that knows how to write an Excel workbook for chart data. | WorkbookWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbookWriter:
"""Service object that knows how to write an Excel workbook for chart data."""
def xlsx_blob(cls, categories, series):
"""Return the byte stream of an Excel file formatted as chart data for a chart having *categories* and *series*."""
<|body_0|>
def _open... | stack_v2_sparse_classes_75kplus_train_005386 | 1,885 | permissive | [
{
"docstring": "Return the byte stream of an Excel file formatted as chart data for a chart having *categories* and *series*.",
"name": "xlsx_blob",
"signature": "def xlsx_blob(cls, categories, series)"
},
{
"docstring": "Enable XlsxWriter Worksheet object to be opened, operated on, and then aut... | 3 | stack_v2_sparse_classes_30k_train_054144 | Implement the Python class `WorkbookWriter` described below.
Class description:
Service object that knows how to write an Excel workbook for chart data.
Method signatures and docstrings:
- def xlsx_blob(cls, categories, series): Return the byte stream of an Excel file formatted as chart data for a chart having *categ... | Implement the Python class `WorkbookWriter` described below.
Class description:
Service object that knows how to write an Excel workbook for chart data.
Method signatures and docstrings:
- def xlsx_blob(cls, categories, series): Return the byte stream of an Excel file formatted as chart data for a chart having *categ... | 3d3528d419c9123e5bed694a7c26245cfd73a0a7 | <|skeleton|>
class WorkbookWriter:
"""Service object that knows how to write an Excel workbook for chart data."""
def xlsx_blob(cls, categories, series):
"""Return the byte stream of an Excel file formatted as chart data for a chart having *categories* and *series*."""
<|body_0|>
def _open... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkbookWriter:
"""Service object that knows how to write an Excel workbook for chart data."""
def xlsx_blob(cls, categories, series):
"""Return the byte stream of an Excel file formatted as chart data for a chart having *categories* and *series*."""
xlsx_file = BytesIO()
with cls... | the_stack_v2_python_sparse | pptx/chart/xlsx.py | clairehsun/org-chart-builder | train | 0 |
77094baf032fa65b36d5f9f4242dd9957a7ae8b4 | [
"super(EditForm, self).__init__(*args, **kwargs)\nfor concept in get_concept_list():\n self.fields['response_%d' % concept.id] = forms.CharField(label=_('%s response' % concept), required=False, widget=forms.Textarea())",
"i = self.instance\ni.interviewee = self.cleaned_data.get('interviewee')\ni.date_of_inter... | <|body_start_0|>
super(EditForm, self).__init__(*args, **kwargs)
for concept in get_concept_list():
self.fields['response_%d' % concept.id] = forms.CharField(label=_('%s response' % concept), required=False, widget=forms.Textarea())
<|end_body_0|>
<|body_start_1|>
i = self.instance
... | EditForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditForm:
def __init__(self, *args, **kwargs):
"""This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data."""
<|body_0|>
def save(self):
"""Saves an updated interview. ... | stack_v2_sparse_classes_75kplus_train_005387 | 11,505 | permissive | [
{
"docstring": "This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Saves an updated interview. Sinc... | 2 | stack_v2_sparse_classes_30k_train_016055 | Implement the Python class `EditForm` described below.
Class description:
Implement the EditForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as... | Implement the Python class `EditForm` described below.
Class description:
Implement the EditForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as... | 4f5fec75d1425de28a26eb3297ea5d4b0ed96c16 | <|skeleton|>
class EditForm:
def __init__(self, *args, **kwargs):
"""This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data."""
<|body_0|>
def save(self):
"""Saves an updated interview. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditForm:
def __init__(self, *args, **kwargs):
"""This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data."""
super(EditForm, self).__init__(*args, **kwargs)
for concept in get_concept_li... | the_stack_v2_python_sparse | conceptum/interviews/forms.py | kevincwebb/conceptum | train | 0 | |
9bea945aefe2568c360c83b43c0e59a3f5fafed0 | [
"if not self.options.physical.user or not self.options.physical.password:\n raise CuckooCriticalError('Physical machine credentials are missing, please add it to the config file')\nfor machine in self.machines():\n if self._status(machine.label) != self.RUNNING:\n raise CuckooCriticalError('Physical ma... | <|body_start_0|>
if not self.options.physical.user or not self.options.physical.password:
raise CuckooCriticalError('Physical machine credentials are missing, please add it to the config file')
for machine in self.machines():
if self._status(machine.label) != self.RUNNING:
... | Manage physical sandboxes. | Physical | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Physical:
"""Manage physical sandboxes."""
def _initialize_check(self):
"""Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical machines are offline."""
<|body_0|>
def _get... | stack_v2_sparse_classes_75kplus_train_005388 | 5,469 | no_license | [
{
"docstring": "Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical machines are offline.",
"name": "_initialize_check",
"signature": "def _initialize_check(self)"
},
{
"docstring": "Retrieve all ... | 6 | stack_v2_sparse_classes_30k_train_011102 | Implement the Python class `Physical` described below.
Class description:
Manage physical sandboxes.
Method signatures and docstrings:
- def _initialize_check(self): Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical ... | Implement the Python class `Physical` described below.
Class description:
Manage physical sandboxes.
Method signatures and docstrings:
- def _initialize_check(self): Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical ... | 36434f6b8f80833b2328eb096ac239f7932a1eb3 | <|skeleton|>
class Physical:
"""Manage physical sandboxes."""
def _initialize_check(self):
"""Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical machines are offline."""
<|body_0|>
def _get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Physical:
"""Manage physical sandboxes."""
def _initialize_check(self):
"""Ensures that credentials have been entered into the config file. @raise CuckooCriticalError: if no credentials were provided or if one or more physical machines are offline."""
if not self.options.physical.user or ... | the_stack_v2_python_sparse | modules/machinery/physical.py | open-nsm/dockoo-cuckoo | train | 5 |
2bdc4dee3b17088e1c890fa69099dca07f972c08 | [
"if self.sent:\n return 'images/double_right_noun.png'\nelse:\n return 'images/double_left_noun.png'\npass",
"if self.sent:\n return 'right'\nelse:\n return 'left'\npass",
"if self.sent:\n return (255, 255, 255)\nelse:\n return (0, 0, 0)\npass",
"if not self.sent:\n return (255, 255, 255)... | <|body_start_0|>
if self.sent:
return 'images/double_right_noun.png'
else:
return 'images/double_left_noun.png'
pass
<|end_body_0|>
<|body_start_1|>
if self.sent:
return 'right'
else:
return 'left'
pass
<|end_body_1|>
<|bo... | parent message type | Message | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""parent message type"""
def get_arrow(self):
"""returns appropriate arrow based on whether it was sent or not"""
<|body_0|>
def alignment(self):
"""returns appropriate alignment based on whether it was sent or not"""
<|body_1|>
def get_col... | stack_v2_sparse_classes_75kplus_train_005389 | 11,693 | permissive | [
{
"docstring": "returns appropriate arrow based on whether it was sent or not",
"name": "get_arrow",
"signature": "def get_arrow(self)"
},
{
"docstring": "returns appropriate alignment based on whether it was sent or not",
"name": "alignment",
"signature": "def alignment(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_012783 | Implement the Python class `Message` described below.
Class description:
parent message type
Method signatures and docstrings:
- def get_arrow(self): returns appropriate arrow based on whether it was sent or not
- def alignment(self): returns appropriate alignment based on whether it was sent or not
- def get_color(s... | Implement the Python class `Message` described below.
Class description:
parent message type
Method signatures and docstrings:
- def get_arrow(self): returns appropriate arrow based on whether it was sent or not
- def alignment(self): returns appropriate alignment based on whether it was sent or not
- def get_color(s... | 14588693a639ad38a35305d6c9ab92bd99b32355 | <|skeleton|>
class Message:
"""parent message type"""
def get_arrow(self):
"""returns appropriate arrow based on whether it was sent or not"""
<|body_0|>
def alignment(self):
"""returns appropriate alignment based on whether it was sent or not"""
<|body_1|>
def get_col... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Message:
"""parent message type"""
def get_arrow(self):
"""returns appropriate arrow based on whether it was sent or not"""
if self.sent:
return 'images/double_right_noun.png'
else:
return 'images/double_left_noun.png'
pass
def alignment(self):... | the_stack_v2_python_sparse | main.py | maxtheaxe/pollen | train | 7 |
0319f4809c5da883fc22f96ce71a75daf22f95c8 | [
"self.object = self.get_object()\nif self.object != request.user and (not request.user.has_perm('accounts.change_user')):\n raise Http404\nreturn super(UserUpdateView, self).dispatch(request, *args, **kwargs)",
"kwargs = super(UserUpdateView, self).get_form_kwargs(form_class_name)\nif form_class_name == 'user_... | <|body_start_0|>
self.object = self.get_object()
if self.object != request.user and (not request.user.has_perm('accounts.change_user')):
raise Http404
return super(UserUpdateView, self).dispatch(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
kwargs = super(UserUpd... | View for updating a user. | UserUpdateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserUpdateView:
"""View for updating a user."""
def dispatch(self, request, *args, **kwargs):
"""Dispatch the UserUpdateView View"""
<|body_0|>
def get_form_kwargs(self, form_class_name):
"""Get kwargs for the forms."""
<|body_1|>
def get_forms(self,... | stack_v2_sparse_classes_75kplus_train_005390 | 18,678 | permissive | [
{
"docstring": "Dispatch the UserUpdateView View",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Get kwargs for the forms.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self, form_class_name)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_005307 | Implement the Python class `UserUpdateView` described below.
Class description:
View for updating a user.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Dispatch the UserUpdateView View
- def get_form_kwargs(self, form_class_name): Get kwargs for the forms.
- def get_forms(self, for... | Implement the Python class `UserUpdateView` described below.
Class description:
View for updating a user.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Dispatch the UserUpdateView View
- def get_form_kwargs(self, form_class_name): Get kwargs for the forms.
- def get_forms(self, for... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class UserUpdateView:
"""View for updating a user."""
def dispatch(self, request, *args, **kwargs):
"""Dispatch the UserUpdateView View"""
<|body_0|>
def get_form_kwargs(self, form_class_name):
"""Get kwargs for the forms."""
<|body_1|>
def get_forms(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserUpdateView:
"""View for updating a user."""
def dispatch(self, request, *args, **kwargs):
"""Dispatch the UserUpdateView View"""
self.object = self.get_object()
if self.object != request.user and (not request.user.has_perm('accounts.change_user')):
raise Http404
... | the_stack_v2_python_sparse | open_connect/accounts/views.py | ofa/connect | train | 66 |
8193d1e570f1a92d34f99483161fff29aa22b679 | [
"if not root:\n return []\nstack = [root]\nres = []\nwhile stack:\n node = stack.pop()\n if node != None:\n res.append(node.val)\n stack.append(node.right) if node.right else stack.append(None)\n stack.append(node.left) if node.left else stack.append(None)\n else:\n res.appen... | <|body_start_0|>
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
if node != None:
res.append(node.val)
stack.append(node.right) if node.right else stack.append(None)
stack.a... | 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_75kplus_train_005391 | 2,212 | 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_050790 | 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:... | 24c22a0ab8948f8bdf477d9505942958fe7bff1b | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
if node != None:
res.append(nod... | the_stack_v2_python_sparse | 297.Serialize and Deserialize Binary Tree_hard.py | YingYang2015/LeetCode | train | 0 | |
3274aac783d977908178fef541195ebd107c4c4e | [
"Item.__init__(self, name, price, dynamicFunc, classCode=ItemClassCode.VESSEL)\nself.offense = int(offense)\nself.defense = int(defense)\nself.capacity = int(capacity)\nself.maneuverability = int(maneuverability)\nself.stealth = int(stealth)\nself.upgradePoints = int(upgradePoints)\nself.upgrades = []",
"assert s... | <|body_start_0|>
Item.__init__(self, name, price, dynamicFunc, classCode=ItemClassCode.VESSEL)
self.offense = int(offense)
self.defense = int(defense)
self.capacity = int(capacity)
self.maneuverability = int(maneuverability)
self.stealth = int(stealth)
self.upgrad... | Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability. | Vessel | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vessel:
"""Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability."""
def __init__(self, name, offense, defense, capacity, maneuverability, stealth, upgradePoints, price, dynamicFunc=None):
"""name - Name of the vessel. offen... | stack_v2_sparse_classes_75kplus_train_005392 | 5,987 | permissive | [
{
"docstring": "name - Name of the vessel. offense - Rating of the offensive capability of the ship. Determines how much damage you do on attacks. defense - Rating of the defensive capability of the ship. Determines how well you mitigate incoming attacks. capacity - Units of commodities that it can carry. maneu... | 2 | stack_v2_sparse_classes_30k_train_004548 | Implement the Python class `Vessel` described below.
Class description:
Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability.
Method signatures and docstrings:
- def __init__(self, name, offense, defense, capacity, maneuverability, stealth, upgradePoints, p... | Implement the Python class `Vessel` described below.
Class description:
Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability.
Method signatures and docstrings:
- def __init__(self, name, offense, defense, capacity, maneuverability, stealth, upgradePoints, p... | ec3c617ad8b60cb07d526edfbbd8d3483e30fdc0 | <|skeleton|>
class Vessel:
"""Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability."""
def __init__(self, name, offense, defense, capacity, maneuverability, stealth, upgradePoints, price, dynamicFunc=None):
"""name - Name of the vessel. offen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vessel:
"""Class that describes a vessel. This includes all its offsensive and defensive weapons as well as its escapability."""
def __init__(self, name, offense, defense, capacity, maneuverability, stealth, upgradePoints, price, dynamicFunc=None):
"""name - Name of the vessel. offense - Rating o... | the_stack_v2_python_sparse | trader/profiles.py | rossh-42/trader | train | 0 |
4ffb2ffd16e7b95902eb122d434f941f6076f133 | [
"update_dict = request.get_json()\nupdate_dict.pop('created', None)\nupdate_dict.pop('id', None)\nupdate_dict.pop('type', None)\nupdate_dict.pop('modified', None)\ntry:\n obj = get_object_or_404(self.resource_object, id)\n return obj.update(update_dict)\nexcept (YetiSTIXError, ValidationError) as err:\n re... | <|body_start_0|>
update_dict = request.get_json()
update_dict.pop('created', None)
update_dict.pop('id', None)
update_dict.pop('type', None)
update_dict.pop('modified', None)
try:
obj = get_object_or_404(self.resource_object, id)
return obj.update(... | Class describing resources to manipulate Indicator objects. | IndicatorResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndicatorResource:
"""Class describing resources to manipulate Indicator objects."""
def put(self, id):
"""Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or a 404 HTTP status code if the object cannot be found."""... | stack_v2_sparse_classes_75kplus_train_005393 | 2,168 | permissive | [
{
"docstring": "Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or a 404 HTTP status code if the object cannot be found.",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Matches a series of binary objects a... | 2 | stack_v2_sparse_classes_30k_train_016791 | Implement the Python class `IndicatorResource` described below.
Class description:
Class describing resources to manipulate Indicator objects.
Method signatures and docstrings:
- def put(self, id): Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or... | Implement the Python class `IndicatorResource` described below.
Class description:
Class describing resources to manipulate Indicator objects.
Method signatures and docstrings:
- def put(self, id): Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or... | 902db77e0f9dce7b8870ed653a8f7670864d146d | <|skeleton|>
class IndicatorResource:
"""Class describing resources to manipulate Indicator objects."""
def put(self, id):
"""Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or a 404 HTTP status code if the object cannot be found."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndicatorResource:
"""Class describing resources to manipulate Indicator objects."""
def put(self, id):
"""Updates a STIX SDO object. Args: id: The object's primary ID. Returns: A JSON representation of the requested object, or a 404 HTTP status code if the object cannot be found."""
upda... | the_stack_v2_python_sparse | yeti/web/api/indicator.py | yeti-platform/TibetanBrownBear | train | 11 |
b691b6457e83c1a829090ccae968fce304849d2e | [
"object.__init__(self)\nself._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)\nself._time_fn = _time_fn\nself._random_fn = _random_fn",
"try:\n timeout = next(self._timeouts)\nexcept StopIteration:\n timeout = None\nif timeout is not None:\n variation_range = timeout * 0.1\n timeout += self._random_fn() * ... | <|body_start_0|>
object.__init__(self)
self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
self._time_fn = _time_fn
self._random_fn = _random_fn
<|end_body_0|>
<|body_start_1|>
try:
timeout = next(self._timeouts)
except StopIteration:
timeout = None
... | Class with lock acquire timeout strategy. | LockAttemptTimeoutStrategy | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockAttemptTimeoutStrategy:
"""Class with lock acquire timeout strategy."""
def __init__(self, _time_fn=time.time, _random_fn=random.random):
"""Initializes this class. @param _time_fn: Time function for unittests @param _random_fn: Random number generator for unittests"""
<|... | stack_v2_sparse_classes_75kplus_train_005394 | 25,079 | permissive | [
{
"docstring": "Initializes this class. @param _time_fn: Time function for unittests @param _random_fn: Random number generator for unittests",
"name": "__init__",
"signature": "def __init__(self, _time_fn=time.time, _random_fn=random.random)"
},
{
"docstring": "Returns the timeout for the next ... | 2 | stack_v2_sparse_classes_30k_train_010386 | Implement the Python class `LockAttemptTimeoutStrategy` described below.
Class description:
Class with lock acquire timeout strategy.
Method signatures and docstrings:
- def __init__(self, _time_fn=time.time, _random_fn=random.random): Initializes this class. @param _time_fn: Time function for unittests @param _rando... | Implement the Python class `LockAttemptTimeoutStrategy` described below.
Class description:
Class with lock acquire timeout strategy.
Method signatures and docstrings:
- def __init__(self, _time_fn=time.time, _random_fn=random.random): Initializes this class. @param _time_fn: Time function for unittests @param _rando... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class LockAttemptTimeoutStrategy:
"""Class with lock acquire timeout strategy."""
def __init__(self, _time_fn=time.time, _random_fn=random.random):
"""Initializes this class. @param _time_fn: Time function for unittests @param _random_fn: Random number generator for unittests"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LockAttemptTimeoutStrategy:
"""Class with lock acquire timeout strategy."""
def __init__(self, _time_fn=time.time, _random_fn=random.random):
"""Initializes this class. @param _time_fn: Time function for unittests @param _random_fn: Random number generator for unittests"""
object.__init__... | the_stack_v2_python_sparse | lib/mcpu.py | ganeti/ganeti | train | 465 |
796c97fa706620ae501f9414f89251b4409d38ea | [
"self.ensure_one()\nif self.communication_channel != 'email':\n return False\nif self.state in ('sent', 'done'):\n raise ValidationError(_('This communication is already sent.'))\nlines_2be_processed = self.credit_control_line_ids.filtered(lambda line: line.state != 'sent')\nif not lines_2be_processed:\n r... | <|body_start_0|>
self.ensure_one()
if self.communication_channel != 'email':
return False
if self.state in ('sent', 'done'):
raise ValidationError(_('This communication is already sent.'))
lines_2be_processed = self.credit_control_line_ids.filtered(lambda line: li... | CreditControlCommunication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
<|body_0|>
def _compute_credit_control_lines_html(self):
"""This method renders the qweb template and returns the result as HTML. :return: HTML strin... | stack_v2_sparse_classes_75kplus_train_005395 | 3,309 | no_license | [
{
"docstring": "Send account follow-up email to the customer. :return:",
"name": "action_send_email",
"signature": "def action_send_email(self)"
},
{
"docstring": "This method renders the qweb template and returns the result as HTML. :return: HTML string",
"name": "_compute_credit_control_li... | 4 | stack_v2_sparse_classes_30k_train_025756 | Implement the Python class `CreditControlCommunication` described below.
Class description:
Implement the CreditControlCommunication class.
Method signatures and docstrings:
- def action_send_email(self): Send account follow-up email to the customer. :return:
- def _compute_credit_control_lines_html(self): This metho... | Implement the Python class `CreditControlCommunication` described below.
Class description:
Implement the CreditControlCommunication class.
Method signatures and docstrings:
- def action_send_email(self): Send account follow-up email to the customer. :return:
- def _compute_credit_control_lines_html(self): This metho... | c04e2b9730db07848c153d8245d2df65ec4e2c8f | <|skeleton|>
class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
<|body_0|>
def _compute_credit_control_lines_html(self):
"""This method renders the qweb template and returns the result as HTML. :return: HTML strin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreditControlCommunication:
def action_send_email(self):
"""Send account follow-up email to the customer. :return:"""
self.ensure_one()
if self.communication_channel != 'email':
return False
if self.state in ('sent', 'done'):
raise ValidationError(_('Thi... | the_stack_v2_python_sparse | altinkaya_credit_control/models/credit_control_communication.py | aaltinisik/customaddons | train | 15 | |
3f0f5c8fccb7fefc63bf8f37f99443721a659ad8 | [
"l = heap.left(i)\nr = heap.right(i)\nlargest = 0\nif l <= heap.heapsize(A) and A[l] >= A[i]:\n largest = l\nelse:\n largest = i\nif r <= heap.heapsize(A) and A[r] >= A[largest]:\n largest = r\nif largest != i:\n A[i], A[largest] = (A[largest], A[i])\n self.maxheapify(A, largest)\nreturn A",
"count... | <|body_start_0|>
l = heap.left(i)
r = heap.right(i)
largest = 0
if l <= heap.heapsize(A) and A[l] >= A[i]:
largest = l
else:
largest = i
if r <= heap.heapsize(A) and A[r] >= A[largest]:
largest = r
if largest != i:
A... | CLRS 第六章 6.2 算法函数和笔记 | Chapter6_2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_0|>
def maxheapify_quick(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_1|>
def minheapify(self, A, i):
"""保持堆:使某一个结点i成为最小堆... | stack_v2_sparse_classes_75kplus_train_005396 | 4,741 | permissive | [
{
"docstring": "保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)",
"name": "maxheapify",
"signature": "def maxheapify(self, A, i)"
},
{
"docstring": "保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)",
"name": "maxheapify_quick",
"signature": "def maxheapify_quick(self, A, i)"
},
{
"docstring": "保持堆:使某一个结点i成为最小堆(其子树本身... | 4 | stack_v2_sparse_classes_30k_train_029069 | Implement the Python class `Chapter6_2` described below.
Class description:
CLRS 第六章 6.2 算法函数和笔记
Method signatures and docstrings:
- def maxheapify(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def maxheapify_quick(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def minheapify(self, A, i): 保持堆:使某一个结点i成为最小堆(其子树本身已经为最小堆)
-... | Implement the Python class `Chapter6_2` described below.
Class description:
CLRS 第六章 6.2 算法函数和笔记
Method signatures and docstrings:
- def maxheapify(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def maxheapify_quick(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def minheapify(self, A, i): 保持堆:使某一个结点i成为最小堆(其子树本身已经为最小堆)
-... | 33662f46dc346203b220d7481d1a4439feda05d2 | <|skeleton|>
class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_0|>
def maxheapify_quick(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_1|>
def minheapify(self, A, i):
"""保持堆:使某一个结点i成为最小堆... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
l = heap.left(i)
r = heap.right(i)
largest = 0
if l <= heap.heapsize(A) and A[l] >= A[i]:
largest = l
else:
largest = i
if... | the_stack_v2_python_sparse | src/chapter6/chapter6_2.py | HideLakitu/IntroductionToAlgorithm.Python | train | 1 |
13b1c91c9b480b9b8a34acfead9d359617857920 | [
"if self == Format.finalfusion:\n embeddings.write(path)\nelif self == Format.word2vec:\n write_word2vec(path, embeddings)\nelif self == Format.text:\n write_text(path, embeddings)\nelif self == Format.textdims:\n write_text_dims(path, embeddings)\nelif self == Format.fasttext:\n write_fasttext(path,... | <|body_start_0|>
if self == Format.finalfusion:
embeddings.write(path)
elif self == Format.word2vec:
write_word2vec(path, embeddings)
elif self == Format.text:
write_text(path, embeddings)
elif self == Format.textdims:
write_text_dims(path,... | Supported embedding formats. | Format | [
"BlueOak-1.0.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
<|body_0|>
def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings:
"""Helper to load different Formats"""
<|bo... | stack_v2_sparse_classes_75kplus_train_005397 | 3,054 | permissive | [
{
"docstring": "Helper to write different Formats",
"name": "write",
"signature": "def write(self, path: str, embeddings: Embeddings)"
},
{
"docstring": "Helper to load different Formats",
"name": "load",
"signature": "def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings"
}... | 2 | stack_v2_sparse_classes_30k_train_047517 | Implement the Python class `Format` described below.
Class description:
Supported embedding formats.
Method signatures and docstrings:
- def write(self, path: str, embeddings: Embeddings): Helper to write different Formats
- def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings: Helper to load different Fo... | Implement the Python class `Format` described below.
Class description:
Supported embedding formats.
Method signatures and docstrings:
- def write(self, path: str, embeddings: Embeddings): Helper to write different Formats
- def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings: Helper to load different Fo... | f7ab0174a66731d0f71635c45d172f7711f6aec8 | <|skeleton|>
class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
<|body_0|>
def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings:
"""Helper to load different Formats"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
if self == Format.finalfusion:
embeddings.write(path)
elif self == Format.word2vec:
write_word2vec(path, embeddings)
... | the_stack_v2_python_sparse | src/finalfusion/scripts/util.py | finalfusion/finalfusion-python | train | 5 |
793748853b6dafb377c0c0fcb1ae125e22c43962 | [
"module_columns = []\ntry:\n module_columns.append(module_columns_dict['cross'])\n module_columns.append(module_columns_dict['deep'])\nexcept:\n raise ValueError(\"the module's name is wrong\")\nsuper().__init__(module_columns=module_columns, init_std=init_std, task=task)\ncross_input_dim = self._getInputD... | <|body_start_0|>
module_columns = []
try:
module_columns.append(module_columns_dict['cross'])
module_columns.append(module_columns_dict['deep'])
except:
raise ValueError("the module's name is wrong")
super().__init__(module_columns=module_columns, init... | Instantiates the Deep&Cross Network architecture. | DCN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCN:
"""Instantiates the Deep&Cross Network architecture."""
def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dropout_rate=0.5, activation='relu', init_method='normal'):
""":param module_columns_dict: :param init_std: :par... | stack_v2_sparse_classes_75kplus_train_005398 | 2,609 | no_license | [
{
"docstring": ":param module_columns_dict: :param init_std: :param task: :param cross_layer: :param hidden_units: :param dropout_rate: :param activation:",
"name": "__init__",
"signature": "def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dr... | 2 | stack_v2_sparse_classes_30k_train_046450 | Implement the Python class `DCN` described below.
Class description:
Instantiates the Deep&Cross Network architecture.
Method signatures and docstrings:
- def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dropout_rate=0.5, activation='relu', init_method='no... | Implement the Python class `DCN` described below.
Class description:
Instantiates the Deep&Cross Network architecture.
Method signatures and docstrings:
- def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dropout_rate=0.5, activation='relu', init_method='no... | 607b0489dae042379d226dc08d49476b7a0d5acb | <|skeleton|>
class DCN:
"""Instantiates the Deep&Cross Network architecture."""
def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dropout_rate=0.5, activation='relu', init_method='normal'):
""":param module_columns_dict: :param init_std: :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DCN:
"""Instantiates the Deep&Cross Network architecture."""
def __init__(self, module_columns_dict, init_std=0.0001, task='binary', cross_layer=3, hidden_units=[128, 64], dropout_rate=0.5, activation='relu', init_method='normal'):
""":param module_columns_dict: :param init_std: :param task: :par... | the_stack_v2_python_sparse | torchctr/models/dcn.py | LUziyee/TorchCTR | train | 15 |
bbe0b670f1ff58eb37399a349d6f4bb74632ceeb | [
"n1, n2 = (len(nums1), len(nums2))\nmidpos = (n1 + n2) // 2\ni, j, res0, res1 = (0, 0, 0, 0)\nfor _ in range(midpos + 1):\n if i < n1 and j < n2 and (nums1[i] <= nums2[j]):\n res0 = res1\n res1 = nums1[i]\n i += 1\n elif i < n1 and j < n2 and (nums1[i] > nums2[j]):\n res0 = res1\n ... | <|body_start_0|>
n1, n2 = (len(nums1), len(nums2))
midpos = (n1 + n2) // 2
i, j, res0, res1 = (0, 0, 0, 0)
for _ in range(midpos + 1):
if i < n1 and j < n2 and (nums1[i] <= nums2[j]):
res0 = res1
res1 = nums1[i]
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_005399 | 1,591 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | b3a2013d1c3c7a5a16727dbc2ecbc934a01a3979 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
n1, n2 = (len(nums1), len(nums2))
midpos = (n1 + n2) // 2
i, j, res0, res1 = (0, 0, 0, 0)
for _ in range(midpos + 1):
if i < n1 and j ... | the_stack_v2_python_sparse | LeetcodePython/MediaofTwoSortedArrays4.py | DianaLuca/Algorithms | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.