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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f1c0355b743e6b3c5a6a7bf | train | function | def retry(howmany):
def tryFunc(func):
def f(*args, **kwargs):
attempts = 0
while attempts < howmany:
try:
return func(*args, **kwargs)
except:
attempts += 1
time.sleep(1)
... | def retry(howmany):
| def tryFunc(func):
def f(*args, **kwargs):
attempts = 0
while attempts < howmany:
try:
return func(*args, **kwargs)
except:
attempts += 1
time.sleep(1)
if attempts >= howma... | ^(https?:\/\/)?([\da-z\.\-\_]+)\.([a-z\.]{2,63})(\/.*)*\/?$"
)
explore_regex = re.compile(r"^\[.+\]\(https?:\/\/[\w\d.\-\/#]+\)$")
def retry(howmany):
| 64 | 64 | 80 | 6 | 58 | Litalku/open-data-registry | ext.py | Python | retry | retry | 24 | 39 | 24 | 24 | 272f88e301ef629df1fb3f05804d2eb2ab283b6a | bigcode/the-stack | train |
407a9f5f798dbb0da9331c49 | train | function | def ext_valid_bucket_regions(value, rule_obj, path):
# Validate required fields in resources
if not isinstance(value, dict):
print("Did not receives a resources dictionary...")
return False
if "Type" not in value:
print("Type is a required resources field")
return False
... | def ext_valid_bucket_regions(value, rule_obj, path):
# Validate required fields in resources
| if not isinstance(value, dict):
print("Did not receives a resources dictionary...")
return False
if "Type" not in value:
print("Type is a required resources field")
return False
if "Description" not in value:
print("Description is a required resources field")
... | exist or there was a momentary glitch".format(url)
)
if not "x-amz-bucket-region" in r.headers:
print(r.headers)
print("{} {} {}".format(r.status_code, r.reason, r.url))
raise Exception("Bucket region missing from request header?")
return r.headers["x-amz-bucket-region"]
def e... | 94 | 95 | 317 | 20 | 74 | Litalku/open-data-registry | ext.py | Python | ext_valid_bucket_regions | ext_valid_bucket_regions | 137 | 181 | 137 | 139 | 164fee4e297d076425ba4774a218de29891f3ecf | bigcode/the-stack | train |
70ddda2d3b4319c7d3eaff58 | train | function | def ext_resources_host(value, rule_obj, path):
if not re.fullmatch(host_regex, value):
print("Host '{}' is not valid".format(value))
return False
return True
| def ext_resources_host(value, rule_obj, path):
| if not re.fullmatch(host_regex, value):
print("Host '{}' is not valid".format(value))
return False
return True
| ):
print(
"ARN '{}' is not valid, it should like like arn:aws:s3:::yourbucket".format(
value
)
)
return False
return True
# Check to make sure we have a valid host
def ext_resources_host(value, rule_obj, path):
| 64 | 64 | 42 | 11 | 52 | Litalku/open-data-registry | ext.py | Python | ext_resources_host | ext_resources_host | 87 | 93 | 87 | 88 | d19a8739600273a205dd7f3f8c0ae747baa8ec30 | bigcode/the-stack | train |
c63d63280a9145e099d4cd7c | train | function | def ext_services(value, rule_obj, path):
if value not in services:
print("Invalid service!", value)
return False
# If we're here, all services were ok
return True
| def ext_services(value, rule_obj, path):
| if value not in services:
print("Invalid service!", value)
return False
# If we're here, all services were ok
return True
| def ext_resources(value, rule_obj, path):
if value not in resources:
print("Invalid resource!", value)
return False
# If we're here, all resources were ok
return True
# Check if provided services are in services.yaml
def ext_services(value, rule_obj, path):
| 64 | 64 | 44 | 10 | 53 | Litalku/open-data-registry | ext.py | Python | ext_services | ext_services | 63 | 69 | 63 | 63 | 15d817d76efe88525cb333c768c6d359eda5bd33 | bigcode/the-stack | train |
a19f1a2f95e7208025013eb7 | train | function | def ext_tags(value, rule_obj, path):
if value not in tags:
print("Invalid tag!", value)
return False
# If we're here, all tags were ok
return True
| def ext_tags(value, rule_obj, path):
| if value not in tags:
print("Invalid tag!", value)
return False
# If we're here, all tags were ok
return True
| :
return func(*args, **kwargs)
except:
attempts += 1
time.sleep(1)
if attempts >= howmany:
raise
return f
return tryFunc
# Check if provided tags are in tags.yaml
def ext_tags(value, r... | 64 | 64 | 44 | 10 | 53 | Litalku/open-data-registry | ext.py | Python | ext_tags | ext_tags | 43 | 49 | 43 | 43 | a439b32351ef1de204f7364f05c727685cd16010 | bigcode/the-stack | train |
89764d261ec01963aa87bb7d | train | function | def ext_resources(value, rule_obj, path):
if value not in resources:
print("Invalid resource!", value)
return False
# If we're here, all resources were ok
return True
| def ext_resources(value, rule_obj, path):
| if value not in resources:
print("Invalid resource!", value)
return False
# If we're here, all resources were ok
return True
| def ext_tags(value, rule_obj, path):
if value not in tags:
print("Invalid tag!", value)
return False
# If we're here, all tags were ok
return True
# Check if provided resources are in resources.yaml
def ext_resources(value, rule_obj, path):
| 64 | 64 | 44 | 10 | 53 | Litalku/open-data-registry | ext.py | Python | ext_resources | ext_resources | 53 | 59 | 53 | 53 | effc5e5f285c872aa6255a24e76eb3635f40ca46 | bigcode/the-stack | train |
3c64aeeefbb3baa872d15e12 | train | function | def ext_resources_arn(value, rule_obj, path):
if not re.fullmatch(arn_regex, value):
print(
"ARN '{}' is not valid, it should like like arn:aws:s3:::yourbucket".format(
value
)
)
return False
return True
| def ext_resources_arn(value, rule_obj, path):
| if not re.fullmatch(arn_regex, value):
print(
"ARN '{}' is not valid, it should like like arn:aws:s3:::yourbucket".format(
value
)
)
return False
return True
| (value, rule_obj, path):
if value not in services:
print("Invalid service!", value)
return False
# If we're here, all services were ok
return True
# Check to make sure we have a valid arn
def ext_resources_arn(value, rule_obj, path):
| 64 | 64 | 65 | 12 | 51 | Litalku/open-data-registry | ext.py | Python | ext_resources_arn | ext_resources_arn | 73 | 83 | 73 | 74 | cacf0bfc0cb5f43b6918007e650fa9e352dd137f | bigcode/the-stack | train |
11837c0148bccc46867dd4e6 | train | class | class Task:
def __init__(self, name):
assert name in ['CartPole-v0', 'MountainCar-v0',
'Pendulum-v0', 'Acrobot-v1']
self.name = name
self.task = gym.make(name)
self.last_state = self.reset()
def reset(self):
state = self.task.re... | class Task:
| def __init__(self, name):
assert name in ['CartPole-v0', 'MountainCar-v0',
'Pendulum-v0', 'Acrobot-v1']
self.name = name
self.task = gym.make(name)
self.last_state = self.reset()
def reset(self):
state = self.task.reset()
sel... | '''
Created on Apr 11, 2018
@author: ywz
'''
import gym
import numpy
import tensorflow as tf
class Task:
| 32 | 108 | 362 | 4 | 27 | jvstinian/Python-Reinforcement-Learning-Projects | Chapter04/task.py | Python | Task | Task | 11 | 62 | 11 | 12 | 4bb207783b6c25cc83c31c1d8179be3e2187436a | bigcode/the-stack | train |
c8c2bd325eb358eb48095439 | train | class | class SessionSaveError(SessionBaseException):
pass
| class SessionSaveError(SessionBaseException):
| pass
| # coding: utf8
class SessionBaseException(BaseException):
pass
class SessionInitializeError(SessionBaseException):
pass
class SessionLoadError(SessionBaseException):
pass
class SessionSaveError(SessionBaseException):
| 46 | 64 | 11 | 8 | 37 | ondrejkajinek/pyGrim | pygrim/components/session/session_exceptions.py | Python | SessionSaveError | SessionSaveError | 16 | 17 | 16 | 16 | 5fa8097a68a1c72a5c37355356c415ab59daf34b | bigcode/the-stack | train |
c42c00bb4044057c4f65f33d | train | class | class SessionLoadError(SessionBaseException):
pass
| class SessionLoadError(SessionBaseException):
| pass
| # coding: utf8
class SessionBaseException(BaseException):
pass
class SessionInitializeError(SessionBaseException):
pass
class SessionLoadError(SessionBaseException):
| 35 | 64 | 11 | 8 | 26 | ondrejkajinek/pyGrim | pygrim/components/session/session_exceptions.py | Python | SessionLoadError | SessionLoadError | 12 | 13 | 12 | 12 | 908e5baf96872f02b67d0df26ae3db96e7b7027d | bigcode/the-stack | train |
cef8e829afe77dde193b5e1a | train | class | class SessionInitializeError(SessionBaseException):
pass
| class SessionInitializeError(SessionBaseException):
| pass
| # coding: utf8
class SessionBaseException(BaseException):
pass
class SessionInitializeError(SessionBaseException):
| 24 | 64 | 11 | 8 | 15 | ondrejkajinek/pyGrim | pygrim/components/session/session_exceptions.py | Python | SessionInitializeError | SessionInitializeError | 8 | 9 | 8 | 8 | b6d20fd13325d35cf155a1b7a20c562a17caa000 | bigcode/the-stack | train |
764682c00300b0b5c4388ee7 | train | class | class SessionBaseException(BaseException):
pass
| class SessionBaseException(BaseException):
| pass
| # coding: utf8
class SessionBaseException(BaseException):
| 13 | 64 | 10 | 7 | 5 | ondrejkajinek/pyGrim | pygrim/components/session/session_exceptions.py | Python | SessionBaseException | SessionBaseException | 4 | 5 | 4 | 4 | 4f84da20bfac89f3633f2900341b2e2d9c47ff23 | bigcode/the-stack | train |
32c831dcd763c46ea319f7b4 | train | function | def Login(*args):
global host, port, user
host, port = entryhost.get().split(':')
user = entryUSER.get()
if not user:
tkinter.messagebox.showwarning('warning', message='User name is empty')
else:
root0.destroy()
| def Login(*args):
| global host, port, user
host, port = entryhost.get().split(':')
user = entryUSER.get()
if not user:
tkinter.messagebox.showwarning('warning', message='User name is empty')
else:
root0.destroy()
| ,text='User name',bg="LightBlue")
labelUSER.place(x=20,y=70,width=100,height=40)
entryUSER = tkinter.Entry(root0, width=60, textvariable=USER)
entryUSER.place(x=120,y=75,width=100,height=30)
def Login(*args):
| 64 | 64 | 61 | 5 | 59 | AustinZhu/cscelab-chatroom | client.py | Python | Login | Login | 40 | 47 | 40 | 40 | 7c53e21e7974b946f7b42014b39128ca19570235 | bigcode/the-stack | train |
475316f3b49855c9c1bb73fa | train | function | def receive():
global uses
while True:
data = s.recv(1024)
data = data.decode()
print(data)
try:
uses = json.loads(data)
listbox1.delete(0, tkinter.END)
listbox1.insert(tkinter.END, "Users online")
listbox1.insert(tkinter.END, "----... | def receive():
| global uses
while True:
data = s.recv(1024)
data = data.decode()
print(data)
try:
uses = json.loads(data)
listbox1.delete(0, tkinter.END)
listbox1.insert(tkinter.END, "Users online")
listbox1.insert(tkinter.END, "------Group chat---... | () + '~' + user + '~' + chat
s.send(message.encode())
INPUT.set('')
sendButton = tkinter.Button(root1, text ="\nsend\n\n\nmessage",anchor = 'n',command = send,font=('Helvetica', 18),bg = 'white')
sendButton.place(x=585,y=320,width=55,height=300)
root1.bind('<Return>', send)
def receive():
| 88 | 88 | 295 | 3 | 85 | AustinZhu/cscelab-chatroom | client.py | Python | receive | receive | 96 | 129 | 96 | 96 | 5a8841226f880636b99eb8ed7c9e214956293525 | bigcode/the-stack | train |
ac8e57fa42ff03a2c2774328 | train | function | def send(*args):
message = entryIuput.get() + '~' + user + '~' + chat
s.send(message.encode())
INPUT.set('')
| def send(*args):
| message = entryIuput.get() + '~' + user + '~' + chat
s.send(message.encode())
INPUT.set('')
| , textvariable=INPUT)
entryIuput.place(x=5,y=320,width=580,height=170)
# online user list
listbox1 = tkinter.Listbox(root1)
listbox1.place(x=510, y=0, width=130, height=320)
def send(*args):
| 64 | 64 | 35 | 5 | 59 | AustinZhu/cscelab-chatroom | client.py | Python | send | send | 86 | 89 | 86 | 86 | 1b524891ecc51f64fa01f0a62f3c2fd1be5aa43b | bigcode/the-stack | train |
1639377440f4f33a84821b6b | train | function | def fibonacci_range(end_point):
"""
fibonnacci_range is a generator function inspired by the range function of python. It produces one fibonnaci number
at a time. The end_point argument signify till which number you want the fibonnacci numbers
:param end_point: integer value. The numbers will be produ... | def fibonacci_range(end_point):
| """
fibonnacci_range is a generator function inspired by the range function of python. It produces one fibonnaci number
at a time. The end_point argument signify till which number you want the fibonnacci numbers
:param end_point: integer value. The numbers will be produced by the generator function ti... | , 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
"""
def fibonacci_range(end_point):
| 64 | 64 | 140 | 6 | 58 | bhavuckj/Journey-with-Euler-Project | Even Fibonacci numbers/solution.py | Python | fibonacci_range | fibonacci_range | 14 | 29 | 14 | 14 | a7863f404f4bcfc778768f2ed165baa402254955 | bigcode/the-stack | train |
34ba776816c4493c49d60f32 | train | class | class Breakpad(recipe_util.Recipe):
@staticmethod
def fetch_spec(props):
url = 'https://chromium.googlesource.com/breakpad/breakpad.git'
solution = {
'name': 'src',
'url': url,
'managed': False,
'custom_deps': {},
'safesync_url': '',
}
spec = {
'solutions': [solut... | class Breakpad(recipe_util.Recipe):
@staticmethod
| def fetch_spec(props):
url = 'https://chromium.googlesource.com/breakpad/breakpad.git'
solution = {
'name': 'src',
'url': url,
'managed': False,
'custom_deps': {},
'safesync_url': '',
}
spec = {
'solutions': [solution],
}
if props.get('target_os'):
spe... | that can be
# found in the LICENSE file.
import sys
import recipe_util # pylint: disable=F0401
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=W0232
class Breakpad(recipe_util.Recipe):
@staticmethod
| 64 | 64 | 177 | 12 | 51 | QtyearLin/depot_tools | recipes/breakpad.py | Python | Breakpad | Breakpad | 12 | 37 | 12 | 13 | 66bbf5eb9b8f3d7bb264ef0a47159391b514ba27 | bigcode/the-stack | train |
d71c53816e2eaad8017936fa | train | function | def main(argv=None):
return Breakpad().handle_args(argv)
| def main(argv=None):
| return Breakpad().handle_args(argv)
| .get('target_os_only'):
spec['target_os_only'] = props['target_os_only']
return {
'type': 'gclient_git',
'gclient_git_spec': spec,
}
@staticmethod
def expected_root(_props):
return 'src'
def main(argv=None):
| 64 | 64 | 14 | 5 | 59 | QtyearLin/depot_tools | recipes/breakpad.py | Python | main | main | 40 | 41 | 40 | 40 | 1755bbfe63ec67fe97b76f6a54d8f5923f71970a | bigcode/the-stack | train |
1dd962ac55d35d64f29a7d7d | train | function | def main(model_path=None, data_path=None):
model = ResidualCNN()
if model_path != None:
model.load(model_path)
training_data_X = None
training_data_y = None
if data_path != None:
file = h5py.File(data_path, 'r')
training_data_X = np.copy(file['X'])
training_data_y = ... | def main(model_path=None, data_path=None):
| model = ResidualCNN()
if model_path != None:
model.load(model_path)
training_data_X = None
training_data_y = None
if data_path != None:
file = h5py.File(data_path, 'r')
training_data_X = np.copy(file['X'])
training_data_y = np.copy(file['y'])
else:
genera... | import numpy as np
import sys
import copy
import random
import keras
import pommerman
import h5py
import constants
from pommerman import agents
import data_generator
from model import ResidualCNN
def main(model_path=None, data_path=None):
| 58 | 64 | 196 | 10 | 47 | amy-cao/playground | pommerman/train_phase1.py | Python | main | main | 15 | 34 | 15 | 15 | 21503bc9e5ac44fcacf958130c5ddeda923ce2c0 | bigcode/the-stack | train |
14a9a0963aa3800abbf7ae38 | train | class | class TripletClient(object):
def __init__(self,url="http://concreteflows.ijs.si/tripletserver/"):
self.base_url = url
@property
def base_url(self):
return self._base_url
@base_url.setter
def base_url(self, value):
self._base_url = value
def reverb(self,text):
r... | class TripletClient(object):
| def __init__(self,url="http://concreteflows.ijs.si/tripletserver/"):
self.base_url = url
@property
def base_url(self):
return self._base_url
@base_url.setter
def base_url(self, value):
self._base_url = value
def reverb(self,text):
r = requests.post(self.base_ur... | Ollie license see below
#---- this script uses the ReVerb triplet extractor, thus follows the ReVerb Software License Agreement (http://reverb.cs.washington.edu/LICENSE.txt)
#---- for the text of the ReVerb license see below
import requests
import json
class TripletClient(object):
| 64 | 64 | 145 | 6 | 57 | xflows/cf_streaming | cf_streaming/tripletclient.py | Python | TripletClient | TripletClient | 10 | 28 | 10 | 10 | f4c13965dab69394251aa312951550f3814962e6 | bigcode/the-stack | train |
770038d40f53a2321ce0c1cb | train | class | class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""
| class TimerError(Exception):
| """A custom exception used to report errors in use of Timer class"""
| _ip', 'numDigits', 'numImages', 'numLinks', 'numParams',
'numTitles', 'num_%20', 'num_@', 'sbr', 'scriptLength', 'specialChars',
'sscr', 'urlIsLive', 'urlLength']
class TimerError(Exception):
| 64 | 64 | 20 | 5 | 59 | deepchecks/url_classification_dl | GUI/gui.py | Python | TimerError | TimerError | 22 | 23 | 22 | 22 | 7a9e47a97569383d3adcc7f45a0254912d106673 | bigcode/the-stack | train |
56a4a7f35d7bff91acbf2c0a | train | class | class Timer:
def __init__(self):
self._start_time = None
def start(self):
"""Start a new timer"""
if self._start_time is not None:
raise TimerError(f"Timer is running. Use .stop() to stop it")
self._start_time = time.perf_counter()
def stop(self):
"""St... | class Timer:
| def __init__(self):
self._start_time = None
def start(self):
"""Start a new timer"""
if self._start_time is not None:
raise TimerError(f"Timer is running. Use .stop() to stop it")
self._start_time = time.perf_counter()
def stop(self):
"""Stop the timer,... | 'numTitles', 'num_%20', 'num_@', 'sbr', 'scriptLength', 'specialChars',
'sscr', 'urlIsLive', 'urlLength']
class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""
class Timer:
| 63 | 64 | 156 | 3 | 60 | deepchecks/url_classification_dl | GUI/gui.py | Python | Timer | Timer | 25 | 43 | 25 | 25 | ae25c67fa351e76cd529d1641f4039353935c3a2 | bigcode/the-stack | train |
58a994bb258d027aaaf7215f | train | function | def __str16bytes(arg):
if len(arg) > 16:
raise argparse.ArgumentTypeError("Invalid key: must be a 16-bytes string")
remaining = 16 - len(arg)
return "_" * remaining + arg
| def __str16bytes(arg):
| if len(arg) > 16:
raise argparse.ArgumentTypeError("Invalid key: must be a 16-bytes string")
remaining = 16 - len(arg)
return "_" * remaining + arg
| log.addHandler(stream_handler)
def __int16bits(arg):
arg = int(arg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError("Invalid Module ID: must be between 0 and 65535")
return arg
def __str16bytes(arg):
| 64 | 64 | 52 | 7 | 56 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __str16bytes | __str16bytes | 55 | 61 | 55 | 55 | b3d506d79245004200de69c410532ac8b4ae29a3 | bigcode/the-stack | train |
5a6e6b169394546b04b89f09 | train | function | def __output_dir(arg):
if not os.path.exists(arg):
return arg
else:
raise argparse.ArgumentTypeError("Output dir {} already exists".format(arg))
| def __output_dir(arg):
| if not os.path.exists(arg):
return arg
else:
raise argparse.ArgumentTypeError("Output dir {} already exists".format(arg))
| if arg == "notset":
return logging.NOTSET
raise argparse.ArgumentTypeError("Invalid log level")
def __input_dir(arg):
if os.path.isdir(arg):
return arg
else:
raise argparse.ArgumentTypeError("Input dir does not exist")
def __output_dir(arg):
| 64 | 64 | 37 | 6 | 58 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __output_dir | __output_dir | 97 | 101 | 97 | 97 | 8fd6e2f51f82e1ba4f49004ef2d9f4ab55b4c71d | bigcode/the-stack | train |
469c89db2ce500bacd13aa8d | train | function | def __input_dir(arg):
if os.path.isdir(arg):
return arg
else:
raise argparse.ArgumentTypeError("Input dir does not exist")
| def __input_dir(arg):
| if os.path.isdir(arg):
return arg
else:
raise argparse.ArgumentTypeError("Input dir does not exist")
| == "warning":
return logging.WARNING
if arg == "info":
return logging.INFO
if arg == "debug":
return logging.DEBUG
if arg == "notset":
return logging.NOTSET
raise argparse.ArgumentTypeError("Invalid log level")
def __input_dir(arg):
| 64 | 64 | 33 | 6 | 58 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __input_dir | __input_dir | 90 | 94 | 90 | 90 | 5a5d670afc699f1e32b7cc7311d7ee1a3461b06a | bigcode/the-stack | train |
52315bd5b1d4660da90d6ef5 | train | function | def __log_level(arg):
arg = arg.lower()
if arg == "critical":
return logging.CRITICAL
if arg == "error":
return logging.ERROR
if arg == "warning":
return logging.WARNING
if arg == "info":
return logging.INFO
if arg == "debug":
return logging.DEBUG
if ... | def __log_level(arg):
| arg = arg.lower()
if arg == "critical":
return logging.CRITICAL
if arg == "error":
return logging.ERROR
if arg == "warning":
return logging.WARNING
if arg == "info":
return logging.INFO
if arg == "debug":
return logging.DEBUG
if arg == "notset":
... | key: must be a 16-bytes string")
remaining = 16 - len(arg)
return "_" * remaining + arg
def __runner(arg):
try:
return Runner.from_str(arg)
except:
raise argparse.ArgumentTypeError("Runner does not exist")
def __log_level(arg):
| 64 | 64 | 98 | 6 | 58 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __log_level | __log_level | 71 | 87 | 71 | 71 | 5a71a68ea476756f047e724fca4e59a8e20ec614 | bigcode/the-stack | train |
5d518971d2ff6c8228c56d14 | train | function | def __int16bits(arg):
arg = int(arg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError("Invalid Module ID: must be between 0 and 65535")
return arg
| def __int16bits(arg):
| arg = int(arg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError("Invalid Module ID: must be between 0 and 65535")
return arg
| (cformat, date_format,
log_colors=colors)
else:
formatter = logging.Formatter(format_str, date_format)
log.setLevel(loglevel)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
def __in... | 64 | 64 | 51 | 7 | 57 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __int16bits | __int16bits | 47 | 52 | 47 | 47 | 15d5c7d1c654ef1f8647af93a88499ab7daec8b7 | bigcode/the-stack | train |
a62040e73036bb40e84f8532 | train | function | def __sp_key(arg):
if os.path.exists(arg):
return arg
else:
raise argparse.ArgumentTypeError("ra_sp public key file does not exist")
| def __sp_key(arg):
| if os.path.exists(arg):
return arg
else:
raise argparse.ArgumentTypeError("ra_sp public key file does not exist")
| ):
return arg
else:
raise argparse.ArgumentTypeError("Input dir does not exist")
def __output_dir(arg):
if not os.path.exists(arg):
return arg
else:
raise argparse.ArgumentTypeError("Output dir {} already exists".format(arg))
def __sp_key(arg):
| 64 | 64 | 36 | 6 | 58 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __sp_key | __sp_key | 104 | 108 | 104 | 104 | 112242e7199768771d182d1895aea53635969ccf | bigcode/the-stack | train |
30d06703cd6d7204c9d23a95 | train | function | def __runner(arg):
try:
return Runner.from_str(arg)
except:
raise argparse.ArgumentTypeError("Runner does not exist")
| def __runner(arg):
| try:
return Runner.from_str(arg)
except:
raise argparse.ArgumentTypeError("Runner does not exist")
| 65535")
return arg
def __str16bytes(arg):
if len(arg) > 16:
raise argparse.ArgumentTypeError("Invalid key: must be a 16-bytes string")
remaining = 16 - len(arg)
return "_" * remaining + arg
def __runner(arg):
| 64 | 64 | 30 | 5 | 58 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | __runner | __runner | 64 | 68 | 64 | 64 | 5dac69398fee884a2da2368430d6bef78ddea62b | bigcode/the-stack | train |
30b5ef8e790931e09a9e36e2 | train | function | def _set_parser():
parser = argparse.ArgumentParser(description='Rust code generator for Authentic Execution')
parser.add_argument('-l', '--loglevel', nargs='?', default=conf.DEFAULT_LOG_LEVEL, type=__log_level)
parser.add_argument('-i', '--input', required=True, type=__input_dir, help='Input folder of the ... | def _set_parser():
| parser = argparse.ArgumentParser(description='Rust code generator for Authentic Execution')
parser.add_argument('-l', '--loglevel', nargs='?', default=conf.DEFAULT_LOG_LEVEL, type=__log_level)
parser.add_argument('-i', '--input', required=True, type=__input_dir, help='Input folder of the software module')
... | import sys
import argparse
import logging
import colorlog
import os
import base64
from . import conf
from .runner import Runner
def _set_parser():
| 36 | 72 | 240 | 5 | 30 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | _set_parser | _set_parser | 11 | 21 | 11 | 11 | 8c73c5e1f1134030812f3d2b6fe1aa856c4ed8cc | bigcode/the-stack | train |
af151668649c2a839ede01bb | train | function | def _set_logging(loglevel):
log = logging.getLogger()
format_str = '%(asctime)s.%(msecs)03d - %(levelname)-8s: %(message)s'
date_format = '%H:%M:%S' #'%Y-%m-%d %H:%M:%S'
if os.isatty(2):
cformat = '%(log_color)s' + format_str
colors = {'DEBUG': 'reset',
'INFO': 'bold_g... | def _set_logging(loglevel):
| log = logging.getLogger()
format_str = '%(asctime)s.%(msecs)03d - %(levelname)-8s: %(message)s'
date_format = '%H:%M:%S' #'%Y-%m-%d %H:%M:%S'
if os.isatty(2):
cformat = '%(log_color)s' + format_str
colors = {'DEBUG': 'reset',
'INFO': 'bold_green',
'WA... | help='Runner name')
parser.add_argument('-s', '--spkey', required=False, type=__sp_key, help='Path to ra_sp public key')
parser.add_argument('-p', '--print', help='Output JSON file (module infos)')
return parser
def _set_logging(loglevel):
| 64 | 64 | 198 | 7 | 56 | gianlu33/rust-sgx-gen | rustsgxgen/initialization.py | Python | _set_logging | _set_logging | 24 | 44 | 24 | 24 | 79c40164c5e090b1ed477af0d766b1f975f97346 | bigcode/the-stack | train |
a7bcf72d91cb3f08313f40ce | train | class | class Column(object):
"""An immutable structure for storing data and mask for a column.
This should be considered as the physical layer that provides
container operations on the data and mask.
These operations work on each data element as plain-old-data.
Any logical operations are implemented in su... | class Column(object):
| """An immutable structure for storing data and mask for a column.
This should be considered as the physical layer that provides
container operations on the data and mask.
These operations work on each data element as plain-old-data.
Any logical operations are implemented in subclasses of *TypedColu... | # Copyright (c) 2018, NVIDIA CORPORATION.
"""
A column is data + validity-mask.
LibGDF operates on column.
"""
import pickle
from numbers import Number
import numpy as np
import pandas as pd
import nvstrings
from librmm_cffi import librmm as rmm
import cudf.bindings.quantile as cpp_quantile
from cudf.bindings.conca... | 146 | 256 | 5,568 | 4 | 141 | razajafri/cudf | python/cudf/cudf/dataframe/column.py | Python | Column | Column | 24 | 802 | 24 | 24 | e911dba4dbf81ac3d53f489e2c14057069af76a2 | bigcode/the-stack | train |
6cc0431f6302097c550c7c00 | train | function | def create(kernel):
result = Tangible()
result.template = "object/tangible/component/droid/shared_manipulator_arm.iff"
result.attribute_template_id = -1
result.stfName("craft_droid_ingredients_n","manipulator_arm")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Tangible()
result.template = "object/tangible/component/droid/shared_manipulator_arm.iff"
result.attribute_template_id = -1
result.stfName("craft_droid_ingredients_n","manipulator_arm")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 73 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/tangible/component/droid/shared_manipulator_arm.py | Python | create | create | 7 | 17 | 7 | 7 | f30f76465ac968b945ab002c19951e70f2990b2b | bigcode/the-stack | train |
635cc3b9f2f7aa8cba5ea138 | train | class | class SimpleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_hand... | class SimpleSwitch13(app_manager.RyuApp):
| OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.d... | from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import... | 119 | 256 | 1,059 | 10 | 108 | jfyao90/SDN_DDoS_Simulation | simple_switch_13.py | Python | SimpleSwitch13 | SimpleSwitch13 | 14 | 136 | 14 | 14 | f230b7175f7423b8db5702cdb332374c47742d82 | bigcode/the-stack | train |
379f30fe42edf92ead21a9a1 | train | class | class AlertHandler(object):
TIME_PATTERN = "%Y-%m-%dT%H:%M:%S%z"
ALERT_LEVEL_MAP = {'error': constants.Severity.CRITICAL,
'warning': constants.Severity.WARNING,
'info': constants.Severity.INFORMATIONAL
}
SECONDS_TO_MS = 1000
def par... | class AlertHandler(object):
| TIME_PATTERN = "%Y-%m-%dT%H:%M:%S%z"
ALERT_LEVEL_MAP = {'error': constants.Severity.CRITICAL,
'warning': constants.Severity.WARNING,
'info': constants.Severity.INFORMATIONAL
}
SECONDS_TO_MS = 1000
def parse_queried_alerts(self, alert... | #
# 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 for the specific language governing permissions and
# limitations under the License.
im... | 111 | 111 | 370 | 5 | 106 | guankc/delfin | delfin/drivers/ibm/ds8k/alert_handler.py | Python | AlertHandler | AlertHandler | 26 | 67 | 26 | 27 | 1084d55010729dd9ad3c5ca1753c5369578a4df5 | bigcode/the-stack | train |
1bf65e5839627ff89ee68857 | train | class | class Plugin_OBJ():
def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
self.plugin_utils = plugin_utils
self.webwatch_html = Watch_HTML(fhdhr, plugin_utils)
self.webwatch_api = WebWatch_Tuner(fhdhr, plugin_utils)
| class Plugin_OBJ():
| def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
self.plugin_utils = plugin_utils
self.webwatch_html = Watch_HTML(fhdhr, plugin_utils)
self.webwatch_api = WebWatch_Tuner(fhdhr, plugin_utils)
|
from .webwatch_html import Watch_HTML
from .webwatch_api import WebWatch_Tuner
class Plugin_OBJ():
| 25 | 64 | 68 | 4 | 20 | deathbybandaid/fHDHR_plugin_web_watch | web/__init__.py | Python | Plugin_OBJ | Plugin_OBJ | 6 | 13 | 6 | 7 | 24fd7ae5e9af9925909dfd35f1af4d795f37f5a1 | bigcode/the-stack | train |
11d85b5e5801ae6cc8884ec6 | train | class | class MockSSHClient(BaseSSHClient):
pass
| class MockSSHClient(BaseSSHClient):
| pass
| self.logger.debug('Executing command: "%s"' % (' '.join(full_cmd)))
child = subprocess.Popen(full_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = child.communicate()
return (stdout, stderr, child.returncode)
class MockSSHClient... | 64 | 64 | 11 | 8 | 56 | Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/compute/ssh.py | Python | MockSSHClient | MockSSHClient | 526 | 527 | 526 | 526 | 93e8257649426900d3c2bcbdcb186a83706cd3a3 | bigcode/the-stack | train |
4dd52aa4b3c2148a8b5de4cd | train | class | class BaseSSHClient(object):
"""
Base class representing a connection over SSH/SCP to a remote node.
"""
def __init__(self, hostname, port=22, username='root', password=None,
key=None, key_files=None, timeout=None):
"""
:type hostname: ``str``
:keyword ... | class BaseSSHClient(object):
| """
Base class representing a connection over SSH/SCP to a remote node.
"""
def __init__(self, hostname, port=22, username='root', password=None,
key=None, key_files=None, timeout=None):
"""
:type hostname: ``str``
:keyword hostname: Hostname or IP addre... | ERROR: type should be string, got " https://bugs.launchpad.net/paramiko/+bug/392973\r\n\r\nimport os\r\nimport time\r\nimport subprocess\r\nimport logging\r\nimport warnings\r\n\r\nfrom os.path import split as psplit\r\nfrom os.path import join as pjoin\r\n\r\nfrom libcloud.utils.logging import ExtraLogFormatter\r\nfrom libcloud.utils.py3 import StringIO\r\nfrom libcloud.utils.py3 import b\r\n\r\n__all__ = [\r\n 'BaseSSHClient',\r\n 'ParamikoSSHClient',\r\n 'ShellOutSSHClient',\r\n\r\n 'SSHCommandTimeoutError'\r\n]\r\n\r\n\r\nclass SSHCommandTimeoutError(Exception):\r\n \"\"\"\r\n Exception which is raised when an SSH command times out.\r\n \"\"\"\r\n def __init__(self, cmd, timeout):\r\n self.cmd = cmd\r\n self.timeout = timeout\r\n message = 'Command didn\\'t finish in %s seconds' % (timeout)\r\n super(SSHCommandTimeoutError, self).__init__(message)\r\n\r\n def __repr__(self):\r\n return ('<SSHCommandTimeoutError: cmd=\"%s\",timeout=%s)>' %\r\n (self.cmd, self.timeout))\r\n\r\n def __str__(self):\r\n return self.message\nclass BaseSSHClient(object):\r\n" | 243 | 243 | 813 | 6 | 236 | Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/compute/ssh.py | Python | BaseSSHClient | BaseSSHClient | 72 | 194 | 72 | 72 | 19fd2e563418bf140ce033c56aed5e4c292e5593 | bigcode/the-stack | train |
9569774360e2910b7379c88d | train | class | class SSHCommandTimeoutError(Exception):
"""
Exception which is raised when an SSH command times out.
"""
def __init__(self, cmd, timeout):
self.cmd = cmd
self.timeout = timeout
message = 'Command didn\'t finish in %s seconds' % (timeout)
super(SSHCommandTimeoutEr... | class SSHCommandTimeoutError(Exception):
| """
Exception which is raised when an SSH command times out.
"""
def __init__(self, cmd, timeout):
self.cmd = cmd
self.timeout = timeout
message = 'Command didn\'t finish in %s seconds' % (timeout)
super(SSHCommandTimeoutError, self).__init__(message)
def __... | LogFormatter
from libcloud.utils.py3 import StringIO
from libcloud.utils.py3 import b
__all__ = [
'BaseSSHClient',
'ParamikoSSHClient',
'ShellOutSSHClient',
'SSHCommandTimeoutError'
]
class SSHCommandTimeoutError(Exception):
| 63 | 64 | 125 | 7 | 56 | Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/compute/ssh.py | Python | SSHCommandTimeoutError | SSHCommandTimeoutError | 54 | 69 | 54 | 54 | 599c60bc7fca3f7f5cbca19b760044d0153a1aea | bigcode/the-stack | train |
22b3fb0b545f0e46c92cecde | train | class | class ParamikoSSHClient(BaseSSHClient):
"""
A SSH Client powered by Paramiko.
"""
# Maximum number of bytes to read at once from a socket
CHUNK_SIZE = 1024
# How long to sleep while waiting for command to finish
SLEEP_DELAY = 1.5
def __init__(self, hostname, port=22, username... | class ParamikoSSHClient(BaseSSHClient):
| """
A SSH Client powered by Paramiko.
"""
# Maximum number of bytes to read at once from a socket
CHUNK_SIZE = 1024
# How long to sleep while waiting for command to finish
SLEEP_DELAY = 1.5
def __init__(self, hostname, port=22, username='root', password=None,
... | the remote node.
:return: True if the file has been successfully deleted, False
otherwise.
:rtype: ``bool``
"""
raise NotImplementedError(
'delete not implemented for this ssh client')
def run(self, cmd):
"""
Run a command on... | 256 | 256 | 1,602 | 9 | 246 | Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/compute/ssh.py | Python | ParamikoSSHClient | ParamikoSSHClient | 197 | 431 | 197 | 197 | 8e823a474cff30897559abf6b681aecd200c7855 | bigcode/the-stack | train |
6681c05b158a89d565d30a66 | train | class | class ShellOutSSHClient(BaseSSHClient):
"""
This client shells out to "ssh" binary to run commands on the remote
server.
Note: This client should not be used in production.
"""
def __init__(self, hostname, port=22, username='root', password=None,
key=None, key_files=N... | class ShellOutSSHClient(BaseSSHClient):
| """
This client shells out to "ssh" binary to run commands on the remote
server.
Note: This client should not be used in production.
"""
def __init__(self, hostname, port=22, username='root', password=None,
key=None, key_files=None, timeout=None):
super(ShellO... | stdout, '_stderr': stderr}
self.logger.debug('Command finished', extra=extra)
return [stdout, stderr, status]
def close(self):
self.logger.debug('Closing server connection')
self.client.close()
return True
def _get_pkey_object(self, key):
"""
... | 182 | 182 | 607 | 9 | 173 | Hybrid-Cloud/badam | patches_tool/aws_patch/aws_deps/libcloud/compute/ssh.py | Python | ShellOutSSHClient | ShellOutSSHClient | 434 | 523 | 434 | 434 | c9c78801fc5637a4576fe0c1661b90e9d647784c | bigcode/the-stack | train |
9a60232de2357248f447f9d9 | train | class | class ZoneAttributeListAPIv2Adapter(base.APIv2Adapter):
ADAPTER_OBJECT = objects.ZoneAttributeList
MODIFICATIONS = {
'options': {
'links': False,
'resource_name': 'zone_attribute',
'collection_name': 'zone_attributes',
}
}
@classmethod
def _rend... | class ZoneAttributeListAPIv2Adapter(base.APIv2Adapter):
| ADAPTER_OBJECT = objects.ZoneAttributeList
MODIFICATIONS = {
'options': {
'links': False,
'resource_name': 'zone_attribute',
'collection_name': 'zone_attributes',
}
}
@classmethod
def _render_list(cls, list_object, *args, **kwargs):
r_li... | classmethod
def _render_object(cls, object, *arg, **kwargs):
return {object.key: object.value}
@classmethod
def _parse_object(cls, values, object, *args, **kwargs):
for key in values.keys():
object.key = key
object.value = values[key]
return object
class Zon... | 85 | 85 | 284 | 14 | 70 | mrlesmithjr/designate | designate/objects/adapters/api_v2/zone_attribute.py | Python | ZoneAttributeListAPIv2Adapter | ZoneAttributeListAPIv2Adapter | 51 | 93 | 51 | 52 | e022980391ec02685be14c7eb7084a61ae4c6101 | bigcode/the-stack | train |
4a9b38473858b4efef0c9667 | train | class | class ZoneAttributeAPIv2Adapter(base.APIv2Adapter):
ADAPTER_OBJECT = objects.ZoneAttribute
MODIFICATIONS = {
'fields': {
'key': {
'read_only': False
},
'value': {
'read_only': False
}
},
'options': {
... | class ZoneAttributeAPIv2Adapter(base.APIv2Adapter):
| ADAPTER_OBJECT = objects.ZoneAttribute
MODIFICATIONS = {
'fields': {
'key': {
'read_only': False
},
'value': {
'read_only': False
}
},
'options': {
'links': False,
'resource_name': 'p... |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from designate import objects
from designate.objects.adapters.api_v2 import base
class ZoneAttributeAPIv2Adapter(base.APIv2Adapter):
| 64 | 64 | 168 | 13 | 50 | mrlesmithjr/designate | designate/objects/adapters/api_v2/zone_attribute.py | Python | ZoneAttributeAPIv2Adapter | ZoneAttributeAPIv2Adapter | 18 | 48 | 18 | 19 | 5a1dbf99f716642ea68ea6645e9edfcbf6010118 | bigcode/the-stack | train |
0665224e8bef63a2ca73be45 | train | class | class Torus(Shape):
def __init__(self, design_space, x=0, y=0, z=0, r1=1, r2=0.5):
super().__init__(design_space, x, y, z)
self.x = x
self.y = y
self.z = z
self.r1 = r1
self.r2 = r2
self.set_limits()
def set_limits(self):
self.x_limits = np.ar... | class Torus(Shape):
| def __init__(self, design_space, x=0, y=0, z=0, r1=1, r2=0.5):
super().__init__(design_space, x, y, z)
self.x = x
self.y = y
self.z = z
self.r1 = r1
self.r2 = r2
self.set_limits()
def set_limits(self):
self.x_limits = np.array(
[sel... | import numexpr as ne
import numpy as np
from MetaStruct.Objects.Shapes.Shape import Shape
class Torus(Shape):
| 26 | 83 | 279 | 6 | 19 | JamesOAR/Meta_Struct_OJ | src/MetaStruct/Objects/Shapes/Torus.py | Python | Torus | Torus | 7 | 39 | 7 | 8 | a7d519e36030f64e63692dd435b2bde95241bcb4 | bigcode/the-stack | train |
a8ec43502eb5cb890c93f749 | train | class | class HipChat(InputAdapter):
"""
An input adapter that allows a ChatterBot instance to get
input statements from a HipChat room.
"""
def __init__(self, **kwargs):
super(HipChat, self).__init__(**kwargs)
self.hipchat_host = kwargs.get('hipchat_host')
self.hipchat_access_toke... | class HipChat(InputAdapter):
| """
An input adapter that allows a ChatterBot instance to get
input statements from a HipChat room.
"""
def __init__(self, **kwargs):
super(HipChat, self).__init__(**kwargs)
self.hipchat_host = kwargs.get('hipchat_host')
self.hipchat_access_token = kwargs.get('hipchat_acces... | from time import sleep
from chatterbot.input import InputAdapter
from chatterbot.conversation import Statement
class HipChat(InputAdapter):
| 27 | 200 | 668 | 6 | 20 | erpnotify2/test-chat | chatterbot/input/hipchat.py | Python | HipChat | HipChat | 6 | 119 | 6 | 6 | d2f9d3b9890d3157bc62fece8d6c5f15a2c04b72 | bigcode/the-stack | train |
4a6247ad2f48442cfe61035a | train | class | class DisplayEmulatorApplication(Thread):
POLL_INTERVAL = 20
def __init__(self, root):
self._port = 6999
self._host = socket.gethostname()
self._client = None
self._socket = None
self._canvas = None
self._closing = False
self._root = root
self._re... | class DisplayEmulatorApplication(Thread):
| POLL_INTERVAL = 20
def __init__(self, root):
self._port = 6999
self._host = socket.gethostname()
self._client = None
self._socket = None
self._canvas = None
self._closing = False
self._root = root
self._render_image = None
self._canvasX =... | import fnmatch, os, socket
import pickle, timer_cm, dill
import ZO
from threading import *
from tkinter import *
from PIL import ImageTk, Image
PIXEL_MULTIPLIER = 10
IMAGE_PATH = '/Users/colind/Documents/Projects/ZeroOne/ZeroOne/Graphics/Images'
def get_images():
return fnmatch.filter(os.listdir(IMAGE_PATH), '*... | 93 | 256 | 1,229 | 7 | 86 | colindomoney-hardware/ZeroOne | Controller/DisplayEmulator/DisplayEmulator.py | Python | DisplayEmulatorApplication | DisplayEmulatorApplication | 17 | 168 | 17 | 17 | 6cf6bf5966fc8e5e4057090815625599748f3da5 | bigcode/the-stack | train |
510b2aacf896511f392c71c7 | train | function | def get_images():
return fnmatch.filter(os.listdir(IMAGE_PATH), '*.png')
| def get_images():
| return fnmatch.filter(os.listdir(IMAGE_PATH), '*.png')
| import pickle, timer_cm, dill
import ZO
from threading import *
from tkinter import *
from PIL import ImageTk, Image
PIXEL_MULTIPLIER = 10
IMAGE_PATH = '/Users/colind/Documents/Projects/ZeroOne/ZeroOne/Graphics/Images'
def get_images():
| 64 | 64 | 18 | 4 | 60 | colindomoney-hardware/ZeroOne | Controller/DisplayEmulator/DisplayEmulator.py | Python | get_images | get_images | 13 | 14 | 13 | 13 | b499b27ba96513fb4e4e00d265486bda320b6ab2 | bigcode/the-stack | train |
7e5061324dfb7bc1676f9945 | train | function | def close_window():
global app
print('CLOSE()')
app.close()
| def close_window():
| global app
print('CLOSE()')
app.close()
| ._render_image = zo_image.get_image_from_zero_one_data(emulator_command.data)
elif emulator_command.command == 'ClearDisplay':
self._canvas.delete('all')
self._canvas.update_idletasks()
else:
print('Unknown command')
# Handle the window close event
def close_windo... | 64 | 64 | 19 | 4 | 59 | colindomoney-hardware/ZeroOne | Controller/DisplayEmulator/DisplayEmulator.py | Python | close_window | close_window | 172 | 175 | 172 | 172 | 605c3ecec52bb3b00904ac483c20d36df19999aa | bigcode/the-stack | train |
718ade66d7f5b7add608cf29 | train | function | def setup(bot):
bot.add_cog(Admin(bot)) | def setup(bot):
| bot.add_cog(Admin(bot)) | checks.is_blacklisted()
@commands.command()
async def clean(self, ctx):
"""Cleans the chat of the bot's messages."""
def is_me(m):
return m.author == self.bot.user
await ctx.message.channel.purge(limit=100, check=is_me)
def setup(bot):
| 64 | 64 | 12 | 4 | 60 | KoocieBoi/Sunny | cogs/admin.py | Python | setup | setup | 100 | 101 | 100 | 100 | 630682b6201599611d68b59e883f442a4b2ecad1 | bigcode/the-stack | train |
8b66a2deae6e58d9cd983d48 | train | class | class Admin:
def __init__(self,bot):
self.bot = bot
@checks.can_kick()
@checks.is_blacklisted()
@commands.command()
async def kick(self, ctx, user : discord.Member):
"""Kicks a user from the server."""
if ctx.author == user:
await ctx.send("You cannot kick yours... | class Admin:
| def __init__(self,bot):
self.bot = bot
@checks.can_kick()
@checks.is_blacklisted()
@commands.command()
async def kick(self, ctx, user : discord.Member):
"""Kicks a user from the server."""
if ctx.author == user:
await ctx.send("You cannot kick yourself.")
... | import discord
from discord.ext import commands
from commons import checks
from asyncio import sleep
class Admin:
| 22 | 256 | 917 | 3 | 18 | KoocieBoi/Sunny | cogs/admin.py | Python | Admin | Admin | 6 | 98 | 6 | 7 | baee1d4a83d2aed374690844ccd9f4aec9c1ccdf | bigcode/the-stack | train |
41265aa942154eb8353af043 | train | function | def get_romaji_to_kana_tree():
global romaji_to_kana_map
if not romaji_to_kana_map:
romaji_to_kana_map = create_romaji_to_kana_map()
return romaji_to_kana_map
| def get_romaji_to_kana_tree():
| global romaji_to_kana_map
if not romaji_to_kana_map:
romaji_to_kana_map = create_romaji_to_kana_map()
return romaji_to_kana_map
| _tree[consonant]
subtree[consonant] = add_tsu(subtree)
# nn should not be っん
del kana_tree["n"]["n"]
return deepcopy(kana_tree)
romaji_to_kana_map = None
def get_romaji_to_kana_tree():
| 64 | 64 | 53 | 9 | 54 | Starwort/wanakana-py | wanakana/utils/romaji_to_kana_map.py | Python | get_romaji_to_kana_tree | get_romaji_to_kana_tree | 220 | 226 | 220 | 220 | 1c1905b32f613a1cd34022be3e110bdd51912ccf | bigcode/the-stack | train |
e0546e95e038afd5605cc7bb | train | function | def create_romaji_to_kana_map():
kana_tree = transform(BASIC_KUNREI)
# pseudo partial application
subtree_of = lambda string: get_subtree_of(kana_tree, string)
# add tya, sya, etc.
for consonant, y_kana in CONSONANTS.items():
for roma, kana in SMALL_Y.items():
# for example kyo ... | def create_romaji_to_kana_map():
| kana_tree = transform(BASIC_KUNREI)
# pseudo partial application
subtree_of = lambda string: get_subtree_of(kana_tree, string)
# add tya, sya, etc.
for consonant, y_kana in CONSONANTS.items():
for roma, kana in SMALL_Y.items():
# for example kyo -> き + ょ
subtree_of(c... | い",
"wu": "う",
"ye": "いぇ",
"wi": "うぃ",
"we": "うぇ",
"kwa": "くぁ",
"whu": "う",
# because it's not thya for てゃ but tha
# and tha is not てぁ, but てゃ
"tha": "てゃ",
"thu": "てゅ",
"tho": "てょ",
"dha": "でゃ",
"dhu": "でゅ",
"dho": "でょ",
}
AIUEO_CONSTRUCTIONS = {
"wh": "う",
... | 231 | 231 | 771 | 9 | 222 | Starwort/wanakana-py | wanakana/utils/romaji_to_kana_map.py | Python | create_romaji_to_kana_map | create_romaji_to_kana_map | 130 | 214 | 130 | 130 | 584c9c9d37876faf0dd33b3cb882cd22414a02ac | bigcode/the-stack | train |
c9ff29177ad9df62d25b2334 | train | class | class Day(OperatorAggCountBase):
def __init__(self):
super(Day, self).__init__()
def get_agg_key(self):
return time.strftime("%Y-%m-%d", time.localtime())
| class Day(OperatorAggCountBase):
| def __init__(self):
super(Day, self).__init__()
def get_agg_key(self):
return time.strftime("%Y-%m-%d", time.localtime())
| # -- coding: UTF-8
import time
from operators.agg_count import OperatorAggCountBase
class Day(OperatorAggCountBase):
| 30 | 64 | 47 | 8 | 21 | meyer-net/robot | src/app/operators/agg_count/day.py | Python | Day | Day | 8 | 13 | 8 | 8 | f5491a9d4f4caed394e313e59dcc06b3b55eff9b | bigcode/the-stack | train |
76f9f18c8cca57712caacf52 | train | function | def pytest_addoption(parser):
default_config_path = Path(__file__).parent / "gd_test_config.yaml"
parser.addoption(
"--gd-test-config",
action="store",
default=str(default_config_path),
help="Absolut path to test configuration",
)
| def pytest_addoption(parser):
| default_config_path = Path(__file__).parent / "gd_test_config.yaml"
parser.addoption(
"--gd-test-config",
action="store",
default=str(default_config_path),
help="Absolut path to test configuration",
)
| # (C) 2021 GoodData Corporation
from pathlib import Path
import pytest
import yaml
def pytest_addoption(parser):
| 28 | 64 | 59 | 6 | 21 | hkad98/gooddata-python-sdk | gooddata-pandas/tests/conftest.py | Python | pytest_addoption | pytest_addoption | 8 | 15 | 8 | 8 | 68f2a26734c2b46e84b66942f75a12754e9e0748 | bigcode/the-stack | train |
18f771d70c545592fdedc41e | train | function | @pytest.fixture(scope="session")
def test_config(request):
config_path = Path(request.config.getoption("--gd-test-config"))
with open(config_path, "rt") as f:
config = yaml.safe_load(f)
return config
| @pytest.fixture(scope="session")
def test_config(request):
| config_path = Path(request.config.getoption("--gd-test-config"))
with open(config_path, "rt") as f:
config = yaml.safe_load(f)
return config
| default_config_path = Path(__file__).parent / "gd_test_config.yaml"
parser.addoption(
"--gd-test-config",
action="store",
default=str(default_config_path),
help="Absolut path to test configuration",
)
@pytest.fixture(scope="session")
def test_config(request):
| 64 | 64 | 49 | 11 | 53 | hkad98/gooddata-python-sdk | gooddata-pandas/tests/conftest.py | Python | test_config | test_config | 18 | 24 | 18 | 19 | 30beaa05b4d82ca58ef908fcb76313adadd61bcc | bigcode/the-stack | train |
3877aae44f389d714fce7963 | train | class | class TestMapManager(unittest.TestCase):
def test_add_map_and_set_active(self):
im = Image.new('L', (800, 800))
d = ImageDraw.Draw(im)
d.rectangle(((100, 100), (600, 600)), fill=100)
d.rectangle(((300, 300), (350, 350)), fill=60)
d.rectangle(((200, 200), (400, 400)), fill=0)... | class TestMapManager(unittest.TestCase):
| def test_add_map_and_set_active(self):
im = Image.new('L', (800, 800))
d = ImageDraw.Draw(im)
d.rectangle(((100, 100), (600, 600)), fill=100)
d.rectangle(((300, 300), (350, 350)), fill=60)
d.rectangle(((200, 200), (400, 400)), fill=0)
b = BytesIO()
im.save(fp=... | #!/usr/bin/env python
import struct
import unittest
from PIL import Image, ImageDraw
from io import BytesIO
import rospy
import rostest
from geometry_msgs.msg import Point, Pose, Quaternion
from nav_msgs.msg import MapMetaData
from sensor_msgs.msg import CompressedImage
from std_msgs.msg import UInt8MultiArray
from ... | 129 | 162 | 542 | 8 | 120 | Boeing/modular_navigation | map_manager/test/test_manager.py | Python | TestMapManager | TestMapManager | 20 | 74 | 20 | 21 | 554353492706a7751d9a74d4af8b3153aef9413e | bigcode/the-stack | train |
b0e5c0b4b0313f45a9f4f66f | train | function | def iv():
"""
The initialization vector to use for encryption or decryption.
It is ignored for MODE_ECB and MODE_CTR.
"""
return chr(0) * 16
| def iv():
| """
The initialization vector to use for encryption or decryption.
It is ignored for MODE_ECB and MODE_CTR.
"""
return chr(0) * 16
| import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode()
unpad = lambda s: s[:-ord(s[len(s)-1:])]
def iv():
| 63 | 64 | 42 | 3 | 60 | jjhenkel/dockerizeme | hard-gists/7b64238424175742a8a1/snippet.py | Python | iv | iv | 23 | 28 | 23 | 23 | ba18689cba97afc4d7def792041a1d817dc63c46 | bigcode/the-stack | train |
a58974da8472f3c08cf3aa53 | train | class | class AESCipher(object):
"""
https://github.com/dlitz/pycrypto
"""
def __init__(self, key):
self.key = key
#self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, message):
"""
It is assumed that you use Python 3.0+
, so plaintext's type must be ... | class AESCipher(object):
| """
https://github.com/dlitz/pycrypto
"""
def __init__(self, key):
self.key = key
#self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, message):
"""
It is assumed that you use Python 3.0+
, so plaintext's type must be str type(== unicode).
... | pad = lambda s: s[:-ord(s[len(s)-1:])]
def iv():
"""
The initialization vector to use for encryption or decryption.
It is ignored for MODE_ECB and MODE_CTR.
"""
return chr(0) * 16
class AESCipher(object):
| 64 | 64 | 188 | 6 | 57 | jjhenkel/dockerizeme | hard-gists/7b64238424175742a8a1/snippet.py | Python | AESCipher | AESCipher | 30 | 54 | 30 | 30 | 1edc4226e264906b62409fb11d20a5652e6a36ee | bigcode/the-stack | train |
c467911044fff3bf023a7eb0 | train | class | class AnimeOnDemandIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?anime-on-demand\.de/anime/(?P<id>\d+)'
_LOGIN_URL = 'https://www.anime-on-demand.de/users/sign_in'
_APPLY_HTML5_URL = 'https://www.anime-on-demand.de/html5apply'
_NETRC_MACHINE = 'animeondemand'
# German-speaking countries of Eu... | class AnimeOnDemandIE(InfoExtractor):
| _VALID_URL = r'https?://(?:www\.)?anime-on-demand\.de/anime/(?P<id>\d+)'
_LOGIN_URL = 'https://www.anime-on-demand.de/users/sign_in'
_APPLY_HTML5_URL = 'https://www.anime-on-demand.de/html5apply'
_NETRC_MACHINE = 'animeondemand'
# German-speaking countries of Europe
_GEO_COUNTRIES = ['AT', 'CH',... | import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
determine_ext,
extract_attributes,
ExtractorError,
join_nonempty,
url_or_none,
urlencode_postdata,
urljoin,
)
class AnimeOnDemandIE(InfoExtractor):
| 64 | 256 | 2,504 | 9 | 55 | olipfei/yt-dlp | yt_dlp/extractor/animeondemand.py | Python | AnimeOnDemandIE | AnimeOnDemandIE | 16 | 282 | 16 | 16 | 15d716449cd37f97717c47ce6780d9772dc06367 | bigcode/the-stack | train |
11291d6f3302ba741b509534 | train | class | class MyProduct(Base):
__tablename__ = 'api_product'
id = Column(Integer, primary_key=True)
name = Column(String)
category = Column(String)
description = Column(String)
@property
def serialize(self):
return {
'id' : self.id,
'name' : self.name,
... | class MyProduct(Base):
| __tablename__ = 'api_product'
id = Column(Integer, primary_key=True)
name = Column(String)
category = Column(String)
description = Column(String)
@property
def serialize(self):
return {
'id' : self.id,
'name' : self.name,
'category' : self.... | sqlalchemy import Column, Integer, String
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:apisbtest0011@192.168.99.100/api_test'
db = SQLAlchemy(app)
Base = automap_base()
class MyProduct(Base):
| 64 | 64 | 92 | 5 | 59 | eduleones/apis-benchmark | flask/app.py | Python | MyProduct | MyProduct | 13 | 27 | 13 | 13 | 2a252ee4619d052b048fed707a7a3940cf627437 | bigcode/the-stack | train |
e3dac9b741c0c6b98a23eed9 | train | function | @app.route("/api/")
def getProductList():
return jsonify(json_list=[i.serialize for i in db.session.query(MyProduct).all()])
| @app.route("/api/")
def getProductList():
| return jsonify(json_list=[i.serialize for i in db.session.query(MyProduct).all()])
| )
@property
def serialize(self):
return {
'id' : self.id,
'name' : self.name,
'category' : self.category,
'description' : self.description
}
Base.prepare()
@app.route("/api/")
def getProductList():
| 64 | 64 | 29 | 10 | 54 | eduleones/apis-benchmark | flask/app.py | Python | getProductList | getProductList | 33 | 35 | 33 | 34 | 3e84b29608fcc0bd0a3822ac6849f9c60c609e59 | bigcode/the-stack | train |
e5178e4e820fed226b87c09b | train | function | def read_barcode(im_array):
return len(im_array) / 2
| def read_barcode(im_array):
| return len(im_array) / 2
| def read_qrcode(im_array):
return len(im_array)
def read_barcode(im_array):
| 20 | 64 | 17 | 7 | 13 | Igorxp5/py-ekstazi | tests/project/project/readers.py | Python | read_barcode | read_barcode | 4 | 5 | 4 | 4 | fb7d4120f7782b834d27b402594e7624c32ad0cd | bigcode/the-stack | train |
d48640a0f6d75c697e416ac0 | train | function | def read_qrcode(im_array):
return len(im_array)
| def read_qrcode(im_array):
| return len(im_array)
| def read_qrcode(im_array):
| 7 | 64 | 13 | 7 | 0 | Igorxp5/py-ekstazi | tests/project/project/readers.py | Python | read_qrcode | read_qrcode | 1 | 2 | 1 | 1 | b44b72af27025e5d31556edf9a120c7b2b4659f1 | bigcode/the-stack | train |
0036c203965cd864bb1c2047 | train | class | class RICO_ComponentDataset(Dataset):
def default_loader(path):
return Image.open(path).convert('RGB')
def reset_iterator(self, split):
del self._prefetch_process[split]
self._prefetch_process[split] = BlobFetcher(split, self, if_shuffle = (split=='train'))
self.iterato... | class RICO_ComponentDataset(Dataset):
| def default_loader(path):
return Image.open(path).convert('RGB')
def reset_iterator(self, split):
del self._prefetch_process[split]
self._prefetch_process[split] = BlobFetcher(split, self, if_shuffle = (split=='train'))
self.iterators[split] = 0
def __init__(self,opt... | _loader(path):
return Image.open(path).convert('RGB')
def get_com2index():
com2index = {
'Toolbar': 1,
'Image': 2,
'Icon': 3,
'Web View': 4,
'Text Button': 5,
'Text': 6,
... | 256 | 256 | 2,693 | 9 | 246 | exnx/gcn-triplet-encoding | dataloaders/dataloader.py | Python | RICO_ComponentDataset | RICO_ComponentDataset | 57 | 330 | 57 | 58 | 403f068cc7ca90e166e490de091322522878a0c6 | bigcode/the-stack | train |
60b5e66938cc94838414232c | train | class | class SubsetSampler(torch.utils.data.sampler.Sampler):
"""Samples elements randomly from a given list of indices, without replacement.
Arguments:
indices (list): a list of indices
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return (self.indic... | class SubsetSampler(torch.utils.data.sampler.Sampler):
| """Samples elements randomly from a given list of indices, without replacement.
Arguments:
indices (list): a list of indices
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return (self.indices[i] for i in range(len(self.indices)))
#retur... | , wrapped = self._get_next_minibatch_inds()
tmp = self.split_loader.next()
if wrapped:
self.reset()
assert tmp[-1] == ix, "ix not equal"
return tmp + [wrapped]
#%%
class SubsetSampler(torch.utils.data.sampler.Sampler):
| 64 | 64 | 110 | 12 | 52 | exnx/gcn-triplet-encoding | dataloaders/dataloader.py | Python | SubsetSampler | SubsetSampler | 401 | 415 | 401 | 401 | de8a2d41b42ea325aaa4be50775568630a3e36bd | bigcode/the-stack | train |
5dd9d07dac3e4a6b5cf8b09f | train | function | def default_loader(path):
return Image.open(path).convert('RGB')
| def default_loader(path):
| return Image.open(path).convert('RGB')
| list [Train/Test]
@author: dipu
"""
import torch
from torch.utils.data import Dataset
import torch.utils.data as data
import os
from PIL import Image
from torchvision import transforms
import numpy as np
import random
import pickle
import torch.nn.functional as F
def default_loader(path):
| 64 | 64 | 15 | 5 | 58 | exnx/gcn-triplet-encoding | dataloaders/dataloader.py | Python | default_loader | default_loader | 23 | 24 | 23 | 23 | bfeda2863cda34e70f39fc227a88ab2546fdf0f4 | bigcode/the-stack | train |
e9454ce746b66e158741b9ae | train | function | def get_com2index():
com2index = {
'Toolbar': 1,
'Image': 2,
'Icon': 3,
'Web View': 4,
'Text Button': 5,
'Text': 6,
'Multi-Tab': 7,
'Card': 8,
... | def get_com2index():
| com2index = {
'Toolbar': 1,
'Image': 2,
'Icon': 3,
'Web View': 4,
'Text Button': 5,
'Text': 6,
'Multi-Tab': 7,
'Card': 8,
'List Item... | """
import torch
from torch.utils.data import Dataset
import torch.utils.data as data
import os
from PIL import Image
from torchvision import transforms
import numpy as np
import random
import pickle
import torch.nn.functional as F
def default_loader(path):
return Image.open(path).convert('RGB')
def get_com2inde... | 70 | 70 | 234 | 6 | 64 | exnx/gcn-triplet-encoding | dataloaders/dataloader.py | Python | get_com2index | get_com2index | 26 | 54 | 26 | 26 | e531c10d8591a2be43b6680ca9135e25661070e0 | bigcode/the-stack | train |
63d295ed4a2db5d5f9b453a9 | train | class | class BlobFetcher():
"""
Experimental class for prefetching blobs in a separate process.
looks like this is what grabs the data
"""
def __init__(self, split, dataloader, if_shuffle=False, num_workers = 4):
"""
db is a list of tuples containing: imcrop_name, caption, bbox_feat of ... | class BlobFetcher():
| """
Experimental class for prefetching blobs in a separate process.
looks like this is what grabs the data
"""
def __init__(self, split, dataloader, if_shuffle=False, num_workers = 4):
"""
db is a list of tuples containing: imcrop_name, caption, bbox_feat of gt box, imname
... | int')
# rela_masks, because no all items in rela_edges and rela_feats are meaningful
sg_data['rela_masks'] = np.zeros(sg_data['rela_edges'].shape[:2], dtype='float32')
for i in range(len(rela_batch)):
sg_data['rela_edges'][i, :rela_batch[i]['edges'].shape[0]] = rela_batch[i]... | 147 | 147 | 492 | 4 | 143 | exnx/gcn-triplet-encoding | dataloaders/dataloader.py | Python | BlobFetcher | BlobFetcher | 333 | 397 | 333 | 333 | 8f9548e92dd0c0a5cbd27f37aabe07f9c57a6868 | bigcode/the-stack | train |
fdf9f8a8f310b149ae766720 | train | function | def test_as_html():
# str case
assert format_html('{}', as_html(part='foo', context={})) == 'foo'
assert format_html('{}', as_html(part='<foo>bar</foo>', context={})) == '<foo>bar</foo>'
assert format_html('{}', as_html(part=mark_safe('<foo>bar</foo>'), context={})) == '<foo>bar</foo>'
... | def test_as_html():
# str case
| assert format_html('{}', as_html(part='foo', context={})) == 'foo'
assert format_html('{}', as_html(part='<foo>bar</foo>', context={})) == '<foo>bar</foo>'
assert format_html('{}', as_html(part=mark_safe('<foo>bar</foo>'), context={})) == '<foo>bar</foo>'
# Template case
request = req('... | get_title,
)
from iommi.style import Style
from iommi.style_base import base
from tests.helpers import req
def test_request_data():
r = Struct(method='POST', POST='POST', GET='GET')
assert request_data(r) == 'POST'
r.method = 'GET'
assert request_data(r) == 'GET'
def test_as_html():
# str case
| 83 | 83 | 279 | 10 | 73 | oanafatu/iommi | iommi/part__tests.py | Python | test_as_html | test_as_html | 29 | 43 | 29 | 30 | 318e865d4c101d1f640d51305b0e9a5479c89bf8 | bigcode/the-stack | train |
791b7ac64f0c020a99a964f0 | train | function | def test_as_html_integer():
assert as_html(part=123, context={}) == '123'
| def test_as_html_integer():
| assert as_html(part=123, context={}) == '123'
| >'), context={})) == '<foo>bar</foo>'
assert format_html('{}', as_html(part=Struct(__html__=lambda: mark_safe('<foo>bar</foo>')), context={})) == '<foo>bar</foo>'
def test_as_html_integer():
| 63 | 64 | 21 | 6 | 57 | oanafatu/iommi | iommi/part__tests.py | Python | test_as_html_integer | test_as_html_integer | 46 | 47 | 46 | 46 | 2296892296a570f65bfa16313055d1b922378b9e | bigcode/the-stack | train |
520b08af679b44ae9bc75adc | train | function | def test_get_title_of_header():
assert get_title(Header(children__foo='foo', children__bar='qwe').bind(request=req('get'))) == 'foo'
| def test_get_title_of_header():
| assert get_title(Header(children__foo='foo', children__bar='qwe').bind(request=req('get'))) == 'foo'
| mi_style=style_name,
)
t = render_root(
part=part.bind(request=req('get')),
context=dict(my_context_variable='my_context_variable'),
)
assert t == 'context_processor_is_called\nroot_part_context_variable\nmy_context_variable\n'
def test_get_title_of_header():
| 64 | 64 | 35 | 7 | 57 | oanafatu/iommi | iommi/part__tests.py | Python | test_get_title_of_header | test_get_title_of_header | 70 | 71 | 70 | 70 | 3df13af24d479f32916fd02fc6ac1468469e9cbf | bigcode/the-stack | train |
3712ac59efa55214d26e0b34 | train | function | def test_context_processor_is_called_on_render_root():
style_name = 'test_context_processor_is_called_on_render_root'
style = Style(
base,
base_template='test_context_processor_is_called_on_render_root.html',
)
register_style(style_name, style)
part = Page(
context__root_par... | def test_context_processor_is_called_on_render_root():
| style_name = 'test_context_processor_is_called_on_render_root'
style = Style(
base,
base_template='test_context_processor_is_called_on_render_root.html',
)
register_style(style_name, style)
part = Page(
context__root_part_context_variable='root_part_context_variable',
... | as_html(part=Struct(__html__=lambda: mark_safe('<foo>bar</foo>')), context={})) == '<foo>bar</foo>'
def test_as_html_integer():
assert as_html(part=123, context={}) == '123'
def test_context_processor_is_called_on_render_root():
| 64 | 64 | 133 | 10 | 54 | oanafatu/iommi | iommi/part__tests.py | Python | test_context_processor_is_called_on_render_root | test_context_processor_is_called_on_render_root | 50 | 67 | 50 | 50 | da03f629cdf675c5a0d06f232374d844b8e63cd4 | bigcode/the-stack | train |
0e838eff19003f72db9d40f8 | train | function | def test_request_data():
r = Struct(method='POST', POST='POST', GET='GET')
assert request_data(r) == 'POST'
r.method = 'GET'
assert request_data(r) == 'GET'
| def test_request_data():
| r = Struct(method='POST', POST='POST', GET='GET')
assert request_data(r) == 'POST'
r.method = 'GET'
assert request_data(r) == 'GET'
| ,
Header,
)
from iommi._web_compat import Template
from iommi.part import (
as_html,
render_root,
request_data,
get_title,
)
from iommi.style import Style
from iommi.style_base import base
from tests.helpers import req
def test_request_data():
| 64 | 64 | 48 | 5 | 58 | oanafatu/iommi | iommi/part__tests.py | Python | test_request_data | test_request_data | 22 | 26 | 22 | 22 | bcc2d9d1327ab5d35a8dccacfde49746ef93dc01 | bigcode/the-stack | train |
d246fe74b79bc52fba3bfa5a | train | function | def get_incident_event_stats(incident, start=None, end=None, data_points=50):
"""
Gets event stats for an incident. If start/end are provided, uses that time
period, otherwise uses the incident start/current_end.
"""
kwargs = build_incident_query_params(incident, start=start, end=end)
rollup = m... | def get_incident_event_stats(incident, start=None, end=None, data_points=50):
| """
Gets event stats for an incident. If start/end are provided, uses that time
period, otherwise uses the incident start/current_end.
"""
kwargs = build_incident_query_params(incident, start=start, end=end)
rollup = max(int(incident.duration.total_seconds() / data_points), 1)
return SnubaTS... | incident=incident,
).values_list('project_id', flat=True))
if project_ids:
params['project_id'] = project_ids
return get_snuba_query_args(incident.query, params)
def get_incident_event_stats(incident, start=None, end=None, data_points=50):
| 64 | 64 | 173 | 20 | 44 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | get_incident_event_stats | get_incident_event_stats | 189 | 211 | 189 | 189 | 51007c1573a095d7a5c746a45c584b8ea20939a6 | bigcode/the-stack | train |
4d092ed3691c0c012b7cfff3 | train | function | def build_incident_query_params(incident, start=None, end=None):
params = {
'start': incident.date_started if start is None else start,
'end': incident.current_end_date if end is None else end,
}
group_ids = list(IncidentGroup.objects.filter(
incident=incident,
).values_list('gro... | def build_incident_query_params(incident, start=None, end=None):
| params = {
'start': incident.date_started if start is None else start,
'end': incident.current_end_date if end is None else end,
}
group_ids = list(IncidentGroup.objects.filter(
incident=incident,
).values_list('group_id', flat=True))
if group_ids:
params['issue.id'] ... | , end)
return TimeSeriesSnapshot.objects.create(
start=start,
end=end,
values=[[row['time'], row['count']] for row in event_stats.data['data']],
period=event_stats.rollup,
)
def build_incident_query_params(incident, start=None, end=None):
| 64 | 64 | 147 | 15 | 49 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | build_incident_query_params | build_incident_query_params | 170 | 186 | 170 | 170 | 46fc2e441e1b2fc7bf0e2785ce5cf6bbadf18c57 | bigcode/the-stack | train |
6ef51bce7c6991fd7eb3ee93 | train | function | def create_event_stat_snapshot(incident, start, end):
"""
Creates an event stats snapshot for an incident in a given period of time.
"""
event_stats = get_incident_event_stats(incident, start, end)
return TimeSeriesSnapshot.objects.create(
start=start,
end=end,
values=[[row['... | def create_event_stat_snapshot(incident, start, end):
| """
Creates an event stats snapshot for an incident in a given period of time.
"""
event_stats = get_incident_event_stats(incident, start, end)
return TimeSeriesSnapshot.objects.create(
start=start,
end=end,
values=[[row['time'], row['count']] for row in event_stats.data['dat... | _value
return IncidentActivity.objects.create(
incident=incident,
type=activity_type.value,
user=user,
value=value,
previous_value=previous_value,
comment=comment,
event_stats_snapshot=event_stats_snapshot,
)
def create_event_stat_snapshot(incident, start,... | 64 | 64 | 94 | 12 | 52 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | create_event_stat_snapshot | create_event_stat_snapshot | 157 | 167 | 157 | 157 | 6057f36416f763fd196500960f762680873cb7da | bigcode/the-stack | train |
65105a7dee7b81186f774937 | train | function | def get_incident_aggregates(incident):
"""
Calculates aggregate stats across the life of an incident.
- count: Total count of events
- unique_users: Total number of unique users
"""
kwargs = build_incident_query_params(incident)
return raw_query(
aggregations=[
('count()'... | def get_incident_aggregates(incident):
| """
Calculates aggregate stats across the life of an incident.
- count: Total count of events
- unique_users: Total number of unique users
"""
kwargs = build_incident_query_params(incident)
return raw_query(
aggregations=[
('count()', '', 'count'),
('uniq', 't... | ',
groupby=['time'],
rollup=rollup,
referrer='incidents.get_incident_event_stats',
limit=10000,
**kwargs
),
kwargs['start'],
kwargs['end'],
rollup,
)
def get_incident_aggregates(incident):
| 64 | 64 | 119 | 10 | 54 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | get_incident_aggregates | get_incident_aggregates | 214 | 229 | 214 | 214 | 15217e9338cac30d2d2b96d1f61b62471754c843 | bigcode/the-stack | train |
f2fdd8b552c51f745fd79d86 | train | function | def create_incident(
organization,
status,
title,
query,
date_started,
date_detected=None,
detection_uuid=None,
projects=None,
groups=None,
):
assert status in (IncidentStatus.CREATED, IncidentStatus.DETECTED)
if date_detected is None:
date_detected = date_started
... | def create_incident(
organization,
status,
title,
query,
date_started,
date_detected=None,
detection_uuid=None,
projects=None,
groups=None,
):
| assert status in (IncidentStatus.CREATED, IncidentStatus.DETECTED)
if date_detected is None:
date_detected = date_started
if groups:
group_projects = [g.project for g in groups]
if projects is None:
projects = []
projects = list(set(projects + group_projects))
... | Status,
TimeSeriesSnapshot,
)
from sentry.utils.snuba import (
raw_query,
SnubaTSResult,
)
MAX_INITIAL_INCIDENT_PERIOD = timedelta(days=7)
class StatusAlreadyChangedError(Exception):
pass
def create_incident(
organization,
status,
title,
query,
date_started,
date_detected=None... | 89 | 89 | 297 | 41 | 47 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | create_incident | create_incident | 31 | 82 | 31 | 41 | b570cf8478b0379779212fde676dd19c3a5d5559 | bigcode/the-stack | train |
399e2e7ddbeeda01b3fd49b0 | train | class | class StatusAlreadyChangedError(Exception):
pass
| class StatusAlreadyChangedError(Exception):
| pass
| IncidentActivity,
IncidentActivityType,
IncidentGroup,
IncidentProject,
IncidentStatus,
TimeSeriesSnapshot,
)
from sentry.utils.snuba import (
raw_query,
SnubaTSResult,
)
MAX_INITIAL_INCIDENT_PERIOD = timedelta(days=7)
class StatusAlreadyChangedError(Exception):
| 64 | 64 | 10 | 7 | 57 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | StatusAlreadyChangedError | StatusAlreadyChangedError | 27 | 28 | 27 | 27 | c88164e71b4a59e80dc50f895801c13146f11146 | bigcode/the-stack | train |
9a024bedc42c7a09564ab9b4 | train | function | def update_incident_status(incident, status, user=None, comment=None):
"""
Updates the status of an Incident and write an IncidentActivity row to log
the change. When the status is CLOSED we also set the date closed to the
current time and (todo) take a snapshot of the current incident state.
"""
... | def update_incident_status(incident, status, user=None, comment=None):
| """
Updates the status of an Incident and write an IncidentActivity row to log
the change. When the status is CLOSED we also set the date closed to the
current time and (todo) take a snapshot of the current incident state.
"""
if incident.status == status.value:
# If the status isn't act... | Type.CREATED
else:
activity_status = IncidentActivityType.DETECTED
event_stats_snapshot = create_initial_event_stats_snapshot(incident)
create_incident_activity(
incident,
activity_status,
event_stats_snapshot=event_stats_snapshot,
)
r... | 75 | 75 | 253 | 16 | 58 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | update_incident_status | update_incident_status | 85 | 117 | 85 | 85 | f18ae431ecf97f35ebf45782264731e65518c50b | bigcode/the-stack | train |
c8beb86aa751bbcde35af1ad | train | function | def create_incident_activity(
incident,
activity_type,
user=None,
value=None,
previous_value=None,
comment=None,
event_stats_snapshot=None,
):
value = six.text_type(value) if value is not None else value
previous_value = six.text_type(previous_value) if previous_value is not None els... | def create_incident_activity(
incident,
activity_type,
user=None,
value=None,
previous_value=None,
comment=None,
event_stats_snapshot=None,
):
| value = six.text_type(value) if value is not None else value
previous_value = six.text_type(previous_value) if previous_value is not None else previous_value
return IncidentActivity.objects.create(
incident=incident,
type=activity_type.value,
user=user,
value=value,
p... |
start = end - (initial_period_length * 8)
return create_event_stat_snapshot(incident, start, end)
def create_incident_activity(
incident,
activity_type,
user=None,
value=None,
previous_value=None,
comment=None,
event_stats_snapshot=None,
):
| 64 | 64 | 123 | 37 | 27 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | create_incident_activity | create_incident_activity | 135 | 154 | 135 | 143 | 5c9913269c066ea112921bc5669ac3ceaac73553 | bigcode/the-stack | train |
4f1256ade21db105ea0f0549 | train | function | def create_initial_event_stats_snapshot(incident):
"""
Creates an event snapshot representing the state at the beginning of
an incident. It's intended to capture the history of the events involved in
the incident, the spike and a short period of time after that.
"""
initial_period_length = min(
... | def create_initial_event_stats_snapshot(incident):
| """
Creates an event snapshot representing the state at the beginning of
an incident. It's intended to capture the history of the events involved in
the incident, the spike and a short period of time after that.
"""
initial_period_length = min(
timezone.now() - incident.date_started,
... | Status.CLOSED.value:
# If we're moving back out of closed status then unset the closed
# date
kwargs['date_closed'] = None
# TODO: Delete snapshot? Not sure if needed
incident.update(**kwargs)
return incident
def create_initial_event_stats_snapshot(incide... | 64 | 64 | 119 | 9 | 54 | 0x11-dev/sentry | src/sentry/incidents/logic.py | Python | create_initial_event_stats_snapshot | create_initial_event_stats_snapshot | 120 | 132 | 120 | 120 | 988e440ac82fc10eaced4061d31153eea1cfb036 | bigcode/the-stack | train |
f91567b8f2ae148cb571517c | train | class | class Sequencer:
def __init__(self):
self.tests = TestList()
self._status = "Idle"
self.active_test = None
self.ABORT = False
# pub.subscribe(self._handle_sequence_abort, "Seq_Abort")
self.test_attempts = 0
self.chk_fail = 0
self.chk_pass = 0
s... | class Sequencer:
| def __init__(self):
self.tests = TestList()
self._status = "Idle"
self.active_test = None
self.ABORT = False
# pub.subscribe(self._handle_sequence_abort, "Seq_Abort")
self.test_attempts = 0
self.chk_fail = 0
self.chk_pass = 0
self.tests_failed ... | return False
return top.current().skip
context = ContextStack()
context.push(test_list)
ret_list = []
while context:
top = context.top()
if top.index >= len(top.testlist): # Finished tests in the test list
context.pop()
if context:
cont... | 256 | 256 | 2,436 | 4 | 251 | stig999/Fixate | src/fixate/sequencer.py | Python | Sequencer | Sequencer | 89 | 394 | 89 | 89 | 2671c6c1d621a5f623f76b50701b887ac0960fdf | bigcode/the-stack | train |
7ad9d5a08b4fabafcbb3ea43 | train | function | def default_retry(*args, **kwargs):
return "RETRY"
| def default_retry(*args, **kwargs):
| return "RETRY"
| RetryExceeded, CheckFail
from fixate.core.ui import user_retry_abort_fail
STATUS_STATES = ["Idle", "Running", "Paused", "Finished", "Restart", "Aborted"]
TARGET_RETURN_STATES = ["Skipped", "Result", "Exception"]
def default_retry(*args, **kwargs):
| 63 | 64 | 15 | 9 | 54 | stig999/Fixate | src/fixate/sequencer.py | Python | default_retry | default_retry | 14 | 15 | 14 | 14 | a7342745e4e8a7f78558cf3cee297ec0de80b08c | bigcode/the-stack | train |
34be39db94bf98e0c3e09ad9 | train | class | class ContextStackNode:
def __init__(self, seq):
self.index = 0
if isinstance(seq, TestList):
self.testlist = seq
elif isinstance(seq, list):
self.testlist = TestList(seq)
def current(self):
next_item = self.testlist[self.index]
if not isinstance(... | class ContextStackNode:
| def __init__(self, seq):
self.index = 0
if isinstance(seq, TestList):
self.testlist = seq
elif isinstance(seq, list):
self.testlist = TestList(seq)
def current(self):
next_item = self.testlist[self.index]
if not isinstance(next_item, TestList) and... | import user_retry_abort_fail
STATUS_STATES = ["Idle", "Running", "Paused", "Finished", "Restart", "Aborted"]
TARGET_RETURN_STATES = ["Skipped", "Result", "Exception"]
def default_retry(*args, **kwargs):
return "RETRY"
class ContextStackNode:
| 64 | 64 | 123 | 5 | 59 | stig999/Fixate | src/fixate/sequencer.py | Python | ContextStackNode | ContextStackNode | 18 | 32 | 18 | 18 | 0a95a3e58828d12b5a605b6d93f60c5383b5fe32 | bigcode/the-stack | train |
1a75435000adf25650baf99a | train | class | class ContextStack(list):
def push(self, test):
self.append(ContextStackNode(test))
def top(self):
return self[-1]
| class ContextStack(list):
| def push(self, test):
self.append(ContextStackNode(test))
def top(self):
return self[-1]
| [self.index]
if not isinstance(next_item, TestList) and isinstance(next_item, list):
# Convert a normal list into a TestList
self.testlist[self.index] = TestList(next_item)
next_item = self.testlist[self.index]
return next_item
class ContextStack(list):
| 64 | 64 | 31 | 5 | 58 | stig999/Fixate | src/fixate/sequencer.py | Python | ContextStack | ContextStack | 35 | 40 | 35 | 35 | a2320540aa7936fa24781aaff2ee4f4d15067b5a | bigcode/the-stack | train |
bc58f6758262df1ef60a558e | train | function | def test_list_repr(test_list):
def levels_repr():
return ".".join(str(x.index + 1) for x in context[1:])
def curr_test_name():
return top.current().test_desc
def curr_test_skip():
if isinstance(top.current(), TestList):
return False
return top.current().skip
... | def test_list_repr(test_list):
| def levels_repr():
return ".".join(str(x.index + 1) for x in context[1:])
def curr_test_name():
return top.current().test_desc
def curr_test_skip():
if isinstance(top.current(), TestList):
return False
return top.current().skip
context = ContextStack()
... | list):
# Convert a normal list into a TestList
self.testlist[self.index] = TestList(next_item)
next_item = self.testlist[self.index]
return next_item
class ContextStack(list):
def push(self, test):
self.append(ContextStackNode(test))
def top(self):
... | 79 | 79 | 265 | 7 | 72 | stig999/Fixate | src/fixate/sequencer.py | Python | test_list_repr | test_list_repr | 43 | 76 | 43 | 43 | 3dc1745215551cd0c2411150cdcf8507818acd2d | bigcode/the-stack | train |
055b2490c374d7c9c2e71936 | train | function | def get_parent_level(level):
m = re.match(r'^\d+$', level)
if m:
return 'Top'
else:
level = re.sub(r'\.\d+$', '', level)
return level
| def get_parent_level(level):
| m = re.match(r'^\d+$', level)
if m:
return 'Top'
else:
level = re.sub(r'\.\d+$', '', level)
return level
| ret_list.append(
{"level": levels_repr(), "test_name": curr_test_name(), "test_type": 'list',
"test_skip": curr_test_skip(),
"parent": get_parent_level(levels_repr())})
context.push(top.current())
return ret_list
def get_parent_level(level):
| 64 | 64 | 49 | 6 | 57 | stig999/Fixate | src/fixate/sequencer.py | Python | get_parent_level | get_parent_level | 79 | 86 | 79 | 79 | b6a67df38601039de106a0d61a8d122c787a7ce4 | bigcode/the-stack | train |
f76c2980c344108f3c3fd114 | train | function | def run(gpuid, n_clusters, num, max_iter, use_custom_kernel, output):
samples = numpy.random.randn(num, 2)
X_train = numpy.r_[samples + 1, samples - 1]
with timer(' CPU '):
centers, pred = fit_xp(X_train, n_clusters, max_iter)
with cupy.cuda.Device(gpuid):
X_train = cupy.asarray(X_trai... | def run(gpuid, n_clusters, num, max_iter, use_custom_kernel, output):
| samples = numpy.random.randn(num, 2)
X_train = numpy.r_[samples + 1, samples - 1]
with timer(' CPU '):
centers, pred = fit_xp(X_train, n_clusters, max_iter)
with cupy.cuda.Device(gpuid):
X_train = cupy.asarray(X_train)
with timer(' GPU '):
if use_custom_kernel:
... | .random.rand(3))
plt.scatter(
centers[:, 0], centers[:, 1], s=120, marker='s', facecolors='y',
edgecolors='k')
plt.savefig(output)
def run(gpuid, n_clusters, num, max_iter, use_custom_kernel, output):
| 64 | 64 | 187 | 20 | 44 | okapies/cupy | examples/kmeans/kmeans.py | Python | run | run | 115 | 134 | 115 | 115 | 3f09cf06b4bdad355080827f3b775552c6cb553d | bigcode/the-stack | train |
714e59879584bea70801a9fd | train | function | @contextlib.contextmanager
def timer(message):
cupy.cuda.Stream.null.synchronize()
start = time.time()
yield
cupy.cuda.Stream.null.synchronize()
end = time.time()
print('%s: %f sec' % (message, end - start))
| @contextlib.contextmanager
def timer(message):
| cupy.cuda.Stream.null.synchronize()
start = time.time()
yield
cupy.cuda.Stream.null.synchronize()
end = time.time()
print('%s: %f sec' % (message, end - start))
| import argparse
import contextlib
import time
import cupy
import matplotlib.pyplot as plt
import numpy
import six
@contextlib.contextmanager
def timer(message):
| 36 | 64 | 61 | 10 | 25 | okapies/cupy | examples/kmeans/kmeans.py | Python | timer | timer | 11 | 18 | 11 | 12 | 3ce5a0472d483e1d0a78531a1a1a042c5d3fd49f | bigcode/the-stack | train |
b536f77f892f153b81281a9e | train | function | def fit_custom(X, n_clusters, max_iter):
assert X.ndim == 2
n_samples = len(X)
pred = cupy.zeros(n_samples)
initial_indexes = numpy.random.choice(n_samples, n_clusters, replace=False)
centers = X[initial_indexes]
for _ in six.moves.range(max_iter):
distances = var_kernel(X[:, None, 0... | def fit_custom(X, n_clusters, max_iter):
| assert X.ndim == 2
n_samples = len(X)
pred = cupy.zeros(n_samples)
initial_indexes = numpy.random.choice(n_samples, n_clusters, replace=False)
centers = X[initial_indexes]
for _ in six.moves.range(max_iter):
distances = var_kernel(X[:, None, 0], X[:, None, 1],
... | = pred == i[:, None]
sums = xp.where(mask[:, :, None], X, 0).sum(axis=1)
counts = xp.count_nonzero(mask, axis=1)
centers = sums / counts
return centers, pred
def fit_custom(X, n_clusters, max_iter):
| 64 | 64 | 198 | 11 | 52 | okapies/cupy | examples/kmeans/kmeans.py | Python | fit_custom | fit_custom | 77 | 101 | 77 | 77 | 33bfc28f222654b0087b7537104b2b06c4568c36 | bigcode/the-stack | train |
977aba8a87a85aa08aad573a | train | function | def draw(X, n_clusters, centers, pred, output):
# Plot the samples and centroids of the fitted clusters into an image file.
for i in six.moves.range(n_clusters):
labels = X[pred == i]
plt.scatter(labels[:, 0], labels[:, 1], c=numpy.random.rand(3))
plt.scatter(
centers[:, 0], centers[... | def draw(X, n_clusters, centers, pred, output):
# Plot the samples and centroids of the fitted clusters into an image file.
| for i in six.moves.range(n_clusters):
labels = X[pred == i]
plt.scatter(labels[:, 0], labels[:, 1], c=numpy.random.rand(3))
plt.scatter(
centers[:, 0], centers[:, 1], s=120, marker='s', facecolors='y',
edgecolors='k')
plt.savefig(output)
| , mask[:, :, None], axis=1)
counts = count_kernel(mask, axis=1)
centers = sums / counts
return centers, pred
def draw(X, n_clusters, centers, pred, output):
# Plot the samples and centroids of the fitted clusters into an image file.
| 64 | 64 | 109 | 30 | 33 | okapies/cupy | examples/kmeans/kmeans.py | Python | draw | draw | 104 | 112 | 104 | 105 | aaec706003c6e8d32edeab3564bd9814a4c89955 | bigcode/the-stack | train |
08b936cd9e79e6394d9d5fe2 | train | function | def fit_xp(X, n_clusters, max_iter):
assert X.ndim == 2
# Get NumPy or CuPy module from the supplied array.
xp = cupy.get_array_module(X)
n_samples = len(X)
# Make an array to store the labels indicating which cluster each sample is
# contained.
pred = xp.zeros(n_samples)
# Choose th... | def fit_xp(X, n_clusters, max_iter):
| assert X.ndim == 2
# Get NumPy or CuPy module from the supplied array.
xp = cupy.get_array_module(X)
n_samples = len(X)
# Make an array to store the labels indicating which cluster each sample is
# contained.
pred = xp.zeros(n_samples)
# Choose the initial centroid for each cluster.
... | 'a + b', 'out = a', '0',
'sum_kernel'
)
count_kernel = cupy.ReductionKernel(
'T mask', 'float32 out',
'mask ? 1.0 : 0.0',
'a + b', 'out = a', '0.0',
'count_kernel'
)
def fit_xp(X, n_clusters, max_iter):
| 87 | 87 | 290 | 12 | 75 | okapies/cupy | examples/kmeans/kmeans.py | Python | fit_xp | fit_xp | 40 | 74 | 40 | 40 | cfa8a5a4657dc9617bc3ef57d1cd8e8027ea96b9 | bigcode/the-stack | train |
306f51e83489fe60a710ea16 | train | class | class ShoppingPerformanceViewServiceClient(
metaclass=ShoppingPerformanceViewServiceClientMeta
):
"""Service to fetch Shopping performance views."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" a... | class ShoppingPerformanceViewServiceClient(
metaclass=ShoppingPerformanceViewServiceClientMeta
):
| """Service to fetch Shopping performance views."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectiv... | PerformanceViewServiceGrpcTransport
class ShoppingPerformanceViewServiceClientMeta(type):
"""Metaclass for the ShoppingPerformanceViewService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
... | 255 | 256 | 3,034 | 19 | 236 | batardo/google-ads-python | google/ads/googleads/v4/services/services/shopping_performance_view_service/client.py | Python | ShoppingPerformanceViewServiceClient | ShoppingPerformanceViewServiceClient | 80 | 454 | 80 | 82 | bb03fc7918e4e994e85735f16c2081e256ae002b | bigcode/the-stack | train |
80e665bb916b92541e51bf8c | train | class | class ShoppingPerformanceViewServiceClientMeta(type):
"""Metaclass for the ShoppingPerformanceViewService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
Or... | class ShoppingPerformanceViewServiceClientMeta(type):
| """Metaclass for the ShoppingPerformanceViewService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[ShoppingPerf... | .resources.types import shopping_performance_view
from google.ads.googleads.v4.services.types import (
shopping_performance_view_service,
)
from .transports.base import (
ShoppingPerformanceViewServiceTransport,
DEFAULT_CLIENT_INFO,
)
from .transports.grpc import ShoppingPerformanceViewServiceGrpcTransport... | 69 | 69 | 230 | 9 | 59 | batardo/google-ads-python | google/ads/googleads/v4/services/services/shopping_performance_view_service/client.py | Python | ShoppingPerformanceViewServiceClientMeta | ShoppingPerformanceViewServiceClientMeta | 46 | 77 | 46 | 46 | f9f2dd827ec2be922bb58f4412de6a952de6f1c1 | bigcode/the-stack | train |
8a0d18286ea80841c30d749c | train | class | class TestIdpInitiatedFlow:
pass
| class TestIdpInitiatedFlow:
| pass
| sp_config), BaseProcessor)
def test_get_processor_loads_custom_processor(self):
sp_config = {
'processor': 'tests.test_views.CustomProcessor'
}
assert isinstance(IdPHandlerViewMixin().get_processor('entity_id', sp_config), CustomProcessor)
class TestIdpInitiatedFlow:
| 64 | 64 | 11 | 8 | 56 | vijithv/djangosaml2idp | tests/test_views.py | Python | TestIdpInitiatedFlow | TestIdpInitiatedFlow | 43 | 44 | 43 | 43 | d25fc428aa1bbfbe1c3ee521ebc5c81196c7f891 | bigcode/the-stack | train |
47673f6270ab33e55a90d89e | train | class | class TestIdPHandlerViewMixin:
def test_get_identity_provides_extra_config(self):
IdPHandlerViewMixin()
def test_get_processor_errors_if_processor_cannot_be_loaded(self):
sp_config = {
'processor': 'this.does.not.exist'
}
with pytest.raises(Exception):
I... | class TestIdPHandlerViewMixin:
| def test_get_identity_provides_extra_config(self):
IdPHandlerViewMixin()
def test_get_processor_errors_if_processor_cannot_be_loaded(self):
sp_config = {
'processor': 'this.does.not.exist'
}
with pytest.raises(Exception):
IdPHandlerViewMixin().get_proces... | pytest
from django.contrib.auth import get_user_model
from djangosaml2idp.views import IdPHandlerViewMixin
from djangosaml2idp.processors import BaseProcessor
User = get_user_model()
class CustomProcessor(BaseProcessor):
pass
class TestIdPHandlerViewMixin:
| 64 | 64 | 170 | 8 | 55 | vijithv/djangosaml2idp | tests/test_views.py | Python | TestIdPHandlerViewMixin | TestIdPHandlerViewMixin | 17 | 40 | 17 | 17 | 8ab96649a7832ca69eee8c2430ddfa6f0e5c0eaf | bigcode/the-stack | train |
6209d87d0b16261f215dbdbe | train | class | class TestMetadata:
pass
| class TestMetadata:
| pass
| def test_get_processor_loads_custom_processor(self):
sp_config = {
'processor': 'tests.test_views.CustomProcessor'
}
assert isinstance(IdPHandlerViewMixin().get_processor('entity_id', sp_config), CustomProcessor)
class TestIdpInitiatedFlow:
pass
class TestMetadata:
| 64 | 64 | 7 | 4 | 59 | vijithv/djangosaml2idp | tests/test_views.py | Python | TestMetadata | TestMetadata | 47 | 48 | 47 | 47 | 0f3cfbcdcb35ea86bf3111f1ab2e31dad227e7ea | bigcode/the-stack | train |
17f522c4b2c1318313dfb172 | train | class | class CustomProcessor(BaseProcessor):
pass
| class CustomProcessor(BaseProcessor):
| pass
| import pytest
from django.contrib.auth import get_user_model
from djangosaml2idp.views import IdPHandlerViewMixin
from djangosaml2idp.processors import BaseProcessor
User = get_user_model()
class CustomProcessor(BaseProcessor):
| 54 | 64 | 9 | 6 | 48 | vijithv/djangosaml2idp | tests/test_views.py | Python | CustomProcessor | CustomProcessor | 13 | 14 | 13 | 13 | 37a8ad34d9013a9530c114653821c7b8bb24a4b9 | bigcode/the-stack | train |
0701949c06838a9eef473ffd | train | class | class LoginFlow:
def test_requires_authentication(self):
"""test redriect to settings.LOGIN_VIEW"""
pass
| class LoginFlow:
| def test_requires_authentication(self):
"""test redriect to settings.LOGIN_VIEW"""
pass
| _processor(self):
sp_config = {
'processor': 'tests.test_views.CustomProcessor'
}
assert isinstance(IdPHandlerViewMixin().get_processor('entity_id', sp_config), CustomProcessor)
class TestIdpInitiatedFlow:
pass
class TestMetadata:
pass
class LoginFlow:
| 64 | 64 | 26 | 4 | 59 | vijithv/djangosaml2idp | tests/test_views.py | Python | LoginFlow | LoginFlow | 51 | 54 | 51 | 51 | db4706217617c32b3beb6b828a8d94fb0c523a83 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.