code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
def test_template_render_with_noautoescape(self):
"""
Test if the autoescape value is getting passed to urlize_quoted_links filter.
"""
template = Template("{% load rest_framework %}"
"{% autoescape off %}{{ content|urlize_quoted_links }}"
"{% endautoescape %}")
rendered = template.render(Context({'content': '"http://example.com"'}))
assert rendered == '"<a href="http://example.com" rel="nofollow">http://example.com</a>"' | Base | 1 |
def new_user():
content = ub.User()
languages = calibre_db.speaking_language()
translations = [LC('en')] + babel.list_translations()
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if request.method == "POST":
to_save = request.form.to_dict()
_handle_new_user(to_save, content, languages, translations, kobo_support)
else:
content.role = config.config_default_role
content.sidebar_view = config.config_default_show
content.locale = config.config_default_locale
content.default_language = config.config_default_language
return render_title_template("user_edit.html", new_user=1, content=content,
config=config, translations=translations,
languages=languages, title=_(u"Add new user"), page="newuser",
kobo_support=kobo_support, registered_oauth=oauth_check) | Base | 1 |
async def on_GET(self, origin, content, query, context, user_id):
content = await self.handler.on_make_leave_request(origin, context, user_id)
return 200, content | Class | 2 |
def test_bind_invalid_entry(topology_st):
"""Test the failing bind does not return information about the entry
:id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f
:customerscenario: True
:setup: Standalone instance
:steps:
1: bind as non existing entry
2: check that bind info does not report 'No such entry'
:expectedresults:
1: pass
2: pass
"""
topology_st.standalone.restart()
INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX
try:
topology_st.standalone.simple_bind_s(INVALID_ENTRY, PASSWORD)
except ldap.LDAPError as e:
log.info('test_bind_invalid_entry: Failed to bind as %s (expected)' % INVALID_ENTRY)
log.info('exception description: ' + e.args[0]['desc'])
if 'info' in e.args[0]:
log.info('exception info: ' + e.args[0]['info'])
assert e.args[0]['desc'] == 'Invalid credentials'
assert 'info' not in e.args[0]
pass
log.info('test_bind_invalid_entry: PASSED')
# reset credentials
topology_st.standalone.simple_bind_s(DN_DM, PW_DM) | Base | 1 |
def CreateID(self):
"""Create a packet ID. All RADIUS requests have a ID which is used to
identify a request. This is used to detect retries and replay attacks.
This function returns a suitable random number that can be used as ID.
:return: ID number
:rtype: integer
"""
return random.randrange(0, 256) | Class | 2 |
def list_entrance_exam_instructor_tasks(request, course_id): # pylint: disable=invalid-name
"""
List entrance exam related instructor tasks.
Takes either of the following query parameters
- unique_student_identifier is an email or username
- all_students is a boolean
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
course = get_course_by_id(course_id)
student = request.GET.get('unique_student_identifier', None)
if student is not None:
student = get_student_from_identifier(student)
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."))
if student:
# Specifying for a single student's entrance exam history
tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key, student)
else:
# Specifying for all student's entrance exam history
tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key)
response_payload = {
'tasks': map(extract_task_features, tasks),
}
return JsonResponse(response_payload) | Compound | 4 |
def setUp(self):
shape = (2, 4, 3)
rand = np.random.random
self.x = rand(shape) + rand(shape).astype(np.complex)*1j
self.x[0,:, 1] = [nan, inf, -inf, nan]
self.dtype = self.x.dtype
self.filename = tempfile.mktemp() | Base | 1 |
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 |
def verify_password(plain_password, user_password):
if plain_password == user_password:
LOG.debug("password true")
return True
return False | Class | 2 |
def __init__(self, expire_on_commit=True):
""" Initialize a new CalibreDB session
"""
self.session = None
if self._init:
self.initSession(expire_on_commit)
self.instances.add(self) | Base | 1 |
def test_list_email_with_no_successes(self, task_history_request):
task_info = FakeContentTask(0, 0, 10, 'expected')
email = FakeEmail(0)
email_info = FakeEmailInfo(email, 0, 10)
task_history_request.return_value = [task_info]
url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
mock_email_info.return_value = email
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
self.assertTrue(task_history_request.called)
returned_info_list = json.loads(response.content)['emails']
self.assertEqual(len(returned_info_list), 1)
returned_info = returned_info_list[0]
expected_info = email_info.to_dict()
self.assertDictEqual(expected_info, returned_info) | Compound | 4 |
def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
for notifier in os.listdir(self.data):
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = self.data + '/' + notifier
self.logger.debug("Running %s %s" % (npath, " ".join(args)))
async_run(npath, args) | Base | 1 |
def get_response(self, url, auth=None, http_method="get", **kwargs):
if is_private_address(url) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:
raise Exception("Can't query private addresses.")
# Get authentication values if not given
if auth is None:
auth = self.get_auth()
# Then call requests to get the response from the given endpoint
# URL optionally, with the additional requests parameters.
error = None
response = None
try:
response = requests_session.request(http_method, url, auth=auth, **kwargs)
# Raise a requests HTTP exception with the appropriate reason
# for 4xx and 5xx response status codes which is later caught
# and passed back.
response.raise_for_status()
# Any other responses (e.g. 2xx and 3xx):
if response.status_code != 200:
error = "{} ({}).".format(self.response_error, response.status_code)
except requests.HTTPError as exc:
logger.exception(exc)
error = "Failed to execute query. " "Return Code: {} Reason: {}".format(
response.status_code, response.text
)
except requests.RequestException as exc:
# Catch all other requests exceptions and return the error.
logger.exception(exc)
error = str(exc)
# Return response and error.
return response, error | Base | 1 |
def parse_soap_enveloped_saml(text, body_class, header_class=None):
"""Parses a SOAP enveloped SAML thing and returns header parts and body
:param text: The SOAP object as XML
:return: header parts and body as saml.samlbase instances
"""
envelope = ElementTree.fromstring(text)
assert envelope.tag == '{%s}Envelope' % NAMESPACE
# print(len(envelope))
body = None
header = {}
for part in envelope:
# print(">",part.tag)
if part.tag == '{%s}Body' % NAMESPACE:
for sub in part:
try:
body = saml2.create_class_from_element_tree(body_class, sub)
except Exception:
raise Exception(
"Wrong body type (%s) in SOAP envelope" % sub.tag)
elif part.tag == '{%s}Header' % NAMESPACE:
if not header_class:
raise Exception("Header where I didn't expect one")
# print("--- HEADER ---")
for sub in part:
# print(">>",sub.tag)
for klass in header_class:
# print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
header[sub.tag] = \
saml2.create_class_from_element_tree(klass, sub)
break
return body, header | Base | 1 |
def test_credits_view_rst(self):
response = self.get_credits("rst")
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.content.decode(),
"\n\n* Czech\n\n * Weblate Test <[email protected]> (1)\n\n",
) | Base | 1 |
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
if not in_path.startswith(os.path.sep):
in_path = os.path.join(os.path.sep, in_path)
normpath = os.path.normpath(in_path)
in_path = os.path.join(self.chroot, normpath[1:])
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path) | Base | 1 |
def from_xml(self, content):
"""
Given some XML data, returns a Python dictionary of the decoded data.
"""
if lxml is None:
raise ImproperlyConfigured("Usage of the XML aspects requires lxml.")
return self.from_etree(parse_xml(StringIO(content)).getroot()) | Class | 2 |
def render_archived_books(page, sort_param):
order = sort_param[0] or []
archived_books = (
ub.session.query(ub.ArchivedBook)
.filter(ub.ArchivedBook.user_id == int(current_user.id))
.filter(ub.ArchivedBook.is_archived == True)
.all()
)
archived_book_ids = [archived_book.book_id for archived_book in archived_books]
archived_filter = db.Books.id.in_(archived_book_ids)
entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books,
0,
archived_filter,
order,
True,
False, 0)
name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
pagename = "archived"
return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
title=name, page=pagename, order=sort_param[1]) | Base | 1 |
def is_private_address(url):
hostname = urlparse(url).hostname
ip_address = socket.gethostbyname(hostname)
return ipaddress.ip_address(text_type(ip_address)).is_private | Base | 1 |
def auth_ldap_use_tls(self):
return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"] | Class | 2 |
def _hkey(s):
return s.title().replace('_', '-') | Base | 1 |
def render_entries(self, entries: Entries) -> Generator[str, None, None]:
"""Return entries in Beancount format.
Only renders :class:`.Balance` and :class:`.Transaction`.
Args:
entries: A list of entries.
Yields:
The entries rendered in Beancount format.
"""
indent = self.ledger.fava_options.indent
for entry in entries:
if isinstance(entry, (Balance, Transaction)):
if isinstance(entry, Transaction) and entry.flag in EXCL_FLAGS:
continue
try:
yield get_entry_slice(entry)[0] + "\n"
except (KeyError, FileNotFoundError):
yield _format_entry(
entry,
self.ledger.fava_options.currency_column,
indent,
) | Base | 1 |
def setUp(self):
self.reactor = ThreadedMemoryReactorClock()
self.hs_clock = Clock(self.reactor)
self.homeserver = setup_test_homeserver(
self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor
) | Base | 1 |
def test_modify_config(self) -> None:
user1 = uuid4()
user2 = uuid4()
# no admins set
self.assertTrue(can_modify_config_impl(InstanceConfig(), UserInfo()))
# with oid, but no admin
self.assertTrue(
can_modify_config_impl(InstanceConfig(), UserInfo(object_id=user1))
)
# is admin
self.assertTrue(
can_modify_config_impl(
InstanceConfig(admins=[user1]), UserInfo(object_id=user1)
)
)
# no user oid set
self.assertFalse(
can_modify_config_impl(InstanceConfig(admins=[user1]), UserInfo())
)
# not an admin
self.assertFalse(
can_modify_config_impl(
InstanceConfig(admins=[user1]), UserInfo(object_id=user2)
)
) | Class | 2 |
def test___post_init__(self):
from openapi_python_client.parser.properties import StringProperty
sp = StringProperty(name="test", required=True, default="A Default Value",)
assert sp.default == '"A Default Value"' | Base | 1 |
def get_field_options(self, field):
options = {}
options['label'] = field.label
options['help_text'] = field.help_text
options['required'] = field.required
options['initial'] = field.default_value
return options | Base | 1 |
def __init__(self, path: Union[str, Path]):
super().__init__(path=Path(path))
self['headers'] = {}
self['cookies'] = {}
self['auth'] = {
'type': None,
'username': None,
'password': None
} | Class | 2 |
def add_original_file(self, filename, original_filename, version):
with open(filename, 'rb') as f:
sample = base64.b64encode(f.read()).decode('utf-8')
original_file = MISPObject('original-imported-file')
original_file.add_attribute(**{'type': 'attachment', 'value': original_filename,
'object_relation': 'imported-sample', 'data': sample})
original_file.add_attribute(**{'type': 'text', 'object_relation': 'format',
'value': 'STIX {}'.format(version)})
self.misp_event.add_object(**original_file) | Base | 1 |
def test_received_headers_too_large(self):
from waitress.utilities import RequestHeaderFieldsTooLarge
self.parser.adj.max_request_header_size = 2
data = b"""\
GET /foobar HTTP/8.4
X-Foo: 1
"""
result = self.parser.received(data)
self.assertEqual(result, 30)
self.assertTrue(self.parser.completed)
self.assertTrue(isinstance(self.parser.error, RequestHeaderFieldsTooLarge)) | Base | 1 |
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp) | Class | 2 |
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False | Class | 2 |
def test_okp_ed25519_should_reject_non_string_key(self):
algo = OKPAlgorithm()
with pytest.raises(TypeError):
algo.prepare_key(None)
with open(key_path("testkey_ed25519")) as keyfile:
algo.prepare_key(keyfile.read())
with open(key_path("testkey_ed25519.pub")) as keyfile:
algo.prepare_key(keyfile.read()) | Class | 2 |
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:
frappe.throw(_("Not permitted"), frappe.PermissionError) | Base | 1 |
def run_query(self, query, user):
query = parse_query(query)
if not isinstance(query, dict):
raise QueryParseError(
"Query should be a YAML object describing the URL to query."
)
if "url" not in query:
raise QueryParseError("Query must include 'url' option.")
if is_private_address(query["url"]) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:
raise Exception("Can't query private addresses.")
method = query.get("method", "get")
request_options = project(query, ("params", "headers", "data", "auth", "json"))
fields = query.get("fields")
path = query.get("path")
if isinstance(request_options.get("auth", None), list):
request_options["auth"] = tuple(request_options["auth"])
elif self.configuration.get("username") or self.configuration.get("password"):
request_options["auth"] = (
self.configuration.get("username"),
self.configuration.get("password"),
)
if method not in ("get", "post"):
raise QueryParseError("Only GET or POST methods are allowed.")
if fields and not isinstance(fields, list):
raise QueryParseError("'fields' needs to be a list.")
response, error = self.get_response(
query["url"], http_method=method, **request_options
)
if error is not None:
return None, error
data = json_dumps(parse_json(response.json(), path, fields))
if data:
return data, None
else:
return None, "Got empty response from '{}'.".format(query["url"]) | Base | 1 |
def upload_cover(request, book):
if 'btn-upload-cover' in request.files:
requested_file = request.files['btn-upload-cover']
# check for empty request
if requested_file.filename != '':
if not current_user.role_upload():
abort(403)
ret, message = helper.save_cover(requested_file, book.path)
if ret is True:
return True
else:
flash(message, category="error")
return False
return None | Base | 1 |
def test_filelike_shortcl_http11(self):
to_send = "GET /filelike_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 test_after_start_response_http10(self):
to_send = "GET /after_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(line, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def setup_logging():
"""Configure the python logging appropriately for the tests.
(Logs will end up in _trial_temp.)
"""
root_logger = logging.getLogger()
log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s"
" - %(message)s"
)
handler = ToTwistedHandler()
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
log_level = os.environ.get("SYDENT_TEST_LOG_LEVEL", "ERROR")
root_logger.setLevel(log_level) | Class | 2 |
def insensitive_starts_with(field: Term, value: str) -> Criterion:
return Upper(field).like(Upper(f"{value}%")) | Base | 1 |
def download_check_files(self, filelist):
# only admins and allowed users may download
if not cherrypy.session['admin']:
uo = self.useroptions.forUser(self.getUserId())
if not uo.getOptionValue('media.may_download'):
return 'not_permitted'
# make sure nobody tries to escape from basedir
for f in filelist:
if '/../' in f:
return 'invalid_file'
# make sure all files are smaller than maximum download size
size_limit = cherry.config['media.maximum_download_size']
try:
if self.model.file_size_within_limit(filelist, size_limit):
return 'ok'
else:
return 'too_big'
except OSError as e: # use OSError for python2 compatibility
return str(e) | Base | 1 |
def testRunCommandInvalidSignature(self, use_tfrt):
self.parser = saved_model_cli.create_parser()
base_path = test.test_src_dir_path(SAVED_MODEL_PATH)
args = self.parser.parse_args([
'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def',
'INVALID_SIGNATURE', '--input_exprs', 'x2=np.ones((3,1))'
] + (['--use_tfrt'] if use_tfrt else []))
with self.assertRaisesRegex(ValueError,
'Could not find signature "INVALID_SIGNATURE"'):
saved_model_cli.run(args) | Base | 1 |
def test_bad_integer(self):
# issue13436: Bad error message with invalid numeric values
body = [ast.ImportFrom(module='time',
names=[ast.alias(name='sleep')],
level=None,
lineno=None, col_offset=None)]
mod = ast.Module(body)
with self.assertRaises(ValueError) as cm:
compile(mod, 'test', 'exec')
self.assertIn("invalid integer value: None", str(cm.exception)) | Base | 1 |
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
) | Class | 2 |
async def on_GET(self, origin, _content, query, context, user_id):
"""
Args:
origin (unicode): The authenticated server_name of the calling server
_content (None): (GETs don't have bodies)
query (dict[bytes, list[bytes]]): Query params from the request.
**kwargs (dict[unicode, unicode]): the dict mapping keys to path
components as specified in the path match regexp.
Returns:
Tuple[int, object]: (response code, response object)
"""
versions = query.get(b"ver")
if versions is not None:
supported_versions = [v.decode("utf-8") for v in versions]
else:
supported_versions = ["1"]
content = await self.handler.on_make_join_request(
origin, context, user_id, supported_versions=supported_versions
)
return 200, content | Class | 2 |
def test_list_report_downloads(self):
url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:
mock_links_for.return_value = [
('mock_file_name_1', 'https://1.mock.url'),
('mock_file_name_2', 'https://2.mock.url'),
]
response = self.client.get(url, {})
expected_response = {
"downloads": [
{
"url": "https://1.mock.url",
"link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>",
"name": "mock_file_name_1"
},
{
"url": "https://2.mock.url",
"link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>",
"name": "mock_file_name_2"
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected_response) | Compound | 4 |
def delete(request, pk, remove=True):
comment = get_object_or_404(Comment, pk=pk)
if is_post(request):
(Comment.objects
.filter(pk=pk)
.update(is_removed=remove))
return redirect(request.GET.get('next', comment.get_absolute_url()))
return render(
request=request,
template_name='spirit/comment/moderate.html',
context={'comment': comment}) | Base | 1 |
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval | Class | 2 |
def set_bookmark(book_id, book_format):
bookmark_key = request.form["bookmark"]
ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),
ub.Bookmark.book_id == book_id,
ub.Bookmark.format == book_format)).delete()
if not bookmark_key:
ub.session_commit()
return "", 204
lbookmark = ub.Bookmark(user_id=current_user.id,
book_id=book_id,
format=book_format,
bookmark_key=bookmark_key)
ub.session.merge(lbookmark)
ub.session_commit("Bookmark for user {} in book {} created".format(current_user.id, book_id))
return "", 201 | Base | 1 |
def valid_id(opts, id_):
'''
Returns if the passed id is valid
'''
try:
return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)
except (AttributeError, KeyError, TypeError) as e:
return False | Base | 1 |
def is_valid_hostname(string: str) -> bool:
"""Validate that a given string is a valid hostname or domain name, with an
optional port number.
For domain names, this only validates that the form is right (for
instance, it doesn't check that the TLD is valid). If a port is
specified, it has to be a valid port number.
:param string: The string to validate
:type string: str
:return: Whether the input is a valid hostname
:rtype: bool
"""
host_parts = string.split(":", 1)
if len(host_parts) == 1:
return hostname_regex.match(string) is not None
else:
host, port = host_parts
valid_hostname = hostname_regex.match(host) is not None
try:
port_num = int(port)
valid_port = (
port == str(port_num) # exclude things like '08090' or ' 8090'
and 1 <= port_num < 65536)
except ValueError:
valid_port = False
return valid_hostname and valid_port | Class | 2 |
def _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | Base | 1 |
def test_certificates_features_against_status(self):
"""
Test certificates with status 'downloadable' should be in the response.
"""
url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
# firstly generating downloadable certificates with 'honor' mode
certificate_count = 3
for __ in xrange(certificate_count):
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
self.assertEqual(len(res_json['certificates']), 0)
# Certificates with status 'downloadable' should be in response.
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
self.assertEqual(len(res_json['certificates']), 1) | Compound | 4 |
def json_dumps(value, indent=None):
if isinstance(value, QuerySet):
result = serialize('json', value, indent=indent)
else:
result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)
return mark_safe(result) | Base | 1 |
def bm_to_item(self, bm):
return bytearray(cPickle.dumps(bm, -1)) | Base | 1 |
def google_remote_app():
if "google" not in oauth.remote_apps:
oauth.remote_app(
"google",
base_url="https://www.google.com/accounts/",
authorize_url="https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent",
request_token_url=None,
request_token_params={
"scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
},
access_token_url="https://accounts.google.com/o/oauth2/token",
access_token_method="POST",
consumer_key=settings.GOOGLE_CLIENT_ID,
consumer_secret=settings.GOOGLE_CLIENT_SECRET,
)
return oauth.google | Base | 1 |
def change_due_date(request, course_id):
"""
Grants a due date extension to a student for a particular unit.
"""
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
student = require_student_from_identifier(request.GET.get('student'))
unit = find_unit(course, request.GET.get('url'))
due_date = parse_datetime(request.GET.get('due_datetime'))
set_due_date_extension(course, unit, student, due_date)
return JsonResponse(_(
'Successfully changed due date for student {0} for {1} '
'to {2}').format(student.profile.name, _display_unit(unit),
due_date.strftime('%Y-%m-%d %H:%M'))) | Compound | 4 |
def save(self):
self.cleaned_data['code'].delete() | Base | 1 |
def delete(request, pk):
favorite = get_object_or_404(TopicFavorite, pk=pk, user=request.user)
favorite.delete()
return redirect(request.POST.get('next', favorite.topic.get_absolute_url())) | Base | 1 |
def auth_user_registration_role(self):
return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"] | Class | 2 |
def intermediate_dir():
""" Location in temp dir for storing .cpp and .o files during
builds.
"""
python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2])
path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name)
if not os.path.exists(path):
os.makedirs(path, mode=0o700)
return path | Class | 2 |
def test_received_nonsense_with_double_cr(self):
data = b"""\
HTTP/1.0 GET /foobar
"""
result = self.parser.received(data)
self.assertEqual(result, 22)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.headers, {}) | Base | 1 |
def parse_json(raw_data):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
return json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
return results | Class | 2 |
def mysql_contains(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}%") | Base | 1 |
def test_received(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
inst.received(b"GET / HTTP/1.1\n\n")
self.assertEqual(inst.server.tasks, [inst])
self.assertTrue(inst.requests) | Base | 1 |
def job_cancel(request, client_id, project_name, job_id):
"""
cancel a job
:param request: request object
:param client_id: client id
:param project_name: project name
:param job_id: job id
:return: json of cancel
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
try:
scrapyd = get_scrapyd(client)
result = scrapyd.cancel(project_name, job_id)
return JsonResponse(result)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'}) | Base | 1 |
def login():
from flask_login import current_user
redirect_url = request.args.get("redirect", request.script_root + url_for("index"))
permissions = sorted(
filter(
lambda x: x is not None and isinstance(x, OctoPrintPermission),
map(
lambda x: getattr(Permissions, x.strip()),
request.args.get("permissions", "").split(","),
),
),
key=lambda x: x.get_name(),
)
if not permissions:
permissions = [Permissions.STATUS, Permissions.SETTINGS_READ]
user_id = request.args.get("user_id", "")
if (not user_id or current_user.get_id() == user_id) and has_permissions(
*permissions
):
return redirect(redirect_url)
render_kwargs = {
"theming": [],
"redirect_url": redirect_url,
"permission_names": map(lambda x: x.get_name(), permissions),
"user_id": user_id,
"logged_in": not current_user.is_anonymous,
}
try:
additional_assets = _add_additional_assets("octoprint.theming.login")
# backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog
additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming")
additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming")
render_kwargs.update({"theming": additional_assets})
except Exception:
_logger.exception("Error processing theming CSS, ignoring")
return render_template("login.jinja2", **render_kwargs) | Base | 1 |
def download_list():
if current_user.get_view_property('download', 'dir') == 'desc':
order = ub.User.name.desc()
order_no = 0
else:
order = ub.User.name.asc()
order_no = 1
if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\
.join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all()
charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \
.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \
.group_by(func.upper(func.substr(ub.User.name, 1, 1))).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Downloads"), page="downloadlist", data="download", order=order_no)
else:
abort(404) | Base | 1 |
def feed_seriesindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
elements = []
if off == 0:
elements.append({'id': "00", 'name':_("All")})
shift = 1
for entry in entries[
off + shift - 1:
int(off + int(config.config_books_per_page) - shift)]:
elements.append({'id': entry.id, 'name': entry.id})
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries) + 1)
return render_xml_template('feed.xml',
letterelements=elements,
folder='opds.feed_letter_series',
pagination=pagination) | Base | 1 |
def handler(request):
"""Scheme handler for qute:// URLs.
Args:
request: QNetworkRequest to answer to.
Return:
A QNetworkReply.
"""
try:
mimetype, data = qutescheme.data_for_url(request.url())
except qutescheme.NoHandlerFound:
errorstr = "No handler found for {}!".format(
request.url().toDisplayString())
return networkreply.ErrorNetworkReply(
request, errorstr, QNetworkReply.ContentNotFoundError)
except qutescheme.QuteSchemeOSError as e:
return networkreply.ErrorNetworkReply(
request, str(e), QNetworkReply.ContentNotFoundError)
except qutescheme.QuteSchemeError as e:
return networkreply.ErrorNetworkReply(request, e.errorstring, e.error)
except qutescheme.Redirect as e:
qtutils.ensure_valid(e.url)
return networkreply.RedirectNetworkReply(e.url)
return networkreply.FixedDataNetworkReply(request, data, mimetype) | Compound | 4 |
def edit_user(user_id):
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User
if not content or (not config.config_anonbrowse and content.name == "Guest"):
flash(_(u"User not found"), category="error")
return redirect(url_for('admin.admin'))
languages = calibre_db.speaking_language(return_all_languages=True)
translations = babel.list_translations() + [LC('en')]
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if request.method == "POST":
to_save = request.form.to_dict()
resp = _handle_edit_user(to_save, content, languages, translations, kobo_support)
if resp:
return resp
return render_title_template("user_edit.html",
translations=translations,
languages=languages,
new_user=0,
content=content,
config=config,
registered_oauth=oauth_check,
mail_configured=config.get_mail_server_configured(),
kobo_support=kobo_support,
title=_(u"Edit User %(nick)s", nick=content.name),
page="edituser") | Base | 1 |
async def on_GET(self, origin, content, query, context):
return await self.handler.on_context_state_request(
origin,
context,
parse_string_from_args(query, "event_id", None, required=False),
) | Class | 2 |
def test_rescore_entrance_exam_single_student(self, act):
""" Test re-scoring of entrance exam for single student. """
url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | Compound | 4 |
def profile():
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [LC('en')]
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if feature_support['oauth'] and config.config_login_type == 2:
oauth_status = get_oauth_status()
local_oauth_check = oauth_check
else:
oauth_status = None
local_oauth_check = {}
if request.method == "POST":
change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
return render_title_template("user_edit.html",
translations=translations,
profile=1,
languages=languages,
content=current_user,
kobo_support=kobo_support,
title=_(u"%(name)s's profile", name=current_user.name),
page="me",
registered_oauth=local_oauth_check,
oauth_status=oauth_status) | Base | 1 |
def make_homeserver(self, reactor, clock):
presence_handler = Mock()
presence_handler.set_state.return_value = defer.succeed(None)
hs = self.setup_test_homeserver(
"red",
http_client=None,
federation_client=Mock(),
presence_handler=presence_handler,
)
return hs | Base | 1 |
async def start_verification(self, client_id, username):
async with self.lock:
await self.db.execute('SELECT code FROM scratchverifier_usage WHERE \
client_id=? AND username=?', (client_id, username))
row = await self.db.fetchone()
if row is not None:
await self.db.execute('UPDATE scratchverifier_usage SET expiry=? \
WHERE client_id=? AND username=? AND code=?', (int(time.time()) + VERIFY_EXPIRY,
client_id, username, row[0]))
return row[0]
code = sha256(
str(client_id).encode()
+ str(time.time()).encode()
+ username.encode()
+ token_bytes()
# 0->A, 1->B, etc, to avoid Scratch's phone number censor
).hexdigest().translate({ord('0') + i: ord('A') + i for i in range(10)})
await self.db.execute('INSERT INTO scratchverifier_usage (client_id, \
code, username, expiry) VALUES (?, ?, ?, ?)', (client_id, code, username,
int(time.time() + VERIFY_EXPIRY)))
await self.db.execute('INSERT INTO scratchverifier_logs (client_id, \
username, log_time, log_type) VALUES (?, ?, ?, ?)', (client_id, username,
int(time.time()), 1))
await self.db.execute('DELETE FROM scratchverifier_usage WHERE \
expiry<=?', (int(time.time()),))
return code | Class | 2 |
def __init__(self, bot):
super().__init__()
self.bot = bot
self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True)
self.config.register_global(custom={}, tenorkey=None)
self.config.register_guild(custom={})
self.try_after = None
| Base | 1 |
def handleMatch(m):
s = m.group(1)
if s.startswith('0x'):
i = int(s, 16)
elif s.startswith('0') and '.' not in s:
try:
i = int(s, 8)
except ValueError:
i = int(s)
else:
i = float(s)
x = complex(i)
if x.imag == 0:
x = x.real
# Need to use string-formatting here instead of str() because
# use of str() on large numbers loses information:
# str(float(33333333333333)) => '3.33333333333e+13'
# float('3.33333333333e+13') => 33333333333300.0
return '%.16f' % x
return str(x) | Base | 1 |
def Ghostscript(tile, size, fp, scale=1):
"""Render an image using Ghostscript"""
# Unpack decoder tile
decoder, tile, offset, data = tile[0]
length, bbox = data
#Hack to support hi-res rendering
scale = int(scale) or 1
orig_size = size
orig_bbox = bbox
size = (size[0] * scale, size[1] * scale)
bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
#print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command
command = ["gs",
"-q", # quite mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%d" % (72*scale), # set input DPI (dots per inch)
"-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % file,# output file
]
if gs_windows_binary is not None:
if gs_windows_binary is False:
raise WindowsError('Unable to locate Ghostscript on paths')
command[0] = gs_windows_binary
# push data through ghostscript
try:
gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# adjust for image origin
if bbox[0] != 0 or bbox[1] != 0:
gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
fp.seek(offset)
while length > 0:
s = fp.read(8192)
if not s:
break
length = length - len(s)
gs.stdin.write(s)
gs.stdin.close()
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
return im | Base | 1 |
def test_get_students_features_teams(self, has_teams):
"""
Test that get_students_features includes team info when the course is
has teams enabled, and does not when the course does not have teams enabled
"""
if has_teams:
self.course = CourseFactory.create(teams_configuration={
'max_size': 2, 'topics': [{'topic-id': 'topic', 'name': 'Topic', 'description': 'A Topic'}]
})
course_instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=course_instructor.username, password='test')
url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertEqual('team' in res_json['feature_names'], has_teams) | Compound | 4 |
def test_notfilelike_nocl_http10(self):
to_send = "GET /notfilelike_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", "HTTP/1.0")
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 get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
path = pathlib.PurePosixPath(path)
try:
location = storage.aws_location
except AttributeError:
location = storage.location
try:
f = storage.open(str(path.relative_to(location)))
f.name = path.name
yield f
except (OSError, ValueError):
logger.exception("File not found: %s", path) | Base | 1 |
def test_received_control_line_finished_all_chunks_not_received(self):
buf = DummyBuffer()
inst = self._makeOne(buf)
result = inst.received(b"a;discard\n")
self.assertEqual(inst.control_line, b"")
self.assertEqual(inst.chunk_remainder, 10)
self.assertEqual(inst.all_chunks_received, False)
self.assertEqual(result, 10)
self.assertEqual(inst.completed, False) | Base | 1 |
def test_date_and_server(self):
to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers.get("server"), "waitress")
self.assertTrue(headers.get("date")) | Base | 1 |
def encode_non_url_reserved_characters(url):
# safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2
return urlquote(url, safe=":/?#[]@!$&'()*+,;=") | Base | 1 |
async def check_credentials(username: str, password: str) -> bool:
return (username, password) == credentials | Base | 1 |
def _bind_write_headers(msg):
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp)
return _write_headers | Class | 2 |
def subscribe_for_tags(request):
"""process subscription of users by tags"""
#todo - use special separator to split tags
tag_names = request.REQUEST.get('tags','').strip().split()
pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
if request.user.is_authenticated():
if request.method == 'POST':
if 'ok' in request.POST:
request.user.mark_tags(
pure_tag_names,
wildcards,
reason = 'good',
action = 'add'
)
request.user.message_set.create(
message = _('Your tag subscription was saved, thanks!')
)
else:
message = _(
'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
) % {'url': request.path + '?tags=' + request.REQUEST['tags']}
request.user.message_set.create(message = message)
return HttpResponseRedirect(reverse('index'))
else:
data = {'tags': tag_names}
return render(request, 'subscribe_for_tags.html', data)
else:
all_tag_names = pure_tag_names + wildcards
message = _('Please sign in to subscribe for: %(tags)s') \
% {'tags': ', '.join(all_tag_names)}
request.user.message_set.create(message = message)
request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
return HttpResponseRedirect(url_utils.get_login_url()) | Base | 1 |
def test_before_start_response_http_11(self):
to_send = "GET /before_start_response 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, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"]
)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def test_credits_one(self, expected_count=1):
self.add_change()
data = generate_credits(
None,
timezone.now() - timedelta(days=1),
timezone.now() + timedelta(days=1),
translation__component=self.component,
)
self.assertEqual(
data, [{"Czech": [("[email protected]", "Weblate Test", expected_count)]}]
) | Base | 1 |
def class_instances_from_soap_enveloped_saml_thingies(text, modules):
"""Parses a SOAP enveloped header and body SAML thing and returns the
thing as a dictionary class instance.
:param text: The SOAP object as XML
:param modules: modules representing xsd schemas
:return: The body and headers as class instances
"""
try:
envelope = ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
env = {"header": [], "body": None}
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
env["body"] = instanciate_class(part[0], modules)
elif part.tag == "{%s}Header" % soapenv.NAMESPACE:
for item in part:
env["header"].append(instanciate_class(item, modules))
return env | Base | 1 |
def pascal_case(value: str) -> str:
return stringcase.pascalcase(_sanitize(value)) | Base | 1 |
def test_digest_object():
credentials = ("joe", "password")
host = None
request_uri = "/test/digest/"
headers = {}
response = {
"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'
}
content = b""
d = httplib2.DigestAuthentication(
credentials, host, request_uri, headers, response, content, None
)
d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46")
our_request = "authorization: " + headers["authorization"]
working_request = (
'authorization: Digest username="joe", realm="myrealm", '
'nonce="KBAA=35", uri="/test/digest/"'
+ ', algorithm=MD5, response="de6d4a123b80801d0e94550411b6283f", '
'qop=auth, nc=00000001, cnonce="33033375ec278a46"'
)
assert our_request == working_request | Class | 2 |
def keccak256_helper(expr, ir_arg, context):
sub = ir_arg # TODO get rid of useless variable
_check_byteslike(sub.typ, expr)
# Can hash literals
# TODO this is dead code.
if isinstance(sub, bytes):
return IRnode.from_list(bytes_to_int(keccak256(sub)), typ=BaseType("bytes32"))
# Can hash bytes32 objects
if is_base_type(sub.typ, "bytes32"):
return IRnode.from_list(
[
"seq",
["mstore", MemoryPositions.FREE_VAR_SPACE, sub],
["sha3", MemoryPositions.FREE_VAR_SPACE, 32],
],
typ=BaseType("bytes32"),
add_gas_estimate=_gas_bound(1),
)
sub = ensure_in_memory(sub, context)
return IRnode.from_list(
[
"with",
"_buf",
sub,
["sha3", ["add", "_buf", 32], ["mload", "_buf"]],
],
typ=BaseType("bytes32"),
annotation="keccak256",
add_gas_estimate=_gas_bound(ceil(sub.typ.maxlen / 32)),
) | Pillar | 3 |
def test_short_body(self):
# check to see if server closes connection when body is too short
# for cl header
to_send = tobytes(
"GET /short_body HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: 0\n"
"\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line = fp.readline() # status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
content_length = int(headers.get("content-length"))
response_body = fp.read(content_length)
self.assertEqual(int(status), 200)
self.assertNotEqual(content_length, len(response_body))
self.assertEqual(len(response_body), content_length - 1)
self.assertEqual(response_body, tobytes("abcdefghi"))
# remote closed connection (despite keepalive header); not sure why
# first send succeeds
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def test_rescore_problem_single(self, act):
""" Test rescoring of a single student. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | Compound | 4 |
def starts_with(field: Term, value: str) -> Criterion:
return field.like(f"{value}%") | Base | 1 |
def __init__(self, hs):
super().__init__(hs)
self.http_client = SimpleHttpClient(hs)
# We create a blacklisting instance of SimpleHttpClient for contacting identity
# servers specified by clients
self.blacklisting_http_client = SimpleHttpClient(
hs, ip_blacklist=hs.config.federation_ip_range_blacklist
)
self.federation_http_client = hs.get_http_client()
self.hs = hs | 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 make_homeserver(self, reactor, clock):
self.http_client = Mock()
hs = self.setup_test_homeserver(http_client=self.http_client)
return hs | Base | 1 |
def feed_get_cover(book_id):
return get_book_cover(book_id) | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.