uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4b8fcb0635eb6ae0edb8fbc8 | train | function | @plugin_function('mds.get.computeImageId')
def get_image_id(operating_system=None, operating_system_version=None,
image_caption=None, shape=None, compartment_id=None,
config=None, interactive=True):
"""Gets a compute image id
Args:
operating_system (str): The na... | @plugin_function('mds.get.computeImageId')
def get_image_id(operating_system=None, operating_system_version=None,
image_caption=None, shape=None, compartment_id=None,
config=None, interactive=True):
| """Gets a compute image id
Args:
operating_system (str): The name of the operating system
operating_system_version (str): The version of the operating system
image_caption (str): The caption of the compute image to use
shape (str): The name of the shape to use.
co... | if raise_exceptions:
raise
print(f"ERROR: {str(e)}")
@plugin_function('mds.get.computeImageId')
def get_image_id(operating_system=None, operating_system_version=None,
image_caption=None, shape=None, compartment_id=None,
config=None, interactive=True):
| 65 | 66 | 222 | 45 | 20 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | get_image_id | get_image_id | 1,351 | 1,377 | 1,351 | 1,354 | 979f8324b2bbc2dbc0bd53dca6cb41a061dc7fcf | bigcode/the-stack | train |
7a9c969efce377447c093e61 | train | function | @plugin_function('mds.delete.computeInstance', shell=True, cli=True, web=True)
def delete_instance(**kwargs):
"""Deletes the compute instance with the given name
If no name is given, it will prompt the user for the name.
Args:
**kwargs: Optional parameters
Keyword Args:
inst... | @plugin_function('mds.delete.computeInstance', shell=True, cli=True, web=True)
def delete_instance(**kwargs):
| """Deletes the compute instance with the given name
If no name is given, it will prompt the user for the name.
Args:
**kwargs: Optional parameters
Keyword Args:
instance_name (str): The name of the instance.
instance_id (str): The OCID of the instance
await_d... | _config=oci.core.models.LaunchInstanceAgentConfigDetails(
plugins_config=[
oci.core.models.InstanceAgentPluginConfigDetails(
desired_state = "ENABLED",
name = "Bastion"
)
... | 255 | 256 | 877 | 25 | 230 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | delete_instance | delete_instance | 1,809 | 1,928 | 1,809 | 1,810 | b9fc844c5491624742a045715a05f2c0aae266bc | bigcode/the-stack | train |
3d33a9f107b648296a07708d | train | function | def format_instance_listing(items, current=None, vnics=None,
config=None):
"""Returns a formated list of instances.
If compartment_id is given, the current and parent compartment
will be listed as well.
Args:
data (list): A list of instance objects.
... | def format_instance_listing(items, current=None, vnics=None,
config=None):
| """Returns a formated list of instances.
If compartment_id is given, the current and parent compartment
will be listed as well.
Args:
data (list): A list of instance objects.
config (object): An OCI config object or None.
compartment_id (str): The OCID of the current co... | remote_file_path, localpath=local_file_path)
finally:
sftp.close()
def get_remote_file_as_file_object(self, remote_file_path, file_object):
sftp = self.client.open_sftp()
try:
sftp.getfo(remotepath=remote_file_path, fl=file_object)
finally:
... | 162 | 162 | 541 | 17 | 145 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | format_instance_listing | format_instance_listing | 172 | 235 | 172 | 173 | aa005bd03e0035924cb3d84031616933c3ffd78d | bigcode/the-stack | train |
c67ef60b26a9e2f0a4566e09 | train | function | @plugin_function('mds.list.computeInstances', shell=True, cli=True, web=True)
def list_instances(**kwargs):
"""Lists instances
This function will list all instances of the compartment with the
given compartment_id.
Args:
**kwargs: Optional parameters
Keyword Args:
compa... | @plugin_function('mds.list.computeInstances', shell=True, cli=True, web=True)
def list_instances(**kwargs):
| """Lists instances
This function will list all instances of the compartment with the
given compartment_id.
Args:
**kwargs: Optional parameters
Keyword Args:
compartment_id (str): OCID of the parent compartment.
config (object): An OCI config object or None.
... | :ignore gbps
out = ""
id = 1
for i in items:
out += (f"{id:>4} " +
core.fixed_len(i.shape, 26, ' ', True) +
core.fixed_len(str(i.ocpus), 7, ' ', align_right=True) +
core.fixed_len(i.processor_description, 35, ' ') +
core.fixed_l... | 167 | 167 | 558 | 25 | 141 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | list_instances | list_instances | 632 | 706 | 632 | 633 | 1f915fedb5be8ba33f736653fe8ecfe65381b7e5 | bigcode/the-stack | train |
857e7c1e9bfdca7bfc84de56 | train | function | def format_shape_listing(data):
"""Returns a formated list of shapes.
Args:
data (list): A list of shape objects.
Returns:
The formated list as string
"""
out = ""
# return compartments in READABLE text output
i = 1
for s in data:
# cSpell:ignore ... | def format_shape_listing(data):
| """Returns a formated list of shapes.
Args:
data (list): A list of shape objects.
Returns:
The formated list as string
"""
out = ""
# return compartments in READABLE text output
i = 1
for s in data:
# cSpell:ignore ocpus
out += f"{i:>4} {s... | }. (Code: {e.code}; Status: {e.status})')
except Exception as e:
if raise_exceptions:
raise
print(f'Could not list the availability domains for this '
f'compartment.\nERROR: {str(e)}')
def format_shape_listing(data):
| 63 | 64 | 149 | 6 | 57 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | format_shape_listing | format_shape_listing | 576 | 596 | 576 | 576 | 7471d52b2a05873b56bc8bcd0e7dc11e674a85ca | bigcode/the-stack | train |
51c674b59fb61da78a07f554 | train | function | @plugin_function('mds.list.computeInstanceVnics')
def list_vnics(**kwargs):
"""Lists all available vnics for the given compartment and
availability_domain
Args:
**kwargs: Optional parameters
Keyword Args:
instance_id (str): OCID of the compute instance
availability_do... | @plugin_function('mds.list.computeInstanceVnics')
def list_vnics(**kwargs):
| """Lists all available vnics for the given compartment and
availability_domain
Args:
**kwargs: Optional parameters
Keyword Args:
instance_id (str): OCID of the compute instance
availability_domain (str): The name of the availability_domain to use.
ignore_curren... | Returns:
The formated list as string
"""
import re
out = ""
i = 1
for v in vnics:
# Shorten to 24 chars max, remove linebreaks
name = re.sub(r'[\n\r]', ' ',
v.display_name[:22] + '..'
if len(v.display_name) > 24
... | 204 | 204 | 681 | 21 | 182 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | list_vnics | list_vnics | 1,410 | 1,495 | 1,410 | 1,411 | c784f688f33bba4b7c5b56e636d5c8d1184f69fc | bigcode/the-stack | train |
982c24d8b84fd86739656325 | train | function | def format_image_listing(data):
"""Returns a formated list of images.
Args:
data (list): A list of images objects.
Returns:
The formated list as string
"""
import math
out = ""
# return compartments in READABLE text output
split = math.ceil(len(data)/2... | def format_image_listing(data):
| """Returns a formated list of images.
Args:
data (list): A list of images objects.
Returns:
The formated list as string
"""
import math
out = ""
# return compartments in READABLE text output
split = math.ceil(len(data)/2)
i = 1
while i <= spli... | \
if len(img.operating_system_version) > 22 \
else img.operating_system_version
return(f"{index+1:>3} {os:16} "
f"{os_version:22} {img.display_name[-12:]:12}")
def format_image_listing(data):
| 63 | 64 | 146 | 6 | 57 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | format_image_listing | format_image_listing | 253 | 279 | 253 | 253 | f35d79bb215d327b36ff5a7afee422b5b7d5757a | bigcode/the-stack | train |
3441600e207d7d038bcb267f | train | function | def format_shapes(items) -> str:
"""Formats a given list of objects in a human readable form
Args:
items: Either a list of objects or a single object
Returns:
The objects formated as str
"""
# If a single db_system was given, wrap it in a list
if not type(items) is l... | def format_shapes(items) -> str:
| """Formats a given list of objects in a human readable form
Args:
items: Either a list of objects or a single object
Returns:
The objects formated as str
"""
# If a single db_system was given, wrap it in a list
if not type(items) is list:
items = [items]
... | >4} {s.shape:20} {s.ocpus:5.1f}x " \
f"{s.processor_description[:22]:22} " \
f"{s.memory_in_gbs:5.0f}GB Ram\n"
i += 1
return out
def format_shapes(items) -> str:
| 71 | 71 | 239 | 8 | 62 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | format_shapes | format_shapes | 599 | 629 | 599 | 599 | 50e82e15143352659dbe8dcabf93cffc0fa3e511 | bigcode/the-stack | train |
68cd21cb8b6b6f016df34470 | train | function | @plugin_function('mds.update.computeInstance')
def update_instance(instance_name=None, **kwargs):
"""Updates a compute instance with the new values
If no name is given, it will prompt the user for the name.
Args:
instance_name (str): The name of the instance.
**kwargs: Additional o... | @plugin_function('mds.update.computeInstance')
def update_instance(instance_name=None, **kwargs):
| """Updates a compute instance with the new values
If no name is given, it will prompt the user for the name.
Args:
instance_name (str): The name of the instance.
**kwargs: Additional options.
Keyword Args:
instance_id (str): The OCID of the instance.
name (st... | += 1
if interactive:
print("")
if instance.lifecycle_state != "TERMINATED":
raise Exception("Instance did not reach the TERMINATED "
"state within 4 minutes.")
if interactive:
... | 170 | 171 | 571 | 20 | 150 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | update_instance | update_instance | 1,931 | 2,006 | 1,931 | 1,932 | 097c6d65af0a38d3b5b9aac6b439473ce2f33097 | bigcode/the-stack | train |
23c207e02489387c5749ff61 | train | class | class SshConnection:
""" A class to handle SSH Connections"""
def __init__(
self, username, host, private_key_file_path="~/.ssh/id_rsa",
private_key_passphrase=None):
""" Opens a ssh connection to the given host
Args:
host (str): The hostname or IP ... | class SshConnection:
| """ A class to handle SSH Connections"""
def __init__(
self, username, host, private_key_file_path="~/.ssh/id_rsa",
private_key_passphrase=None):
""" Opens a ssh connection to the given host
Args:
host (str): The hostname or IP of the host to connect... | not limited to OpenSSL) that is licensed under separate terms, as
# designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they ... | 256 | 256 | 930 | 5 | 250 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | SshConnection | SshConnection | 31 | 169 | 31 | 31 | 897133d6548c1ee8ad731b56e79237cb102a0561 | bigcode/the-stack | train |
9db9b76e902bbe9bd2bbb6b3 | train | function | def format_compute_images(items) -> str:
"""Formats a given list of objects in a human readable form
Args:
items: Either a list of objects or a single object
Returns:
The objects formated as str
"""
# If a single db_system was given, wrap it in a list
if not type(ite... | def format_compute_images(items) -> str:
| """Formats a given list of objects in a human readable form
Args:
items: Either a list of objects or a single object
Returns:
The objects formated as str
"""
# If a single db_system was given, wrap it in a list
if not type(items) is list:
items = [items]
... | _item(data, i-1)
if i+split < len(data):
out += f" {format_image_list_item(data, split+i-1)}\n"
else:
out += "\n"
i += 1
return out
def format_compute_images(items) -> str:
| 64 | 64 | 196 | 9 | 54 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | format_compute_images | format_compute_images | 282 | 307 | 282 | 282 | 87bffcfc320001e7d72c2b2edbb33be72b8b43a5 | bigcode/the-stack | train |
b55bdbfc4f41a7ef38f8827b | train | function | @plugin_function('mds.list.computeImages')
def list_images(**kwargs):
"""Gets a compute image
Args:
**kwargs: Additional options
Keyword Args:
operating_system (str): The name of the operating system
operating_system_version (str): The version of the operating system
... | @plugin_function('mds.list.computeImages')
def list_images(**kwargs):
| """Gets a compute image
Args:
**kwargs: Additional options
Keyword Args:
operating_system (str): The name of the operating system
operating_system_version (str): The version of the operating system
image_caption (str): The caption of the compute image to use
... |
config_profile (str): The name of an OCI config profile
interactive (bool): Indicates whether to execute in interactive mode
raise_exceptions (bool): If true exceptions are raised
Returns:
The shape's name (which is the shape's id) or None
"""
shape_name = kwargs.... | 244 | 244 | 815 | 16 | 227 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | list_images | list_images | 1,158 | 1,260 | 1,158 | 1,159 | 0f90afadafdc3a2ccf73f85a631dde529b75d65c | bigcode/the-stack | train |
763e2025388647c9a983160f | train | function | @plugin_function('mds.get.computeInstancePublicIp')
def get_instance_public_ip(**kwargs):
"""Returns the public ip of an instance
If no name is given, it will prompt the user for the name.
Args:
**kwargs: Optional parameters
Keyword Args:
instance_name (str): The name of the... | @plugin_function('mds.get.computeInstancePublicIp')
def get_instance_public_ip(**kwargs):
| """Returns the public ip of an instance
If no name is given, it will prompt the user for the name.
Args:
**kwargs: Optional parameters
Keyword Args:
instance_name (str): The name of the instance.
instance_id (str): The OCID of the instance
private_ip_fallback... | 'ERROR: {e.message}. (Code: {e.code}; Status: {e.status})')
except Exception as e:
if raise_exceptions:
raise
print(f'ERROR: {e}')
@plugin_function('mds.get.computeInstanceId')
def get_instance_id(instance_name=None, compartment_id=None, config=None,
intera... | 222 | 222 | 743 | 20 | 201 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | get_instance_public_ip | get_instance_public_ip | 842 | 940 | 842 | 843 | fd1e60e6097bbd7fff099567c1957e5f4a024f7f | bigcode/the-stack | train |
597888f081e05a2499406ccc | train | function | @plugin_function('mds.get.computeInstance', shell=True, cli=True, web=True)
def get_instance(**kwargs):
"""Returns an instance object based on instance_name or instance_id
Args:
**kwargs: Optional parameters
Keyword Args:
instance_name (str): The name of the instance
insta... | @plugin_function('mds.get.computeInstance', shell=True, cli=True, web=True)
def get_instance(**kwargs):
| """Returns an instance object based on instance_name or instance_id
Args:
**kwargs: Optional parameters
Keyword Args:
instance_name (str): The name of the instance
instance_id (str): OCID of the instance
ignore_current (bool): Whether the current instance should be ... | _oci_compute_client(config=config)
# List the compute instances
instances = compute.list_instances(
compartment_id=compartment_id).data
# Filter out all deleted compartments
instances = [c for c in instances if c.lifecycle_state != "DELETED" and
... | 256 | 256 | 885 | 25 | 230 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | get_instance | get_instance | 709 | 817 | 709 | 710 | 1cb6432d95b5c585102fcf8ad4894ab40c932798 | bigcode/the-stack | train |
10907527850d93481f586ea1 | train | function | @plugin_function('mds.get.computeImage')
def get_image(**kwargs):
"""Gets a compute image
Args:
**kwargs: Additional options
Keyword Args:
operating_system (str): The name of the operating system
operating_system_version (str): The version of the operating system
... | @plugin_function('mds.get.computeImage')
def get_image(**kwargs):
| """Gets a compute image
Args:
**kwargs: Additional options
Keyword Args:
operating_system (str): The name of the operating system
operating_system_version (str): The version of the operating system
image_caption (str): The caption of the compute image to use
... | Operation cancelled.")
# Filter by given operating_system and sort by operating_system,
# operating_system_version DESC, time_created
images = sorted(sorted(
[i for i in images if i.operating_system == operating_system],
key=lambda img: (img.ope... | 210 | 211 | 706 | 16 | 194 | mike-lischke/mysql-shell-plugins | mds_plugin/compute.py | Python | get_image | get_image | 1,263 | 1,348 | 1,263 | 1,264 | 5f5a10f0c7c6740bcf446a423119177533327e6d | bigcode/the-stack | train |
0b06d4b24db3560156d9605e | train | class | class Migration(migrations.Migration):
dependencies = [("data_import", "0023_auto_20191106_2330")]
operations = [
migrations.AlterField(
model_name="datafilekey", name="datafile_id", field=models.BigIntegerField()
)
]
| class Migration(migrations.Migration):
| dependencies = [("data_import", "0023_auto_20191106_2330")]
operations = [
migrations.AlterField(
model_name="datafilekey", name="datafile_id", field=models.BigIntegerField()
)
]
| # Generated by Django 2.2.13 on 2020-12-22 17:57
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 61 | 7 | 30 | danamlewis/open-humans | data_import/migrations/0024_auto_20201222_1757.py | Python | Migration | Migration | 6 | 14 | 6 | 7 | 0d2a750ddded762afa219b16004b1dafdafd615e | bigcode/the-stack | train |
1a82420399bc3071691f3117 | train | class | class DebugServer(object):
def __init__(self, *args):
assert len(args) >= 2
host = '*'
port = int(args[1])
self._addr = 'tcp://{}:{}'.format(host, port)
print('serving on {}'.format(self._addr))
self._context = zmq.Context()
self._socket = self._context.sock... | class DebugServer(object):
| def __init__(self, *args):
assert len(args) >= 2
host = '*'
port = int(args[1])
self._addr = 'tcp://{}:{}'.format(host, port)
print('serving on {}'.format(self._addr))
self._context = zmq.Context()
self._socket = self._context.socket(zmq.PAIR)
self._s... | import time
import zmq
class DebugServer(object):
| 12 | 64 | 192 | 5 | 6 | aunsbjerg/robotdebug | robotdebug/DebugServer.py | Python | DebugServer | DebugServer | 4 | 40 | 4 | 5 | 62db9b87bdae73b1d69a7a2926f657bb31e271d4 | bigcode/the-stack | train |
c23a1179c7438ea610547904 | train | class | class binary_focal_loss(nn.Module):
def __init__(self, pos_weight, balance_param=1, gamma=2):
super(binary_focal_loss, self).__init__()
self.pos_weight = pos_weight
self.balance_param = balance_param
self.gamma = gamma
def forward(self, input, target):
assert target.si... | class binary_focal_loss(nn.Module):
| def __init__(self, pos_weight, balance_param=1, gamma=2):
super(binary_focal_loss, self).__init__()
self.pos_weight = pos_weight
self.balance_param = balance_param
self.gamma = gamma
def forward(self, input, target):
assert target.size() == input.size()
# compu... | import torch
import torch.nn as nn
import torch.nn.functional as F
class binary_focal_loss(nn.Module):
| 24 | 64 | 166 | 8 | 15 | ZhaoZhibin/Physionet2020model | loss/focal_loss.py | Python | binary_focal_loss | binary_focal_loss | 5 | 24 | 5 | 6 | 8708ccc6b7efd8915a1ddd0ce19bc703d9c053f2 | bigcode/the-stack | train |
40781672e31c2ef47836959b | train | function | def generate_metadata(build_env, backend):
# type: (BuildEnvironment, Pep517HookCaller) -> str
"""Generate metadata using mechanisms described in PEP 517.
Returns the generated metadata directory.
"""
metadata_tmpdir = TempDirectory(
kind="modern-metadata", globally_managed=True
)
... | def generate_metadata(build_env, backend):
# type: (BuildEnvironment, Pep517HookCaller) -> str
| """Generate metadata using mechanisms described in PEP 517.
Returns the generated metadata directory.
"""
metadata_tmpdir = TempDirectory(
kind="modern-metadata", globally_managed=True
)
metadata_dir = metadata_tmpdir.path
with build_env:
# Note that Pep517HookCaller imple... | Y_CHECK_RUNNING:
from pip._internal.build_env import BuildEnvironment
from pip._vendor.pep517.wrappers import Pep517HookCaller
logger = logging.getLogger(__name__)
def generate_metadata(build_env, backend):
# type: (BuildEnvironment, Pep517HookCaller) -> str
| 64 | 64 | 173 | 24 | 40 | realxwx/leetcode-solve | venv/lib/python3.8/site-packages/pip/_internal/operations/build/metadata.py | Python | generate_metadata | generate_metadata | 21 | 43 | 21 | 22 | b2cbf8774de83b587a0c03d301e0b950d0a33e59 | bigcode/the-stack | train |
844d678d9aba49c8e3c9cc6d | train | class | class TestEdgeAPI(unittest.TestCase):
def test_invoke_apis_via_edge(self):
edge_port = config.EDGE_PORT_HTTP or config.EDGE_PORT
edge_url = '%s://localhost:%s' % (get_service_protocol(), edge_port)
if is_api_enabled('s3'):
self._invoke_s3_via_edge(edge_url)
self._in... | class TestEdgeAPI(unittest.TestCase):
| def test_invoke_apis_via_edge(self):
edge_port = config.EDGE_PORT_HTTP or config.EDGE_PORT
edge_url = '%s://localhost:%s' % (get_service_protocol(), edge_port)
if is_api_enabled('s3'):
self._invoke_s3_via_edge(edge_url)
self._invoke_s3_via_edge_multipart_form(edge_ur... | import io
import os
import json
import time
import unittest
import requests
from localstack import config
from localstack.utils.aws import aws_stack
from localstack.utils.common import short_uid, get_service_protocol, to_str, get_free_tcp_port
from localstack.utils.bootstrap import is_api_enabled
from localstack.servic... | 86 | 256 | 1,346 | 8 | 77 | freakinhippie/localstack | tests/integration/test_edge.py | Python | TestEdgeAPI | TestEdgeAPI | 14 | 148 | 14 | 15 | 70bfba38cc48e6ff4f170632703a17bd7017a6d0 | bigcode/the-stack | train |
5ae95dd5249dcb34a1510ca9 | train | class | class SpriteAdv(Sprite, StaticSourceMixin):
"""Extends Sprite class functionality.
Offers:
additional end-of-life functionality (see End-Of-Life section)
additional scheduling events functionality (see Scheduling section)
register of live sprites
sound via inherited StaticSource... | class SpriteAdv(Sprite, StaticSourceMixin):
| """Extends Sprite class functionality.
Offers:
additional end-of-life functionality (see End-Of-Life section)
additional scheduling events functionality (see Scheduling section)
register of live sprites
sound via inherited StaticSourceMixin (see documentation for
St... | ++.
ATTRIBUTES
--sprint-- ++sprite++
--margin-- ++margin++
"""
def __init__(self, sprite: Sprite, margin: Optional[int] = None):
"""Define rectangle to encompass ++sprite++ plus ++margin++"""
self.sprite = Sprite
self.margin = margin
if isinstance(spr... | 256 | 256 | 2,646 | 9 | 247 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | SpriteAdv | SpriteAdv | 243 | 561 | 243 | 243 | 7a3333fa774c8e084d724f2466166b9b51c8d04b | bigcode/the-stack | train |
a363cd45a50074610b7e5ce3 | train | function | def anim(filename, rows: int, cols: int ,
frame_duration: float = 0.1, loop=True) -> Animation:
"""Create Animation object from image of regularly arranged subimages.
+filename+ Name of file in resource directory of image of subimages
regularly arranged over +rows+ rows and +cols+ column... | def anim(filename, rows: int, cols: int ,
frame_duration: float = 0.1, loop=True) -> Animation:
| """Create Animation object from image of regularly arranged subimages.
+filename+ Name of file in resource directory of image of subimages
regularly arranged over +rows+ rows and +cols+ columns.
+frame_duration+ Seconds each frame of animation should be displayed.
"""
img = pyglet.reso... | assert anchor in ['origin', 'center']
animation = pyglet.resource.animation(filename)
if anchor == 'center':
centre_animation(animation)
return animation
def anim(filename, rows: int, cols: int ,
frame_duration: float = 0.1, loop=True) -> Animation:
| 64 | 64 | 135 | 30 | 33 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | anim | anim | 112 | 124 | 112 | 113 | 83ad9972d5c4c1da75d2d1e6a2198ddd931c7ef7 | bigcode/the-stack | train |
8c4f1b645052c75abe78a8ea | train | class | class PhysicalSprite(SpriteAdv):
"""Extends SpriteAdv for 2D movement and collision detection.
The PhysicalSprite class:
defines the window area within which physical sprites can move.
can evalutate collisions between live physical sprites instances.
A physcial sprite:
h... | class PhysicalSprite(SpriteAdv):
| """Extends SpriteAdv for 2D movement and collision detection.
The PhysicalSprite class:
defines the window area within which physical sprites can move.
can evalutate collisions between live physical sprites instances.
A physcial sprite:
has a speed and a rotation speed.
... | ._on_kill()
self.die()
def _waiting_for_quiet(self, dt: float):
if not self.sound_playing:
self.unschedule(self._waiting_for_quiet)
self._dying_loudly.remove(self)
def _die_loudly(self):
self._dying_loudly.append(self)
self.schedule_interval(self... | 256 | 256 | 3,962 | 6 | 250 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | PhysicalSprite | PhysicalSprite | 573 | 1,037 | 573 | 573 | 959d1af09ef83d0a184128f7240a9618f74d3ffa | bigcode/the-stack | train |
3bdca37610b823767b824ac0 | train | function | def centre_animation(animation: Animation):
"""Centre all +animation+ frames"""
for frame in animation.frames:
centre_image(frame.image)
| def centre_animation(animation: Animation):
| """Centre all +animation+ frames"""
for frame in animation.frames:
centre_image(frame.image)
| """Set +image+ anchor points to centre of image"""
if not isinstance(image, collections.abc.Sequence):
image = [image]
for img in image:
img.anchor_x = img.width // 2
img.anchor_y = img.height // 2
def centre_animation(animation: Animation):
| 64 | 64 | 29 | 7 | 56 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | centre_animation | centre_animation | 60 | 63 | 60 | 60 | 88501d198fba4e0621e3a120ce0dcef34fce88ef | bigcode/the-stack | train |
66984ae8bdb9d29bb4825939 | train | class | class AvoidRect(InRect):
"""Define rectangular area around a sprite.
Intended use is to avoid AvoidRects when positioning other sprites in
order that the sprites do not overlap / immediately collide.
Extends InRect to define a rectangle that encompasses a ++sprite++ and
any ++margin++.
... | class AvoidRect(InRect):
| """Define rectangular area around a sprite.
Intended use is to avoid AvoidRects when positioning other sprites in
order that the sprites do not overlap / immediately collide.
Extends InRect to define a rectangle that encompasses a ++sprite++ and
any ++margin++.
ATTRIBUTES
--sprint--... | def inside(self, position: Tuple[int, int]) -> bool:
"""Return boolean advising if +position+ lies in rectangle.
+position+ (x, y)
"""
x = position[0]
y = position[1]
if self.x_from <= x <= self.x_to and self.y_from <= y <= self.y_to:
return True
... | 93 | 93 | 310 | 6 | 86 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | AvoidRect | AvoidRect | 202 | 241 | 202 | 202 | 20fab5c2580753f75c1a170f0f79f719e804a498 | bigcode/the-stack | train |
243c9bde646fe4fcaeb1b60b | train | function | def vector_anchor_to_rotated_point(x: int, y: int,
rotation: Union[int, float]
) -> Tuple[int, int]:
"""Return vector to rotated point.
Where +x+ and +y+ describe a point relative to an image's anchor
when rotated 0 degrees, return... | def vector_anchor_to_rotated_point(x: int, y: int,
rotation: Union[int, float]
) -> Tuple[int, int]:
| """Return vector to rotated point.
Where +x+ and +y+ describe a point relative to an image's anchor
when rotated 0 degrees, returns the vector, as (x, y) from the anchor
to the same point if the image were rotated by +rotation+ degrees.
+rotation+ Degrees of rotation, clockwise positive... | -> int:
"""Return distance between +sprite1+ and +sprite2+ in pixels"""
return physics.distance(sprite1.position, sprite2.position)
def vector_anchor_to_rotated_point(x: int, y: int,
rotation: Union[int, float]
) -> Tuple[int, int]:
| 64 | 64 | 201 | 32 | 32 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | vector_anchor_to_rotated_point | vector_anchor_to_rotated_point | 130 | 148 | 130 | 132 | 6985fb408879e8efff1097b3a6e0b8fe0e811897 | bigcode/the-stack | train |
7ed8a2a84f93ce41cece70c2 | train | function | def centre_image(image: Union[TextureRegion, Sequence[TextureRegion]]):
"""Set +image+ anchor points to centre of image"""
if not isinstance(image, collections.abc.Sequence):
image = [image]
for img in image:
img.anchor_x = img.width // 2
img.anchor_y = img.height // 2
| def centre_image(image: Union[TextureRegion, Sequence[TextureRegion]]):
| """Set +image+ anchor points to centre of image"""
if not isinstance(image, collections.abc.Sequence):
image = [image]
for img in image:
img.anchor_x = img.width // 2
img.anchor_y = img.height // 2
| import wraps
import pyglet
from pyglet.image import Texture, TextureRegion, Animation
from pyglet.sprite import Sprite
from pyglet.media import StaticSource
from .audio_ext import StaticSourceMixin
from .. import physics
def centre_image(image: Union[TextureRegion, Sequence[TextureRegion]]):
| 64 | 64 | 74 | 16 | 47 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | centre_image | centre_image | 52 | 58 | 52 | 52 | b0cba3a698ab1e1c4f2bab87d80375e751dc95f8 | bigcode/the-stack | train |
b35c76b7178745e25dacf6b0 | train | function | def load_image(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> TextureRegion:
"""Load image with +filename+ from resource.
+anchor+ Set anchor points to image 'origin' or 'center'"""
assert anchor in ['origin', 'center']
img = pyglet.resource.image(filename)
if a... | def load_image(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> TextureRegion:
| """Load image with +filename+ from resource.
+anchor+ Set anchor points to image 'origin' or 'center'"""
assert anchor in ['origin', 'center']
img = pyglet.resource.image(filename)
if anchor == 'center':
centre_image(img)
return img
| .anchor_y = img.height // 2
def centre_animation(animation: Animation):
"""Centre all +animation+ frames"""
for frame in animation.frames:
centre_image(frame.image)
def load_image(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> TextureRegion:
| 64 | 64 | 90 | 26 | 38 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | load_image | load_image | 65 | 74 | 65 | 66 | 8b779874004bf567aa5460445d27c77e5a7b9723 | bigcode/the-stack | train |
613997d91dbd0b020dbeff55 | train | class | class OneShotAnimatedSprite(SpriteAdv):
"""Extends SpriteAdv to offer a one shot animation.
Objects decease automatically when animation ends.
"""
def on_animation_end(self):
"""Event handler"""
self.die()
| class OneShotAnimatedSprite(SpriteAdv):
| """Extends SpriteAdv to offer a one shot animation.
Objects decease automatically when animation ends.
"""
def on_animation_end(self):
"""Event handler"""
self.die()
|
# end-of-life operations
self.unschedule_all()
if die_loudly:
self._die_loudly()
else:
self.stop_sound()
self.live_sprites.remove(self)
super().delete()
self._on_die()
class OneShotAnimatedSprite(SpriteAdv):
| 64 | 64 | 51 | 8 | 56 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | OneShotAnimatedSprite | OneShotAnimatedSprite | 563 | 571 | 563 | 563 | 601c3e830de9634012fb084ef38d494b5074bb5c | bigcode/the-stack | train |
62fb1feda37f5c11a81260f4 | train | class | class InRect(object):
"""Check if a point lies within a defined rectangle.
Class only accommodates rectangles that with sides that are parallel
to the x and y axes.
Constructor defines rectangle.
METHODS
--inside(position)-- Returns boolean advising if +position+ in rectangle.
... | class InRect(object):
| """Check if a point lies within a defined rectangle.
Class only accommodates rectangles that with sides that are parallel
to the x and y axes.
Constructor defines rectangle.
METHODS
--inside(position)-- Returns boolean advising if +position+ in rectangle.
ATTRIBUTES
--wid... | by +rotation+ degrees.
+rotation+ Degrees of rotation, clockwise positive, 0 pointing 'right',
i.e. as for a sprite's 'rotation' attribute.
"""
dist = physics.distance((0,0), (x, y))
angle = math.asin(y/x)
rotation = -math.radians(rotation)
angle_ = angle + rotation
x_ = dist... | 115 | 116 | 388 | 5 | 110 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | InRect | InRect | 150 | 200 | 150 | 150 | 8248de5b02cb7d8630610aea49dcbf316a32b120 | bigcode/the-stack | train |
003780628aec35b13f3be818 | train | class | class PhysicalSpriteInteractive(PhysicalSprite):
"""Extends base to provide user control via keyboard keys.
User control defined via key press, key release and key hold handlers
which can be triggered on user interaction with:
a single key
a single key plus one or more modifiers
... | class PhysicalSpriteInteractive(PhysicalSprite):
| """Extends base to provide user control via keyboard keys.
User control defined via key press, key release and key hold handlers
which can be triggered on user interaction with:
a single key
a single key plus one or more modifiers
any numerical key
any numercial key of ... | y_inbounds:
return self._move_to(x, y)
elif self._at_boundary == 'stop':
return self.stop()
elif self._at_boundary == 'die':
return self.die()
elif self._at_boundary == 'kill':
return self.kill()
else:
if not x_inbounds:
... | 256 | 256 | 3,701 | 8 | 248 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | PhysicalSpriteInteractive | PhysicalSpriteInteractive | 1,040 | 1,432 | 1,040 | 1,040 | d8d885b7acb8a448e06d30f43e0839e7f120d977 | bigcode/the-stack | train |
60864c3cba4ffa4eba161708 | train | function | def load_image_sequence(filename: str, num_images: int, placeholder='?',
anchor: Union['origin', 'center'] = 'origin'
) -> List[pyglet.image.Texture]:
"""Load sequence of images from resource.
+num_images+ Number of images in sequence.
+anchor+ Set anchor... | def load_image_sequence(filename: str, num_images: int, placeholder='?',
anchor: Union['origin', 'center'] = 'origin'
) -> List[pyglet.image.Texture]:
| """Load sequence of images from resource.
+num_images+ Number of images in sequence.
+anchor+ Set anchor points to image 'origin' or 'center'.
+filename+ Name of image filename where +filename+ includes a
+placeholder+ character that represents position where filenames
are sequentiall... | ']
img = pyglet.resource.image(filename)
if anchor == 'center':
centre_image(img)
return img
def load_image_sequence(filename: str, num_images: int, placeholder='?',
anchor: Union['origin', 'center'] = 'origin'
) -> List[pyglet.image.Texture]:
| 67 | 67 | 224 | 41 | 25 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | load_image_sequence | load_image_sequence | 76 | 97 | 76 | 78 | 3e0a61cc5ae9923a3dd69a09529a15462b111851 | bigcode/the-stack | train |
46a107497eb1a6592f9dfa6d | train | function | def load_animation(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> Animation:
"""Loads animation from resource.
+filename+ Name of animation file. Acceptable filetypes inlcude .gif.
+anchor+ Anchor each animation image to image 'origin' or 'center'.
"""
asser... | def load_animation(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> Animation:
| """Loads animation from resource.
+filename+ Name of animation file. Acceptable filetypes inlcude .gif.
+anchor+ Anchor each animation image to image 'origin' or 'center'.
"""
assert anchor in ['origin', 'center']
animation = pyglet.resource.animation(filename)
if anchor == 'center':
... | my_img_seq_2.png
"""
return [ load_image(filename.replace(placeholder, str(i)), anchor=anchor)
for i in range(0, num_images) ]
def load_animation(filename: str, anchor: Union['origin', 'center'] = 'origin'
) -> Animation:
| 64 | 64 | 106 | 25 | 39 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | load_animation | load_animation | 99 | 110 | 99 | 100 | b1e34efd74b2f382bb70ba4ba575fb139874d405 | bigcode/the-stack | train |
38a1fd7ccfc31ed002ce0e46 | train | function | def distance(sprite1: Sprite, sprite2: Sprite) -> int:
"""Return distance between +sprite1+ and +sprite2+ in pixels"""
return physics.distance(sprite1.position, sprite2.position)
| def distance(sprite1: Sprite, sprite2: Sprite) -> int:
| """Return distance between +sprite1+ and +sprite2+ in pixels"""
return physics.distance(sprite1.position, sprite2.position)
| displayed.
"""
img = pyglet.resource.image(filename)
image_grid = pyglet.image.ImageGrid(img, rows, cols)
animation = image_grid.get_animation(frame_duration, True)
centre_animation(animation)
return animation
def distance(sprite1: Sprite, sprite2: Sprite) -> int:
| 64 | 64 | 44 | 15 | 48 | maread99/pyrrhoids | pyroids/lib/pyglet_lib/sprite_ext.py | Python | distance | distance | 126 | 128 | 126 | 126 | 206b13c12ce5a77bbf843345a867b8ff7f681332 | bigcode/the-stack | train |
7b559a725b30d746d65feb0b | train | class | class TestAnnotationClasses(BaseTestCase):
PROJECT_NAME = "test_assign_images"
TEST_FOLDER_PATH = "data_set/sample_project_vector"
TEST_FOLDER_NAME = "test_folder"
PROJECT_DESCRIPTION = "desc"
PROJECT_TYPE = "Vector"
EXAMPLE_IMAGE_1 = "example_image_1.jpg"
EXAMPLE_IMAGE_2 = "example_image_2.... | class TestAnnotationClasses(BaseTestCase):
| PROJECT_NAME = "test_assign_images"
TEST_FOLDER_PATH = "data_set/sample_project_vector"
TEST_FOLDER_NAME = "test_folder"
PROJECT_DESCRIPTION = "desc"
PROJECT_TYPE = "Vector"
EXAMPLE_IMAGE_1 = "example_image_1.jpg"
EXAMPLE_IMAGE_2 = "example_image_2.jpg"
@property
def folder_path(sel... | import os
from os.path import dirname
import src.superannotate as sa
from tests.integration.base import BaseTestCase
class TestAnnotationClasses(BaseTestCase):
| 34 | 256 | 1,609 | 8 | 25 | xalgorithm/superannotate-python-sdk | tests/integration/test_assign_images.py | Python | TestAnnotationClasses | TestAnnotationClasses | 8 | 187 | 8 | 8 | bb746ed32326e1f0120befcdde41099fc3f4d5d1 | bigcode/the-stack | train |
ecba6d0b22757c78bf181613 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_reschedule(
run_engine, _, redis_stream, redis_cache, logger_checker, monkeypatch
):
monkeypatch.setattr("mergify_engine.worker.WORKER_PROCES... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_reschedule(
run_engine, _, redis_stream, redis_cache, logger_checker, monkeypatch
):
| monkeypatch.setattr("mergify_engine.worker.WORKER_PROCESSING_DELAY", 3000)
await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
score = (await redis_stream.zrange("streams", 0, -1, wit... | len(await redis_stream.keys("bucket-sources~*"))
assert 0 == len(await redis_stream.hgetall("attempts"))
# Check engine have been run with expect data
assert 200 == len(run_engine.mock_calls)
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("... | 106 | 106 | 356 | 56 | 50 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_reschedule | test_worker_reschedule | 1,017 | 1,058 | 1,017 | 1,022 | cbac377399ddd5e46eddb834c2aef9a132706cb1 | bigcode/the-stack | train |
407332ea0de6b56cc360f1c5 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_ignore_503(
run_engine, _, redis_stream, redis_cache, logger_checker
):
response = mock.Mock()
response.text = "Server Error: S... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_ignore_503(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| response = mock.Mock()
response.text = "Server Error: Sorry, this diff is taking too long to generate."
response.status_code = 503
response.json.side_effect = json.JSONDecodeError("whatever", "", 0)
response.reason_phrase = "Service Unavailable"
response.url = "https://api.github.com/repositorie... | await worker.run_engine(installation, 123, "repo", 1234, [])
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_ignore_503(
run_engine, _, redis_stream, redis_cache, logger_c... | 74 | 75 | 252 | 55 | 19 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_ignore_503 | test_stream_processor_ignore_503 | 922 | 953 | 922 | 927 | 3a0dbcc67e2441a48b084646d11f58c8afa0e449 | bigcode/the-stack | train |
d17b0785683b890d1afa094e | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_waiting_tasks(
run_engine, _, redis_stream, redis_cache, logger_checker
):
buckets = set()
bucket_sources = set()
for installati... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_waiting_tasks(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| buckets = set()
bucket_sources = set()
for installation_id in range(8):
for pull_number in range(1, 3):
for data in range(3):
owner = f"owner-{installation_id}"
repo = f"repo-{installation_id}"
repo_id = installation_id
owne... | None or (await w._redis_stream.zcard("streams")) > 0
) and time.monotonic() - started_at < test_timeout:
await asyncio.sleep(0.5)
w.stop()
await w.wait_shutdown_complete()
@dataclasses.dataclass
class InstallationMatcher:
owner: str
def __eq__(self, installation: object) -> bool:
... | 160 | 160 | 536 | 55 | 104 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_with_waiting_tasks | test_worker_with_waiting_tasks | 57 | 129 | 57 | 62 | 861369cf9a036881fec88def2d141c9084a4916c | bigcode/the-stack | train |
cdbd0cd344994de042ce35fd | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_after_read_error(
run_engine, _, redis_stream, redis_cache
):
response = mock.Mock()
response.json.return_value = {"me... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_after_read_error(
run_engine, _, redis_stream, redis_cache
):
| response = mock.Mock()
response.json.return_value = {"message": "boom"}
response.status_code = 503
run_engine.side_effect = httpx.ReadError(
"Server disconnected while attempting read",
request=mock.Mock(),
)
p = worker.StreamProcessor(redis_stream, redis_cache)
installatio... | data},
)
await worker.async_status()
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_after_read_error(
run_engine, _, redis_stream, redis_cache
):
| 64 | 64 | 190 | 54 | 10 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_retrying_after_read_error | test_stream_processor_retrying_after_read_error | 898 | 919 | 898 | 903 | 9aaf722efa6234afeafb994b647020ea1e0cc3fc | bigcode/the-stack | train |
243fb582ff43b3a9c6395643 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_one_task(
run_engine, _, redis_stream, redis_cache, logger_checker
):
await worker.push(
redis_stream,
123,
"own... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_one_task(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"comment",
... | },
],
)
assert run_engine.mock_calls[2] == mock.call(
InstallationMatcher(owner="owner"),
123,
"repo",
456,
[
{
"event_type": "push",
"data": {"payload": "foobar"},
"timestamp": mock.ANY,
... | 128 | 128 | 428 | 54 | 74 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_with_one_task | test_worker_with_one_task | 265 | 326 | 265 | 270 | 8ea8c0ace8d938377503c034a11cfe27668d1d67 | bigcode/the-stack | train |
a44693e5ecb59f1bb491cc15 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
@mock.patch("mergify_engine.clients.github.aget_client")
@mock.patch("mergify_engine.github_events.extract_pull_numbers_from_event")
async def test_worker_expanded_events(... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
@mock.patch("mergify_engine.clients.github.aget_client")
@mock.patch("mergify_engine.github_events.extract_pull_numbers_from_event")
async def test_worker_expanded_events(... | client = mock.Mock(
name="foo",
owner="owner",
repo="repo",
auth=mock.Mock(
installation={"id": 12345}, owner="owner", repo="repo", owner_id=123
),
)
client.__aenter__ = mock.AsyncMock(return_value=client)
client.__aexit__ = mock.AsyncMock()
client... | with expect data
assert 16 == len(run_engine.mock_calls)
assert (
mock.call(
InstallationMatcher(owner="owner-0"),
0,
"repo-0",
1,
[
{
"event_type": "pull_request",
"data": {"payload": 0}... | 254 | 254 | 848 | 101 | 153 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_expanded_events | test_worker_expanded_events | 132 | 262 | 132 | 145 | 934e7c8b20c7ca7a36aefb2371e70edfbad6998e | bigcode/the-stack | train |
edc3aedeb66d3305de80d27a | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
async def test_worker_debug_report(_, redis_stream, redis_cache, logger_checker):
for installation_id in range(8):
for pull_number in range(2):
for data in range(3):
owner = f"own... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
async def test_worker_debug_report(_, redis_stream, redis_cache, logger_checker):
| for installation_id in range(8):
for pull_number in range(2):
for data in range(3):
owner = f"owner-{installation_id}"
repo = f"repo-{installation_id}"
await worker.push(
redis_stream,
123,
... | 0 == (await redis_stream.zcard("streams"))
assert 0 == len(await redis_stream.hgetall("attempts"))
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
async def test_worker_debug_report(_, redis_stream, redis_cache, logger_checker):
| 63 | 64 | 127 | 35 | 28 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_debug_report | test_worker_debug_report | 876 | 895 | 876 | 878 | 822f12007abf4c281eadd8c665527e6b807dd1b0 | bigcode/the-stack | train |
73bb1f930078dbfbfbeb0a11 | train | class | @dataclasses.dataclass
class InstallationMatcher:
owner: str
def __eq__(self, installation: object) -> bool:
if not isinstance(installation, context.Installation):
return NotImplemented
return self.owner == installation.owner_login
| @dataclasses.dataclass
class InstallationMatcher:
| owner: str
def __eq__(self, installation: object) -> bool:
if not isinstance(installation, context.Installation):
return NotImplemented
return self.owner == installation.owner_login
| redis_stream is None or (await w._redis_stream.zcard("streams")) > 0
) and time.monotonic() - started_at < test_timeout:
await asyncio.sleep(0.5)
w.stop()
await w.wait_shutdown_complete()
@dataclasses.dataclass
class InstallationMatcher:
| 64 | 64 | 53 | 9 | 55 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | InstallationMatcher | InstallationMatcher | 47 | 54 | 47 | 48 | d11714aff432b01241b35b52b289db2ef6b06c84 | bigcode/the-stack | train |
38a71d4e6d518491723abd49 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
async def test_worker_drop_bucket(_, redis_stream, redis_cache, logger_checker):
buckets = set()
bucket_sources = set()
_id = 123
for pull_number in range(2):
for data in range(3):
ow... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
async def test_worker_drop_bucket(_, redis_stream, redis_cache, logger_checker):
| buckets = set()
bucket_sources = set()
_id = 123
for pull_number in range(2):
for data in range(3):
owner = f"owner-{_id}"
repo = f"repo-{_id}"
repo_id = _id
owner_id = _id
buckets.add(f"bucket~{owner_id}~{owner}")
bucket_so... | stream_name is not None
await p.consume(stream_name)
assert 0 == (await redis_stream.zcard("streams"))
assert 0 == len(await redis_stream.keys("bucket~*"))
assert 0 == len(await redis_stream.hgetall("attempts"))
assert received == [wanted_owner_id, unwanted_owner_id]
@pytest.mark.asyncio
@mock... | 106 | 106 | 355 | 35 | 71 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_drop_bucket | test_worker_drop_bucket | 833 | 873 | 833 | 835 | f175572a21951c59ba38f4df5034379758a45bc2 | bigcode/the-stack | train |
0db57063c7f1b2352d814581 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_multiple_workers(
run_engine, _, redis_stream, redis_cache, logger_checker
):
buckets = set()
bucket_sources = set()
for install... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_with_multiple_workers(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| buckets = set()
bucket_sources = set()
for installation_id in range(100):
for pull_number in range(1, 3):
for data in range(3):
owner = f"owner-{installation_id}"
repo = f"repo-{installation_id}"
repo_id = installation_id
ow... | 123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
await run_worker()
# Check redis is empty
assert 0 == (await redis_stream.zcard("streams"))
assert 0 == len(await redis_stream.keys("stream~*"))
assert 0 == len(await redis_stream.hgetall("attempts"))
... | 135 | 136 | 456 | 54 | 81 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_with_multiple_workers | test_worker_with_multiple_workers | 956 | 1,014 | 956 | 961 | 39263c5c7bb7953c188071254e4cc157e823138d | bigcode/the-stack | train |
b8d0aa1c9cdbfbe67ef81321 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_stuck_shutdown(
run_engine, _, redis_stream, redis_cache, logger_checker
):
async def fake_engine(*args, **kwargs):
await asyncio.sle... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_stuck_shutdown(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| async def fake_engine(*args, **kwargs):
await asyncio.sleep(10000000)
run_engine.side_effect = fake_engine
await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
await run_wo... | assert planned_for > planned_for_rescheduled
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_worker_stuck_shutdown(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| 64 | 64 | 140 | 54 | 9 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_worker_stuck_shutdown | test_worker_stuck_shutdown | 1,061 | 1,081 | 1,061 | 1,066 | 5c7a0657bd4eea7befbef90babeee669602f1ad6 | bigcode/the-stack | train |
ad8a4baca1ff0043b2e1676a | train | function | @pytest.mark.asyncio
@mock.patch.object(worker, "LOG")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_stream_failure(
run_engine, _, logger, redis_stream, redis_cache
):
logs.setup_logging()... | @pytest.mark.asyncio
@mock.patch.object(worker, "LOG")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_stream_failure(
run_engine, _, logger, redis_stream, redis_cache
):
| logs.setup_logging()
response = mock.Mock()
response.json.return_value = {"message": "boom"}
response.status_code = 401
run_engine.side_effect = http.HTTPClientSideError(
message="foobar", request=response.request, response=response
)
await worker.push(
redis_stream,
... | b"bucket~123~owner": b"1"} == await redis_stream.hgetall("attempts")
run_engine.side_effect = None
await p.consume("bucket~123~owner")
assert len(run_engine.mock_calls) == 2
assert 0 == (await redis_stream.zcard("streams"))
assert 0 == len(await redis_stream.keys("bucket~*"))
assert 0 == await... | 225 | 225 | 751 | 64 | 161 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_retrying_stream_failure | test_stream_processor_retrying_stream_failure | 624 | 714 | 624 | 630 | 47459b9f07476cbc65b6aead753270069682e0f1 | bigcode/the-stack | train |
711f85aa02804e5646f39846 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_unexisting_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
p = worker.StreamProcessor(redis_stream, redis_cache)
awa... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_unexisting_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| p = worker.StreamProcessor(redis_stream, redis_cache)
await p.consume("buckets~2~notexists")
assert len(run_engine.mock_calls) == 0
| .ANY,
},
],
)
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_unexisting_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| 64 | 64 | 92 | 55 | 9 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_consume_unexisting_stream | test_consume_unexisting_stream | 329 | 337 | 329 | 334 | a48928b20af0ee94305626d6144c76fbb07f0ee2 | bigcode/the-stack | train |
a93a2419dba0782abeff66de | train | function | @pytest.mark.asyncio
@mock.patch.object(worker, "LOG")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_stream_recovered(
run_engine, _, logger, redis_stream, redis_cache
):
logs.setup_logging... | @pytest.mark.asyncio
@mock.patch.object(worker, "LOG")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_stream_recovered(
run_engine, _, logger, redis_stream, redis_cache
):
| logs.setup_logging()
response = mock.Mock()
response.json.return_value = {"message": "boom"}
response.status_code = 401
run_engine.side_effect = http.HTTPClientSideError(
message="foobar", request=response.request, response=response
)
await worker.push(
redis_stream,
... | to process pull request, retrying",
)
assert logger.info.mock_calls[1].args == (
"failed to process pull request, retrying",
)
assert logger.error.mock_calls[0].args == (
"failed to process pull request, abandoning",
)
assert 0 == (await redis_stream.zcard("streams"))
assert... | 203 | 204 | 681 | 65 | 138 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_retrying_stream_recovered | test_stream_processor_retrying_stream_recovered | 535 | 621 | 535 | 541 | 27b20b84c376976a2f9920090b510535ff13c2b6 | bigcode/the-stack | train |
5262ca33a94c23402fa90bca | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.daiquiri.getLogger")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_pull(
run_engine,
_,
logger_class,
redis_stream,
redis... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.daiquiri.getLogger")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_retrying_pull(
run_engine,
_,
logger_class,
redis_stream,
redis... | logs.setup_logging()
logger = logger_class.return_value
# One retries once, the other reaches max_retry
run_engine.side_effect = [
exceptions.MergeableStateUnknown(mock.Mock()),
exceptions.MergeableStateUnknown(mock.Mock()),
mock.Mock(),
exceptions.MergeableStateUnknown(... | assert len(run_engine.mock_calls) == 1
assert run_engine.mock_calls[0] == mock.call(
InstallationMatcher(owner="owner"),
123,
"repo",
123,
[
{
"event_type": "pull_request",
"data": {"payload": "whatever"},
"timestam... | 255 | 256 | 1,055 | 76 | 179 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_retrying_pull | test_stream_processor_retrying_pull | 404 | 532 | 404 | 414 | 60f107455e749c5446de0a86bc4bbe62f8e2fb9a | bigcode/the-stack | train |
a9884e7f06c53bfad6554014 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_date_scheduling(
run_engine, _, redis_stream, redis_cache, logger_checker
):
# Don't process it before 2040
with freeze_time("... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_date_scheduling(
run_engine, _, redis_stream, redis_cache, logger_checker
):
# Don't process it before 2040
| with freeze_time("2040-01-01"):
await worker.push(
redis_stream,
123,
"owner1",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
unwanted_owner_id = "owner1"
with freeze_time("202... | be clean
assert len(run_engine.mock_calls) == 2
assert len(logger.error.mock_calls) == 2
assert logger.error.mock_calls[0].args == ("failed to process pull request",)
assert logger.error.mock_calls[1].args == ("failed to process pull request",)
assert 1 == (await redis_stream.zcard("streams"))
... | 175 | 176 | 589 | 65 | 110 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_date_scheduling | test_stream_processor_date_scheduling | 754 | 830 | 754 | 761 | 980759da9c1dadf90232e5753243badfc4955bc3 | bigcode/the-stack | train |
8a468e21b37acca1c700a5e2 | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_good_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
await worker.push(
redis_stream,
123,
"owne... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_good_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
| await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"comment",
... | .get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_consume_unexisting_stream(
run_engine, _, redis_stream, redis_cache, logger_checker
):
p = worker.StreamProcessor(redis_stream, redis_cache)
await p.consume("buckets~2~notexists")
assert len(run_engine.mock_calls) == 0
@p... | 130 | 130 | 436 | 54 | 75 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_consume_good_stream | test_consume_good_stream | 340 | 401 | 340 | 345 | 3e3ebb962b698b2d79f63d84f0f0b5dc412fd821 | bigcode/the-stack | train |
d5c0184e46ec6aa7541089be | train | function | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.daiquiri.getLogger")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_pull_unexpected_error(
run_engine, _, logger_class, redis_stream, redis_cache
)... | @pytest.mark.asyncio
@mock.patch("mergify_engine.worker.daiquiri.getLogger")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_pull_unexpected_error(
run_engine, _, logger_class, redis_stream, redis_cache
)... | logs.setup_logging()
logger = logger_class.return_value
run_engine.side_effect = Exception
await worker.push(
redis_stream,
123,
"owner",
123,
"repo",
123,
"pull_request",
{"payload": "whatever"},
)
p = worker.StreamProcessor(red... | 1 == len(await redis_stream.hgetall("attempts"))
@pytest.mark.asyncio
@mock.patch("mergify_engine.worker.daiquiri.getLogger")
@mock.patch("mergify_engine.worker.subscription.Subscription.get_subscription")
@mock.patch("mergify_engine.worker.run_engine")
async def test_stream_processor_pull_unexpected_error(
run_eng... | 85 | 86 | 289 | 72 | 13 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | test_stream_processor_pull_unexpected_error | test_stream_processor_pull_unexpected_error | 717 | 751 | 717 | 723 | 1627a67eec594ed6a244496ca0fc26c4f219040b | bigcode/the-stack | train |
d1a9e204ac23565aa9d6a52d | train | function | async def run_worker(test_timeout=10, **kwargs):
w = worker.Worker(**kwargs)
await w.start()
started_at = time.monotonic()
while (
w._redis_stream is None or (await w._redis_stream.zcard("streams")) > 0
) and time.monotonic() - started_at < test_timeout:
await asyncio.sleep(0.5)
... | async def run_worker(test_timeout=10, **kwargs):
| w = worker.Worker(**kwargs)
await w.start()
started_at = time.monotonic()
while (
w._redis_stream is None or (await w._redis_stream.zcard("streams")) > 0
) and time.monotonic() - started_at < test_timeout:
await asyncio.sleep(0.5)
w.stop()
await w.wait_shutdown_complete()
| from mergify_engine import context
from mergify_engine import date
from mergify_engine import exceptions
from mergify_engine import logs
from mergify_engine import worker
from mergify_engine import worker_lua
from mergify_engine.clients import http
async def run_worker(test_timeout=10, **kwargs):
| 64 | 64 | 96 | 12 | 51 | ErwanSimonetti/mergify-engine | mergify_engine/tests/unit/test_worker.py | Python | run_worker | run_worker | 35 | 44 | 35 | 35 | 3b1e76294d3bf7fc9d2bdfce2467bb494caf39ca | bigcode/the-stack | train |
e0f5783819880be34ef032d2 | train | class | class PayloadManager:
payloads: Dict = dict()
@classmethod
def init(cls, payloads: List[Tuple[str, Callable, Tuple, Callable, Tuple, Union[float, None]]]):
for payload in payloads:
cls.payloads[payload[0]] = PayloadProcess(payload)
@classmethod
def initStart(cls, payloads: List... | class PayloadManager:
| payloads: Dict = dict()
@classmethod
def init(cls, payloads: List[Tuple[str, Callable, Tuple, Callable, Tuple, Union[float, None]]]):
for payload in payloads:
cls.payloads[payload[0]] = PayloadProcess(payload)
@classmethod
def initStart(cls, payloads: List[Tuple[str, Callable, ... | from typing import List, Tuple, Dict, Union, Any
from collections.abc import Callable
from .PayloadProcess import PayloadProcess
class PayloadManager:
| 32 | 218 | 728 | 4 | 27 | Colorado-School-of-Mines-Robotics-Club/SpaceGrantMachineVision | Code/source/concurrency/PayloadManager.py | Python | PayloadManager | PayloadManager | 6 | 111 | 6 | 6 | 9f009518c1723695c5427f51344b49fa5b116278 | bigcode/the-stack | train |
21844e22518c0a710b4f3645 | train | function | @app.route("/")
@login_required
def home():
user = current_user.email
passwd = current_user.password
name = current_user.username
return render_template("home.html", user=user, passwd=passwd, username=name)
| @app.route("/")
@login_required
def home():
| user = current_user.email
passwd = current_user.password
name = current_user.username
return render_template("home.html", user=user, passwd=passwd, username=name)
| .filter_by(id=2).first()
user_datastore.add_role_to_user(user=user, role=user_role)
db.session.commit()
return
# =================== ALL CONFIGS ABOVE THE LINE. ============================
# Application Home Page Redirect after Login or Registration.
@app.route("/")
@login_required
def home():
| 63 | 64 | 48 | 9 | 54 | mkeneth/init_flask_Security | flask_secure/__init__.py | Python | home | home | 71 | 77 | 71 | 73 | 3980416293ebe61b48a172532c364cfa658517b2 | bigcode/the-stack | train |
234e6e9c2f33e7dd862ec86b | train | function | @app.route("/admin/")
@roles_required('admin')
def admin():
user = current_user.email
passwd = current_user.password
name = current_user.username
return render_template("home.html", user=user, passwd=passwd, username=name) | @app.route("/admin/")
@roles_required('admin')
def admin():
| user = current_user.email
passwd = current_user.password
name = current_user.username
return render_template("home.html", user=user, passwd=passwd, username=name) | .
@app.route("/")
@login_required
def home():
user = current_user.email
passwd = current_user.password
name = current_user.username
return render_template("home.html", user=user, passwd=passwd, username=name)
@app.route("/admin/")
@roles_required('admin')
def admin():
| 64 | 64 | 53 | 14 | 50 | mkeneth/init_flask_Security | flask_secure/__init__.py | Python | admin | admin | 79 | 85 | 79 | 81 | 33e8e3c89e4a4ec87d87ab9942de3724eacaf222 | bigcode/the-stack | train |
bc65ff8f7187d3f20e6cb598 | train | function | @user_registered.connect_via(app)
def _after_reg_hook(sender, user, **extra):
user_role = Role.query.filter_by(id=2).first()
user_datastore.add_role_to_user(user=user, role=user_role)
db.session.commit()
return
| @user_registered.connect_via(app)
def _after_reg_hook(sender, user, **extra):
| user_role = Role.query.filter_by(id=2).first()
user_datastore.add_role_to_user(user=user, role=user_role)
db.session.commit()
return
| ()
user_datastore.add_role_to_user(user=admin_user, role=user_role)
db.session.commit()
except AttributeError:
pass
# Assigning user roles to all the other people who register.
@user_registered.connect_via(app)
def _after_reg_hook(sender, user, **extra):
| 64 | 64 | 57 | 20 | 44 | mkeneth/init_flask_Security | flask_secure/__init__.py | Python | _after_reg_hook | _after_reg_hook | 61 | 66 | 61 | 62 | 72ce110b447d3db48d55ef0c89987f9ab2a12611 | bigcode/the-stack | train |
bc47c51c9c4e7bab1185c06f | train | class | class RepositoryCollaborator(pulumi.CustomResource):
invitation_id: pulumi.Output[str]
"""
ID of the invitation to be used in `.UserInvitationAccepter`
"""
permission: pulumi.Output[str]
"""
The permission of the outside collaborator for the repository.
Must be one of `pull`, `push`, or ... | class RepositoryCollaborator(pulumi.CustomResource):
| invitation_id: pulumi.Output[str]
"""
ID of the invitation to be used in `.UserInvitationAccepter`
"""
permission: pulumi.Output[str]
"""
The permission of the outside collaborator for the repository.
Must be one of `pull`, `push`, or `admin`. Defaults to `push`.
"""
repository: ... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class Reposito... | 83 | 256 | 1,084 | 10 | 72 | timmyers/pulumi-github | sdk/python/pulumi_github/repository_collaborator.py | Python | RepositoryCollaborator | RepositoryCollaborator | 12 | 116 | 12 | 12 | 32602a5944742fb964630c669a1abff224e056b2 | bigcode/the-stack | train |
eae522ee9e04b90b6be2865a | train | function | def pad(features, multiple, name=None):
"""Pads height and width of tensor to a multiple of `multiple`."""
with tf.name_scope(name, 'pad', values=[features]):
height = tf.shape(features)[1]
width = tf.shape(features)[2]
pad_height = (multiple - height % multiple) % multiple
pad_width = (multiple - ... | def pad(features, multiple, name=None):
| """Pads height and width of tensor to a multiple of `multiple`."""
with tf.name_scope(name, 'pad', values=[features]):
height = tf.shape(features)[1]
width = tf.shape(features)[2]
pad_height = (multiple - height % multiple) % multiple
pad_width = (multiple - width % multiple) % multiple
pad_to... | 0 / blur_steps
output_frames.append(tf.reduce_sum(warped * mask, axis=3))
with tf.name_scope(None, 'outputs', values=[output_frames]):
output = tf.add_n(output_frames) / len(frames)
return output
def pad(features, multiple, name=None):
| 64 | 64 | 213 | 9 | 54 | deepneuralmachine/google-research | motion_blur/train/network.py | Python | pad | pad | 87 | 108 | 87 | 87 | a980df7f05c64c63c3ddb930f27e7bb920142de3 | bigcode/the-stack | train |
407de7278fe1a54f6f1b3bd6 | train | function | def crop(features, height, width, name=None):
"""Crops a rectangle with `height` and `width` from `features`."""
with tf.name_scope(name, 'crop', values=[features]):
y0 = (tf.shape(features)[1] - height) // 2
x0 = (tf.shape(features)[2] - width) // 2
return features[:, y0:y0 + height, x0:x0 + width, :]
| def crop(features, height, width, name=None):
| """Crops a rectangle with `height` and `width` from `features`."""
with tf.name_scope(name, 'crop', values=[features]):
y0 = (tf.shape(features)[1] - height) // 2
x0 = (tf.shape(features)[2] - width) // 2
return features[:, y0:y0 + height, x0:x0 + width, :]
| , padding, mode='CONSTANT')
batch_size = tf.shape(features)[0]
height = tf.shape(features)[1]
width = tf.shape(features)[2]
return tf.reshape(features, [batch_size, height, width, 6])
def crop(features, height, width, name=None):
| 64 | 64 | 99 | 11 | 53 | deepneuralmachine/google-research | motion_blur/train/network.py | Python | crop | crop | 111 | 116 | 111 | 111 | e595fbc7d376053e32acc8745ce65525a7a02ba6 | bigcode/the-stack | train |
4373b5973a491f9a2596c7ef | train | function | def inference(frame_0,
frame_1,
blur_steps=17,
num_convs=3,
levels=((32, 64), (64, 64), (128, 128), (256, 256), 256),
is_training=False):
"""Creates the graph that generates the motion blur from two input frames."""
del is_training # Unused.
... | def inference(frame_0,
frame_1,
blur_steps=17,
num_convs=3,
levels=((32, 64), (64, 64), (128, 128), (256, 256), 256),
is_training=False):
| """Creates the graph that generates the motion blur from two input frames."""
del is_training # Unused.
inputs = tf.concat([frame_0, frame_1], axis=-1)
inputs = tf.identity(inputs, 'inputs')
multiple = 2**(len(levels) - 1)
features = pad(inputs, multiple)
skip_connections = []
with tf.name_scope('e... | :y0 + height, x0:x0 + width, :]
def apply_conv(features, num_channels, name=None):
"""Applies a 3x3 spatial convolution with leaky relu activation."""
return tf.layers.conv2d(
features,
num_channels,
3,
padding='same',
activation=tf.nn.leaky_relu,
name=name)
def inference(frame... | 137 | 137 | 459 | 58 | 79 | deepneuralmachine/google-research | motion_blur/train/network.py | Python | inference | inference | 130 | 181 | 130 | 135 | 9c417f43edb72bb6ca50d4214490f3ca787f6544 | bigcode/the-stack | train |
6a3c505e9f54a9f412d995db | train | function | def apply_line_prediction(inputs,
features,
blur_steps,
learn_alpha=True,
name=None):
"""Applies "Line Prediction" layer to input images."""
inputs.shape.assert_is_compatible_with([None, None, None, 6])
with t... | def apply_line_prediction(inputs,
features,
blur_steps,
learn_alpha=True,
name=None):
| """Applies "Line Prediction" layer to input images."""
inputs.shape.assert_is_compatible_with([None, None, None, 6])
with tf.name_scope(name, 'blur_prediction', values=[inputs, features]):
with tf.name_scope(None, 'input_frames', values=[inputs]):
frames = [inputs[:, :, :, :3], inputs[:, :, :, 3:]]
... | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License... | 182 | 182 | 607 | 22 | 159 | deepneuralmachine/google-research | motion_blur/train/network.py | Python | apply_line_prediction | apply_line_prediction | 30 | 84 | 30 | 34 | 775056928435ec3603678165ede0e60316f52f6d | bigcode/the-stack | train |
7b08c6805ee4d4e723fc5a81 | train | function | def apply_conv(features, num_channels, name=None):
"""Applies a 3x3 spatial convolution with leaky relu activation."""
return tf.layers.conv2d(
features,
num_channels,
3,
padding='same',
activation=tf.nn.leaky_relu,
name=name)
| def apply_conv(features, num_channels, name=None):
| """Applies a 3x3 spatial convolution with leaky relu activation."""
return tf.layers.conv2d(
features,
num_channels,
3,
padding='same',
activation=tf.nn.leaky_relu,
name=name)
| = (tf.shape(features)[1] - height) // 2
x0 = (tf.shape(features)[2] - width) // 2
return features[:, y0:y0 + height, x0:x0 + width, :]
def apply_conv(features, num_channels, name=None):
| 63 | 64 | 65 | 11 | 52 | deepneuralmachine/google-research | motion_blur/train/network.py | Python | apply_conv | apply_conv | 119 | 127 | 119 | 119 | ec6b21799d285acb289a5109add0c126cad54a28 | bigcode/the-stack | train |
32beacf1314bfc96bbad48f0 | train | class | class AccessMixin:
def check_origin(self, origin):
return True
def open(self, id_user):
self.id_user = id_user
def on_close(self):
if self.client.subscribed:
self.client.unsubscribe(self.channel)
self.client.disconnect()
| class AccessMixin:
| def check_origin(self, origin):
return True
def open(self, id_user):
self.id_user = id_user
def on_close(self):
if self.client.subscribed:
self.client.unsubscribe(self.channel)
self.client.disconnect()
| **kwargs)
self.id_user = ''
self.client = tornadoredis.Client()
self.listen()
@tornado.gen.engine
def listen(self):
self.client.connect()
yield tornado.gen.Task(self.client.subscribe, self.channel)
self.client.listen(self.on_message)
class AccessMixin:
| 64 | 64 | 57 | 4 | 60 | Firexd2/social-network | alerts/mixins.py | Python | AccessMixin | AccessMixin | 22 | 33 | 22 | 23 | e29914dffff477c10ea360d045017e5d349cc771 | bigcode/the-stack | train |
bbe659d4ec7a8312ba6bfa6f | train | class | class RedisConnectMixin:
channel = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.id_user = ''
self.client = tornadoredis.Client()
self.listen()
@tornado.gen.engine
def listen(self):
self.client.connect()
yield tornado.... | class RedisConnectMixin:
| channel = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.id_user = ''
self.client = tornadoredis.Client()
self.listen()
@tornado.gen.engine
def listen(self):
self.client.connect()
yield tornado.gen.Task(self.client.subsc... | import tornado.gen
import tornadoredis
class RedisConnectMixin:
| 15 | 64 | 90 | 5 | 9 | Firexd2/social-network | alerts/mixins.py | Python | RedisConnectMixin | RedisConnectMixin | 5 | 19 | 5 | 6 | 924a73f1cb3ec967abeffdc2aaeb71e9e25008a5 | bigcode/the-stack | train |
50e70d8032520c8c35839dd3 | train | class | class HandlerRedisMessages(AccessMixin, RedisConnectMixin):
"""
Собирает все методы для приема сообщений от redis
"""
| class HandlerRedisMessages(AccessMixin, RedisConnectMixin):
| """
Собирает все методы для приема сообщений от redis
"""
| def check_origin(self, origin):
return True
def open(self, id_user):
self.id_user = id_user
def on_close(self):
if self.client.subscribed:
self.client.unsubscribe(self.channel)
self.client.disconnect()
class HandlerRedisMessages(AccessMixin, RedisConnectMixin):... | 64 | 64 | 28 | 12 | 52 | Firexd2/social-network | alerts/mixins.py | Python | HandlerRedisMessages | HandlerRedisMessages | 36 | 39 | 36 | 36 | a1dff0526cd30dcdc460deaf9979f149f0b251d2 | bigcode/the-stack | train |
5cc83598815b356f6734c3a5 | train | function | def enum_field(enum_type):
def encode_enum(value):
return value.value
def decode_enum(t, value):
return t(value)
return field(
metadata={
"dataclasses_json": {
"encoder": encode_enum,
"decoder": partial(decode_enum, enum_type),
... | def enum_field(enum_type):
| def encode_enum(value):
return value.value
def decode_enum(t, value):
return t(value)
return field(
metadata={
"dataclasses_json": {
"encoder": encode_enum,
"decoder": partial(decode_enum, enum_type),
}
}
)
| datetime_utils import fromisoformat
DATETIME_FIELD = field(
metadata={
"dataclasses_json": {
"encoder": datetime.isoformat,
"decoder": fromisoformat,
"mm_field": marshmallow_fields.DateTime(format="iso"),
}
}
)
def enum_field(enum_type):
| 64 | 64 | 69 | 6 | 58 | remo5000/magma | symphony/cli/pyinventory/graphql/add_location_type_mutation.py | Python | enum_field | enum_field | 27 | 41 | 27 | 27 | 8177be76ed9fb19fec406f4c8e15f5e6b05bea29 | bigcode/the-stack | train |
0593c68108f5aec6b2353f27 | train | class | class SurveyQuestionType(Enum):
BOOL = "BOOL"
EMAIL = "EMAIL"
COORDS = "COORDS"
PHONE = "PHONE"
TEXT = "TEXT"
TEXTAREA = "TEXTAREA"
PHOTO = "PHOTO"
WIFI = "WIFI"
CELLULAR = "CELLULAR"
FLOAT = "FLOAT"
INTEGER = "INTEGER"
DATE = "DATE"
| class SurveyQuestionType(Enum):
| BOOL = "BOOL"
EMAIL = "EMAIL"
COORDS = "COORDS"
PHONE = "PHONE"
TEXT = "TEXT"
TEXTAREA = "TEXTAREA"
PHOTO = "PHOTO"
WIFI = "WIFI"
CELLULAR = "CELLULAR"
FLOAT = "FLOAT"
INTEGER = "INTEGER"
DATE = "DATE"
| date = "date"
enum = "enum"
range = "range"
email = "email"
gps_location = "gps_location"
equipment = "equipment"
location = "location"
service = "service"
datetime_local = "datetime_local"
class SurveyQuestionType(Enum):
| 64 | 64 | 87 | 6 | 58 | remo5000/magma | symphony/cli/pyinventory/graphql/add_location_type_mutation.py | Python | SurveyQuestionType | SurveyQuestionType | 60 | 72 | 60 | 60 | e171f9bbf3a5082a8929dfcefe09280a73846519 | bigcode/the-stack | train |
040fce56c4cc18a58bf2525d | train | class | @dataclass_json
@dataclass
class AddLocationTypeInput:
@dataclass_json
@dataclass
class PropertyTypeInput:
name: str
type: PropertyKind = enum_field(PropertyKind)
id: Optional[str] = None
index: Optional[int] = None
category: Optional[str] = None
stringValue: ... | @dataclass_json
@dataclass
class AddLocationTypeInput:
@dataclass_json
@dataclass
| class PropertyTypeInput:
name: str
type: PropertyKind = enum_field(PropertyKind)
id: Optional[str] = None
index: Optional[int] = None
category: Optional[str] = None
stringValue: Optional[str] = None
intValue: Optional[int] = None
booleanValue: Optional... | _local"
class SurveyQuestionType(Enum):
BOOL = "BOOL"
EMAIL = "EMAIL"
COORDS = "COORDS"
PHONE = "PHONE"
TEXT = "TEXT"
TEXTAREA = "TEXTAREA"
PHOTO = "PHOTO"
WIFI = "WIFI"
CELLULAR = "CELLULAR"
FLOAT = "FLOAT"
INTEGER = "INTEGER"
DATE = "DATE"
@dataclass_json
@dataclass
c... | 113 | 113 | 378 | 24 | 89 | remo5000/magma | symphony/cli/pyinventory/graphql/add_location_type_mutation.py | Python | AddLocationTypeInput | AddLocationTypeInput | 75 | 121 | 75 | 79 | ae17521648874c4c118c0e48a5b814a989df082c | bigcode/the-stack | train |
c9ebc432b1765cd13fb2ae2e | train | class | class PropertyKind(Enum):
string = "string"
int = "int"
bool = "bool"
float = "float"
date = "date"
enum = "enum"
range = "range"
email = "email"
gps_location = "gps_location"
equipment = "equipment"
location = "location"
service = "service"
datetime_local = "datetime... | class PropertyKind(Enum):
| string = "string"
int = "int"
bool = "bool"
float = "float"
date = "date"
enum = "enum"
range = "range"
email = "email"
gps_location = "gps_location"
equipment = "equipment"
location = "location"
service = "service"
datetime_local = "datetime_local"
| (value):
return value.value
def decode_enum(t, value):
return t(value)
return field(
metadata={
"dataclasses_json": {
"encoder": encode_enum,
"decoder": partial(decode_enum, enum_type),
}
}
)
class PropertyKind(Enum):
| 64 | 64 | 87 | 5 | 59 | remo5000/magma | symphony/cli/pyinventory/graphql/add_location_type_mutation.py | Python | PropertyKind | PropertyKind | 44 | 57 | 44 | 44 | 3292b50af62aa5dfd1a798a02b90fc058d51ab01 | bigcode/the-stack | train |
9f8418cffea6e4f2d028241c | train | class | @dataclass_json
@dataclass
class AddLocationTypeMutation:
__QUERY__ = """
mutation AddLocationTypeMutation($input: AddLocationTypeInput!) {
addLocationType(input: $input) {
id
name
propertyTypes {
id
name
type
index
stringValue
intValue
booleanValue
... | @dataclass_json
@dataclass
class AddLocationTypeMutation:
| __QUERY__ = """
mutation AddLocationTypeMutation($input: AddLocationTypeInput!) {
addLocationType(input: $input) {
id
name
propertyTypes {
id
name
type
index
stringValue
intValue
booleanValue
floatValue
latitudeValue
longitudeValue
... | id: Optional[str] = None
categoryTitle: str
categoryDescription: str
id: Optional[str] = None
surveyTemplateQuestions: Optional[List[SurveyTemplateQuestionInput]] = None
name: str
properties: List[PropertyTypeInput]
surveyTemplateCategories: List[SurveyTemplateCategoryInpu... | 116 | 116 | 389 | 13 | 102 | remo5000/magma | symphony/cli/pyinventory/graphql/add_location_type_mutation.py | Python | AddLocationTypeMutation | AddLocationTypeMutation | 124 | 188 | 124 | 126 | d04c82614192470cd60cf5b417a4c7a672df680d | bigcode/the-stack | train |
6873218623391a0c6f7a1b61 | train | function | def ShowExceptionClient( e, do_wait = True ):
( etype, value, tb ) = sys.exc_info()
if etype is None:
etype = type( e )
value = str( e )
trace = 'No error trace--here is the stack:' + os.linesep + ''.join( traceback.format_stack() )
else:
... | def ShowExceptionClient( e, do_wait = True ):
| ( etype, value, tb ) = sys.exc_info()
if etype is None:
etype = type( e )
value = str( e )
trace = 'No error trace--here is the stack:' + os.linesep + ''.join( traceback.format_stack() )
else:
trace = ''.join( traceback.format_exceptio... | def OrdIsAlphaLower( o ):
return 97 <= o and o <= 122
def OrdIsAlphaUpper( o ):
return 65 <= o and o <= 90
def OrdIsAlpha( o ):
return OrdIsAlphaLower( o ) or OrdIsAlphaUpper( o )
def OrdIsNumber( o ):
return 48 <= o and o <= 57
def ShowExceptionClient( e, do_wait = Tr... | 101 | 101 | 337 | 13 | 87 | sorashi/hydrus | include/ClientData.py | Python | ShowExceptionClient | ShowExceptionClient | 353 | 415 | 353 | 354 | 641c505f157ab9fdfca771290b99052c471a5155 | bigcode/the-stack | train |
0ffa8d6ae6febbe3f8df14c2 | train | function | def OrdIsAlphaLower( o ):
return 97 <= o and o <= 122
| def OrdIsAlphaLower( o ):
| return 97 <= o and o <= 122
| namespaced_predicate ] = unnamespaced_predicate_dict[ unnamespaced_predicate ]
return list(master_predicate_dict.values())
def OrdIsSensibleASCII( o ):
return 32 <= o and o <= 127
def OrdIsAlphaLower( o ):
| 64 | 64 | 21 | 9 | 54 | sorashi/hydrus | include/ClientData.py | Python | OrdIsAlphaLower | OrdIsAlphaLower | 337 | 339 | 337 | 338 | c8570456eaf5e2f7ae99213460871d5c270c6db1 | bigcode/the-stack | train |
603d69abd19d5ab4ad0a5792 | train | function | def GetDifferentLighterDarkerColour( colour, intensity = 3 ):
new_hue = colour.hsvHueF()
if new_hue == -1: # completely achromatic
new_hue = 0.5
else:
new_hue = ( new_hue + 0.33 ) % 1.0
new_saturation = colour.hsvSaturationF()
i... | def GetDifferentLighterDarkerColour( colour, intensity = 3 ):
| new_hue = colour.hsvHueF()
if new_hue == -1: # completely achromatic
new_hue = 0.5
else:
new_hue = ( new_hue + 0.33 ) % 1.0
new_saturation = colour.hsvSaturationF()
if ColourIsGreyish( colour ):
new_saturation = 0.2
... | _zoom = '{:.2f}%'.format( zoom_percent )
if pretty_zoom.endswith( '00%' ):
pretty_zoom = '{:.0f}%'.format( zoom_percent )
return pretty_zoom
def GetDifferentLighterDarkerColour( colour, intensity = 3 ):
| 64 | 64 | 158 | 17 | 46 | sorashi/hydrus | include/ClientData.py | Python | GetDifferentLighterDarkerColour | GetDifferentLighterDarkerColour | 193 | 215 | 193 | 194 | f5f63b945c75942f5fbecfe1f0237dcfe086a7b7 | bigcode/the-stack | train |
aee4ab3019510a928ce4a1d9 | train | function | def ConvertZoomToPercentage( zoom ):
zoom_percent = zoom * 100
pretty_zoom = '{:.2f}%'.format( zoom_percent )
if pretty_zoom.endswith( '00%' ):
pretty_zoom = '{:.0f}%'.format( zoom_percent )
return pretty_zoom
| def ConvertZoomToPercentage( zoom ):
| zoom_percent = zoom * 100
pretty_zoom = '{:.2f}%'.format( zoom_percent )
if pretty_zoom.endswith( '00%' ):
pretty_zoom = '{:.0f}%'.format( zoom_percent )
return pretty_zoom
| content_updates = [ HydrusData.ContentUpdate( HC.CONTENT_TYPE_MAPPINGS, action, ( tag, hashes ) ) for tag in tags ]
service_keys_to_content_updates[ service_key ] = content_updates
return service_keys_to_content_updates
def ConvertZoomToPercentage( zoom ):
| 64 | 64 | 67 | 9 | 54 | sorashi/hydrus | include/ClientData.py | Python | ConvertZoomToPercentage | ConvertZoomToPercentage | 180 | 191 | 180 | 181 | ed9fe9f911c97e6badbee0a86b8196ec5899bded | bigcode/the-stack | train |
99bcb17770b9b73210507e91 | train | class | class Imageboard( HydrusData.HydrusYAMLBase ):
yaml_tag = '!Imageboard'
def __init__( self, name, post_url, flood_time, form_fields, restrictions ):
self._name = name
self._post_url = post_url
self._flood_time = flood_time
self._form_fields = form_fields
... | class Imageboard( HydrusData.HydrusYAMLBase ):
| yaml_tag = '!Imageboard'
def __init__( self, name, post_url, flood_time, form_fields, restrictions ):
self._name = name
self._post_url = post_url
self._flood_time = flood_time
self._form_fields = form_fields
self._restrictions = restrictions
... | return connection_string
def HasAccessKey( self ): return self._access_key is not None and self._access_key != ''
def SetAccessKey( self, access_key ): self._access_key = access_key
class Imageboard( HydrusData.HydrusYAMLBase ):
| 64 | 64 | 161 | 15 | 48 | sorashi/hydrus | include/ClientData.py | Python | Imageboard | Imageboard | 640 | 662 | 640 | 641 | b57d7124d4c4789ff83b80874d2b754ca93c61a7 | bigcode/the-stack | train |
1d44fe668b245534cc4053ec | train | function | def ConvertServiceKeysToTagsToServiceKeysToContentUpdates( hashes, service_keys_to_tags ):
service_keys_to_content_updates = {}
for ( service_key, tags ) in service_keys_to_tags.items():
if len( tags ) == 0:
continue
try:
... | def ConvertServiceKeysToTagsToServiceKeysToContentUpdates( hashes, service_keys_to_tags ):
| service_keys_to_content_updates = {}
for ( service_key, tags ) in service_keys_to_tags.items():
if len( tags ) == 0:
continue
try:
service = HG.client_controller.services_manager.GetService( service_key )
... | locations ) + '->'
s += ', '.join( actions ) + extra_words + ' ' + HydrusData.ToHumanInt( num_files ) + ' files'
return s
def ConvertServiceKeysToTagsToServiceKeysToContentUpdates( hashes, service_keys_to_tags ):
| 64 | 64 | 184 | 21 | 42 | sorashi/hydrus | include/ClientData.py | Python | ConvertServiceKeysToTagsToServiceKeysToContentUpdates | ConvertServiceKeysToTagsToServiceKeysToContentUpdates | 144 | 178 | 144 | 145 | 29bff33ba4fda84020fb3010b93e773b05391735 | bigcode/the-stack | train |
ea5448cd17133e3326b80f7d | train | class | class Booru( HydrusData.HydrusYAMLBase ):
yaml_tag = '!Booru'
def __init__( self, name, search_url, search_separator, advance_by_page_num, thumb_classname, image_id, image_data, tag_classnames_to_namespaces ):
self._name = name
self._search_url = search_url
self._searc... | class Booru( HydrusData.HydrusYAMLBase ):
| yaml_tag = '!Booru'
def __init__( self, name, search_url, search_separator, advance_by_page_num, thumb_classname, image_id, image_data, tag_classnames_to_namespaces ):
self._name = name
self._search_url = search_url
self._search_separator = search_separator
self._ad... | components.append( service.GetName() )
else:
components.append( 'unknown service!' )
return ' '.join( components )
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable... | 79 | 79 | 266 | 15 | 63 | sorashi/hydrus | include/ClientData.py | Python | Booru | Booru | 561 | 583 | 561 | 562 | 8eacb6eb725e9f554c4941ae421ff76c4e1edfd1 | bigcode/the-stack | train |
b6442be7f86d8cbe7f82d075 | train | class | class Credentials( HydrusData.HydrusYAMLBase ):
yaml_tag = '!Credentials'
def __init__( self, host, port, access_key = None ):
HydrusData.HydrusYAMLBase.__init__( self )
if host == 'localhost':
host = '127.0.0.1'
... | class Credentials( HydrusData.HydrusYAMLBase ):
| yaml_tag = '!Credentials'
def __init__( self, host, port, access_key = None ):
HydrusData.HydrusYAMLBase.__init__( self )
if host == 'localhost':
host = '127.0.0.1'
self._host = host
self._port = port
s... | _data, self._tag_classnames_to_namespaces )
def GetGalleryParsingInfo( self ): return ( self._search_url, self._advance_by_page_num, self._search_separator, self._thumb_classname )
def GetName( self ): return self._name
def GetNamespaces( self ): return list(self._tag_classnames_to_namespaces... | 105 | 105 | 353 | 14 | 91 | sorashi/hydrus | include/ClientData.py | Python | Credentials | Credentials | 587 | 638 | 587 | 588 | d15c6b14ae83b72c613437eb54cb18f706278dbe | bigcode/the-stack | train |
47ef4f34418908a3b8127099 | train | function | def OrdIsAlphaUpper( o ):
return 65 <= o and o <= 90
| def OrdIsAlphaUpper( o ):
| return 65 <= o and o <= 90
|
return list(master_predicate_dict.values())
def OrdIsSensibleASCII( o ):
return 32 <= o and o <= 127
def OrdIsAlphaLower( o ):
return 97 <= o and o <= 122
def OrdIsAlphaUpper( o ):
| 64 | 64 | 21 | 9 | 54 | sorashi/hydrus | include/ClientData.py | Python | OrdIsAlphaUpper | OrdIsAlphaUpper | 341 | 343 | 341 | 342 | fb1a0fe466aedef10cc482d67e63e0016cdeb49b | bigcode/the-stack | train |
18a65387465c85e4ff4ce722 | train | class | class ApplicationCommand( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_APPLICATION_COMMAND
SERIALISABLE_NAME = 'Application Command'
SERIALISABLE_VERSION = 2
def __init__( self, command_type = None, data = None ):
if command_t... | class ApplicationCommand( HydrusSerialisable.SerialisableBase ):
| SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_APPLICATION_COMMAND
SERIALISABLE_NAME = 'Application Command'
SERIALISABLE_VERSION = 2
def __init__( self, command_type = None, data = None ):
if command_type is None:
command_type = CC.APPLICATION_CO... | '__name__' ):
title = str( etype.__name__ )
else:
title = str( etype )
job_key.SetVariable( 'popup_title', title )
job_key.SetVariable( 'popup_text_1', first_line )
job_key.SetVariable( 'popup_... | 213 | 214 | 714 | 13 | 200 | sorashi/hydrus | include/ClientData.py | Python | ApplicationCommand | ApplicationCommand | 430 | 555 | 430 | 431 | d53a93f0a5bc4c98f560466e185f70ebda226efc | bigcode/the-stack | train |
03e9079e4a52f1e86c7adb86 | train | function | def ColourIsGreyish( colour: QG.QColor ):
it_is_greyish = colour.hsvSaturationF() < 0.12
return it_is_greyish
| def ColourIsGreyish( colour: QG.QColor ):
| it_is_greyish = colour.hsvSaturationF() < 0.12
return it_is_greyish
| Text( text )
time.sleep( 1 )
def ColourIsBright( colour: QG.QColor ):
it_is_bright = colour.valueF() > 0.75
return it_is_bright
def ColourIsGreyish( colour: QG.QColor ):
| 64 | 64 | 42 | 14 | 49 | sorashi/hydrus | include/ClientData.py | Python | ColourIsGreyish | ColourIsGreyish | 90 | 94 | 90 | 91 | 7eac2db56ebb2ff896da5c624ccfef8daab63d7a | bigcode/the-stack | train |
c30beec2299d80b37e210479 | train | function | def OrdIsNumber( o ):
return 48 <= o and o <= 57
| def OrdIsNumber( o ):
| return 48 <= o and o <= 57
| 97 <= o and o <= 122
def OrdIsAlphaUpper( o ):
return 65 <= o and o <= 90
def OrdIsAlpha( o ):
return OrdIsAlphaLower( o ) or OrdIsAlphaUpper( o )
def OrdIsNumber( o ):
| 63 | 64 | 20 | 8 | 55 | sorashi/hydrus | include/ClientData.py | Python | OrdIsNumber | OrdIsNumber | 349 | 351 | 349 | 350 | 860cd298bf9d0c8cd332d43e0d3a3474651a889e | bigcode/the-stack | train |
303cfb37a42ed8f6924a73f3 | train | function | def ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates ):
num_files = 0
actions = set()
locations = set()
extra_words = ''
for ( service_key, content_updates ) in list(service_keys_to_content_updates.items()):
if len( content_updates ) >... | def ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates ):
| num_files = 0
actions = set()
locations = set()
extra_words = ''
for ( service_key, content_updates ) in list(service_keys_to_content_updates.items()):
if len( content_updates ) > 0:
name = HG.client_controller.services_manager.GetName( service_key... | right = colour.valueF() > 0.75
return it_is_bright
def ColourIsGreyish( colour: QG.QColor ):
it_is_greyish = colour.hsvSaturationF() < 0.12
return it_is_greyish
def ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates ):
| 79 | 79 | 264 | 18 | 60 | sorashi/hydrus | include/ClientData.py | Python | ConvertServiceKeysToContentUpdatesToPrettyString | ConvertServiceKeysToContentUpdatesToPrettyString | 96 | 142 | 96 | 97 | 45c590f1ad5a0a4dcf37985b52f7189396951dbc | bigcode/the-stack | train |
b6351a8573ae995d389b050d | train | function | def MergePredicates( predicates, add_namespaceless = False ):
master_predicate_dict = {}
for predicate in predicates:
# this works because predicate.__hash__ exists
if predicate in master_predicate_dict:
master_predicate_dict[ predicate ].AddC... | def MergePredicates( predicates, add_namespaceless = False ):
| master_predicate_dict = {}
for predicate in predicates:
# this works because predicate.__hash__ exists
if predicate in master_predicate_dict:
master_predicate_dict[ predicate ].AddCounts( predicate )
else:
... |
elif min_b == 0:
( min_answer, max_answer ) = ( min_a, max_a )
else:
if max_a is None:
max_a = min_a
if max_b is None:
max_b = min_b
min_answer = max(... | 110 | 111 | 373 | 15 | 95 | sorashi/hydrus | include/ClientData.py | Python | MergePredicates | MergePredicates | 275 | 331 | 275 | 276 | 5fa8801c86f6e2696c584f8429e7014b19a80573 | bigcode/the-stack | train |
3323697dadd02ba9e00130ac | train | function | def OrdIsSensibleASCII( o ):
return 32 <= o and o <= 127
| def OrdIsSensibleASCII( o ):
| return 32 <= o and o <= 127
| with our new count total
if count > 1:
master_predicate_dict[ unnamespaced_predicate ] = unnamespaced_predicate_dict[ unnamespaced_predicate ]
return list(master_predicate_dict.values())
def OrdIsSensibleASCII( o ... | 63 | 64 | 22 | 10 | 53 | sorashi/hydrus | include/ClientData.py | Python | OrdIsSensibleASCII | OrdIsSensibleASCII | 333 | 335 | 333 | 334 | c6fe8220530225fb8b8a26eb38c6442f91b645ab | bigcode/the-stack | train |
4b4c9f056a54becd2be7c639 | train | function | def ShowTextClient( text ):
job_key = ClientThreading.JobKey()
job_key.SetVariable( 'popup_text_1', str( text ) )
text = job_key.ToString()
HydrusData.Print( text )
HG.client_controller.pub( 'message', job_key )
| def ShowTextClient( text ):
| job_key = ClientThreading.JobKey()
job_key.SetVariable( 'popup_text_1', str( text ) )
text = job_key.ToString()
HydrusData.Print( text )
HG.client_controller.pub( 'message', job_key )
| = job_key.ToString()
HydrusData.Print( 'Exception:' )
HydrusData.DebugPrint( text )
HG.client_controller.pub( 'message', job_key )
if do_wait:
time.sleep( 1 )
def ShowTextClient( text ):
| 62 | 64 | 67 | 8 | 54 | sorashi/hydrus | include/ClientData.py | Python | ShowTextClient | ShowTextClient | 418 | 428 | 418 | 419 | f8a2ca11b938e7ed9ab3392f47eaa1a9980b8ac0 | bigcode/the-stack | train |
fe001ba1f2c3a39ea6d4230b | train | function | def MergeCounts( min_a, max_a, min_b, max_b ):
# 100-None and 100-None returns 100-200
# 1-None and 4-5 returns 5-6
# 1-2, and 5-7 returns 6, 9
if min_a == 0:
( min_answer, max_answer ) = ( min_b, max_b )
elif min_b == 0:
( min_answer, max_answer ... | def MergeCounts( min_a, max_a, min_b, max_b ):
# 100-None and 100-None returns 100-200
# 1-None and 4-5 returns 5-6
# 1-2, and 5-7 returns 6, 9
| if min_a == 0:
( min_answer, max_answer ) = ( min_b, max_b )
elif min_b == 0:
( min_answer, max_answer ) = ( min_a, max_a )
else:
if max_a is None:
max_a = min_a
if max_b is None:
... | def MergeCounts( min_a, max_a, min_b, max_b ):
# 100-None and 100-None returns 100-200
# 1-None and 4-5 returns 5-6
# 1-2, and 5-7 returns 6, 9
| 70 | 64 | 190 | 70 | 0 | sorashi/hydrus | include/ClientData.py | Python | MergeCounts | MergeCounts | 243 | 273 | 243 | 248 | ff848a993f8a7a3dc3eebfe8fb5043bff38d8fb7 | bigcode/the-stack | train |
596965a2db84d254667dec67 | train | function | def GetLighterDarkerColour( colour, intensity = 3 ):
if intensity is None or intensity == 0:
return colour
# darker/lighter works by multiplying value, so when it is closer to 0, lmao
breddy_darg_made = 0.25
if colour.value() < breddy_darg_made:
... | def GetLighterDarkerColour( colour, intensity = 3 ):
| if intensity is None or intensity == 0:
return colour
# darker/lighter works by multiplying value, so when it is closer to 0, lmao
breddy_darg_made = 0.25
if colour.value() < breddy_darg_made:
colour = QG.QColor.fromHslF( colour.hsvHueF(), colour.hsvS... |
new_colour = QG.QColor.fromHsvF( new_hue, new_saturation, colour.valueF(), colour.alphaF() )
return GetLighterDarkerColour( new_colour, intensity )
def GetLighterDarkerColour( colour, intensity = 3 ):
| 63 | 64 | 170 | 16 | 47 | sorashi/hydrus | include/ClientData.py | Python | GetLighterDarkerColour | GetLighterDarkerColour | 217 | 240 | 217 | 218 | ef729d07fc55b3a2d6432bab8bc7a336560741a7 | bigcode/the-stack | train |
02d8957ac64377e916416aad | train | function | def OrdIsAlpha( o ):
return OrdIsAlphaLower( o ) or OrdIsAlphaUpper( o )
| def OrdIsAlpha( o ):
| return OrdIsAlphaLower( o ) or OrdIsAlphaUpper( o )
| ):
return 32 <= o and o <= 127
def OrdIsAlphaLower( o ):
return 97 <= o and o <= 122
def OrdIsAlphaUpper( o ):
return 65 <= o and o <= 90
def OrdIsAlpha( o ):
| 64 | 64 | 25 | 8 | 55 | sorashi/hydrus | include/ClientData.py | Python | OrdIsAlpha | OrdIsAlpha | 345 | 347 | 345 | 346 | 3c7e5dd4c4de7de08f68118d58f1c479cdd93241 | bigcode/the-stack | train |
3eafdc60464fd22dd88032f4 | train | function | def AddPaddingToDimensions( dimensions, padding ):
( x, y ) = dimensions
return ( x + padding, y + padding )
| def AddPaddingToDimensions( dimensions, padding ):
| ( x, y ) = dimensions
return ( x + padding, y + padding )
| HydrusGlobals as HG
from . import HydrusSerialisable
import traceback
import os
import sqlite3
import sys
import time
import yaml
from qtpy import QtGui as QG
from . import QtPorting as QP
def AddPaddingToDimensions( dimensions, padding ):
| 64 | 64 | 31 | 11 | 52 | sorashi/hydrus | include/ClientData.py | Python | AddPaddingToDimensions | AddPaddingToDimensions | 18 | 22 | 18 | 19 | 7815069c37194025c151e610fec0737e21cb7bf0 | bigcode/the-stack | train |
d5101e3ea03562ce535173ba | train | function | def CatchExceptionClient( etype, value, tb ):
try:
trace_list = traceback.format_tb( tb )
trace = ''.join( trace_list )
pretty_value = str( value )
if os.linesep in pretty_value:
( first_line, anything_else ) = pretty_... | def CatchExceptionClient( etype, value, tb ):
| try:
trace_list = traceback.format_tb( tb )
trace = ''.join( trace_list )
pretty_value = str( value )
if os.linesep in pretty_value:
( first_line, anything_else ) = pretty_value.split( os.linesep, 1 )
... | Globals as HG
from . import HydrusSerialisable
import traceback
import os
import sqlite3
import sys
import time
import yaml
from qtpy import QtGui as QG
from . import QtPorting as QP
def AddPaddingToDimensions( dimensions, padding ):
( x, y ) = dimensions
return ( x + padding, y + padding )
def Catch... | 95 | 96 | 321 | 13 | 82 | sorashi/hydrus | include/ClientData.py | Python | CatchExceptionClient | CatchExceptionClient | 24 | 82 | 24 | 25 | b2616018a20f30a5a71b1ec684fd7007cf97f596 | bigcode/the-stack | train |
c888008205e9d5eec7ce6576 | train | function | def ColourIsBright( colour: QG.QColor ):
it_is_bright = colour.valueF() > 0.75
return it_is_bright
| def ColourIsBright( colour: QG.QColor ):
| it_is_bright = colour.valueF() > 0.75
return it_is_bright
| .linesep
text += str( ( etype, value, tb ) )
try: text += traceback.format_exc()
except: pass
HydrusData.ShowText( text )
time.sleep( 1 )
def ColourIsBright( colour: QG.QColor ):
| 63 | 64 | 36 | 13 | 50 | sorashi/hydrus | include/ClientData.py | Python | ColourIsBright | ColourIsBright | 84 | 88 | 84 | 85 | fff51f5d45bb8cf9cf233726e44b0fd43391f63f | bigcode/the-stack | train |
a3d6639039c790726e9bd9b2 | train | class | class Migration(migrations.Migration):
dependencies = [
('order', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='order',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),... | class Migration(migrations.Migration):
| dependencies = [
('order', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='order',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-02 14:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 64 | 64 | 67 | 7 | 56 | PainterPuppets/GlamorganBookStore | order/migrations/0002_auto_20170702_1451.py | Python | Migration | Migration | 10 | 22 | 10 | 11 | dc40664ac507f310328f02327b533db59166ea2e | bigcode/the-stack | train |
088cfa0e34953d443440bd2e | train | function | def gelu(x, approximate):
if approximate:
y_ref = 0.5 * x * (1.0 + np.tanh(
np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
else:
y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
return y_ref.astype(x.dtype)
| def gelu(x, approximate):
| if approximate:
y_ref = 0.5 * x * (1.0 + np.tanh(
np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
else:
y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
return y_ref.astype(x.dtype)
| permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from scipy.special import erf
import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
import paddle
import paddle.nn.functional as F
def gelu(x, approximate):
| 64 | 64 | 90 | 7 | 56 | DevilCarp/Paddle | python/paddle/fluid/tests/unittests/test_gelu_op.py | Python | gelu | gelu | 26 | 32 | 26 | 26 | 20eb596e6b0c2c9b891e96679b3c86e38296bc26 | bigcode/the-stack | train |
01e2c34cfede6f148f8ae71f | train | class | class TestGeluOp(unittest.TestCase):
def _test_case1_cpu(self, approximate):
x = np.random.uniform(-1, 1, size=(11, 17)).astype(np.float32)
y_ref = gelu(x, approximate)
place = fluid.CPUPlace()
with dg.guard(place) as g:
x_var = dg.to_variable(x)
y_var = flui... | class TestGeluOp(unittest.TestCase):
| def _test_case1_cpu(self, approximate):
x = np.random.uniform(-1, 1, size=(11, 17)).astype(np.float32)
y_ref = gelu(x, approximate)
place = fluid.CPUPlace()
with dg.guard(place) as g:
x_var = dg.to_variable(x)
y_var = fluid.layers.gelu(x_var, approximate)
... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from scipy.special import erf
import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
import paddle
i... | 172 | 172 | 576 | 9 | 163 | DevilCarp/Paddle | python/paddle/fluid/tests/unittests/test_gelu_op.py | Python | TestGeluOp | TestGeluOp | 35 | 92 | 35 | 35 | ee84a92660d5e0843d773d432a821b7c3f4d59ea | bigcode/the-stack | train |
6dd055d00bec6d89ffd7f60b | train | function | @pytest.mark.parametrize("rights", [
([]),
([{
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/"
}, {
"rights": "Copyright (C) 2020. All rights reserved."
... | @pytest.mark.parametrize("rights", [
([]),
([{
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/"
}, {
"rights": "Copyright (C) 2020. All rights reserved."
... | metadata = minimal_record['metadata']
# NOTE: this is done to get possible load transformations out of the way
metadata = MetadataSchema().load(metadata)
metadata['rights'] = rights
assert metadata == MetadataSchema().load(metadata)
| @pytest.mark.parametrize("rights", [
([]),
([{
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/"
}, {
"rights": "Copyright (C) 2020. All rights reserved."
... | 101 | 64 | 153 | 101 | 0 | kprzerwa/invenio-rdm-records | tests/services/schemas/test_right.py | Python | test_valid_rights | test_valid_rights | 62 | 79 | 62 | 73 | 5741022c2599efefbd6c14fc70284639d7b58eb1 | bigcode/the-stack | train |
335af908049708607d294151 | train | function | def test_invalid_extra_right():
invalid_extra = {
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/",
"extra": "field"
}
with pytest.raises(ValidationError):
... | def test_invalid_extra_right():
| invalid_extra = {
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/",
"extra": "field"
}
with pytest.raises(ValidationError):
data = RightsSchema().load... | .raises(ValidationError):
data = RightsSchema().load(invalid_no_right)
@pytest.mark.parametrize("invalid_right", [("MIT"), ({})])
def test_invalid_right(invalid_right):
with pytest.raises(ValidationError):
data = RightsSchema().load(invalid_right)
def test_invalid_extra_right():
| 64 | 64 | 89 | 6 | 58 | kprzerwa/invenio-rdm-records | tests/services/schemas/test_right.py | Python | test_invalid_extra_right | test_invalid_extra_right | 50 | 59 | 50 | 50 | 2865c6ee3c2c76db81319d328262ccc2ec3db495 | bigcode/the-stack | train |
16699beb0139c0744b31ffb2 | train | function | def test_valid_full():
valid_full = {
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/"
}
assert valid_full == RightsSchema().load(valid_full)
| def test_valid_full():
| valid_full = {
"rights": "Creative Commons Attribution 4.0 International",
"scheme": "spdx",
"identifier": "cc-by-4.0",
"uri": "https://creativecommons.org/licenses/by/4.0/"
}
assert valid_full == RightsSchema().load(valid_full)
| ; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Test rights schema."""
import pytest
from marshmallow import ValidationError
from invenio_rdm_records.services.schemas.metadata import MetadataSchema, \
RightsSchema
def test_valid_full():
| 64 | 64 | 74 | 5 | 58 | kprzerwa/invenio-rdm-records | tests/services/schemas/test_right.py | Python | test_valid_full | test_valid_full | 17 | 24 | 17 | 17 | c70ae1edf1ee77eb70684667c4e42055c0b4eb11 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.