code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union[Endpoint, ParseError]: """ Construct an endpoint from the OpenAPI data """ if data.operationId is None: return ParseError(data=data, detail="Path operations with operationId are not yet supported") endpoint = Endpoint( path=path, method=method, description=data.description, name=data.operationId, requires_security=bool(data.security), tag=tag, ) result = Endpoint._add_parameters(endpoint, data) if isinstance(result, ParseError): return result result = Endpoint._add_responses(result, data.responses) if isinstance(result, ParseError): return result result = Endpoint._add_body(result, data) return result
Base
1
def test_can_read_token_from_query_parameters(self): """Tests that Sydent correct extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_token ) token = tokenFromRequest(request) self.assertEqual(token, self.test_token)
Class
2
def edit_book_series_index(series_index, book): # Add default series_index to book modif_date = False series_index = series_index or '1' if not series_index.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=series_index), category="warning") return False if str(book.series_index) != series_index: book.series_index = series_index modif_date = True return modif_date
Base
1
def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format self.save(file, format) return file
Base
1
def check_xsrf_cookie(self): """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. To prevent cross-site request forgery, we set an ``_xsrf`` cookie and include the same value as a non-cookie field with all ``POST`` requests. If the two do not match, we reject the form submission as a potential forgery. The ``_xsrf`` value may be set as either a form field named ``_xsrf`` or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken`` (the latter is accepted for compatibility with Django). See http://en.wikipedia.org/wiki/Cross-site_request_forgery Prior to release 1.1.1, this check was ignored if the HTTP header ``X-Requested-With: XMLHTTPRequest`` was present. This exception has been shown to be insecure and has been removed. For more information please see http://www.djangoproject.com/weblog/2011/feb/08/security/ http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails """ token = (self.get_argument("_xsrf", None) or self.request.headers.get("X-Xsrftoken") or self.request.headers.get("X-Csrftoken")) if not token: raise HTTPError(403, "'_xsrf' argument missing from POST") if not _time_independent_equals(utf8(self.xsrf_token), utf8(token)): raise HTTPError(403, "XSRF cookie does not match POST argument")
Base
1
def test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl 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") ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed (no content-length) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
Base
1
def test_confirmation_key_of_wrong_type(self) -> None: email = self.nonreg_email("alice") realm = get_realm("zulip") inviter = self.example_user("iago") prereg_user = PreregistrationUser.objects.create( email=email, referred_by=inviter, realm=realm ) url = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) registration_key = url.split("/")[-1] # Mainly a test of get_object_from_key, rather than of the invitation pathway with self.assertRaises(ConfirmationKeyException) as cm: get_object_from_key(registration_key, Confirmation.INVITATION) self.assertEqual(cm.exception.error_type, ConfirmationKeyException.DOES_NOT_EXIST) # Verify that using the wrong type doesn't work in the main confirm code path email_change_url = create_confirmation_link(prereg_user, Confirmation.EMAIL_CHANGE) email_change_key = email_change_url.split("/")[-1] url = "/accounts/do_confirm/" + email_change_key result = self.client_get(url) self.assertEqual(result.status_code, 404) self.assert_in_response( "Whoops. We couldn't find your confirmation link in the system.", result )
Base
1
def vote(request, pk): # TODO: check if user has access to this topic/poll poll = get_object_or_404( CommentPoll.objects.unremoved(), pk=pk ) if not request.user.is_authenticated: return redirect_to_login(next=poll.get_absolute_url()) form = PollVoteManyForm(user=request.user, poll=poll, data=request.POST) if form.is_valid(): CommentPollChoice.decrease_vote_count(poll=poll, voter=request.user) form.save_m2m() CommentPollChoice.increase_vote_count(poll=poll, voter=request.user) return redirect(request.POST.get('next', poll.get_absolute_url())) messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', poll.get_absolute_url()))
Base
1
def connectionMade(self): method = getattr(self.factory, 'method', b'GET') self.sendCommand(method, self.factory.path) if self.factory.scheme == b'http' and self.factory.port != 80: host = self.factory.host + b':' + intToBytes(self.factory.port) elif self.factory.scheme == b'https' and self.factory.port != 443: host = self.factory.host + b':' + intToBytes(self.factory.port) else: host = self.factory.host self.sendHeader(b'Host', self.factory.headers.get(b"host", host)) self.sendHeader(b'User-Agent', self.factory.agent) data = getattr(self.factory, 'postdata', None) if data is not None: self.sendHeader(b"Content-Length", intToBytes(len(data))) cookieData = [] for (key, value) in self.factory.headers.items(): if key.lower() not in self._specialHeaders: # we calculated it on our own self.sendHeader(key, value) if key.lower() == b'cookie': cookieData.append(value) for cookie, cookval in self.factory.cookies.items(): cookieData.append(cookie + b'=' + cookval) if cookieData: self.sendHeader(b'Cookie', b'; '.join(cookieData)) self.endHeaders() self.headers = {} if data is not None: self.transport.write(data)
Class
2
def edit_book_comments(comments, book): modif_date = False if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date
Base
1
def formatType(self): format_type = self.type.lower() if format_type == 'amazon': return u"Amazon" elif format_type.startswith("amazon_"): return u"Amazon.{0}".format(format_type[7:]) elif format_type == "isbn": return u"ISBN" elif format_type == "doi": return u"DOI" elif format_type == "douban": return u"Douban" elif format_type == "goodreads": return u"Goodreads" elif format_type == "babelio": return u"Babelio" elif format_type == "google": return u"Google Books" elif format_type == "kobo": return u"Kobo" elif format_type == "litres": return u"ЛитРес" elif format_type == "issn": return u"ISSN" elif format_type == "isfdb": return u"ISFDB" if format_type == "lubimyczytac": return u"Lubimyczytac" else: return self.type
Base
1
def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode( _sha("%s%s%s" % (cnonce, iso_now, password)).digest() ).strip()
Class
2
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); }
Base
1
def del_version(request, client_id, project, version): if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.delete_version(project=project, version=version) return JsonResponse(result) except ConnectionError: return JsonResponse({'message': 'Connect Error'})
Base
1
def test_unicode_encode_error(self, mocker): url = QUrl('file:///tmp/foo') req = QNetworkRequest(url) err = UnicodeEncodeError('ascii', '', 0, 2, 'foo') mocker.patch('os.path.isdir', side_effect=err) reply = filescheme.handler(req) assert reply is None
Compound
4
def test_visitor(self): class CustomVisitor(self.asdl.VisitorBase): def __init__(self): super().__init__() self.names_with_seq = [] def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value) def visitSum(self, sum): for t in sum.types: self.visit(t) def visitConstructor(self, cons): for f in cons.fields: if f.seq: self.names_with_seq.append(cons.name) v = CustomVisitor() v.visit(self.types['mod']) self.assertEqual(v.names_with_seq, ['Module', 'Interactive', 'Suite'])
Base
1
async def customize_global(self, ctx, command: str.lower, *, response: str = None): """ Globally customize the response to an action. You can use {0} or {user} to dynamically replace with the specified target of the action. Formats like {0.name} or {0.mention} can also be used. """ if not response: await self.config.clear_raw("custom", command) else: await self.config.set_raw("custom", command, value=response) await ctx.tick()
Base
1
def make_homeserver(self, reactor, clock): # we mock out the keyring so as to skip the authentication check on the # federation API call. mock_keyring = Mock(spec=["verify_json_for_server"]) mock_keyring.verify_json_for_server.return_value = defer.succeed(True) # we mock out the federation client too mock_federation_client = Mock(spec=["put_json"]) mock_federation_client.put_json.return_value = defer.succeed((200, "OK")) # the tests assume that we are starting at unix time 1000 reactor.pump((1000,)) hs = self.setup_test_homeserver( notifier=Mock(), http_client=mock_federation_client, keyring=mock_keyring, replication_streams={}, ) return hs
Base
1
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label=label, selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color return result
Base
1
def make_sydent(test_config={}): """Create a new sydent Args: test_config (dict): any configuration variables for overriding the default sydent config """ # Use an in-memory SQLite database. Note that the database isn't cleaned up between # tests, so by default the same database will be used for each test if changed to be # a file on disk. if 'db' not in test_config: test_config['db'] = {'db.file': ':memory:'} else: test_config['db'].setdefault('db.file', ':memory:') reactor = MemoryReactorClock() return Sydent(reactor=reactor, cfg=parse_config_dict(test_config))
Class
2
def table_get_locale(): locale = babel.list_translations() + [LC('en')] ret = list() current_locale = get_locale() for loc in locale: ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)}) return json.dumps(ret)
Base
1
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)
Base
1
def __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=False):
Base
1
def auth_username_ci(self): return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
Class
2
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())
Class
2
def test_challenge_with_vhm(self): rc, root, folder, object = self._makeTree() response = FauxCookieResponse() vhm = 'http://localhost/VirtualHostBase/http/test/VirtualHostRoot/xxx' actualURL = 'http://test/xxx' request = FauxRequest(RESPONSE=response, URL=vhm, ACTUAL_URL=actualURL) root.REQUEST = request helper = self._makeOne().__of__(root) helper.challenge(request, response) self.assertEqual(response.status, 302) self.assertEqual(len(response.headers), 3) loc = response.headers['Location'] self.assertTrue(loc.endswith(quote(actualURL))) self.assertFalse(loc.endswith(quote(vhm))) self.assertEqual(response.headers['Cache-Control'], 'no-cache') self.assertEqual(response.headers['Expires'], 'Sat, 01 Jan 2000 00:00:00 GMT')
Base
1
def _deny_hook(self, resource=None): app = self.get_app() if current_user.is_authenticated(): status = 403 else: status = 401 #abort(status) if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') if current_user.is_authenticated(): auth_dict = { "authenticated": True, "user": current_user.email, "roles": current_user.role, } else: auth_dict = { "authenticated": False, "user": None, "url": url } return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json")
Base
1
def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", str(cm.exception))
Base
1
def rescore_entrance_exam(request, course_id): """ Starts a background process a students attempts counter for entrance exam. Optionally deletes student state for a problem. Limited to instructor access. Takes either of the following query parameters - unique_student_identifier is an email or username - all_students is a boolean all_students and unique_student_identifier cannot both be present. """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = get_course_with_access( request.user, 'staff', course_id, depth=None ) student_identifier = request.GET.get('unique_student_identifier', None) student = None if student_identifier is not None: student = get_student_from_identifier(student_identifier) all_students = request.GET.get('all_students') in ['true', 'True', True] if not course.entrance_exam_id: return HttpResponseBadRequest( _("Course has no entrance exam section.") ) if all_students and student: return HttpResponseBadRequest( _("Cannot rescore with all_students and unique_student_identifier.") ) try: entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id) except InvalidKeyError: return HttpResponseBadRequest(_("Course has no valid entrance exam section.")) response_payload = {} if student: response_payload['student'] = student_identifier else: response_payload['student'] = _("All Students") instructor_task.api.submit_rescore_entrance_exam_for_student(request, entrance_exam_key, student) response_payload['task'] = 'created' return JsonResponse(response_payload)
Compound
4
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)
Base
1
def test_modify_access_bad_action(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'robot-not-an-action', }) self.assertEqual(response.status_code, 400)
Compound
4
def __new__(cls, sourceName: str): """Dispatches to the right subclass.""" if cls != InputSource: # Only take control of calls to InputSource(...) itself. return super().__new__(cls) if sourceName == "-": return StdinInputSource(sourceName) if sourceName.startswith("https:"): return UrlInputSource(sourceName) return FileInputSource(sourceName)
Base
1
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)
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 test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body) ) self.connect() self.sock.send(s) 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, "1024") self.assertEqual(echo.body, tobytes(body))
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 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating')).order_by(order).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(), title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no) else: abort(404)
Base
1
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
Base
1
def sentences_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_execute(self.prop_sentences_victim(type, data))
Base
1
def _get_mw(): crawler = _get_crawler({}) return SplashMiddleware.from_crawler(crawler)
Class
2
def post(self, request): totp_secret = pyotp.random_base32() request.user.totp_secret = totp_secret request.user.totp_status = TOTPStatus.VERIFYING request.user.save() add_2fa.send(sender=self.__class__, user=request.user) return FormattedResponse({"totp_secret": totp_secret})
Class
2
def rescore_problem(request, course_id): """ Starts a background process a students attempts counter. Optionally deletes student state for a problem. Limited to instructor access. Takes either of the following query paremeters - problem_to_reset is a urlname of a problem - unique_student_identifier is an email or username - all_students is a boolean all_students and unique_student_identifier cannot both be present. """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) problem_to_reset = strip_if_string(request.GET.get('problem_to_reset')) student_identifier = request.GET.get('unique_student_identifier', None) student = None if student_identifier is not None: student = get_student_from_identifier(student_identifier) all_students = request.GET.get('all_students') in ['true', 'True', True] if not (problem_to_reset and (all_students or student)): return HttpResponseBadRequest("Missing query parameters.") if all_students and student: return HttpResponseBadRequest( "Cannot rescore with all_students and unique_student_identifier." ) try: module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset) except InvalidKeyError: return HttpResponseBadRequest("Unable to parse problem id") response_payload = {} response_payload['problem_to_reset'] = problem_to_reset if student: response_payload['student'] = student_identifier instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student) response_payload['task'] = 'created' elif all_students: instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key) response_payload['task'] = 'created' else: return HttpResponseBadRequest() return JsonResponse(response_payload)
Compound
4
def check_valid_read_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all(): return False return True
Base
1
def table_get_locale(): locale = babel.list_translations() + [LC('en')] ret = list() current_locale = get_locale() for loc in locale: ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)}) return json.dumps(ret)
Base
1
def test_request_body_too_large_with_wrong_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\n" "Content-Length: 5\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # first request succeeds (content-length 5) 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)) # second response is an error response line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
Base
1
def atom_timestamp(self): return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '')
Base
1
def sql_execute(self, sentence): self.cursor.execute(sentence) return self.cursor.fetchall()
Base
1
def command_dispatch(request): """ Xtheme command dispatch view. :param request: A request :type request: django.http.HttpRequest :return: A response :rtype: django.http.HttpResponse """ command = request.POST.get("command") if command: response = handle_command(request, command) if response: return response raise Problem("Error! Unknown command: `%r`" % command)
Base
1
def test_digest_object_with_opaque(): credentials = ("joe", "password") host = None request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, response, content, None ) d.request("GET", request_uri, headers, content, cnonce="5ec2") our_request = "authorization: " + headers["authorization"] working_request = ( 'authorization: Digest username="joe", realm="myrealm", ' 'nonce="30352fd", uri="/digest/opaque/", algorithm=MD5' + ', response="a1fab43041f8f3789a447f48018bee48", qop=auth, nc=00000001, ' 'cnonce="5ec2", opaque="atestopaque"' ) assert our_request == working_request
Class
2
def publish(request, user_id=None): initial = None if user_id: # todo: move to form user_to = get_object_or_404(User, pk=user_id) initial = {'users': [user_to.st.nickname]} user = request.user tform = TopicForPrivateForm( user=user, data=post_data(request)) cform = CommentForm( user=user, data=post_data(request)) tpform = TopicPrivateManyForm( user=user, data=post_data(request), initial=initial) if (is_post(request) and all([tform.is_valid(), cform.is_valid(), tpform.is_valid()]) and not request.is_limited()): if not user.st.update_post_hash(tform.get_topic_hash()): return redirect( request.POST.get('next', None) or tform.category.get_absolute_url()) # wrap in transaction.atomic? topic = tform.save() cform.topic = topic comment = cform.save() comment_posted(comment=comment, mentions=None) tpform.topic = topic tpform.save_m2m() TopicNotification.bulk_create( users=tpform.get_users(), comment=comment) return redirect(topic.get_absolute_url()) return render( request=request, template_name='spirit/topic/private/publish.html', context={ 'tform': tform, 'cform': cform, 'tpform': tpform})
Base
1
def list_instructor_tasks(request, course_id): """ List instructor tasks. Takes optional query paremeters. - With no arguments, lists running tasks. - `problem_location_str` lists task history for problem - `problem_location_str` and `unique_student_identifier` lists task history for problem AND student (intersection) """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) problem_location_str = strip_if_string(request.GET.get('problem_location_str', False)) student = request.GET.get('unique_student_identifier', None) if student is not None: student = get_student_from_identifier(student) if student and not problem_location_str: return HttpResponseBadRequest( "unique_student_identifier must accompany problem_location_str" ) if problem_location_str: try: module_state_key = course_id.make_usage_key_from_deprecated_string(problem_location_str) except InvalidKeyError: return HttpResponseBadRequest() if student: # Specifying for a single student's history on this problem tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key, student) else: # Specifying for single problem's history tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key) else: # If no problem or student, just get currently running tasks tasks = instructor_task.api.get_running_instructor_tasks(course_id) response_payload = { 'tasks': map(extract_task_features, tasks), } return JsonResponse(response_payload)
Compound
4
def _factorial(x): if x<=10000: return float(math.factorial(x)) else: raise Exception('factorial argument too large')
Base
1
def mysql_insensitive_starts_with(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"{value}%"))
Base
1
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "server", http_client=None, federation_sender=Mock() ) return hs
Base
1
def upload_new_file_gdrive(book_id, first_author, renamed_author, title, title_dir, original_filepath, filename_ext): error = False book = calibre_db.get_book(book_id) file_name = get_valid_filename(title, chars=42) + ' - ' + \ get_valid_filename(first_author, chars=42) + \ filename_ext rename_all_authors(first_author, renamed_author, gdrive=True) gdrive_path = os.path.join(get_valid_filename(first_author, chars=96), title_dir + " (" + str(book_id) + ")") book.path = gdrive_path.replace("\\", "/") gd.uploadFileToEbooksFolder(os.path.join(gdrive_path, file_name).replace("\\", "/"), original_filepath) return rename_files_on_change(first_author, renamed_author, localbook=book, gdrive=True)
Base
1
def test_patch_bot_role(self) -> None: self.login("desdemona") email = "[email protected]" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_success(result) user_profile = self.get_bot_user(email) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) # Test for not allowing a non-owner user to make assign a bot an owner role desdemona = self.example_user("desdemona") do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_OWNER) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_error(result, "Must be an organization owner")
Class
2
def testDuplicateHeaders(self): # Ensure that headers with the same key get concatenated as per # RFC2616. data = b"""\ GET /foobar HTTP/8.4 x-forwarded-for: 10.11.12.13 x-forwarded-for: unknown,127.0.0.1 X-Forwarded_for: 255.255.255.255 content-length: 7 Hello. """ self.feed(data) self.assertTrue(self.parser.completed) self.assertEqual( self.parser.headers, { "CONTENT_LENGTH": "7", "X_FORWARDED_FOR": "10.11.12.13, unknown,127.0.0.1", }, )
Base
1
def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id): """Send email with attachments""" book = calibre_db.get_book(book_id) if convert == 1: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'epub', book_format.lower(), user_id, kindle_mail) if convert == 2: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'azw3', book_format.lower(), user_id, kindle_mail) for entry in iter(book.data): if entry.format.upper() == book_format.upper(): converted_file_name = entry.name + '.' + book_format.lower() link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(book.title)) EmailText = _(u"%(book)s send to Kindle", book=link) WorkerThread.add(user_id, TaskEmail(_(u"Send to Kindle"), book.path, converted_file_name, config.get_mail_settings(), kindle_mail, EmailText, _(u'This e-mail has been sent via Calibre-Web.'))) return return _(u"The requested file could not be read. Maybe wrong permissions?")
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.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date
Base
1
def qute_settings(url): """Handler for qute://settings. View/change qute configuration.""" if url.path() == '/set': return _qute_settings_set(url) src = jinja.render('settings.html', title='settings', configdata=configdata, confget=config.instance.get_str) return 'text/html', src
Compound
4
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 order_no, with_count=True) for lang in languages: upper_lang = lang[0].name[0].upper() if upper_lang not in charlist: charlist.append(upper_lang) return render_title_template('languages.html', languages=languages, charlist=charlist, title=_(u"Languages"), page="langlist", data="language", order=order_no) else: abort(404)
Base
1
def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False,
Class
2
def edit_user_table(): visibility = current_user.view_settings.get('useredit', {}) languages = calibre_db.speaking_language() translations = babel.list_translations() + [LC('en')] allUser = ub.session.query(ub.User) tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() if config.config_restricted_column: custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all() else: custom_values = [] if not config.config_anonbrowse: allUser = allUser.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) kobo_support = feature_support['kobo'] and config.config_kobo_sync return render_title_template("user_table.html", users=allUser.all(), tags=tags, custom_values=custom_values, translations=translations, languages=languages, visiblility=visibility, all_roles=constants.ALL_ROLES, kobo_support=kobo_support, sidebar_settings=constants.sidebar_settings, title=_(u"Edit Users"), page="usertable")
Base
1
def test_filename(self): tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) fp[:] = self.data[:] self.assertEqual(abspath, fp.filename) b = fp[:1] self.assertEqual(abspath, b.filename) del b del fp os.unlink(tmpname)
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 predefined tags like a, b, ul etc. for key, value in frappe.form_dict.items(): if isinstance(value, string_types): frappe.form_dict[key] = frappe.utils.sanitize_html(value) else: if not method in frappe.whitelisted: frappe.throw(_("Not permitted"), frappe.PermissionError)
Base
1
async def on_message(self, message): if message.author.bot: return ctx = await self.bot.get_context(message) if ctx.prefix is None or not ctx.invoked_with.replace("_", "").isalpha(): return if ctx.valid and ctx.command.enabled: try: if await ctx.command.can_run(ctx): return except commands.errors.CheckFailure: return ctx.command = self.act await self.bot.invoke(ctx)
Base
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> """, )
Base
1
def sql_one_row(self, sentence, column): self.cursor.execute(sentence) return self.cursor.fetchone()[column]
Base
1
def test_multi_file( self, driver, live_server, freeze, upload_file, another_upload_file, yet_another_upload_file,
Base
1
def mysql_starts_with(field: Field, value: str) -> Criterion: return functions.Cast(field, SqlTypes.CHAR).like(f"{value}%")
Base
1
def delete(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment_id': like.comment.pk}) return json_response({'url_create': url, }) return redirect(request.POST.get('next', like.comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/delete.html', context={'like': like})
Base
1
def handle(self, command, kwargs=None): """ Dispatch and handle processing of the given command. :param command: Name of command to run. :type command: unicode :param kwargs: Arguments to pass to the command handler. If empty, `request.POST` is used. :type kwargs: dict :return: response. :rtype: HttpResponse """ kwargs = kwargs or dict(six.iteritems(self.request.POST)) try: handler = self.get_command_handler(command) if not handler or not callable(handler): raise Problem(_("Error! Invalid command `%s`.") % command) kwargs.pop("csrfmiddlewaretoken", None) # The CSRF token should never be passed as a kwarg kwargs.pop("command", None) # Nor the command kwargs.update(request=self.request, basket=self.basket) kwargs = self.preprocess_kwargs(command, kwargs) response = handler(**kwargs) or {} except (Problem, ValidationError) as exc: if not self.ajax: raise msg = exc.message if hasattr(exc, "message") else exc response = { "error": force_text(msg, errors="ignore"), "code": force_text(getattr(exc, "code", None) or "", errors="ignore"), } response = self.postprocess_response(command, kwargs, response) if self.ajax: return JsonResponse(response) return_url = response.get("return") or kwargs.get("return") if return_url and return_url.startswith("/"): return HttpResponseRedirect(return_url) return redirect("shuup:basket")
Base
1
def checkin(pickledata): config = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(pickledata))) r, message = read_host_config(SESSION, config) if r is not None: return message + 'checked in successful' else: return message + 'error checking in'
Base
1
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")
Base
1
def test_get_header_lines_folded(self): # From RFC2616: # HTTP/1.1 header field values can be folded onto multiple lines if the # continuation line begins with a space or horizontal tab. All linear # white space, including folding, has the same semantics as SP. A # recipient MAY replace any linear white space with a single SP before # interpreting the field value or forwarding the message downstream. # We are just preserving the whitespace that indicates folding. result = self._callFUT(b"slim\n slam") self.assertEqual(result, [b"slim slam"])
Base
1
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) to_name = helper.get_valid_filename(to_book.title, chars=96) + ' - ' + \ helper.get_valid_filename(to_book.authors[0].name, chars=96) for book_id in vals: from_book = calibre_db.get_book(book_id) if from_book: for element in from_book.data: if element.format not in to_file: # create new data entry with: book_id, book_format, uncompressed_size, name filepath_new = os.path.normpath(os.path.join(config.config_calibre_dir, to_book.path, to_name + "." + element.format.lower())) filepath_old = os.path.normpath(os.path.join(config.config_calibre_dir, from_book.path, element.name + "." + element.format.lower())) copyfile(filepath_old, filepath_new) to_book.data.append(db.Data(to_book.id, element.format, element.uncompressed_size, to_name)) delete_book_from_table(from_book.id,"", True) return json.dumps({'success': True}) return ""
Base
1
def check_username(username): username = username.strip() if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar(): log.error(u"This username is already taken") raise Exception (_(u"This username is already taken")) return username
Base
1
def job_browse(job_id: int, path): """ Browse directory of the job. :param job_id: int :param path: str """ try: # Query job information job_info = query_internal_api(f"/internal/jobs/{job_id}", "get") # Base directory of the job job_base_dir = os.path.dirname(os.path.dirname(job_info["outputdir"])) except Exception as err: # Display error on the GUI flash(str(err), "danger") return redirect(url_for("job_page", job_id=job_id)) # Join the base and the requested path abs_path = os.path.join(job_base_dir, path) # URL path variable for going back back_path = os.path.dirname(abs_path).replace(job_base_dir, "") # If path doesn't exist if not os.path.exists(abs_path): flash("Directory for this job does not exist.", "warning") return redirect(url_for("job_page", job_id=job_id)) # Check if path is a file and send if os.path.isfile(abs_path): return send_file(abs_path) files_info = [] # Show directory contents files = os.listdir(abs_path) # Store directory information for file in files: files_info.append({ "file": file, "directory": os.path.isdir(os.path.join(abs_path, file)) }) return render_template('job_dir.html', title=f"Job {job_id} Directory", job_id=job_id, abs_path=abs_path, files_info=files_info, back_path=back_path)
Base
1
def to_dict(self) -> Dict[str, Any]: an_enum_value = self.an_enum_value.value if isinstance(self.a_camel_date_time, datetime): a_camel_date_time = self.a_camel_date_time.isoformat() else: a_camel_date_time = self.a_camel_date_time.isoformat() a_date = self.a_date.isoformat() if self.nested_list_of_enums is None: nested_list_of_enums = None else: nested_list_of_enums = [] for nested_list_of_enums_item_data in self.nested_list_of_enums: 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 = nested_list_of_enums_item_item_data.value nested_list_of_enums_item.append(nested_list_of_enums_item_item) nested_list_of_enums.append(nested_list_of_enums_item) some_dict = self.some_dict return { "an_enum_value": an_enum_value, "aCamelDateTime": a_camel_date_time, "a_date": a_date, "nested_list_of_enums": nested_list_of_enums, "some_dict": some_dict, }
Base
1
async def on_PUT(self, origin, content, query, room_id, event_id): content = await self.handler.on_send_leave_request(origin, content, room_id) return 200, (200, content)
Class
2
def allow_all(tag: str, name: str, value: str) -> bool: return True
Base
1
def build_cert(self, key_filename, entry, metadata): """ creates a new certificate according to the specification """ req_config = self.build_req_config(entry, metadata) req = self.build_request(key_filename, req_config, entry) ca = self.cert_specs[entry.get('name')]['ca'] ca_config = self.CAs[ca]['config'] days = self.cert_specs[entry.get('name')]['days'] passphrase = self.CAs[ca].get('passphrase') if passphrase: cmd = "openssl ca -config %s -in %s -days %s -batch -passin pass:%s" % (ca_config, req, days, passphrase) else: cmd = "openssl ca -config %s -in %s -days %s -batch" % (ca_config, req, days) cert = Popen(cmd, shell=True, stdout=PIPE).stdout.read() try: os.unlink(req_config) os.unlink(req) except OSError: self.logger.error("Failed to unlink temporary files") return cert
Class
2
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, B2_ACCOUNT_INFO_ENV_VAR: os.path.join(d, 'b2_account_info'), } ) expected_path = os.path.abspath(os.path.join(d, 'b2_account_info')) actual_path = os.path.abspath(account_info.filename) assert expected_path == actual_path
Base
1
def to_yaml(self, data, options=None): """ Given some Python data, produces YAML output. """ options = options or {} if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.dump(self.to_simple(data, options))
Class
2
def get(image_file, domain, title, singer, album): import ast import base64 import json import os from html import unescape import requests api = f"http://{domain}:7873/bGVhdmVfcmlnaHRfbm93" with open(image_file, "rb") as f: im_bytes = f.read() f.close() im_b64 = base64.b64encode(im_bytes).decode("utf8") headers = {"Content-type": "application/json", "Accept": "text/plain"} status = try_get_cached(domain, {"title": title, "singer": singer, "album": album}) status = ast.literal_eval(str(status)) if status is None: print("Cached version not found. Uploading image with song metadata.") payload = json.dumps( {"image": im_b64, "title": title, "singer": singer, "album": album} ) response = requests.post(api, data=payload, headers=headers) data = unescape(response.text) print(data) data = ast.literal_eval(data)["entry"] print(data) else: data = status # data = [{"title": title, "singer": singer, "album": album}, file_name, file_ending] cmd = "del " + image_file os.system(cmd) return data
Base
1
def test_login_get(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') response = self.client.get('/accounts/login/code/', { 'code': login_code.code, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].cleaned_data['code'], login_code) self.assertTrue(response.wsgi_request.user.is_anonymous) self.assertTrue(LoginCode.objects.filter(pk=login_code.pk).exists())
Base
1
def check_valid_read_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all(): return False return True
Base
1
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)
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: str :return: Whether the client_secret is valid :rtype: bool """ return client_secret_regex.match(client_secret) is not None
Class
2
def __init__(self, expression, delimiter, **extra): super().__init__(expression, delimiter=delimiter, **extra)
Base
1
def publish(request, topic_id, pk=None): initial = None if pk: # todo: move to form comment = get_object_or_404( Comment.objects.for_access(user=request.user), pk=pk) quote = markdown.quotify(comment.comment, comment.user.st.nickname) initial = {'comment': quote} user = request.user topic = get_object_or_404( Topic.objects.opened().for_access(user), pk=topic_id) form = CommentForm( user=user, topic=topic, data=post_data(request), initial=initial) if is_post(request) and not request.is_limited() and form.is_valid(): if not user.st.update_post_hash(form.get_comment_hash()): # Hashed comment may have not been saved yet return redirect( request.POST.get('next', None) or Comment .get_last_for_topic(topic_id) .get_absolute_url()) comment = form.save() comment_posted(comment=comment, mentions=form.mentions) return redirect(request.POST.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/publish.html', context={ 'form': form, 'topic': topic})
Base
1
def list_forum_members(request, course_id): """ Lists forum members of a certain rolename. Limited to staff access. The requesting user must be at least staff. Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR which is limited to instructors. Takes query parameter `rolename`. """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = get_course_by_id(course_id) has_instructor_access = has_access(request.user, 'instructor', course) has_forum_admin = has_forum_access( request.user, course_id, FORUM_ROLE_ADMINISTRATOR ) rolename = request.GET.get('rolename') # default roles require either (staff & forum admin) or (instructor) if not (has_forum_admin or has_instructor_access): return HttpResponseBadRequest( "Operation requires staff & forum admin or instructor access" ) # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor) if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access: return HttpResponseBadRequest("Operation requires instructor access.") # filter out unsupported for roles if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]: return HttpResponseBadRequest(strip_tags( "Unrecognized rolename '{}'.".format(rolename) )) try: role = Role.objects.get(name=rolename, course_id=course_id) users = role.users.all().order_by('username') except Role.DoesNotExist: users = [] def extract_user_info(user): """ Convert user to dict for json rendering. """ return { 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, } response_payload = { 'course_id': course_id.to_deprecated_string(), rolename: map(extract_user_info, users), } return JsonResponse(response_payload)
Compound
4
def setUp(self): self.mock_resource = MockHttpResource(prefix=PATH_PREFIX) self.mock_handler = Mock( spec=[ "get_displayname", "set_displayname", "get_avatar_url", "set_avatar_url", "check_profile_query_allowed", ] ) self.mock_handler.get_displayname.return_value = defer.succeed(Mock()) self.mock_handler.set_displayname.return_value = defer.succeed(Mock()) self.mock_handler.get_avatar_url.return_value = defer.succeed(Mock()) self.mock_handler.set_avatar_url.return_value = defer.succeed(Mock()) self.mock_handler.check_profile_query_allowed.return_value = defer.succeed( Mock() ) hs = yield setup_test_homeserver( self.addCleanup, "test", http_client=None, resource_for_client=self.mock_resource, federation=Mock(), federation_client=Mock(), profile_handler=self.mock_handler, ) async def _get_user_by_req(request=None, allow_guest=False): return synapse.types.create_requester(myid) hs.get_auth().get_user_by_req = _get_user_by_req profile.register_servlets(hs, self.mock_resource)
Base
1
def sentences_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_execute(self.prop_sentences_victim(type, data))
Base
1
def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
Class
2
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs): kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) success_status = "The {report_type} report is being created.".format(report_type=report_type) if report_type == 'problem responses': with patch(task_api_endpoint): response = self.client.get(url, {'problem_location': ''}) self.assertIn(success_status, response.content) else: CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint): response = self.client.get(url, {}) self.assertIn(success_status, response.content)
Compound
4
def delete_book_gdrive(book, book_format): error = None if book_format: name = '' for entry in book.data: if entry.format.upper() == book_format: name = entry.name + '.' + book_format gFile = gd.getFileFromEbooksFolder(book.path, name) else: gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), book.path.split('/')[1]) if gFile: gd.deleteDatabaseEntry(gFile['id']) gFile.Trash() else: error = _(u'Book path %(path)s not found on Google Drive', path=book.path) # file not found return error is None, error
Base
1
void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_activation_max, uint8* output_data, const Dims<4>& output_dims) { AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height, filter_width, filter_height, output_activation_min, output_activation_max, output_data, output_dims); }
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 Error: this module does not support running commands via %s" % self.runner.become_method) if in_data: raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining") # Ignores privilege escalation local_cmd = self._generate_cmd(executable, cmd) vvv("EXEC %s" % (local_cmd), host=self.jail) p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring), cwd=self.runner.basedir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return (p.returncode, '', stdout, stderr)
Base
1
def testInputPreProcessErrorBadFormat(self): input_str = 'inputx=file[[v1]v2' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:file' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_inputs_arg_string(input_str) input_str = 'inputx:np.zeros((5))' with self.assertRaises(RuntimeError): saved_model_cli.preprocess_input_exprs_arg_string(input_str)
Base
1
def fetch_file(self, in_path, out_path): ''' fetch a file from chroot to local ''' in_path = self._normalize_path(in_path, self.get_jail_path()) vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail) self._copy_file(in_path, out_path)
Base
1