code stringlengths 12 2.05k | label_name stringclasses 5
values | label int64 0 4 |
|---|---|---|
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.BoolDefinition):
return old.BaseType("bool")
if isinstance(typ, new.AddressDefinition):
return old.BaseType("address")
if isinstance(typ, new.InterfaceDefinition):
return old.InterfaceType(typ._i... | Class | 2 |
def get(cls, uuid):
"""Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method.
"""
url = urljoin(recurly.base_uri(), cls.member_path ... | Base | 1 |
def testSizeAndClear(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32, name='x')
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
wi... | Base | 1 |
def make_tarfile(output_filename, source_dir, archive_name, custom_filter=None):
# Helper for filtering out modification timestamps
def _filter_timestamps(tar_info):
tar_info.mtime = 0
return tar_info if custom_filter is None else custom_filter(tar_info)
unzipped_filename = tempfile.mktemp(... | Class | 2 |
def test_entrance_exam_delete_state_with_staff(self):
""" Test entrance exam delete state failure with staff access. """
self.client.logout()
staff_user = StaffFactory(course_key=self.course.id)
self.client.login(username=staff_user.username, password='test')
url = reverse('r... | Compound | 4 |
def _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | Base | 1 |
def MD5(self,data:str):
sha = hashlib.md5(bytes(data.encode()))
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt) | Base | 1 |
def MD5(self,data:str):
sha = hashlib.md5(bytes(data.encode()))
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt) | Class | 2 |
def logout():
if current_user is not None and current_user.is_authenticated:
ub.delete_user_session(current_user.id, flask_session.get('_id',""))
logout_user()
if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):
logout_oauth_user()
... | Base | 1 |
def test_get_students_who_may_enroll(self):
"""
Test whether get_students_who_may_enroll returns an appropriate
status message when users request a CSV file of students who
may enroll in a course.
"""
url = reverse(
'get_students_who_may_enroll',
... | Compound | 4 |
def __init__(self, conn=None, host=None, result=None,
comm_ok=True, diff=dict()):
# which host is this ReturnData about?
if conn is not None:
self.host = conn.host
delegate = getattr(conn, 'delegate', None)
if delegate is not None:
self.h... | Class | 2 |
def list_zones(self):
pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#stdout, stderr = p.communicate()
... | Base | 1 |
def make_homeserver(self, reactor, clock):
self.push_attempts = []
m = Mock()
def post_json_get_json(url, body):
d = Deferred()
self.push_attempts.append((d, url, body))
return make_deferred_yieldable(d)
m.post_json_get_json = post_json_get_json... | Base | 1 |
def __init__(self, crawler, splash_base_url, slot_policy, log_400):
self.crawler = crawler
self.splash_base_url = splash_base_url
self.slot_policy = slot_policy
self.log_400 = log_400
self.crawler.signals.connect(self.spider_opened, signals.spider_opened) | Class | 2 |
def test_get_conditions(self, freeze):
conditions = ClearableFileInput().get_conditions(None)
assert all(
condition in conditions
for condition in [
{"bucket": "test-bucket"},
{"success_action_status": "201"},
["starts-with", "$... | Base | 1 |
def get_current_phase(self, requested_phase_identifier):
found = False
for phase in self.phases:
if phase.is_valid():
phase.process()
if found or not requested_phase_identifier or requested_phase_identifier == phase.identifier:
found = True # ... | Base | 1 |
def get_http_client(self) -> MatrixFederationHttpClient:
tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory) | Base | 1 |
def __init__(self, text, book):
self.text = text
self.book = book | Base | 1 |
def test_modify_access_allow(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_user.email,
'rolename': 'staff',
'action': 'allow',
})... | Compound | 4 |
def test_get_student_progress_url_nostudent(self):
""" Test that the endpoint 400's when requesting an unknown email. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.s... | Compound | 4 |
def save_cover_from_url(url, book_path):
try:
if not cli.allow_localhost:
# 127.0.x.x, localhost, [::1], [::ffff:7f00:1]
ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0]
if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1":
log.... | Base | 1 |
def visit_Call(self, node):
""" A couple function calls are supported: bson's ObjectId() and
datetime().
"""
if isinstance(node.func, ast.Name):
expr = None
if node.func.id == 'ObjectId':
expr = "('" + node.args[0].s + "')"
elif nod... | Base | 1 |
def prop_sentences_stats(self, type, vId = None):
return {
'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC",
'a... | Base | 1 |
def test_modify_access_allow_with_uname(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_instructor.username,
'rolename': 'staff',
'action':... | Compound | 4 |
def camera_img_return_path(camera_unique_id, img_type, filename):
"""Return an image from stills or time-lapses"""
camera = Camera.query.filter(Camera.unique_id == camera_unique_id).first()
camera_path = assure_path_exists(
os.path.join(PATH_CAMERAS, '{uid}'.format(uid=camera.unique_id)))
if img... | Base | 1 |
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None):
''' run a command on the zone '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: thi... | Base | 1 |
def testInputParserBothDuplicate(self):
x0 = np.array([[1], [2]])
input_path = os.path.join(test.get_temp_dir(), 'input.npz')
np.savez(input_path, a=x0)
x1 = np.ones([2, 10])
input_str = 'x0=' + input_path + '[a]'
input_expr_str = 'x0=np.ones([2,10])'
feed_dict = saved_model_cli.load_input... | Base | 1 |
def _cnonce():
dig = _md5(
(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).encode("utf-8")
).hexdigest()
return dig[:16] | Class | 2 |
def whitelist(f):
"""Decorator: Whitelist method to be called remotely via REST API."""
f.whitelisted = True
return f | Base | 1 |
def test_visitor(self):
class CustomVisitor(self.asdl.VisitorBase):
def __init__(self):
super().__init__()
self.names_with_seq = []
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def v... | Base | 1 |
def _expand_user_properties(self, template):
# Make sure username and servername match the restrictions for DNS labels
# Note: '-' is not in safe_chars, as it is being used as escape character
safe_chars = set(string.ascii_lowercase + string.digits)
# Set servername based on whether... | Class | 2 |
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc) | Class | 2 |
def test_reset_extension_to_deleted_date(self):
"""
Test that we can delete a due date extension after deleting the normal
due date, without causing an error.
"""
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response =... | Compound | 4 |
def read_config(self, config, **kwargs):
# FIXME: federation_domain_whitelist needs sytests
self.federation_domain_whitelist = None # type: Optional[dict]
federation_domain_whitelist = config.get("federation_domain_whitelist", None)
if federation_domain_whitelist is not None:
... | Base | 1 |
def debug_decisions(self, text):
"""
Classifies candidate periods as sentence breaks, yielding a dict for
each that may be used to understand why the decision was made.
See format_debug_decision() to help make this output readable.
"""
for match in self._lang_vars.p... | Class | 2 |
def task_remove(request, task_id):
"""
remove task by task_id
:param request:
:return:
"""
if request.method == 'POST':
try:
# delete job from DjangoJob
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clien... | Base | 1 |
def test_magic_response2():
# check 'body' handling and another 'headers' format
mw = _get_mw()
req = SplashRequest('http://example.com/', magic_response=True,
headers={'foo': 'bar'}, dont_send_headers=True)
req = mw.process_request(req, None)
assert 'headers' not in req.meta... | Class | 2 |
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
"args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
"keywords=[]))])"
)
... | Base | 1 |
def resolve_orders(root: models.User, info, **kwargs):
from ..order.types import OrderCountableConnection
def _resolve_orders(orders):
requester = get_user_or_app_from_context(info.context)
if not requester.has_perm(OrderPermissions.MANAGE_ORDERS):
orders = l... | Class | 2 |
def remove_auth_hashes(input: Optional[str]):
if not input:
return input
# If there are no hashes, skip the RE for performance.
if not any([pw_hash in input for pw_hash in PASSWORD_HASHERS_ALL.keys()]):
return input
return re_remove_passwords.sub(r'\1 %s # Filtered for security' % PASSW... | Base | 1 |
def get_email_content_response(self, num_emails, task_history_request, with_failures=False):
""" Calls the list_email_content endpoint and returns the repsonse """
self.setup_fake_email_info(num_emails, with_failures)
task_history_request.return_value = self.tasks.values()
url = reve... | Compound | 4 |
def property_from_data(
name: str, required: bool, data: Union[oai.Reference, oai.Schema] | Base | 1 |
def test_process_request__multiple_files(self, rf):
storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file"))
storage.save("tmp/s3file/s3_other_file.txt", ContentFile(b"other s3file"))
request = rf.post(
"/",
data={
"file": [
"... | Base | 1 |
def load_event(self, args, filename, from_misp, stix_version):
self.outputname = '{}.json'.format(filename)
if len(args) > 0 and args[0]:
self.add_original_file(filename, args[0], stix_version)
try:
event_distribution = args[1]
if not isinstance(event_dist... | Base | 1 |
def main(srcfile, dump_module=False):
argv0 = sys.argv[0]
components = argv0.split(os.sep)
argv0 = os.sep.join(components[-2:])
auto_gen_msg = common_msg % argv0
mod = asdl.parse(srcfile)
if dump_module:
print('Parsed Module:')
print(mod)
if not asdl.check(mod):
sys.e... | Base | 1 |
def test_evaluate_dict_key_as_underscore(self):
ec = self._makeContext()
self.assertEqual(ec.evaluate('d/_'), 'under') | Base | 1 |
def job_list(request, client_id, project_name):
"""
get job list of project from one client
:param request: request object
:param client_id: client id
:param project_name: project name
:return: list of jobs
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)... | Base | 1 |
def test_basic_lua(settings):
class LuaScriptSpider(ResponseSpider):
""" Make a request using a Lua script similar to the one from README
"""
def start_requests(self):
yield SplashRequest(self.url + "#foo", endpoint='execute',
args={'lua_source': DEFA... | Class | 2 |
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
out_path = self._normalize_path(out_path, self.get_jail_path())
vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail)
self._copy_file(in_path, out_path) | Base | 1 |
def testInputParserPythonExpression(self):
x1 = np.ones([2, 10])
x2 = np.array([[1], [2], [3]])
x3 = np.mgrid[0:5, 0:5]
x4 = [[3], [4]]
input_expr_str = ('x1=np.ones([2,10]);x2=np.array([[1],[2],[3]]);'
'x3=np.mgrid[0:5,0:5];x4=[[3],[4]]')
feed_dict = saved_model_cli.load... | Base | 1 |
def get_install_extras_require():
extras_require = {
'action': ['chevron'],
'browser': ['zeroconf==0.19.1' if PY2 else 'zeroconf>=0.19.1'],
'cloud': ['requests'],
'docker': ['docker>=2.0.0'],
'export': ['bernhard', 'cassandra-driver', 'couchdb', 'elasticsearch',
... | Base | 1 |
def constructObject(data):
try:
classBase = eval(data[""] + "." + data[""].title())
except NameError:
logger.error("Don't know how to handle message type: \"%s\"", data[""])
return None
try:
returnObj = classBase()
returnObj.decode(data)
except KeyError as e:
... | Base | 1 |
def home_get_preview():
vId = request.form['vId']
d = db.sentences_stats('get_preview', vId)
n = db.sentences_stats('id_networks', vId)
return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n}); | Base | 1 |
def test_with_admins(self) -> None:
no_admins = InstanceConfig(admins=None)
with_admins = InstanceConfig(admins=[UUID(int=0)])
with_admins_2 = InstanceConfig(admins=[UUID(int=1)])
no_admins.update(with_admins)
self.assertEqual(no_admins.admins, None)
with_admins.upd... | Class | 2 |
def render_html(request):
"""
render html with url
:param request:
:return:
"""
if request.method == 'GET':
url = request.GET.get('url')
url = unquote(base64.b64decode(url).decode('utf-8'))
js = request.GET.get('js', 0)
script = request.GET.get('script')
t... | Base | 1 |
def add_security_headers(resp):
resp.headers['Content-Security-Policy'] = "default-src 'self' 'unsafe-inline' 'unsafe-eval';"
if request.endpoint == "editbook.edit_book":
resp.headers['Content-Security-Policy'] += "img-src * data:"
resp.headers['X-Content-Type-Options'] = 'nosniff'
resp.headers[... | Compound | 4 |
def mysql_insensitive_ends_with(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"%{value}")) | Base | 1 |
def test_digest():
# Test that we support Digest Authentication
http = httplib2.Http()
password = tests.gen_password()
handler = tests.http_reflect_with_auth(
allow_scheme="digest", allow_credentials=(("joe", password),)
)
with tests.server_request(handler, request_count=3) as uri:
... | Class | 2 |
def format_date(self, data):
"""
A hook to control how dates are formatted.
Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).
Default is ``iso-8601``, which looks like "2010-1... | Class | 2 |
def test_bad_request(settings):
class BadRequestSpider(ResponseSpider):
custom_settings = {'HTTPERROR_ALLOW_ALL': True}
def start_requests(self):
yield SplashRequest(self.url, endpoint='execute',
args={'lua_source': DEFAULT_SCRIPT, 'wait': 'bar'})
cl... | Class | 2 |
def get_install_requires():
requires = ['psutil>=5.3.0', 'future']
if sys.platform.startswith('win'):
requires.append('bottle')
requires.append('requests')
return requires | Base | 1 |
def relative(self, relativePath) -> FileInputSource:
return FileInputSource(os.path.join(self.directory(), relativePath)) | Base | 1 |
def test_http11_list(self):
body = string.ascii_letters
to_send = "GET /list HTTP/1.1\n" "Content-Length: %d\n\n" % len(body)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, heade... | Base | 1 |
def move_files_on_change(calibre_path, new_authordir, new_titledir, localbook, db_filename, original_filepath, path):
new_path = os.path.join(calibre_path, new_authordir, new_titledir)
new_name = get_valid_filename(localbook.title, chars=96) + ' - ' + new_authordir
try:
if original_filepath:
... | Base | 1 |
def __init__(self, hs):
self.hs = hs
self.auth = hs.get_auth()
self.client = hs.get_http_client()
self.clock = hs.get_clock()
self.server_name = hs.hostname
self.store = hs.get_datastore()
self.max_upload_size = hs.config.max_upload_size
self.max_image... | Base | 1 |
def boboAwareZopeTraverse(object, path_items, econtext):
"""Traverses a sequence of names, first trying attributes then items.
This uses zope.traversing path traversal where possible and interacts
correctly with objects providing OFS.interface.ITraversable when
necessary (bobo-awareness).
"""
r... | Base | 1 |
def new_user():
content = ub.User()
languages = calibre_db.speaking_language()
translations = [LC('en')] + babel.list_translations()
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if request.method == "POST":
to_save = request.form.to_dict()
_handle_new_user(to_sa... | Base | 1 |
def test_after_start_response_http11(self):
to_send = "GET /after_start_response HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line,... | Base | 1 |
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self._type_string
return f"Optional[{self._type_string}]" | Base | 1 |
def test_course_has_entrance_exam_in_student_attempts_reset(self):
""" Test course has entrance exam id set while resetting attempts"""
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(ur... | Compound | 4 |
async def customize(self, ctx, command: str.lower, *, response: str = None):
"""
Customize the response to an action.
You can use {0} or {user} to dynamically replace with the specified target of the action.
Formats like {0.name} or {0.mention} can also be used.
"""
... | Base | 1 |
def help_page(page_slug: str) -> str:
"""Fava's included documentation."""
if page_slug not in HELP_PAGES:
abort(404)
html = markdown2.markdown_path(
(resource_path("help") / (page_slug + ".md")),
extras=["fenced-code-blocks", "tables", "header-ids"],
)
return render_template... | Base | 1 |
def _configuration_oauth_helper(to_save):
active_oauths = 0
reboot_required = False
for element in oauthblueprints:
if to_save["config_" + str(element['id']) + "_oauth_client_id"] != element['oauth_client_id'] \
or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != eleme... | Base | 1 |
def update_dir_structure_gdrive(book_id, first_author, renamed_author):
book = calibre_db.get_book(book_id)
authordir = book.path.split('/')[0]
titledir = book.path.split('/')[1]
new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)
new_titledir = get_valid_filename(book.tit... | Base | 1 |
def test_tofile_sep(self):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
f = open(self.filename, 'w')
x.tofile(f, sep=',')
f.close()
f = open(self.filename, 'r')
s = f.read()
f.close()
assert_equal(s, '1.51,2.0,3.51,4.0')
os.unlink(self.filenam... | Base | 1 |
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc":
return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
... | Base | 1 |
def is_valid_client_secret(client_secret):
"""Validate that a given string matches the client_secret regex defined by the spec
:param client_secret: The client_secret to validate
:type client_secret: unicode
:return: Whether the client_secret is valid
:rtype: bool
"""
return client_secret_... | Base | 1 |
def make_homeserver(self, reactor, clock):
self.fetches = []
def get_file(destination, path, output_stream, args=None, max_size=None):
"""
Returns tuple[int,dict,str,int] of file length, response headers,
absolute URI, and response code.
"""
... | Base | 1 |
def __new__(cls, sourceName: str):
"""Dispatches to the right subclass."""
if cls != InputSource:
# Only take control of calls to InputSource(...) itself.
return super().__new__(cls)
if sourceName == "-":
return StdinInputSource(sourceName)
if sou... | Base | 1 |
def feed_hot():
off = request.args.get("offset") or 0
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
hot_books = all_books.offset(off).limit(config.config_books_per_page)
entries = lis... | Base | 1 |
def decompile(self):
self.writeln("** Decompiling APK...", clr.OKBLUE)
with ZipFile(self.file) as zipped:
try:
dex = self.tempdir + "/" + self.apk.package + ".dex"
with open(dex, "wb") as classes:
classes.write(zipped.read("classes.dex"))
except Exception as e:
sys.exit(self.writeln(str(e), ... | Base | 1 |
def yet_another_upload_file(request):
path = tempfile.mkdtemp()
file_name = os.path.join(path, "yet_another_%s.txt" % request.node.name)
with open(file_name, "w") as f:
f.write(request.node.name)
return file_name | Base | 1 |
def test_received_trailer_startswith_lf(self):
buf = DummyBuffer()
inst = self._makeOne(buf)
inst.all_chunks_received = True
result = inst.received(b"\n")
self.assertEqual(result, 1)
self.assertEqual(inst.completed, True) | Base | 1 |
def start_requests(self):
yield SplashRequest(self.url, endpoint='execute',
args={'lua_source': DEFAULT_SCRIPT}) | Class | 2 |
def test_uses_default(self):
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
}
)
actual_path = os.path.abspath(account_info.filename)
assert os.path.join(self.home, '.b2_account_... | Base | 1 |
def test_is_valid_hostname(self):
"""Tests that the is_valid_hostname function accepts only valid
hostnames (or domain names), with optional port number.
"""
self.assertTrue(is_valid_hostname("example.com"))
self.assertTrue(is_valid_hostname("EXAMPLE.COM"))
self.asse... | Base | 1 |
def test_reset_student_attempts_invalid_entrance_exam(self):
""" Test reset for invalid entrance exam. """
url = reverse('reset_student_attempts_for_entrance_exam',
kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})
response = self.client.get(url, {
... | Compound | 4 |
def test_module(self):
body = [ast.Num(42)]
x = ast.Module(body)
self.assertEqual(x.body, body) | Base | 1 |
def filter(self, names):
for name in [_hkey(n) for n in names]:
if name in self.dict:
del self.dict[name] | Base | 1 |
def _redirect_request_using_get(self, request, redirect_url):
redirected = request.replace(url=redirect_url, method='GET', body='')
redirected.headers.pop('Content-Type', None)
redirected.headers.pop('Content-Length', None)
return redirected | Class | 2 |
def main():
app = create_app()
init_errorhandler()
app.register_blueprint(web)
app.register_blueprint(opds)
app.register_blueprint(jinjia)
app.register_blueprint(about)
app.register_blueprint(shelf)
app.register_blueprint(admi)
app.register_blueprint(remotelogin)
app.register_b... | Base | 1 |
def _get_index_absolute_path(index):
return os.path.join(INDEXDIR, index) | Base | 1 |
def image(self, request, pk):
obj = self.get_object()
if obj.get_space() != request.space:
raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403)
serializer = self.serializer_class(obj, data=request.data, partial=True)
... | Base | 1 |
def parse(self, response):
yield {'response': response} | Class | 2 |
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
par... | Class | 2 |
async def check_credentials(username, password):
return password == "iloveyou" | Base | 1 |
def load(self):
config_type = type(self).__name__.lower()
try:
with self.path.open(encoding=UTF8) as f:
try:
data = json.load(f)
except ValueError as e:
raise ConfigFileError(
f'invalid {confi... | Class | 2 |
def test_received_headers_finished_expect_continue_false(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.expect_continue = False
preq.headers_finished = True
preq.completed = False
... | Base | 1 |
def edit_single_cc_data(book_id, book, column_id, to_save):
cc = (calibre_db.session.query(db.Custom_Columns)
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions))
.filter(db.Custom_Columns.id == column_id)
.all())
return edit_cc_data(book_id, book, to_save, cc) | Base | 1 |
def __init__(self, **kwargs):
self.basic_auth = get_anymail_setting('webhook_authorization', default=[],
kwargs=kwargs) # no esp_name -- auth is shared between ESPs
# Allow a single string:
if isinstance(self.basic_auth, six.string_types):
... | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.