code stringlengths 12 2.05k | label_name stringlengths 6 8 | label int64 0 95 |
|---|---|---|
def feed_author(book_id):
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books,
db.Books.authors.... | CWE-918 | 16 |
def test_received_headers_finished_expect_continue_true(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.expect_continue = True
preq.headers_finished = True
preq.completed = False
... | CWE-444 | 41 |
def kebab_case(value: str) -> str:
return stringcase.spinalcase(group_title(_sanitize(value))) | CWE-94 | 14 |
def test_file_position_after_fromfile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
... | CWE-59 | 36 |
def expr(self, node, msg=None, *, exc=ValueError):
mod = ast.Module([ast.Expr(node)])
self.mod(mod, msg, exc=exc) | CWE-125 | 47 |
def ratings_list():
if current_user.check_visibility(constants.SIDEBAR_RATING):
if current_user.get_view_property('ratings', 'dir') == 'desc':
order = db.Ratings.rating.desc()
order_no = 0
else:
order = db.Ratings.rating.asc()
order_no = 1
entr... | CWE-918 | 16 |
def test_keepalive_http10_explicit(self):
# If header Connection: Keep-Alive is explicitly sent,
# we want to keept the connection open, we also need to return
# the corresponding header
data = "Keep me alive"
s = tobytes(
"GET / HTTP/1.0\n"
"Connectio... | CWE-444 | 41 |
def __getattr__(_self, attr):
if attr == "nameResolver":
return nameResolver
else:
return getattr(real_reactor, attr) | CWE-601 | 11 |
def show_book(book_id):
entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True)
if entries:
read_book = entries[1]
archived_book = entries[2]
entry = entries[0]
entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED
... | CWE-918 | 16 |
def feed_read_books():
off = request.args.get("offset") or 0
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True)
return render_xml_template('feed.xml', entries=result, pagination=pagination) | CWE-918 | 16 |
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Err... | CWE-59 | 36 |
def put_file(path):
try:
dest_path = sanitized_join(
path,
pathlib.Path(app.config["DATA_ROOT"]),
)
except ValueError:
return flask.Response(
"Not Found",
404,
mimetype="text/plain",
)
verification_key = flask.reque... | CWE-22 | 2 |
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if ITraversable.providedBy(base):
base = getattr(base, cls.... | CWE-22 | 2 |
def allow_all(tag: str, name: str, value: str) -> bool:
return True | CWE-79 | 1 |
def _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | CWE-22 | 2 |
def _create(self):
url = urljoin(recurly.base_uri(), self.collection_path)
return self.post(url) | CWE-918 | 16 |
def render_delete_book_result(book_format, jsonResponse, warning, book_id):
if book_format:
if jsonResponse:
return json.dumps([warning, {"location": url_for("editbook.edit_book", book_id=book_id),
"type": "success",
... | CWE-918 | 16 |
def scriptPath(*pathSegs):
startPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
return os.path.join(startPath, *pathSegs) | CWE-78 | 6 |
def feed_seriesindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\
.group_by(func.upper(func.substr(db.Seri... | CWE-918 | 16 |
def _consumer(self, auth):
auth.process_response()
errors = auth.get_errors()
if not errors:
if auth.is_authenticated():
return True
else:
return False
else:
current_app.logger.error('Error processing %s' % (', '.joi... | CWE-601 | 11 |
def feed_ratings(book_id):
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books,
db.Books.ratings... | CWE-918 | 16 |
def test_parse_header_11_te_chunked(self):
# NB: test that capitalization of header value is unimportant
data = b"GET /foobar HTTP/1.1\ntransfer-encoding: ChUnKed"
self.parser.parse_header(data)
self.assertEqual(self.parser.body_rcv.__class__.__name__, "ChunkedReceiver") | CWE-444 | 41 |
def test_confirmation_expired(self) -> None:
email = self.nonreg_email("alice")
realm = get_realm("zulip")
inviter = self.example_user("iago")
prereg_user = PreregistrationUser.objects.create(
email=email, referred_by=inviter, realm=realm
)
date_sent = tim... | CWE-613 | 7 |
def print_train_stats():
print(
"TEMPLATE STATISTICS (TRAIN) {} templates, {} rules)".format(
len(template_counts), len(tids)
)
)
print(
"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc... | CWE-1333 | 73 |
def parse(source, filename='<unknown>', mode='exec'):
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
"""
return compile(source, filename, mode, PyCF_ONLY_AST) | CWE-125 | 47 |
def __init__(self, hs):
self.server_name = hs.hostname
self.client = hs.get_http_client() | CWE-601 | 11 |
def test_login_unknown_code(self):
response = self.client.post('/accounts-rest/login/code/', {
'code': 'unknown',
})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(), {
'code': ['Login code is invalid. It might have expired.'],
... | CWE-312 | 71 |
def publish(request, category_id=None):
if category_id:
get_object_or_404(
Category.objects.visible(),
pk=category_id)
user = request.user
form = TopicForm(
user=user,
data=post_data(request),
initial={'category': category_id})
cform = CommentForm... | CWE-601 | 11 |
def delete(request, pk, remove=True):
comment = get_object_or_404(Comment, pk=pk)
if is_post(request):
(Comment.objects
.filter(pk=pk)
.update(is_removed=remove))
return redirect(request.GET.get('next', comment.get_absolute_url()))
return render(
request=request,
... | CWE-601 | 11 |
def PUT(self, path, body, ensure_encoding=True, log_request_body=True):
return self._request('PUT', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body) | CWE-295 | 52 |
def test_property_from_data_array(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},)
ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty")
FloatProperty = mocker.patch(f"{MOD... | CWE-94 | 14 |
def convert_bookformat(book_id):
# check to see if we have form fields to work with - if not send user back
book_format_from = request.form.get('book_format_from', None)
book_format_to = request.form.get('book_format_to', None)
if (book_format_from is None) or (book_format_to is None):
flash(_... | CWE-918 | 16 |
def get(self, arg,word=None):
#print "match auto"
try:
limit = self.get_argument("limit")
word = self.get_argument("word")
callback = self.get_argument("callback") #jsonp
result = rtxcomplete.prefix(word,limit)
result = callback+"("+json.... | CWE-79 | 1 |
def test_logout_get(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar')
self.client.login(username=self.user.username, code=login_code.code)
response = self.client.post('/accounts/logout/?next=/accounts/login/')
self.assertEqual(response.status_code, 302)
... | CWE-312 | 71 |
def test_get_frontend_context_variables_xss(component):
# Set component.name to a potential XSS attack
component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
frontend_context_variables = component.get_frontend_context_variables()
frontend_context_v... | CWE-79 | 1 |
def check_username(username):
username = username.strip()
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
log.error(u"This username is already taken")
raise Exception (_(u"This username is already taken"))
return username | CWE-918 | 16 |
def test_before_start_response_http_11_close(self):
to_send = tobytes(
"GET /before_start_response HTTP/1.1\n" "Connection: close\n\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
... | CWE-444 | 41 |
async def ignore(self, ctx, command: str.lower):
"""
Ignore or unignore the specified action.
The bot will no longer respond to these actions.
"""
try:
custom = await self.config.guild(ctx.guild).get_raw("custom", command)
except KeyError:
... | CWE-502 | 15 |
def make_homeserver(self, reactor, clock):
self.http_client = Mock()
hs = self.setup_test_homeserver(http_client=self.http_client)
return hs | CWE-601 | 11 |
def index():
""" Index handler """
send = request.vars.send
if DEMO_MODE:
session.authorized = True
session.last_time = t0
if not send:
send = URL('site')
if session.authorized:
redirect(send)
elif failed_login_count() >= allowed_number_of_attempts:
time.... | CWE-601 | 11 |
def __init__(self, hs: "HomeServer"):
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self.clock = hs.get_clock()
self._instance_name = hs.get_instance_name()
# These are safe to load in monolith mode, but will explode if we try
# and use them.... | CWE-601 | 11 |
def _returndata_encoding(contract_sig):
if contract_sig.is_from_json:
return Encoding.JSON_ABI
return Encoding.ABI | CWE-190 | 19 |
def test_short_body(self):
# check to see if server closes connection when body is too short
# for cl header
to_send = tobytes(
"GET /short_body HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: 0\n"
"\n"
)
self.connect()
... | CWE-444 | 41 |
def test_filelike_http11(self):
to_send = "GET /filelike HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
... | CWE-444 | 41 |
def adv_search_serie(q, include_series_inputs, exclude_series_inputs):
for serie in include_series_inputs:
q = q.filter(db.Books.series.any(db.Series.id == serie))
for serie in exclude_series_inputs:
q = q.filter(not_(db.Books.series.any(db.Series.id == serie)))
return q | CWE-918 | 16 |
def _is_javascript_scheme(s):
if _is_image_dataurl(s):
return None
return _is_possibly_malicious_scheme(s) | CWE-79 | 1 |
def create_book_on_upload(modif_date, meta):
title = meta.title
authr = meta.author
sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)
title_dir = helper.get_valid_filename(title, chars=96)
author_dir = helper.get_valid_filename(db_author.name, chars=9... | CWE-918 | 16 |
def test_received_cl_too_large(self):
from waitress.utilities import RequestEntityTooLarge
self.parser.adj.max_request_body_size = 2
data = b"""\
GET /foobar HTTP/8.4
Content-Length: 10
"""
result = self.parser.received(data)
self.assertEqual(result, 41)
self.assert... | CWE-444 | 41 |
def on_permitted_domain(team: Team, request: HttpRequest) -> bool:
permitted_domains = ["127.0.0.1", "localhost"]
for url in team.app_urls:
hostname = parse_domain(url)
if hostname:
permitted_domains.append(hostname)
origin = parse_domain(request.headers.get("Origin"))
refe... | CWE-601 | 11 |
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args) | CWE-79 | 1 |
def job_cancel(request, client_id, project_name, job_id):
"""
cancel a job
:param request: request object
:param client_id: client id
:param project_name: project name
:param job_id: job id
:return: json of cancel
"""
if request.method == 'GET':
client = Client.objects.get(id... | CWE-78 | 6 |
def test_received_preq_completed_empty(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.completed = True
preq.empty = True
inst.received(b"GET / HTTP/1.1\n\n")
self.assertEqual(in... | CWE-444 | 41 |
def table_get_locale():
locale = babel.list_translations() + [LC('en')]
ret = list()
current_locale = get_locale()
for loc in locale:
ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)})
return json.dumps(ret) | CWE-918 | 16 |
def test_get_header_lines_folded(self):
# From RFC2616:
# HTTP/1.1 header field values can be folded onto multiple lines if the
# continuation line begins with a space or horizontal tab. All linear
# white space, including folding, has the same semantics as SP. A
# recipient ... | CWE-444 | 41 |
def table_get_custom_enum(c_id):
ret = list()
cc = (calibre_db.session.query(db.Custom_Columns)
.filter(db.Custom_Columns.id == c_id)
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())
ret.append({'value': "", 'text': ""})
for idx, en in enumerate(cc.... | CWE-918 | 16 |
def edit_user_table():
visibility = current_user.view_settings.get('useredit', {})
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [LC('en')]
allUser = ub.session.query(ub.User)
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
... | CWE-918 | 16 |
def render_hot_books(page, order):
if current_user.check_visibility(constants.SIDEBAR_HOT):
if order[1] not in ['hotasc', 'hotdesc']:
# Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+
#if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or
... | CWE-918 | 16 |
def get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
path = pathlib.PurePosixPath(path)
try:
location = storage.aws_location
except AttributeError:
location = storage.l... | CWE-22 | 2 |
def property_from_data(
name: str, required: bool, data: Union[oai.Reference, oai.Schema] | CWE-94 | 14 |
def test_stopped_typing(self):
self.room_members = [U_APPLE, U_BANANA, U_ONION]
# Gut-wrenching
from synapse.handlers.typing import RoomMember
member = RoomMember(ROOM_ID, U_APPLE.to_string())
self.handler._member_typing_until[member] = 1002000
self.handler._room_ty... | CWE-601 | 11 |
def test_invalid_sum(self):
pos = dict(lineno=2, col_offset=3)
m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
self.assertIn("but got <_ast.expr", str(cm.exception)) | CWE-125 | 47 |
def feed_ratingindex():
off = request.args.get("offset") or 0
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
(db.Ratings.rating / 2).label('name')) \
.join(db.books_ratings_link)\
.join(db.Books)\
.filte... | CWE-918 | 16 |
def _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | CWE-22 | 2 |
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... | CWE-125 | 47 |
def _get_index_absolute_path(index):
return os.path.join(INDEXDIR, index) | CWE-22 | 2 |
def __init__(self, expression, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expression.
ordering = (
(OrderBy(F(o[1:]), descending=T... | CWE-89 | 0 |
def open_soap_envelope(text):
"""
:param text: SOAP message
:return: dictionary with two keys "body"/"header"
"""
try:
envelope = ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
... | CWE-611 | 13 |
def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host).
Always returns ``False`` on an empty url.
"""
if not url:
return False
netloc = urllib_parse.urlparse(url)[1]
return not netloc or netloc == host | CWE-79 | 1 |
def testUnravelIndexZeroDim(self):
with self.cached_session():
for dtype in [dtypes.int32, dtypes.int64]:
with self.assertRaisesRegex(errors.InvalidArgumentError,
"index is out of bound as with dims"):
indices = constant_op.constant([2, 5, 7], dtype=dtyp... | CWE-369 | 60 |
def sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId)) | CWE-79 | 1 |
def render_edit_book(book_id):
cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)
if not book:
flash(_(u"Oops! Selected book title is unavailable. File does not exis... | CWE-918 | 16 |
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... | CWE-918 | 16 |
def __init__(self, sydent):
self.sydent = sydent
# The default endpoint factory in Twisted 14.0.0 (which we require) uses the
# BrowserLikePolicyForHTTPS context factory which will do regular cert validation
# 'like a browser'
self.agent = Agent(
self.sydent.react... | CWE-918 | 16 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
"red", http_client=None, federation_client=Mock(),
)
self.event_source = hs.get_event_sources().sources["typing"]
hs.get_federation_handler = Mock()
async def get_user_by_access_token(... | CWE-601 | 11 |
def glob_to_regex(glob):
"""Converts a glob to a compiled regex object.
The regex is anchored at the beginning and end of the string.
Args:
glob (str)
Returns:
re.RegexObject
"""
res = ""
for c in glob:
if c == "*":
res = res + ".*"
elif c == "?... | CWE-331 | 72 |
def update(request, pk):
topic = Topic.objects.for_update_or_404(pk, request.user)
category_id = topic.category_id
form = TopicForm(
user=request.user,
data=post_data(request),
instance=topic)
if is_post(request) and form.is_valid():
topic = form.save()
if topic.c... | CWE-601 | 11 |
def _factorial(x):
if x<=10000:
return float(math.factorial(x))
else:
raise Exception('factorial argument too large') | CWE-94 | 14 |
def get_file(recipe):
if not recipe.link:
recipe.link = Dropbox.get_share_link(recipe)
recipe.save()
response = requests.get(recipe.link.replace('www.dropbox.', 'dl.dropboxusercontent.'))
return io.BytesIO(response.content) | CWE-918 | 16 |
def test_mixed(self):
self.assertEqual(self._callFUT(b"\n\n00\r\n\r\n"), 2) | CWE-444 | 41 |
async def tenorkey(self, ctx):
"""
Sets a Tenor GIF API key to enable reaction gifs with act commands.
You can obtain a key from here: https://tenor.com/developer/dashboard
"""
instructions = [
"Go to the Tenor developer dashboard: https://tenor.com/develo... | CWE-502 | 15 |
def encode_non_url_reserved_characters(url):
# safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2
return urlquote(url, safe=":/?#[]@!$&'()*+,;=") | CWE-601 | 11 |
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False):
# Create new_author_dir from parameter or from database
# Create new title_dir from database and add id
if first_author:
new_authordir = get_valid_filename(first_author, chars=96)
for r in re... | CWE-918 | 16 |
def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id):
"""Send email with attachments"""
book = calibre_db.get_book(book_id)
if convert == 1:
# returns None if success, otherwise errormessage
return convert_book_format(book_id, calibrepath, u'epub', book_format.low... | CWE-918 | 16 |
def test_http11_listlentwo(self):
body = string.ascii_letters
to_send = "GET /list_lentwo HTTP/1.1\n" "Content-Length: %s\n\n" % len(body)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb")
l... | CWE-444 | 41 |
def opds_download_link(book_id, book_format):
# I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest
# workaround, loading the user from the request and checking it's download rights here
# in case of anonymous browsing user is None
user = load_user_f... | CWE-918 | 16 |
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" or ip == "0.0.0.0" or... | CWE-918 | 16 |
def testCapacity(self):
capacity = 3
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.int32, name='x')
pi = array_ops.placeholder(dtypes.int64, name='pi')
gi = array_ops.placeholder(dtypes.int64, name='gi')
with ops.device(tes... | CWE-843 | 43 |
def make_homeserver(self, reactor, clock):
config = self.default_config()
config["redaction_retention_period"] = "30d"
return self.setup_test_homeserver(
resource_for_federation=Mock(), http_client=None, config=config
) | CWE-601 | 11 |
def test_process_request__no_file(self, rf, caplog):
request = rf.post("/", data={"file": "does_not_exist.txt", "s3file": "file"})
S3FileMiddleware(lambda x: None)(request)
assert not request.FILES.getlist("file")
assert "File not found: does_not_exist.txt" in caplog.text | CWE-22 | 2 |
def _contains_display_name(self, display_name: str) -> bool:
if not display_name:
return False
body = self._event.content.get("body", None)
if not body or not isinstance(body, str):
return False
# Similar to _glob_matches, but do not treat display_name as a ... | CWE-331 | 72 |
def get_response(self):
token_serializer = self.token_serializer_class(
instance=self.token,
context=self.get_serializer_context(),
)
data = token_serializer.data
data['next'] = self.serializer.validated_data['code'].next
return Response(data, status=s... | CWE-312 | 71 |
def test_file_insert(self, request, driver, live_server, upload_file, freeze):
driver.get(live_server + self.url)
file_input = driver.find_element(By.XPATH, "//input[@name='file']")
file_input.send_keys(upload_file)
assert file_input.get_attribute("name") == "file"
with wait_... | CWE-22 | 2 |
def valid_id(opts, id_):
'''
Returns if the passed id is valid
'''
try:
return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)
except (AttributeError, KeyError, TypeError) as e:
return False | CWE-22 | 2 |
def render_prepare_search_form(cc):
# prepare data for search-form
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(text('books_tags_link.tag'))\
.order_by(db.Tags.name).all()
series... | CWE-918 | 16 |
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()
... | CWE-918 | 16 |
def test_request_login_code(self):
response = self.client.post('/accounts-rest/login/', {
'username': self.user.username,
'next': '/private/',
})
self.assertEqual(response.status_code, 200)
login_code = LoginCode.objects.filter(user=self.user).first()
... | CWE-312 | 71 |
def _decompress(compressed_path: Text, target_path: Text) -> None:
with tarfile.open(compressed_path, "r:gz") as tar:
tar.extractall(target_path) # target dir will be created if it not exists | CWE-23 | 74 |
def test_credits_one(self, expected_count=1):
self.add_change()
data = generate_credits(
None,
timezone.now() - timedelta(days=1),
timezone.now() + timedelta(days=1),
translation__component=self.component,
)
self.assertEqual(
... | CWE-79 | 1 |
def test_build_attr(self):
assert set(ClearableFileInput().build_attrs({}).keys()) == {
"class",
"data-url",
"data-fields-x-amz-algorithm",
"data-fields-x-amz-date",
"data-fields-x-amz-signature",
"data-fields-x-amz-credential",
... | CWE-22 | 2 |
def test_filelike_nocl_http10(self):
to_send = "GET /filelike_nocl HTTP/1.0\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, "200", "OK"... | CWE-444 | 41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.