code stringlengths 12 2.05k | label_name stringlengths 6 8 | label int64 0 95 |
|---|---|---|
def should_run(self):
if self.force:
return True
if not os.path.exists(self.bower_dir):
return True
return mtime(self.bower_dir) < mtime(pjoin(repo_root, 'bower.json')) | CWE-79 | 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):
... | CWE-532 | 28 |
def innerfn(fn):
global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func
whitelisted.append(fn)
allowed_http_methods_for_whitelisted_func[fn] = methods
if allow_guest:
guest_methods.append(fn)
if xss_safe:
xss_safe_methods.append(fn)
return fn | CWE-79 | 1 |
def test_open_with_filename(self):
tmpname = mktemp('', 'mmap')
fp = memmap(tmpname, dtype=self.dtype, mode='w+',
shape=self.shape)
fp[:] = self.data[:]
del fp
os.unlink(tmpname) | CWE-59 | 36 |
def from_dict(d: Dict[str, Any]) -> AModel:
an_enum_value = AnEnum(d["an_enum_value"])
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]:
a_camel_date_time: Union[datetime, date]
try:
a_camel_date_time = datetime.fromisoformat(d["aCa... | CWE-94 | 14 |
def send_note_attachment(filename):
"""Return a file from the note attachment directory"""
file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)
if file_path is not None:
try:
return send_file(file_path, as_attachment=True)
except Exception:
logger.exception("Send... | CWE-22 | 2 |
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... | CWE-94 | 14 |
inline void AveragePool(const float* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int kwidth, int kheight,
float output_activation_min,
float output_activation_ma... | CWE-835 | 42 |
def test_received_body_too_large(self):
from waitress.utilities import RequestEntityTooLarge
self.parser.adj.max_request_body_size = 2
data = b"""\
GET /foobar HTTP/1.1
Transfer-Encoding: chunked
X-Foo: 1
20;\r\n
This string has 32 characters\r\n
0\r\n\r\n"""
result = self.parser.r... | CWE-444 | 41 |
def extract_messages(obj_list):
"""
Extract "messages" from a list of exceptions or other objects.
For ValidationErrors, `messages` are flattened into the output.
For Exceptions, `args[0]` is added into the output.
For other objects, `force_text` is called.
:param obj_list: List of exceptions ... | CWE-79 | 1 |
def setup_logging():
"""Configure the python logging appropriately for the tests.
(Logs will end up in _trial_temp.)
"""
root_logger = logging.getLogger()
log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s"
" - %(message)s"
)
handler = ToTwistedHandler()
... | CWE-918 | 16 |
def generate_code(cls):
hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256')
m = getattr(hashlib, hash_algorithm)()
m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8'))
m.update(os.urandom(16))
if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', F... | CWE-312 | 71 |
def table_xchange_author_title():
vals = request.get_json().get('xchange')
if vals:
for val in vals:
modif_date = False
book = calibre_db.get_book(val)
authors = book.title
book.authors = calibre_db.order_authors([book])
author_names = []
... | CWE-918 | 16 |
def test_notfilelike_iobase_http11(self):
to_send = "GET /notfilelike_iobase 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 = rea... | CWE-444 | 41 |
def _get_index_absolute_path(index):
return os.path.join(INDEXDIR, index) | CWE-22 | 2 |
def post_json_get_nothing(self, uri, post_json, opts):
"""Make a POST request to an endpoint returning JSON and parse result
:param uri: The URI to make a POST request to.
:type uri: unicode
:param post_json: A Python object that will be converted to a JSON
string and P... | CWE-770 | 37 |
def admin():
version = updater_thread.get_current_version_info()
if version is False:
commit = _(u'Unknown')
else:
if 'datetime' in version:
commit = version['datetime']
tz = timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)
... | CWE-918 | 16 |
def test_chunking_request_with_content(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
expected = s * 12
header = tobytes("GET / HTTP/1.1\n" "Transfer-Encoding: chunked\n\n")
self.connect()
self.sock.send(header)
f... | CWE-444 | 41 |
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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
self.store = hs.get_datastore()
return hs | CWE-601 | 11 |
def test_after_write_cb(self):
to_send = "GET /after_write_cb 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, "200", "OK", "HTTP... | CWE-444 | 41 |
def render_search_results(term, offset=None, order=None, limit=None):
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
entries, result_count, pagination = calibre_db.get_search_results(term,
offset,
... | CWE-918 | 16 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
self.handler = hs.get_device_handler()
self.store = hs.get_datastore()
return hs | CWE-601 | 11 |
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... | CWE-94 | 14 |
def test_request_body_too_large_with_no_cl_http10(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.0\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_... | CWE-444 | 41 |
def feed_category(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.tags.a... | CWE-918 | 16 |
def test_date_parsing(value, result):
if result == errors.DateError:
with pytest.raises(errors.DateError):
parse_date(value)
else:
assert parse_date(value) == result | CWE-835 | 42 |
def func_begin(self, name):
ctype = get_c_type(name)
self.emit("PyObject*", 0)
self.emit("ast2obj_%s(void* _o)" % (name), 0)
self.emit("{", 0)
self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
self.emit("PyObject *result = NULL, *value = NULL;", 1)
self.emit('if... | CWE-125 | 47 |
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... | CWE-918 | 16 |
def testInputPreProcessFormats(self):
input_str = 'input1=/path/file.txt[ab3];input2=file2'
input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'
input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)
input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(
input_exp... | CWE-94 | 14 |
def execute_cmd(cmd, from_async=False):
"""execute a request as python module"""
for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
# override using the first hook
cmd = hook
break
# via server script
if run_server_script_api(cmd):
return None
try:
method = get_attr(cmd)
ex... | CWE-79 | 1 |
def test_counts_view_html(self):
response = self.get_counts("html")
self.assertEqual(response.status_code, 200)
self.assertHTMLEqual(
response.content.decode(),
"""
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Count total</th>
<th>... | CWE-79 | 1 |
def testFlushFunction(self):
logdir = self.get_temp_dir()
with context.eager_mode():
writer = summary_ops.create_file_writer_v2(
logdir, max_queue=999999, flush_millis=999999)
with writer.as_default():
get_total = lambda: len(events_from_logdir(logdir))
# Note: First tf.c... | CWE-475 | 76 |
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
if not in_path.startswith(os.path.sep):
in_path = os.path.join(os.path.sep, in_path)
normpath = os.path.normpath(in_path)
in_path = os.path.join(self.chroot, normpath[1:])
vvv("FE... | CWE-59 | 36 |
def make_homeserver(self, reactor, clock):
self.fetches = []
async 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.
"""
... | CWE-601 | 11 |
def unarchive(byte_array: bytes, directory: Text) -> Text:
"""Tries to unpack a byte array interpreting it as an archive.
Tries to use tar first to unpack, if that fails, zip will be used."""
try:
tar = tarfile.open(fileobj=IOReader(byte_array))
tar.extractall(directory)
tar.close(... | 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 test_http10_generator(self):
body = string.ascii_letters
to_send = (
"GET / HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: %d\n\n" % len(body)
)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.soc... | CWE-444 | 41 |
def strip_illegal_bytes_parser(xml):
return parse(BytesIO(re_xml_illegal_bytes.sub(b'', xml))) | CWE-611 | 13 |
def create_access(request, topic_id):
topic_private = TopicPrivate.objects.for_create_or_404(topic_id, request.user)
form = TopicPrivateInviteForm(
topic=topic_private.topic,
data=post_data(request))
if form.is_valid():
form.save()
notify_access(user=form.get_user(), topic_p... | CWE-601 | 11 |
def whitelist(allow_guest=False, xss_safe=False, methods=None):
"""
Decorator for whitelisting a function and making it accessible via HTTP.
Standard request will be `/api/method/[path.to.method]`
:param allow_guest: Allow non logged-in user to access this method.
:param methods: Allowed http method to access the... | CWE-79 | 1 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
return hs | CWE-601 | 11 |
def setUp(self):
self.mock_federation_resource = MockHttpResource()
self.mock_http_client = Mock(spec=[])
self.mock_http_client.put_json = DeferredMockCallable()
hs = yield setup_test_homeserver(
self.addCleanup, http_client=self.mock_http_client, keyring=Mock(),
... | CWE-601 | 11 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
"server", http_client=None, federation_sender=Mock()
)
return hs | CWE-601 | 11 |
def func_begin(self, name):
ctype = get_c_type(name)
self.emit("PyObject*", 0)
self.emit("ast2obj_%s(void* _o)" % (name), 0)
self.emit("{", 0)
self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
self.emit("PyObject *result = NULL, *value = NULL;", 1)
self.emit('if... | CWE-125 | 47 |
def category_list():
if current_user.check_visibility(constants.SIDEBAR_CATEGORY):
if current_user.get_view_property('category', 'dir') == 'desc':
order = db.Tags.name.desc()
order_no = 0
else:
order = db.Tags.name.asc()
order_no = 1
entries = ... | CWE-918 | 16 |
def get_file(path):
try:
data_file, metadata = get_info(
path,
pathlib.Path(app.config["DATA_ROOT"])
)
except (OSError, ValueError):
return flask.Response(
"Not Found",
404,
mimetype="text/plain",
)
response = flask... | CWE-22 | 2 |
def edit_book_languages(languages, book, upload=False, invalid=None):
input_languages = languages.split(',')
unknown_languages = []
if not upload:
input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages)
else:
input_l = isoLanguages.get_valid_language_c... | CWE-918 | 16 |
def mysql_insensitive_exact(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).eq(functions.Upper(f"{value}")) | CWE-89 | 0 |
def test_notfilelike_http10(self):
to_send = "GET /notfilelike 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", "H... | CWE-444 | 41 |
def test_parse_header_no_cr_in_headerplus(self):
data = b"GET /foobar HTTP/8.4"
self.parser.parse_header(data)
self.assertEqual(self.parser.first_line, data) | CWE-444 | 41 |
def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
for notifier in os.listdir(self.data):
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notif... | CWE-78 | 6 |
def list_users():
off = int(request.args.get("offset") or 0)
limit = int(request.args.get("limit") or 10)
search = request.args.get("search")
sort = request.args.get("sort", "id")
state = None
if sort == "state":
state = json.loads(request.args.get("state", "[]"))
else:
if so... | CWE-918 | 16 |
def _download_file(bucket, filename, local_dir):
key = bucket.get_key(filename)
local_filename = os.path.join(local_dir, filename)
key.get_contents_to_filename(local_filename)
return local_filename | CWE-22 | 2 |
def handleMatch(m):
s = m.group(1)
if s.startswith('0x'):
i = int(s, 16)
elif s.startswith('0') and '.' not in s:
try:
i = int(s, 8)
except ValueError:
i = int(s)
else:
... | CWE-94 | 14 |
def initSession(self, expire_on_commit=True):
self.session = self.session_factory()
self.session.expire_on_commit = expire_on_commit
self.update_title_sort(self.config) | CWE-918 | 16 |
def create_code_for_user(cls, user, next=None):
if not user.is_active:
return None
code = cls.generate_code()
login_code = LoginCode(user=user, code=code)
if next is not None:
login_code.next = next
login_code.save()
return login_code | CWE-312 | 71 |
def update(request, pk):
comment = Comment.objects.for_update_or_404(pk, request.user)
form = CommentForm(data=post_data(request), instance=comment)
if is_post(request) and form.is_valid():
pre_comment_update(comment=Comment.objects.get(pk=comment.pk))
comment = form.save()
post_comm... | CWE-601 | 11 |
def get_header_lines(header):
"""
Splits the header into lines, putting multi-line headers together.
"""
r = []
lines = header.split(b"\n")
for line in lines:
if line.startswith((b" ", b"\t")):
if not r:
# https://corte.si/posts/code/pathod/pythonservers/index... | CWE-444 | 41 |
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... | CWE-444 | 41 |
def store_user_session():
if flask_session.get('_user_id', ""):
try:
if not check_user_session(flask_session.get('_user_id', ""), flask_session.get('_id', "")):
user_session = User_Sessions(flask_session.get('_user_id', ""), flask_session.get('_id', ""))
session.a... | CWE-79 | 1 |
def load_hparams_from_yaml(config_yaml: str, use_omegaconf: bool = True) -> Dict[str, Any]:
"""Load hparams from a file.
Args:
config_yaml: Path to config yaml file
use_omegaconf: If omegaconf is available and ``use_omegaconf=True``,
the hparams will be converted to ... | CWE-502 | 15 |
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\
.filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
if len(include_shelf_inputs) > 0:
q = q.filter(ub.BookShelf.shelf.in_... | CWE-918 | 16 |
def test_notfilelike_shortcl_http11(self):
to_send = "GET /notfilelike_shortcl 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 = r... | CWE-444 | 41 |
def _inject_metadata_into_fs(metadata, fs, execute=None):
metadata_path = os.path.join(fs, "meta.js")
metadata = dict([(m.key, m.value) for m in metadata])
utils.execute('tee', metadata_path,
process_input=jsonutils.dumps(metadata), run_as_root=True) | CWE-22 | 2 |
def test_get_frontend_context_variables_safe(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>'
class Meta:
safe = [
"name",
]
setattr(component, "Meta", Me... | CWE-79 | 1 |
def test_get_imports(self, mocker):
from openapi_python_client.parser.properties import DateTimeProperty
name = mocker.MagicMock()
mocker.patch("openapi_python_client.utils.snake_case")
p = DateTimeProperty(name=name, required=True, default=None)
assert p.get_imports(prefix=... | CWE-94 | 14 |
def test_uses_existing_file_and_ignores_xdg(self):
with WindowsSafeTempDir() as d:
default_db_file_location = os.path.join(self.home, '.b2_account_info')
open(default_db_file_location, 'a').close()
account_info = self._make_sqlite_account_info(
env={
... | CWE-367 | 29 |
def register(request, registration_form=RegistrationForm):
if request.user.is_authenticated:
return redirect(request.GET.get('next', reverse('spirit:user:update')))
form = registration_form(data=post_data(request))
if (is_post(request) and
not request.is_limited() and
form.i... | CWE-601 | 11 |
def test_send_empty_body(self):
to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK",... | CWE-444 | 41 |
def testColocation(self):
gpu_dev = test.gpu_device_name()
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(gpu_dev):
stager = data_flow_ops.MapStagingArea([d... | CWE-843 | 43 |
def mysql_ends_with(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}") | CWE-89 | 0 |
def test_send_event_single_sender(self):
"""Test that using a single federation sender worker correctly sends a
new event.
"""
mock_client = Mock(spec=["put_json"])
mock_client.put_json.return_value = make_awaitable({})
self.make_worker_hs(
"synapse.app.f... | CWE-601 | 11 |
def test_bad_integer(self):
# issue13436: Bad error message with invalid numeric values
body = [ast.ImportFrom(module='time',
names=[ast.alias(name='sleep')],
level=None,
lineno=None, col_offset=None)]
... | CWE-125 | 47 |
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, initial_filename='bookmarks.pickle')
if filename:
with open(filename, 'wb') as fileobj:
... | CWE-502 | 15 |
def check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):
if not config_calibre_dir:
return False, False
dbpath = os.path.join(config_calibre_dir, "metadata.db")
if not os.path.exists(dbpath):
return False, False
try:
check_eng... | CWE-918 | 16 |
async def initialize(self, bot):
# temporary backwards compatibility
key = await self.config.tenorkey()
if not key:
return
await bot.set_shared_api_tokens("tenor", api_key=key)
await self.config.tenorkey.clear()
| CWE-502 | 15 |
def test_http11_generator(self):
body = string.ascii_letters
to_send = "GET / 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")
line, headers... | CWE-444 | 41 |
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}); | CWE-79 | 1 |
def import_bookmarks(self):
files = choose_files(self, 'export-viewer-bookmarks', _('Import bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, select_only_single_file=True)
if not files:
return
filename = files[0]
imported = None
... | CWE-502 | 15 |
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 testSimple(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(te... | CWE-843 | 43 |
def test_file_position_after_tofile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
err_msg = "%d" % (size,)
f = open(self.filename, 'wb')
f.seek(... | CWE-59 | 36 |
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to th... | CWE-502 | 15 |
def parse_line(s):
s = s.rstrip()
r = re.sub(REG_LINE_GPERF, '', s)
if r != s: return r
r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)
if r != s: return r
r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\1)', s)
if r != s: return r
r = re.sub(REG_UNFOLD_KEY, 'unicode_unf... | CWE-787 | 24 |
def render_search_results(term, offset=None, order=None, limit=None):
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
entries, result_count, pagination = calibre_db.get_search_results(term,
offset,
... | CWE-918 | 16 |
def post(self, request, *args, **kwargs): # doccov: ignore
command = request.POST.get("command")
if command:
dispatcher = getattr(self, "dispatch_%s" % command, None)
if not callable(dispatcher):
raise Problem(_("Unknown command: `%s`.") % command)
... | CWE-79 | 1 |
def get_http_client(self) -> MatrixFederationHttpClient:
tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory) | CWE-601 | 11 |
def _remove_javascript_link(self, link):
# links like "j a v a s c r i p t:" might be interpreted in IE
new = _substitute_whitespace('', link)
if _is_javascript_scheme(new):
# FIXME: should this be None to delete?
return ''
return link | CWE-79 | 1 |
def test_send_with_body(self):
to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n"
to_send += "hello"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.ass... | CWE-444 | 41 |
def test_double_linefeed(self):
self.assertEqual(self._callFUT(b"\n\n"), 2) | CWE-444 | 41 |
def upload_cover(request, book):
if 'btn-upload-cover' in request.files:
requested_file = request.files['btn-upload-cover']
# check for empty request
if requested_file.filename != '':
if not current_user.role_upload():
abort(403)
ret, message = helper.... | CWE-918 | 16 |
async def check_credentials(username: str, password: str) -> bool:
return (username, password) == credentials | CWE-203 | 38 |
def view_configuration():
read_column = calibre_db.session.query(db.Custom_Columns)\
.filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all()
restrict_columns = calibre_db.session.query(db.Custom_Columns)\
.filter(and_(db.Custom_Columns.datatype == 'text'... | CWE-918 | 16 |
void AveragePool(const float* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int kwidth, int kheight, float* output_data,
const Dims<4>& output_dims) {
float output_activation_min, output_activation_max;
G... | CWE-835 | 42 |
def emit(self, s, depth, reflow=True):
# XXX reflow long lines?
if reflow:
lines = reflow_lines(s, depth)
else:
lines = [s]
for line in lines:
line = (" " * TABSIZE * depth) + line + "\n"
self.file.write(line) | CWE-125 | 47 |
def item_to_bm(self, item):
return cPickle.loads(bytes(item.data(Qt.UserRole))) | CWE-502 | 15 |
def _request(self, method, path, queries=(), body=None, ensure_encoding=True,
log_request_body=True): | CWE-295 | 52 |
def _not_here_yet(request, *args, **kwargs):
return HttpResponse("Not here yet: %s (%r, %r)" % (request.path, args, kwargs), status=410) | CWE-79 | 1 |
def test_filelike_nocl_http11(self):
to_send = "GET /filelike_nocl 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.