code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def setup_db(cls, config_calibre_dir, app_db_path): cls.dispose() if not config_calibre_dir: cls.config.invalidate() return False dbpath = os.path.join(config_calibre_dir, "metadata.db") if not os.path.exists(dbpath): cls.config.invalidate() ...
Base
1
def get_image(path): def get_absolute_path(path): import os script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in rel_path = path abs_file_path = os.path.join(script_dir, rel_path) return abs_file_path return send_file( get_absolute_path(f"....
Base
1
def create(request, comment_id): comment = get_object_or_404( Comment.objects.exclude(user=request.user), pk=comment_id) form = LikeForm( user=request.user, comment=comment, data=post_data(request)) if is_post(request) and form.is_valid(): like = form.save() ...
Base
1
def check_auth(username, password): try: username = username.encode('windows-1252') except UnicodeEncodeError: username = username.encode('utf-8') user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.decode('utf-8').lower())...
Base
1
def item_to_bm(self, item): return cPickle.loads(bytes(item.data(Qt.UserRole)))
Base
1
def whitelist(f): """Decorator: Whitelist method to be called remotely via REST API.""" f.whitelisted = True return f
Base
1
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...
Base
1
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute(...
Base
1
def edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comm...
Base
1
def cookies(self) -> RequestsCookieJar: jar = RequestsCookieJar() for name, cookie_dict in self['cookies'].items(): jar.set_cookie(create_cookie( name, cookie_dict.pop('value'), **cookie_dict)) jar.clear_expired_cookies() return jar
Class
2
def test_reset_nonexistent_extension(self): url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) sel...
Compound
4
def set_admins(self) -> None: name = self.results["deploy"]["func-name"]["value"] key = self.results["deploy"]["func-key"]["value"] table_service = TableService(account_name=name, account_key=key) if self.admins: update_admins(table_service, self.application_name, self.ad...
Class
2
def parse_soap_enveloped_saml_thingy(text, expected_tags): """Parses a SOAP enveloped SAML thing and returns the thing as a string. :param text: The SOAP object as XML string :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelo...
Base
1
def get(self): if not current_user.is_authenticated(): return "Must be logged in to log out", 200 logout_user() return "Logged Out", 200
Base
1
def validate_request(self, request): """If configured for webhook basic auth, validate request has correct auth.""" if self.basic_auth: basic_auth = get_request_basic_auth(request) if basic_auth is None or basic_auth not in self.basic_auth: # noinspection PyUn...
Class
2
def test_dir(self, tmpdir): url = QUrl.fromLocalFile(str(tmpdir)) req = QNetworkRequest(url) reply = filescheme.handler(req) # The URL will always use /, even on Windows - so we force this here # too. tmpdir_path = str(tmpdir).replace(os.sep, '/') assert reply...
Compound
4
def test_manage_pools(self) -> None: user1 = uuid4() user2 = uuid4() # by default, any can modify self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo() ) ) # with oid, but no ad...
Class
2
def _parse_cache_control(headers): retval = {} if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] par...
Class
2
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)
Class
2
def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value)
Base
1
def main(): app = create_app() init_errorhandler() app.register_blueprint(web) app.register_blueprint(opds) app.register_blueprint(jinjia) app.register_blueprint(about) app.register_blueprint(shelf) app.register_blueprint(admi) app.register_blueprint(remotelogin) app.register_b...
Base
1
def test_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin): session = Session(self.config_dir) session['cookies'] = initial_cookie session.remove_cookies([expired_cookie]) assert expired_cookie not in session.cookies
Class
2
def test_modify_access_with_fake_user(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': 'GandalfTheGrey', 'rolename': 'staff', 'action': 'revoke', ...
Compound
4
def get_user_profile(access_token): headers = {"Authorization": "OAuth {}".format(access_token)} response = requests.get( "https://www.googleapis.com/oauth2/v1/userinfo", headers=headers ) if response.status_code == 401: logger.warning("Failed getting user profile (response code 401).")...
Base
1
def auth_user_registration(self): return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION"]
Class
2
def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\n" " Host: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response...
Base
1
def delete_user_session(user_id, session_key): try: log.info("Deleted session_key : " + session_key) session.query(User_Sessions).filter(User_Sessions.user_id==user_id, User_Sessions.session_key==session_key).delete() session.commit() except (e...
Base
1
def sentences_stats(self, type, vId = None): return self.sql_execute(self.prop_sentences_stats(type, vId))
Base
1
def set_admins(self) -> None: name = self.results["deploy"]["func-name"]["value"] key = self.results["deploy"]["func-key"]["value"] table_service = TableService(account_name=name, account_key=key) if self.admins: update_admins(table_service, self.application_name, self.ad...
Class
2
async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match], Optional[str]]: """ Return True if `text` matches any regex from `word_watchlist` or `token_watchlist` configs. `word_watchlist`'s patterns are placed between word boundaries while `token_watchlist` is ...
Class
2
def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param x...
Base
1
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...
Base
1
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(...
Base
1
def mysql_ends_with(field: Field, value: str) -> Criterion: return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}")
Base
1
def test_can_read_token_from_headers(self): """Tests that Sydent correct extracts an auth token from request headers""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details" ) request.requestHeaders.addRawHea...
Class
2
def test_get_students_features(self): """ Test that some minimum of information is formatted correctly in the response to get_students_features. """ for student in self.students: student.profile.city = "Mos Eisley {}".format(student.id) student.profile...
Compound
4
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...
Base
1
def _on_load_started(self) -> None: self._progress = 0 self._has_ssl_errors = False self.data.viewing_source = False self._set_load_status(usertypes.LoadStatus.loading) self.load_started.emit()
Class
2
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...
Base
1
def load(doc): code = config.retrieveBoilerplateFile(doc, "bs-extensions") exec(code, globals())
Base
1
def authorize_and_redirect(request): if not request.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not request.META.get("HTTP_REFERER"): return HttpResponse('You need to make a request that includes the "Referer" header.', status=400) referer...
Base
1
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...
Base
1
def feed_booksindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\ .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all() elements = [] if off ==...
Base
1
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require ...
Base
1
def setUp(self, request): self.db_path = tempfile.NamedTemporaryFile( prefix='tmp_b2_tests_%s__' % (request.node.name,), delete=True ).name try: os.unlink(self.db_path) except OSError: pass self.home = tempfile.mkdtemp() yield ...
Base
1
def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile: raise Impossible() obj = self.node.as_const(eval_ctx) # don't evaluate context functions args = [x.as_const(eval_ctx) for x in self.args] if isinstance(ob...
Base
1
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...
Base
1
async def message(self, ctx, *, message: str): """Set the message that is shown at the start of each ticket channel.\n\nUse ``{user.mention}`` to mention the person who created the ticket.""" try: message.format(user=ctx.author) await self.config.guild(ctx.guild).message.set(...
Class
2
def merge_list_book(): vals = request.get_json().get('Merge_books') to_file = list() if vals: # load all formats from target book to_book = calibre_db.get_book(vals[0]) vals.pop(0) if to_book: for file in to_book.data: to_file.append(file.format) ...
Base
1
def test_constant_initializer_with_numpy(self): initializer = initializers.Constant(np.ones((3, 2))) model = sequential.Sequential() model.add(layers.Dense(2, input_shape=(3,), kernel_initializer=initializer)) model.add(layers.Dense(3)) model.compile( loss='mse', optimizer='sgd', ...
Base
1
def _build_ssl_context( disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None, maximum_version=None, minimum_version=None, key_password=None,
Class
2
def _load_yamlconfig(self, configfile): yamlconfig = None try: if self._recent_pyyaml(): # https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation # only for 5.1+ yamlconfig = yaml.load(open(configfile), Loader=yaml.FullLoad...
Base
1
def _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]: with open(args.blueprint.model_opt_path) as f: all_model_opts = yaml.load(f.read()) active_model_opts = { model: opt for model, opt in all_model_opts.items() if self.conversations_nee...
Base
1
def should_deny_admin(self): return self.totp_status != TOTPStatus.ENABLED and config.get( "enable_force_admin_2fa" )
Class
2
def _copy_file(self, in_path, out_path): 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 er...
Base
1
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)
Base
1
def _should_decode(typ): # either a basetype which needs to be clamped # or a complex type which contains something that # needs to be clamped. if isinstance(typ, BaseType): return typ.typ not in ("int256", "uint256", "bytes32") if isinstance(typ, (ByteArrayLike, DArrayType)): return...
Base
1
def testInvalidSparseTensor(self): with test_util.force_cpu(): shape = [2, 2] val = [0] dense = constant_op.constant(np.zeros(shape, dtype=np.int32)) for bad_idx in [ [[-1, 0]], # -1 is invalid. [[1, 3]], # ...so is 3. ]: sparse = sparse_tensor.SparseTe...
Class
2
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
Class
2
def get_cc_columns(filter_config_custom_read=False): tmpcc = calibre_db.session.query(db.Custom_Columns)\ .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() cc = [] r = None if config.config_columns_to_ignore: r = re.compile(config.config_columns_to_ignore) for col i...
Base
1
def builtin_roles(self): return self._builtin_roles
Class
2
def feed_get_cover(book_id): return get_book_cover(book_id)
Base
1
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( http_client=None, homeserver_to_use=GenericWorkerServer ) return hs
Base
1
def insensitive_ends_with(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"%{value}"))
Base
1
def load_djpeg(self): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file)) try: self.im = Image.core.open_ppm(file) finally: try: os.unl...
Base
1
def all(cls, **kwargs): """Return a `Page` of instances of this `Resource` class from its general collection endpoint. Only `Resource` classes with specified `collection_path` endpoints can be requested with this method. Any provided keyword arguments are passed to the API e...
Base
1
async def send_transaction(self, account, to, selector_name, calldata, nonce=None, max_fee=0): return await self.send_transactions(account, [(to, selector_name, calldata)], nonce, max_fee)
Class
2
def test_proxy_headers(self): to_send = ( "GET / HTTP/1.0\n" "Content-Length: 0\n" "Host: www.google.com:8080\n" "X-Forwarded-For: 192.168.1.1\n" "X-Forwarded-Proto: https\n" "X-Forwarded-Port: 5000\n\n" ) to_send = toby...
Base
1
def test_change_response_class_to_text(): mw = _get_mw() req = SplashRequest('http://example.com/', magic_response=True) req = mw.process_request(req, None) # Such response can come when downloading a file, # or returning splash:html(): the headers say it's binary, # but it can be decoded so it ...
Class
2
def test_notfilelike_http11(self): to_send = "GET /notfilelike 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) ...
Base
1
def login(): form = forms.UserForm() if form.validate_on_submit(): db = get_db() user = db.search( (Query().username == form.username.data) & (Query().type == "user") ) if user and check_password_hash(user[0]["hashed_password"], form.password.data): user ...
Base
1
def authenticate(self, username, password): child = None try: child = pexpect.spawn('/bin/sh', ['-c', '/bin/su -c "/bin/echo SUCCESS" - %s' % username], timeout=5) child.expect('.*:') child.sendline(password) result = child.expect(['su: .*', 'SUCCESS']...
Base
1
async def send_transactions(self, account, calls, nonce=None, max_fee=0): if nonce is None: execution_info = await account.get_nonce().call() nonce, = execution_info.result build_calls = [] for call in calls: build_call = list(call) build_call...
Class
2
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, ...
Base
1
def test_modify_access_revoke_self(self): """ Test that an instructor cannot remove instructor privelages from themself. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_stude...
Compound
4
def feed_unread_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True) return render_xml_template('feed.xml', entries=result, pagination=pagination)
Base
1
def kebab_case(value: str) -> str: return stringcase.spinalcase(group_title(_sanitize(value)))
Base
1
def gravatar(context, user, size=None): """ Outputs the HTML for displaying a user's gravatar. This can take an optional size of the image (defaults to 80 if not specified). This is also influenced by the following settings: GRAVATAR_SIZE - Default size for gravatars GRAVATAR_R...
Base
1
def test_get_student_progress_url_noparams(self): """ Test that the endpoint 404's without the required query params. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.s...
Compound
4
def 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 ...
Base
1
def _cnonce(): dig = _md5( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).hexdigest() return dig[:16]
Class
2
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(...
Class
2
def test_file(self, tmpdir): filename = tmpdir / 'foo' filename.ensure() url = QUrl.fromLocalFile(str(filename)) req = QNetworkRequest(url) reply = filescheme.handler(req) assert reply is None
Compound
4
def _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
Class
2
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
Base
1
def test_request_body_too_large_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n" repeat = control_line + s to_send += repeat * ((self.toobig // len(repeat)) ...
Base
1
def __post_init__(self, title: str) -> None: # type: ignore super().__post_init__() reference = Reference.from_ref(title) dedup_counter = 0 while reference.class_name in _existing_enums: existing = _existing_enums[reference.class_name] if self.values == exist...
Base
1
def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace: """Parse environment arguments if they are defined. Examples: >>> from pytorch_lightning import Trainer >>> parse_env_variables(Trainer) Namespace() >>> import os ...
Base
1
async def on_PUT(self, origin, content, query, room_id): content = await self.handler.on_exchange_third_party_invite_request( room_id, content ) return 200, content
Class
2
def test_expect_continue(self): # specifying Connection: close explicitly data = "I have expectations" to_send = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "Expect: 100-continue\n" "\n" "%s"...
Base
1
def test_login_post(self): login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/') response = self.client.post('/accounts/login/code/', { 'code': login_code.code, }) self.assertEqual(response.status_code, 302) self.assertEqual(resp...
Base
1
def parse_configuration_file(config_path): """ Read the config file for an experiment to get ParlAI settings. :param config_path: path to config :return: parsed configuration dictionary """ result = {} result["configs"] = {} with open(config_path) as f: cfg = ya...
Base
1
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:])
Base
1
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...
Base
1
public void testEqualsInsertionOrderDifferentHeaderNames() { final HttpHeadersBase h1 = newEmptyHeaders(); h1.add("a", "b"); h1.add("c", "d"); final HttpHeadersBase h2 = newEmptyHeaders(); h2.add("c", "d"); h2.add("a", "b"); assertThat(h1).isEqualTo(h2); }
Class
2
static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) { Ruby runtime = context.getRuntime(); XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz); xmlSchema.setInstanceVariable("@errors", runtime.newEmptyArray(...
Base
1
protected SymbolContext getContextLegacy() { throw new UnsupportedOperationException(); }
Base
1
public static SocketFactory getSocketFactory(Properties info) throws PSQLException { // Socket factory String socketFactoryClassName = PGProperty.SOCKET_FACTORY.get(info); if (socketFactoryClassName == null) { return SocketFactory.getDefault(); } try { return (SocketFactory) ObjectFact...
Class
2
public void canMixConvertedAndNormalValues() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name", "value"); headers.addInt("name", 100); assertThat(headers.size()).isEqualTo(2); assertThat(headers.contains("name")).isTrue(); assertThat(headers.con...
Class
2
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (keySpec == null) { ...
Base
1