code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def __init__( self, *, resource_group: str, location: str, application_name: str, owner: str, client_id: Optional[str], client_secret: Optional[str], app_zip: str, tools: str, instance_specific: str, third_party: str, ...
Class
2
def make_homeserver(self, reactor, clock): self.http_client = Mock() return self.setup_test_homeserver(http_client=self.http_client)
Base
1
def test_received_nonsense_nothing(self): data = b"""\ """ result = self.parser.received(data) self.assertEqual(result, 2) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {})
Base
1
def __init__( self, cache, safe=safename
Class
2
def convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_...
Base
1
def _create(self): url = urljoin(recurly.base_uri(), self.collection_path) return self.post(url)
Base
1
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
Base
1
def render(self, name, value, attrs=None): html = super(AdminURLFieldWidget, self).render(name, value, attrs) if value: value = force_text(self._format_value(value)) final_attrs = {'href': mark_safe(smart_urlquote(value))} html = format_html( '<p c...
Base
1
def make_homeserver(self, reactor, clock): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = ...
Base
1
def test_keepalive_http11_explicit(self): # Explicitly set keep-alive data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: keep-alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) ...
Base
1
def is_2fa_enabled(self): return self.totp_status == TOTPStatus.ENABLED
Class
2
def _decompress(compressed_path: Text, target_path: Text) -> None: with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists
Base
1
def test_get_problem_responses_successful(self): """ Test whether get_problem_responses returns an appropriate status message if CSV generation was started successfully. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.cour...
Compound
4
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...
Base
1
def test_get_mpi_implementation(self): def test(output, expected, exit_code=0): ret = (output, exit_code) if output is not None else None env = {'VAR': 'val'} with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m: impleme...
Class
2
def test_received_chunked_completed_sets_content_length(self): 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) data = data[result:] r...
Base
1
def ready(self): pass
Base
1
def test_it_works_with_explicit_external_host(self, app, monkeypatch): with app.test_request_context(): monkeypatch.setattr('flask.request.host_url', 'http://example.com') result = _validate_redirect_url('http://works.com', _external_host='...
Base
1
def _affinity_host(self, context, instance_id): return self.compute_api.get(context, instance_id)['host']
Class
2
def test_keepalive_http_10(self): # Handling of Keep-Alive within HTTP 1.0 data = "Default: Don't keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) response = http...
Base
1
def atom_timestamp(self): return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '')
Base
1
def put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' if not out_path.startswith(os.path.sep): out_path = os.path.join(os.path.sep, out_path) normpath = os.path.normpath(out_path) out_path = os.path.join(self.chroot, normpath[1:]) v...
Base
1
def snake_case(value: str) -> str: return stringcase.snakecase(group_title(_sanitize(value)))
Base
1
def logout(): if current_user is not None and current_user.is_authenticated: ub.delete_user_session(current_user.id, flask_session.get('_id',"")) logout_user() if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() ...
Base
1
def fetch_file(self, in_path, out_path): ''' fetch a file from zone to local ''' in_path = self._normalize_path(in_path, self.get_zone_path()) vvv("FETCH %s TO %s" % (in_path, out_path), host=self.zone) self._copy_file(in_path, out_path)
Base
1
def test_adjust_timeout(): mw = _get_mw() req1 = scrapy.Request("http://example.com", meta = { 'splash': {'args': {'timeout': 60, 'html': 1}}, # download_timeout is always present, # it is set by DownloadTimeoutMiddleware 'download_timeout': 30, }) req1 = mw.process_requ...
Class
2
def _glob_to_re(glob: str, word_boundary: bool) -> Pattern: """Generates regex for a given glob. Args: glob word_boundary: Whether to match against word boundaries or entire string. """ if IS_GLOB.search(glob): r = re.escape(glob) r = r.replace(r"\*", ".*?") r =...
Base
1
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: unicode :return: Whether the client_secret is valid :rtype: bool """ return client_secret_...
Class
2
def testValuesInVariable(self): indices = constant_op.constant([[1]], dtype=dtypes.int64) values = variables.Variable([1], trainable=False, dtype=dtypes.float32) shape = constant_op.constant([1], dtype=dtypes.int64) sp_input = sparse_tensor.SparseTensor(indices, values, shape) sp_output = sparse_...
Class
2
def get_release_file(root, request): session = DBSession() f = ReleaseFile.by_id(session, int(request.matchdict['file_id'])) rv = {'id': f.id, 'url': f.url, 'filename': f.filename, } f.downloads += 1 f.release.downloads += 1 f.release.package.downloads += 1 ses...
Class
2
def sync_tree(self): LOGGER.info("sync tree to host") self.transfer_inst.tree.remote(self.tree_, role=consts.HOST, idx=-1) """ federation.remote(obj=self.tree_, name=self.transfer...
Class
2
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...
Base
1
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
Base
1
def __init__(self, hs): super().__init__(hs) self.clock = hs.get_clock() self.client = hs.get_http_client() self.key_servers = self.config.key_servers
Base
1
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( resource_for_federation=Mock(), http_client=None ) return hs
Base
1
def test_modify_access_revoke_with_username(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.username, 'rolename': 'staff', 'action': ...
Compound
4
def _re_word_boundary(r: str) -> str: """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't us...
Base
1
def test_equal_body(self): # check server doesnt close connection when body is equal to # cl header to_send = tobytes( "GET /equal_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() s...
Base
1
def language_overview(): if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all": order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1 charlist = list() languages = calibre_db.speaking_language(reverse_order=not ...
Base
1
def respond_error(self, context, exception): context.respond_server_error() stack = traceback.format_exc() return """ <html> <body> <style> body { font-family: sans-serif; color: #888; ...
Base
1
def __init__(self, private_key): self.signer = Signer(private_key) self.public_key = self.signer.public_key
Class
2
def test_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': se...
Compound
4
def skip(self, type): if type == TType.STOP: return elif type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte() elif type == TType.I16: self.readI16() elif type == TType.I32: self.readI32() ...
Class
2
def __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=form...
Base
1
def test_before_start_response_http_10(self): to_send = "GET /before_start_response 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(li...
Base
1
def __setstate__(self, state): """Restore from pickled state.""" self.__dict__ = state self._lock = threading.Lock() self._descriptor_cache = weakref.WeakKeyDictionary() self._key_for_call_stats = self._get_key_for_call_stats()
Class
2
def _getKeysForServer(self, server_name): """Get the signing key data from a homeserver. :param server_name: The name of the server to request the keys from. :type server_name: unicode :return: The verification keys returned by the server. :rtype: twisted.internet.defer.Def...
Base
1
def test_received_control_line_finished_all_chunks_received(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"0;discard\n") self.assertEqual(inst.control_line, b"") self.assertEqual(inst.all_chunks_received, True) self.assertEqual(result, 1...
Base
1
def test_list_entrance_exam_instructor_tasks_student(self): """ Test list task history for entrance exam AND student. """ # create a re-score entrance exam task url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { ...
Compound
4
def run_custom_method(doctype, name, custom_method): """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}""" doc = frappe.get_doc(doctype, name) if getattr(doc, custom_method, frappe._dict()).is_whitelisted: frappe.call(getattr(doc, custom_method), **frappe.local.form_dict) else: ...
Base
1
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...
Base
1
def delete(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: # We request the manifest for the object. If one exists, # that means the object was uploaded in chunks/segm...
Class
2
def get_cms_details(url): # this function will fetch cms details using cms_detector response = {} cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py -u {} --random-agent --batch --follow-redirect'.format(url) os.system(cms_detector_command) response['status'] = False response['mes...
Base
1
def test_process_request__no_location(self, rf, settings): settings.AWS_LOCATION = "" uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded") request = rf.post("/", data={"file": uploaded_file}) S3FileMiddleware(lambda x: None)(request) assert request.FILES.getli...
Base
1
def set(self, key, value, serialize=True, timeout=0): """ Set a key/value pair in memcache :param key: key :param value: value :param serialize: if True, value is pickled before sending to memcache :param timeout: ttl in memcache """ key = md5hash(key...
Base
1
def testStringNGramsBadDataSplits(self, splits): data = ["aa", "bb", "cc", "dd", "ee", "ff"] with self.assertRaisesRegex(errors.InvalidArgumentError, "Invalid split value"): self.evaluate( gen_string_ops.string_n_grams( data=data, dat...
Base
1
def test_logout_get(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') self.client.login(username=self.user.username, code=login_code.code) response = self.client.post('/accounts/logout/?next=/accounts/login/') self.assertEqual(response.status_code, 302) ...
Base
1
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False): ''' return a configuration variable with casting ''' value = _get_config(p, section, key, env_var, default) if boolean: return mk_boolean(value) if value and integer: return int(value) if...
Class
2
def test_basic_auth_invalid_credentials(self): with self.assertRaises(InvalidStatusCode) as raised: self.start_client(user_info=("hello", "ihateyou")) self.assertEqual(raised.exception.status_code, 401)
Base
1
def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False)) )
Class
2
def crawl_items(spider_cls, resource_cls, settings, spider_kwargs=None): """ Use spider_cls to crawl resource_cls. URL of the resource is passed to the spider as ``url`` argument. Return ``(items, resource_url, crawler)`` tuple. """ spider_kwargs = {} if spider_kwargs is None else spider_kwargs ...
Class
2
def test_register(self) -> None: reset_emails_in_zulip_realm() realm = get_realm("zulip") stream_names = [f"stream_{i}" for i in range(40)] for stream_name in stream_names: stream = self.make_stream(stream_name, realm=realm) DefaultStream.objects.create(strea...
Base
1
def create(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) form = FavoriteForm(user=request.user, topic=topic, data=request.POST) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next',...
Base
1
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)
Base
1
def _get_obj_abosolute_path(dataset, rel_path): return os.path.join(DATAROOT, dataset, rel_path)
Base
1
def _request(self, method, path, queries=(), body=None, ensure_encoding=True, log_request_body=True):
Base
1
def _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = os.path.join(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_...
Base
1
def test_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK"...
Base
1
def connect(self, port=None): ''' connect to the chroot; nothing to do here ''' vvv("THIS IS A LOCAL CHROOT DIR", host=self.jail) return self
Base
1
def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False # Chrome...
Base
1
def test_get_student_exam_results(self): """ Test whether get_proctored_exam_results returns an appropriate status message when users request a CSV file. """ url = reverse( 'get_proctored_exam_results', kwargs={'course_id': unicode(self.course.id)} ...
Compound
4
def test_credits_view_html(self): response = self.get_credits("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), "<table>\n" "<tr>\n<th>Czech</th>\n" '<td><ul><li><a href="mailto:weblate@example...
Base
1
def test_certificates_features_group_by_mode(self): """ Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating download...
Compound
4
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( http_client=None, homeserver_to_use=GenericWorkerServer ) return hs
Base
1
def sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path: result = (root / path).absolute() if not str(result).startswith(str(root) + "/"): raise ValueError("resulting path is outside root") return result
Base
1
def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return self.user_consent_version = str(consent_config["version"]) self.us...
Base
1
def get_list(an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...)): """ Get a list of things """ return
Base
1
def test_request_body_too_large_with_no_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\nConnection: Keep-Alive\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0...
Base
1
async def on_PUT(self, origin, content, query, context, event_id): # TODO(paul): assert that context/event_id parsed from path actually # match those given in content content = await self.handler.on_send_join_request(origin, content, context) return 200, (200, content)
Class
2
def __init__(self, method, uri, headers, bodyProducer, persistent=False): """ @param method: The HTTP method for this request, ex: b'GET', b'HEAD', b'POST', etc. @type method: L{bytes} @param uri: The relative URI of the resource to request. For example, C{b...
Class
2
def _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
Class
2
def clean_code(self): code = self.cleaned_data['code'] username = code.user.get_username() user = authenticate(self.request, **{ get_user_model().USERNAME_FIELD: username, 'code': code.code, }) if not user: raise forms.ValidationError( ...
Base
1
def field_names(ctx, rd, field): ''' Get a list of all names for the specified field Optional: ?library_id=<default library> ''' db, library_id = get_library_data(ctx, rd)[:2] return tuple(db.all_field_names(field))
Base
1
def from_yaml(self, content): """ Given some YAML data, returns a Python dictionary of the decoded data. """ if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.load(content)
Class
2
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)] ...
Base
1
def extra_view_dispatch(request, view): """ Dispatch to an Xtheme extra view. :param request: A request. :type request: django.http.HttpRequest :param view: View name. :type view: str :return: A response of some kind. :rtype: django.http.HttpResponse """ theme = getattr(request,...
Base
1
def async_run(prog, args): pid = os.fork() if pid: os.waitpid(pid, 0) else: dpid = os.fork() if not dpid: os.system(" ".join([prog] + args)) os._exit(0)
Base
1
def check_read_formats(entry): EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'} bookformats = list() if len(entry.data): for ele in iter(entry.data): if ele.format.upper() in EXTENSIONS_READER: bookformats.append(ele.format.lower()) return bookf...
Base
1
def cookies(self, jar: RequestsCookieJar): # <https://docs.python.org/3/library/cookielib.html#cookie-objects> stored_attrs = ['value', 'path', 'secure', 'expires'] self['cookies'] = {} for cookie in jar: self['cookies'][cookie.name] = { attname: getattr(c...
Class
2
def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None ...
Base
1
def init_app(app): from redash.authentication import ( google_oauth, saml_auth, remote_user_auth, ldap_auth, ) login_manager.init_app(app) login_manager.anonymous_user = models.AnonymousUser login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION ...
Base
1
def test_get_frontend_context_variables_xss(component): # Set component.name to a potential XSS attack component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>' frontend_context_variables = component.get_frontend_context_variables() frontend_context_v...
Base
1
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False): # Create new_author_dir from parameter or from database # Create new title_dir from database and add id if first_author: new_authordir = get_valid_filename(first_author, chars=96) for r in re...
Base
1
def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm bcrypt = self._load_library() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None...
Class
2
def test_get_files_from_storage(self): content = b"test_get_files_from_storage" name = storage.save( "tmp/s3file/test_get_files_from_storage", ContentFile(content) ) files = S3FileMiddleware.get_files_from_storage( [os.path.join(storage.aws_location, name)] ...
Base
1
def insensitive_exact(field: Term, value: str) -> Criterion: return Upper(field).eq(Upper(f"{value}"))
Base
1
def _configuration_oauth_helper(to_save): active_oauths = 0 reboot_required = False for element in oauthblueprints: if to_save["config_" + str(element['id']) + "_oauth_client_id"] != element['oauth_client_id'] \ or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != eleme...
Base
1
def is_whitelisted(method): # check if whitelisted if frappe.session['user'] == 'Guest': if (method not in frappe.guest_methods): frappe.throw(_("Not permitted"), frappe.PermissionError) if method not in frappe.xss_safe_methods: # strictly sanitize form_dict # escapes html characters like <> except for ...
Base
1
def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False, config_read_column=False, *join):
Base
1
def basic_parser(xml): return parse(BytesIO(xml))
Base
1