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): self.basic_auth = [self.basic_auth] if self.warn_if_no_basic_auth and len(self.basic_auth) < 1: warnings.warn( "Your Anymail webhooks are insecure and open to anyone on the web. " "You should set WEBHOOK_AUTHORIZATION in your ANYMAIL settings. " "See 'Securing webhooks' in the Anymail docs.", AnymailInsecureWebhookWarning) # noinspection PyArgumentList super(AnymailBasicAuthMixin, self).__init__(**kwargs)
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["aCamelDateTime"]) return a_camel_date_time except: pass a_camel_date_time = date.fromisoformat(d["aCamelDateTime"]) return a_camel_date_time a_camel_date_time = _parse_a_camel_date_time(d["aCamelDateTime"]) a_date = date.fromisoformat(d["a_date"]) nested_list_of_enums = [] for nested_list_of_enums_item_data in d.get("nested_list_of_enums") or []: nested_list_of_enums_item = [] for nested_list_of_enums_item_item_data in nested_list_of_enums_item_data: nested_list_of_enums_item_item = DifferentEnum(nested_list_of_enums_item_item_data) nested_list_of_enums_item.append(nested_list_of_enums_item_item) nested_list_of_enums.append(nested_list_of_enums_item) some_dict = d.get("some_dict") return AModel( an_enum_value=an_enum_value, a_camel_date_time=a_camel_date_time, a_date=a_date, nested_list_of_enums=nested_list_of_enums, some_dict=some_dict, )
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 note attachment")
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_inputs_from_input_arg_string( '', input_expr_str, '') self.assertTrue(np.all(feed_dict['x1'] == x1)) self.assertTrue(np.all(feed_dict['x2'] == x2)) self.assertTrue(np.all(feed_dict['x3'] == x3)) self.assertTrue(np.all(feed_dict['x4'] == x4))
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_max, float* output_data, const Dims<4>& output_dims) { tflite::PoolParams params; params.stride_height = stride_height; params.stride_width = stride_width; params.filter_height = kheight; params.filter_width = kwidth; params.padding_values.height = pad_height; params.padding_values.width = pad_width; params.float_activation_min = output_activation_min; params.float_activation_max = output_activation_max; AveragePool(params, DimsToShape(input_dims), input_data, DimsToShape(output_dims), output_data); }
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.received(data) self.assertEqual(result, 58) self.parser.received(data[result:]) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))
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 etc. :type obj_list: Iterable[object] :rtype: Iterable[str] """ for obj in obj_list: if isinstance(obj, ValidationError): for msg in obj.messages: yield force_text(msg) continue if isinstance(obj, Exception): if len(obj.args): yield force_text(obj.args[0]) continue yield force_text(obj)
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() formatter = logging.Formatter(log_format) handler.setFormatter(formatter) root_logger.addHandler(handler) log_level = os.environ.get("SYDENT_TEST_LOG_LEVEL", "ERROR") root_logger.setLevel(log_level)
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', False): hashed = str(int(m.hexdigest(), 16)) else: hashed = m.hexdigest() return hashed
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 = [] for authr in book.authors: author_names.append(authr.name.replace('|', ',')) title_change = handle_title_on_edit(book, " ".join(author_names)) input_authors, authorchange, renamed = handle_author_on_edit(book, authors) if authorchange or title_change: edited_books_id = book.id modif_date = True if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() if edited_books_id: helper.update_dir_structure(edited_books_id, config.config_calibre_dir, input_authors[0], renamed_author=renamed) if modif_date: book.last_modified = datetime.utcnow() try: calibre_db.session.commit() except (OperationalError, IntegrityError) as e: calibre_db.session.rollback() log.error_or_exception("Database error: %s", e) return json.dumps({'success': False}) if config.config_use_google_drive: gdriveutils.updateGdriveCalibreFromLocal() return json.dumps({'success': True}) return ""
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 = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body)
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 POSTed to the given URI. :type post_json: dict[any, any] :param opts: A dictionary of request options. Currently only opts.headers is supported. :type opts: dict[str,any] :return: a response from the remote server. :rtype: twisted.internet.defer.Deferred[twisted.web.iweb.IResponse] """ json_bytes = json.dumps(post_json).encode("utf8") headers = opts.get('headers', Headers({ b"Content-Type": [b"application/json"], })) logger.debug("HTTP POST %s -> %s", json_bytes, uri) response = yield self.agent.request( b"POST", uri.encode("utf8"), headers, bodyProducer=FileBodyProducer(BytesIO(json_bytes)) ) # Ensure the body object is read otherwise we'll leak HTTP connections # as per # https://twistedmatrix.com/documents/current/web/howto/client.html yield readBody(response) defer.returnValue(response)
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) form_date = datetime.strptime(commit[:19], "%Y-%m-%dT%H:%M:%S") if len(commit) > 19: # check if string has timezone if commit[19] == '+': form_date -= timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) elif commit[19] == '-': form_date += timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) commit = format_datetime(form_date - tz, format='short', locale=get_locale()) else: commit = version['version'] allUser = ub.session.query(ub.User).all() email_settings = config.get_mail_settings() kobo_support = feature_support['kobo'] and config.config_kobo_sync return render_title_template("admin.html", allUser=allUser, email=email_settings, config=config, commit=commit, feature_support=feature_support, kobo_support=kobo_support, title=_(u"Admin page"), page="admin")
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) fp = self.sock.makefile("rb", 0) for n in range(12): self.sock.send(control_line) self.sock.send(s) self.sock.send(b"0\r\n\r\n") line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(echo.body, expected) self.assertEqual(echo.content_length, str(len(expected))) self.assertFalse("transfer-encoding" in headers)
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/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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, order, limit, False, config.config_read_column, *join) return render_title_template('search.html', searchterm=term, pagination=pagination, query=term, adv_searchterm=term, entries=entries, result_count=result_count, title=_(u"Search"), page="search", order=order[1])
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 node.func.id == 'datetime': values = [] for arg in node.args: values.append(str(arg.n)) expr = "(" + ", ".join(values) + ")" if expr: self.current_value = eval(node.func.id + expr)
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_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # extra bytes are thrown away (no pipelining), connection closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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.any(db.Tags.id == book_id), [db.Books.timestamp.desc()]) return render_xml_template('feed.xml', entries=entries, pagination=pagination)
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 (!o) {', 1) self.emit("Py_INCREF(Py_None);", 2) self.emit('return Py_None;', 2) self.emit("}", 1) self.emit('', 0)
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.title, chars=96) + u" (" + str(book_id) + u")" if titledir != new_titledir: gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), titledir) if gFile: gd.moveGdriveFileRemote(gFile, new_titledir) book.path = book.path.split('/')[0] + u'/' + new_titledir gd.updateDatabaseOnEdit(gFile['id'], book.path) # only child folder affected else: return _(u'File %(file)s not found on Google Drive', file=book.path) # file not found if authordir != new_authordir and authordir not in renamed_author: gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), new_titledir) if gFile: gd.moveGdriveFolderRemote(gFile, new_authordir) book.path = new_authordir + u'/' + book.path.split('/')[1] gd.updateDatabaseOnEdit(gFile['id'], book.path) else: return _(u'File %(file)s not found on Google Drive', file=authordir) # file not found # change location in database to new author/title path book.path = os.path.join(new_authordir, new_titledir).replace('\\', '/') return rename_files_on_change(first_author, renamed_author, book, gdrive=True)
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_expr_str) self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(input_dict['input2'] == ('file2', None)) print(input_expr_dict['input3']) self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2])) self.assertAllClose(input_expr_dict['input4'], [4, 5]) self.assertTrue(len(input_dict) == 2) self.assertTrue(len(input_expr_dict) == 2)
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) except Exception as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if from_async: method = method.queue is_whitelisted(method) is_valid_http_method(method) return frappe.call(method, **frappe.form_dict)
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>Edits total</th> <th>Source words total</th> <th>Source chars total</th> <th>Target words total</th> <th>Target chars total</th> <th>Count new</th> <th>Edits new</th> <th>Source words new</th> <th>Source chars new</th> <th>Target words new</th> <th>Target chars new</th> <th>Count approved</th> <th>Edits approved</th> <th>Source words approved</th> <th>Source chars approved</th> <th>Target words approved</th> <th>Target chars approved</th> <th>Count edited</th> <th>Edits edited</th> <th>Source words edited</th> <th>Source chars edited</th> <th>Target words edited</th> <th>Target chars edited</th> </tr> <tr> <td>Weblate Test</td> <td>[email protected]</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>1</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </table> """, )
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.compat.v1.Event is always file_version. self.assertEqual(1, get_total()) summary_ops.write('tag', 1, step=0) summary_ops.write('tag', 1, step=0) self.assertEqual(1, get_total()) summary_ops.flush() self.assertEqual(3, get_total()) # Test "writer" parameter summary_ops.write('tag', 1, step=0) self.assertEqual(3, get_total()) summary_ops.flush(writer=writer) self.assertEqual(4, get_total()) summary_ops.write('tag', 1, step=0) self.assertEqual(4, get_total()) summary_ops.flush(writer=writer._resource) # pylint:disable=protected-access self.assertEqual(5, get_total())
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("FETCH %s TO %s" % (in_path, out_path), host=self.chroot) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shutil.copyfile(in_path, out_path) except shutil.Error: traceback.print_exc() raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path)) except IOError: traceback.print_exc() raise errors.AnsibleError("failed to transfer file to %s" % out_path)
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. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return await make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, http_client=client) return hs
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() return directory except tarfile.TarError: zip_ref = zipfile.ZipFile(IOReader(byte_array)) zip_ref.extractall(directory) zip_ref.close() return directory
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.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) f = open(p, "w") f.write(auto_gen_msg) f.write('#include "asdl.h"\n\n') c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) f.write("PyObject* Ta3AST_mod2obj(mod_ty t);\n") f.write("mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n") f.write("int Ta3AST_Check(PyObject* obj);\n") f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "w") f.write(auto_gen_msg) f.write('#include <stddef.h>\n') f.write('\n') f.write('#include "Python.h"\n') f.write('#include "%s-ast.h"\n' % mod.name) f.write('\n') f.write("static PyTypeObject AST_type;\n") v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), Obj2ModPrototypeVisitor(f), FunctionVisitor(f), ObjVisitor(f), Obj2ModVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
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.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("content-length"), None) self.assertEqual(headers.get("connection"), "close") self.assertEqual(response_body, tobytes(body)) # remote closed connection (despite keepalive header), because # generators cannot have a content-length divined self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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_private=topic_private) else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', topic_private.get_absolute_url()))
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 method. Use as: @frappe.whitelist() def myfunc(param1, param2): pass """ if not methods: methods = ['GET', 'POST', 'PUT', 'DELETE'] 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 return innerfn
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(), ) self.filtering = hs.get_filtering() self.datastore = hs.get_datastore()
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 (!o) {', 1) self.emit("Py_INCREF(Py_None);", 2) self.emit('return Py_None;', 2) self.emit("}", 1) self.emit('', 0)
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 = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Categories"), page="catlist", data="category", order=order_no) else: abort(404)
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.make_response(flask.send_file( str(data_file), )) generate_headers( response.headers, metadata["headers"], ) return response
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_codes(get_locale(), input_languages, unknown_languages) for l in unknown_languages: log.error("'%s' is not a valid language", l) if isinstance(invalid, list): invalid.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) # ToDo: Not working correct if upload and len(input_l) == 1: # If the language of the file is excluded from the users view, it's not imported, to allow the user to view # the book it's language is set to the filter language if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all": input_l[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code # Remove duplicates input_l = helper.uniq(input_l) return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages')
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", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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 (notifier[-4:] == '.swp') or (notifier in ['SCCS', '.svn', '4913'])): continue npath = self.data + '/' + notifier self.logger.debug("Running %s %s" % (npath, " ".join(args))) async_run(npath, args)
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 sort not in ub.User.__table__.columns.keys(): sort = "id" order = request.args.get("order", "").lower() if sort != "state" and order: order = text(sort + " " + order) elif not state: order = ub.User.id.asc() all_user = ub.session.query(ub.User) if not config.config_anonbrowse: all_user = all_user.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) total_count = filtered_count = all_user.count() if search: all_user = all_user.filter(or_(func.lower(ub.User.name).ilike("%" + search + "%"), func.lower(ub.User.kindle_mail).ilike("%" + search + "%"), func.lower(ub.User.email).ilike("%" + search + "%"))) if state: users = calibre_db.get_checkbox_sorted(all_user.all(), state, off, limit, request.args.get("order", "").lower()) else: users = all_user.order_by(order).offset(off).limit(limit).all() if search: filtered_count = len(users) for user in users: if user.default_language == "all": user.default = _("All") else: user.default = LC.parse(user.default_language).get_language_name(get_locale()) table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": users} js_list = json.dumps(table_entries, cls=db.AlchemyEncoder) response = make_response(js_list) response.headers["Content-Type"] = "application/json; charset=utf-8" return response
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: i = float(s) x = complex(i) if x.imag == 0: x = x.real # Need to use string-formatting here instead of str() because # use of str() on large numbers loses information: # str(float(33333333333333)) => '3.33333333333e+13' # float('3.33333333333e+13') => 33333333333300.0 return '%.16f' % x return str(x)
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_comment_update(comment=comment) return redirect(request.POST.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/update.html', context={'form': form})
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.html raise ParsingError('Malformed header line "%s"' % tostr(line)) r[-1] += line else: r.append(line) return r
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, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(headers["content-length"], str(len(body))) self.assertEqual(response_body, tobytes(body)) # remote keeps connection open because it divined the content length # from a length-1 list self.sock.send(to_send) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1")
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.add(user_session) session.commit() log.info("Login and store session : " + flask_session.get('_id', "")) else: log.info("Found stored session : " + flask_session.get('_id', "")) except (exc.OperationalError, exc.InvalidRequestError) as e: session.rollback() log.exception(e) else: log.error("No user id in session")
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 ``DictConfig`` if possible. >>> hparams = Namespace(batch_size=32, learning_rate=0.001, data_root='./any/path/here') >>> path_yaml = './testing-hparams.yaml' >>> save_hparams_to_yaml(path_yaml, hparams) >>> hparams_new = load_hparams_from_yaml(path_yaml) >>> vars(hparams) == hparams_new True >>> os.remove(path_yaml) """ fs = get_filesystem(config_yaml) if not fs.exists(config_yaml): rank_zero_warn(f"Missing Tags: {config_yaml}.", category=RuntimeWarning) return {} with fs.open(config_yaml, "r") as fp: hparams = yaml.load(fp, Loader=yaml.UnsafeLoader) if _OMEGACONF_AVAILABLE: if use_omegaconf: try: return OmegaConf.create(hparams) except (UnsupportedValueType, ValidationError): pass return hparams
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_(include_shelf_inputs)) return q
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 = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, 1) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377" in response_body)
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", Meta()) frontend_context_variables = component.get_frontend_context_variables() frontend_context_variables_dict = orjson.loads(frontend_context_variables) assert len(frontend_context_variables_dict) == 1 assert ( frontend_context_variables_dict.get("name") == '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>' )
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="") == { "from datetime import datetime", "from typing import cast", } p.required = False assert p.get_imports(prefix="") == { "from typing import Optional", "from datetime import datetime", "from typing import cast", }
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={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, } ) actual_path = os.path.abspath(account_info.filename) assert default_db_file_location == actual_path assert not os.path.exists(os.path.join(d, 'b2'))
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.is_valid()): user = form.save() send_activation_email(request, user) messages.info( request, _( "We have sent you an email to %(email)s " "so you can activate your account!") % {'email': form.get_email()}) # TODO: email-less activation # if not settings.REGISTER_EMAIL_ACTIVATION_REQUIRED: # login(request, user) # return redirect(request.GET.get('next', reverse('spirit:user:update'))) return redirect(reverse(settings.LOGIN_URL)) return render( request=request, template_name='spirit/user/auth/register.html', context={'form': form})
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", "HTTP/1.0") self.assertEqual(echo.content_length, "0") self.assertEqual(echo.body, b"")
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([dtypes.float32]) y = stager.put(1, [v], [0]) expected_name = gpu_dev if 'gpu' not in gpu_dev else '/device:GPU:0' self.assertEqual(y.device, expected_name) with ops.device('/cpu:0'): _, x = stager.get(1) y = stager.peek(1)[0] _, z = stager.get() self.assertEqual(x[0].device, '/device:CPU:0') self.assertEqual(y.device, '/device:CPU:0') self.assertEqual(z[0].device, '/device:CPU:0') G.finalize()
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.federation_sender", {"send_federation": True}, http_client=mock_client, ) user = self.register_user("user", "pass") token = self.login("user", "pass") room = self.create_room_with_remote_server(user, token) mock_client.put_json.reset_mock() self.create_and_send_event(room, UserID.from_string(user)) self.replicate() # Assert that the event was sent out over federation. mock_client.put_json.assert_called() self.assertEqual(mock_client.put_json.call_args[0][0], "other_server") self.assertTrue(mock_client.put_json.call_args[1]["data"].get("pdus"))
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)] mod = ast.Module(body) with self.assertRaises(ValueError) as cm: compile(mod, 'test', 'exec') self.assertIn("invalid integer value: None", str(cm.exception))
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: cPickle.dump(self.get_bookmarks(), fileobj, -1)
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_engine = create_engine('sqlite://', echo=False, isolation_level="SERIALIZABLE", connect_args={'check_same_thread': False}, poolclass=StaticPool) with check_engine.begin() as connection: connection.execute(text("attach database '{}' as calibre;".format(dbpath))) connection.execute(text("attach database '{}' as app_settings;".format(app_db_path))) local_session = scoped_session(sessionmaker()) local_session.configure(bind=connection) database_uuid = local_session().query(Library_Id).one_or_none() # local_session.dispose() check_engine.connect() db_change = config_calibre_uuid != database_uuid.uuid except Exception: return False, False return True, db_change
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, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in chunks(body, 10): expected += tobytes( "%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk) ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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 with open(filename, 'rb') as fileobj: imported = cPickle.load(fileobj) if imported is not None: bad = False try: for bm in imported: if 'title' not in bm: bad = True break except Exception: pass if not bad: bookmarks = self.get_bookmarks() for bm in imported: if bm not in bookmarks: bookmarks.append(bm) self.set_bookmarks([bm for bm in bookmarks if bm['title'] != 'calibre_current_page_bookmark']) self.edited.emit(self.get_bookmarks())
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.any(db.Ratings.id == book_id), [db.Books.timestamp.desc()]) return render_xml_template('feed.xml', entries=entries, pagination=pagination)
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(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea([dtypes.float32]) stage = stager.put(pi, [v], [0]) k, y = stager.get(gi) y = math_ops.reduce_max(math_ops.matmul(y, y)) G.finalize() with self.session(graph=G) as sess: sess.run(stage, feed_dict={x: -1, pi: 0}) for i in range(10): _, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i}) self.assertAllClose(4 * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)
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(size-1) f.write(b'\0') f.seek(10) f.write(b'12') np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10 + 2 + 8, err_msg=err_msg) f = open(self.filename, 'r+b') f.read(2) f.seek(0, 1) # seek between read&write required by ANSI C np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) os.unlink(self.filename)
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 the corresponding functions / classes. Args: **kwargs: Additional keyword arguments to be passed to `yaml.dump()`. Returns: A YAML string. Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError( 'Requires yaml module installed (`pip install pyyaml`).') return yaml.dump(self._updated_config(), **kwargs)
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_unfold_key(OnigCodePoint code)', s) if r != s: return r r = re.sub(REG_ENTRY, '{\\1, \\2, \\3}', s) if r != s: return r r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\1, \\2}', s) if r != s: return r r = re.sub(REG_IF_LEN, 'if (0 == 0)', s) if r != s: return r r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s) if r != s: return r r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s) if r != s: return r r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s) if r != s: return r return s
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, order, limit, False, config.config_read_column, *join) return render_title_template('search.html', searchterm=term, pagination=pagination, query=term, adv_searchterm=term, entries=entries, result_count=result_count, title=_(u"Search"), page="search", order=order[1])
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) dispatch_kwargs = dict(request.POST.items()) rv = dispatcher(**dispatch_kwargs) if rv: return rv self.request.method = "GET" # At this point, we won't want to cause form validation self.build_form() # and it's not a bad idea to rebuild the form return super(EditorView, self).get(request, *args, **kwargs) if request.POST.get("save") and self.form and self.form.is_valid(): self.form.save() self.save_layout() # after we save the new layout configs, make sure to reload the saved data in forms # so the returned get() response contains updated data self.build_form() if request.POST.get("publish") == "1": return self.dispatch_publish() return self.get(request, *args, **kwargs)
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.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(echo.content_length, "5") self.assertEqual(echo.body, b"hello")
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.save_cover(requested_file, book.path) if ret is True: return True else: flash(message, category="error") return False return None
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', db.Custom_Columns.mark_for_delete == 0)).all() languages = calibre_db.speaking_language() translations = [LC('en')] + babel.list_translations() return render_title_template("config_view_edit.html", conf=config, readColumns=read_column, restrictColumns=restrict_columns, languages=languages, translations=translations, title=_(u"UI Configuration"), page="uiconfig")
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; GetActivationMinMax(Ac, &output_activation_min, &output_activation_max); AveragePool(input_data, input_dims, stride_width, stride_height, pad_width, pad_height, kwidth, kheight, output_activation_min, output_activation_max, output_data, output_dims); }
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) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body)
CWE-444
41