code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
def _get_unauth_response(self, request, reason):
"""
Get an error response (or raise a Problem) for a given request and reason message.
:type request: Request.
:param request: HttpRequest
:type reason: Reason string.
:param reason: str
"""
if request.is_ajax():
return HttpResponseForbidden(json.dumps({"error": force_text(reason)}))
error_params = urlencode({"error": force_text(reason)})
login_url = force_str(reverse("shuup_admin:login") + "?" + error_params)
resp = redirect_to_login(next=request.path, login_url=login_url)
if is_authenticated(request.user):
# Instead of redirecting to the login page, let the user know what's wrong with
# a helpful link.
raise (
Problem(_("Can't view this page. %(reason)s") % {"reason": reason}).with_link(
url=resp.url, title=_("Log in with different credentials...")
)
)
return resp | Base | 1 |
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, initial_filename='bookmarks.pickle')
if filename:
with open(filename, 'wb') as fileobj:
cPickle.dump(self.get_bookmarks(), fileobj, -1) | Base | 1 |
def test_with_admins(self) -> None:
no_admins = InstanceConfig(admins=None)
with_admins = InstanceConfig(admins=[UUID(int=0)])
with_admins_2 = InstanceConfig(admins=[UUID(int=1)])
no_admins.update(with_admins)
self.assertEqual(no_admins.admins, None)
with_admins.update(with_admins_2)
self.assertEqual(with_admins.admins, with_admins_2.admins) | Class | 2 |
def feed_author(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.authors.any(db.Authors.id == book_id),
[db.Books.timestamp.desc()])
return render_xml_template('feed.xml', entries=entries, pagination=pagination) | Base | 1 |
def test_uses_xdg_config_home(self, apiver):
with WindowsSafeTempDir() as d:
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
XDG_CONFIG_HOME_ENV_VAR: d,
}
)
if apiver in ['v0', 'v1']:
expected_path = os.path.abspath(os.path.join(self.home, '.b2_account_info'))
else:
assert os.path.exists(os.path.join(d, 'b2'))
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 wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect(request.GET.get('next', request.user.st.get_absolute_url()))
return view_func(request, *args, **kwargs) | Base | 1 |
def test_login_inactive_user(self):
self.user.is_active = False
self.user.save()
login_code = LoginCode.objects.create(user=self.user, code='foobar')
response = self.client.post('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['form'].errors, {
'code': ['Unable to log in with provided login code.'],
}) | Base | 1 |
def head_file(path):
try:
data_file, metadata = get_info(
path,
pathlib.Path(app.config["DATA_ROOT"])
)
stat = data_file.stat()
except (OSError, ValueError):
return flask.Response(
"Not Found",
404,
mimetype="text/plain",
)
response = flask.Response()
response.headers["Content-Length"] = str(stat.st_size)
generate_headers(
response.headers,
metadata["headers"],
)
return response | Base | 1 |
def update(request, pk):
notification = get_object_or_404(TopicNotification, pk=pk, user=request.user)
form = NotificationForm(data=request.POST, instance=notification)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get(
'next', notification.topic.get_absolute_url())) | Base | 1 |
def save_cover(img, book_path):
content_type = img.headers.get('content-type')
if use_IM:
if content_type not in ('image/jpeg', 'image/png', 'image/webp', 'image/bmp'):
log.error("Only jpg/jpeg/png/webp/bmp files are supported as coverfile")
return False, _("Only jpg/jpeg/png/webp/bmp files are supported as coverfile")
# convert to jpg because calibre only supports jpg
if content_type != 'image/jpg':
try:
if hasattr(img, 'stream'):
imgc = Image(blob=img.stream)
else:
imgc = Image(blob=io.BytesIO(img.content))
imgc.format = 'jpeg'
imgc.transform_colorspace("rgb")
img = imgc
except (BlobError, MissingDelegateError):
log.error("Invalid cover file content")
return False, _("Invalid cover file content")
else:
if content_type not in 'image/jpeg':
log.error("Only jpg/jpeg files are supported as coverfile")
return False, _("Only jpg/jpeg files are supported as coverfile")
if config.config_use_google_drive:
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
ret, message = save_cover_from_filestorage(tmp_dir, "uploaded_cover.jpg", img)
if ret is True:
gd.uploadFileToEbooksFolder(os.path.join(book_path, 'cover.jpg').replace("\\","/"),
os.path.join(tmp_dir, "uploaded_cover.jpg"))
log.info("Cover is saved on Google Drive")
return True, None
else:
return False, message
else:
return save_cover_from_filestorage(os.path.join(config.config_calibre_dir, book_path), "cover.jpg", img) | Base | 1 |
def try_ldap_login(login, password):
""" Connect to a LDAP directory to verify user login/passwords"""
result = "Wrong login/password"
s = Server(config.LDAPURI, port=config.LDAPPORT,
use_ssl=False, get_info=ALL)
# 1. connection with service account to find the user uid
uid = useruid(s, login)
if uid:
# 2. Try to bind the user to the LDAP
c = Connection(s, user = uid , password = password, auto_bind = True)
c.open()
c.bind()
result = c.result["description"] # "success" if bind is ok
c.unbind()
return result | Class | 2 |
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 testRunCommandInvalidInputKeyError(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',
'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))'
] + (['--use_tfrt'] if use_tfrt else []))
with self.assertRaises(ValueError):
saved_model_cli.run(args) | Base | 1 |
def test_list_instructor_tasks_running(self, act):
""" Test list of all running tasks. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks) | Compound | 4 |
def test_captcha_validate_value(self):
captcha = FlaskSessionCaptcha(self.app)
_default_routes(captcha, self.app)
with self.app.test_request_context('/'):
captcha.generate()
answer = captcha.get_answer()
assert not captcha.validate(value="wrong")
captcha.generate()
answer = captcha.get_answer()
assert captcha.validate(value=answer) | Class | 2 |
async def handle_404(request, response):
if 'json' not in response.headers['Content-Type']:
if request.path.endswith('/'):
return web.HTTPFound(request.path.rstrip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(request.path)
}, status=404)
return response | Base | 1 |
def get(self, path: str) -> None:
parts = path.split("/")
component_name = parts[0]
component_root = self._registry.get_component_path(component_name)
if component_root is None:
self.write("not found")
self.set_status(404)
return
filename = "/".join(parts[1:])
abspath = os.path.join(component_root, filename)
LOGGER.debug("ComponentRequestHandler: GET: %s -> %s", path, abspath)
try:
with open(abspath, "rb") as file:
contents = file.read()
except (OSError) as e:
LOGGER.error(f"ComponentRequestHandler: GET {path} read error", exc_info=e)
self.write("read error")
self.set_status(404)
return
self.write(contents)
self.set_header("Content-Type", self.get_content_type(abspath))
self.set_extra_headers(path) | Base | 1 |
def icalc(self, irc, msg, args, text):
"""<math expression>
This is the same as the calc command except that it allows integer
math, and can thus cause the bot to suck up CPU. Hence it requires
the 'trusted' capability to use.
"""
if self._calc_match_forbidden_chars.match(text):
# Note: this is important to keep this to forbid usage of
# __builtins__
irc.error(_('There\'s really no reason why you should have '
'underscores or brackets in your mathematical '
'expression. Please remove them.'))
return
# This removes spaces, too, but we'll leave the removal of _[] for
# safety's sake.
text = self._calc_remover(text)
if 'lambda' in text:
irc.error(_('You can\'t use lambda in this command.'))
return
text = text.replace('lambda', '')
try:
self.log.info('evaluating %q from %s', text, msg.prefix)
irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
except OverflowError:
maxFloat = math.ldexp(0.9999999999999999, 1024)
irc.error(_('The answer exceeded %s or so.') % maxFloat)
except TypeError:
irc.error(_('Something in there wasn\'t a valid number.'))
except NameError as e:
irc.error(_('%s is not a defined function.') % str(e).split()[1])
except Exception as e:
irc.error(utils.exnToString(e)) | Base | 1 |
def CreateAuthenticator():
"""Create a packet autenticator. All RADIUS packets contain a sixteen
byte authenticator which is used to authenticate replies from the
RADIUS server and in the password hiding algorithm. This function
returns a suitable random string that can be used as an authenticator.
:return: valid packet authenticator
:rtype: binary string
"""
data = []
for i in range(16):
data.append(random.randrange(0, 256))
if six.PY3:
return bytes(data)
else:
return ''.join(chr(b) for b in data) | Class | 2 |
def check_send_to_kindle_with_converter(formats):
bookformats = list()
if 'EPUB' in formats and 'MOBI' not in formats:
bookformats.append({'format': 'Mobi',
'convert': 1,
'text': _('Convert %(orig)s to %(format)s and send to Kindle',
orig='Epub',
format='Mobi')})
if 'AZW3' in formats and not 'MOBI' in formats:
bookformats.append({'format': 'Mobi',
'convert': 2,
'text': _('Convert %(orig)s to %(format)s and send to Kindle',
orig='Azw3',
format='Mobi')})
return bookformats | Base | 1 |
def test_basic(settings):
items, url, crawler = yield crawl_items(ResponseSpider, HelloWorld,
settings)
assert len(items) == 1
resp = items[0]['response']
assert resp.url == url
assert resp.css('body::text').extract_first().strip() == "hello world!" | Class | 2 |
def generate_auth_token(user_id):
host_list = request.host.rsplit(':')
if len(host_list) == 1:
host = ':'.join(host_list)
else:
host = ':'.join(host_list[0:-1])
if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'):
warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device')
return render_title_template(
"generate_kobo_auth_url.html",
title=_(u"Kobo Setup"),
warning = warning
)
else:
# Invalidate any prevously generated Kobo Auth token for this user.
auth_token = ub.session.query(ub.RemoteAuthToken).filter(
ub.RemoteAuthToken.user_id == user_id
).filter(ub.RemoteAuthToken.token_type==1).first()
if not auth_token:
auth_token = ub.RemoteAuthToken()
auth_token.user_id = user_id
auth_token.expiration = datetime.max
auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8")
auth_token.token_type = 1
ub.session.add(auth_token)
ub.session_commit()
books = calibre_db.session.query(db.Books).join(db.Data).all()
for book in books:
formats = [data.format for data in book.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:
helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
return render_title_template(
"generate_kobo_auth_url.html",
title=_(u"Kobo Setup"),
kobo_auth_url=url_for(
"kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True
),
warning = False
) | Base | 1 |
def PUT(self, path, body, ensure_encoding=True, log_request_body=True):
return self._request('PUT', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body) | Base | 1 |
def jstree_data(node, selected_node):
result = []
result.append('{')
result.append('"text": "{}",'.format(node.label))
result.append(
'"state": {{ "opened": true, "selected": {} }},'.format(
'true' if node == selected_node else 'false'
)
)
result.append(
'"data": {{ "href": "{}" }},'.format(node.get_absolute_url())
)
children = node.get_children().order_by('label',)
if children:
result.append('"children" : [')
for child in children:
result.extend(jstree_data(node=child, selected_node=selected_node))
result.append(']')
result.append('},')
return result | Base | 1 |
def test_parse_header_11_te_chunked(self):
# NB: test that capitalization of header value is unimportant
data = b"GET /foobar HTTP/1.1\ntransfer-encoding: ChUnKed"
self.parser.parse_header(data)
self.assertEqual(self.parser.body_rcv.__class__.__name__, "ChunkedReceiver") | Base | 1 |
def test_unicorn_render_context_variable():
token = Token(
TokenType.TEXT,
"unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg=test_var.nested",
)
unicorn_node = unicorn(None, token)
context = {"test_var": {"nested": "variable!"}}
actual = unicorn_node.render(context)
assert "->variable!<-" in actual | Base | 1 |
def generate_auth_token(user_id):
host_list = request.host.rsplit(':')
if len(host_list) == 1:
host = ':'.join(host_list)
else:
host = ':'.join(host_list[0:-1])
if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'):
warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device')
return render_title_template(
"generate_kobo_auth_url.html",
title=_(u"Kobo Setup"),
warning = warning
)
else:
# Invalidate any prevously generated Kobo Auth token for this user.
auth_token = ub.session.query(ub.RemoteAuthToken).filter(
ub.RemoteAuthToken.user_id == user_id
).filter(ub.RemoteAuthToken.token_type==1).first()
if not auth_token:
auth_token = ub.RemoteAuthToken()
auth_token.user_id = user_id
auth_token.expiration = datetime.max
auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8")
auth_token.token_type = 1
ub.session.add(auth_token)
ub.session_commit()
books = calibre_db.session.query(db.Books).join(db.Data).all()
for book in books:
formats = [data.format for data in book.data]
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:
helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
return render_title_template(
"generate_kobo_auth_url.html",
title=_(u"Kobo Setup"),
kobo_auth_url=url_for(
"kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True
),
warning = False
) | Pillar | 3 |
def test_request_login_code(self):
response = self.client.post('/accounts/login/', {
'username': self.user.username,
'next': '/private/',
})
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '/accounts/login/code/')
login_code = LoginCode.objects.filter(user=self.user).first()
self.assertIsNotNone(login_code)
self.assertEqual(login_code.next, '/private/')
self.assertEqual(len(mail.outbox), 1)
self.assertIn(
'http://testserver/accounts/login/code/?code={}'.format(login_code.code),
mail.outbox[0].body,
) | Base | 1 |
def send_note_attachment(filename):
"""Return a file from the note attachment directory"""
file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)
if file_path is not None:
try:
return send_file(file_path, as_attachment=True)
except Exception:
logger.exception("Send note attachment") | Base | 1 |
def login_user(self, username, password, otp, context, **kwargs):
user = authenticate(request=context.get('request'),
username=username, password=password)
if not user:
login_reject.send(sender=self.__class__, username=username, reason='creds')
raise FormattedException(m='incorrect_username_or_password', d={'reason': 'incorrect_username_or_password'},
status_code=HTTP_401_UNAUTHORIZED)
if not user.email_verified and not user.is_superuser:
login_reject.send(sender=self.__class__, username=username, reason='email')
raise FormattedException(m='email_verification_required', d={'reason': 'email_verification_required'},
status_code=HTTP_401_UNAUTHORIZED)
if not user.can_login():
login_reject.send(sender=self.__class__, username=username, reason='closed')
raise FormattedException(m='login_not_open', d={'reason': 'login_not_open'},
status_code=HTTP_401_UNAUTHORIZED)
if user.totp_status == TOTPStatus.ENABLED:
if not otp or otp == '':
login_reject.send(sender=self.__class__, username=username, reason='no_2fa')
raise FormattedException(m='2fa_required', d={'reason': '2fa_required'},
status_code=HTTP_401_UNAUTHORIZED)
totp = pyotp.TOTP(user.totp_secret)
if not totp.verify(otp, valid_window=1):
login_reject.send(sender=self.__class__, username=username, reason='incorrect_2fa')
raise FormattedException(m='incorrect_2fa', d={'reason': 'incorrect_2fa'},
status_code=HTTP_401_UNAUTHORIZED)
login.send(sender=self.__class__, user=user)
return user | Class | 2 |
def test_modify_access_bad_role(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': 'robot-not-a-roll',
'action': 'revoke',
})
self.assertEqual(response.status_code, 400) | Compound | 4 |
def build_request(self, key_filename, req_config, entry):
"""
creates the certificate request
"""
req = tempfile.mkstemp()[1]
days = self.cert_specs[entry.get('name')]['days']
key = self.data + key_filename
cmd = "openssl req -new -config %s -days %s -key %s -text -out %s" % (req_config,
days,
key,
req)
res = Popen(cmd, shell=True, stdout=PIPE).stdout.read()
return req | Class | 2 |
def should_run(self):
if self.force:
return True
if not os.path.exists(self.bower_dir):
return True
return mtime(self.bower_dir) < mtime(pjoin(repo_root, 'bower.json')) | Base | 1 |
def test_file_position_after_tofile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
err_msg = "%d" % (size,)
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
f.seek(10)
f.write(b'12')
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10 + 2 + 8, err_msg=err_msg)
f = open(self.filename, 'r+b')
f.read(2)
f.seek(0, 1) # seek between read&write required by ANSI C
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10, err_msg=err_msg)
os.unlink(self.filename) | Base | 1 |
def append(self, key, value):
self.dict.setdefault(_hkey(key), []).append(
value if isinstance(value, unicode) else str(value)) | Base | 1 |
def feed_category(book_id):
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books,
db.Books.tags.any(db.Tags.id == book_id),
[db.Books.timestamp.desc()])
return render_xml_template('feed.xml', entries=entries, pagination=pagination) | Base | 1 |
def edit(request, user_id):
user = get_object_or_404(User, pk=user_id)
uform = UserForm(data=post_data(request), instance=user)
form = UserProfileForm(data=post_data(request), instance=user.st)
if is_post(request) and all([uform.is_valid(), form.is_valid()]):
uform.save()
form.save()
messages.info(request, _("This profile has been updated!"))
return redirect(request.GET.get("next", request.get_full_path()))
return render(
request=request,
template_name='spirit/user/admin/edit.html',
context={'form': form, 'uform': uform}) | Base | 1 |
def __init__(self, app, conf):
self.app = app
self.memcache_servers = conf.get('memcache_servers')
if not self.memcache_servers:
path = os.path.join(conf.get('swift_dir', '/etc/swift'),
'memcache.conf')
memcache_conf = ConfigParser()
if memcache_conf.read(path):
try:
self.memcache_servers = \
memcache_conf.get('memcache', 'memcache_servers')
except (NoSectionError, NoOptionError):
pass
if not self.memcache_servers:
self.memcache_servers = '127.0.0.1:11211'
self.memcache = MemcacheRing(
[s.strip() for s in self.memcache_servers.split(',') if s.strip()]) | Base | 1 |
def edit_book_languages(languages, book, upload=False, invalid=None):
input_languages = languages.split(',')
unknown_languages = []
if not upload:
input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages)
else:
input_l = isoLanguages.get_valid_language_codes(get_locale(), input_languages, unknown_languages)
for l in unknown_languages:
log.error("'%s' is not a valid language", l)
if isinstance(invalid, list):
invalid.append(l)
else:
raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l))
# ToDo: Not working correct
if upload and len(input_l) == 1:
# If the language of the file is excluded from the users view, it's not imported, to allow the user to view
# the book it's language is set to the filter language
if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all":
input_l[0] = calibre_db.session.query(db.Languages). \
filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code
# Remove duplicates
input_l = helper.uniq(input_l)
return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages') | Base | 1 |
def make_homeserver(self, reactor, clock):
self.hs = self.setup_test_homeserver(
"red", http_client=None, federation_client=Mock(),
)
self.hs.get_federation_handler = Mock()
self.hs.get_federation_handler.return_value.maybe_backfill = Mock(
return_value=make_awaitable(None)
)
async def _insert_client_ip(*args, **kwargs):
return None
self.hs.get_datastore().insert_client_ip = _insert_client_ip
return self.hs | Base | 1 |
def another_upload_file(request):
path = tempfile.mkdtemp()
file_name = os.path.join(path, "another_%s.txt" % request.node.name)
with open(file_name, "w") as f:
f.write(request.node.name)
return file_name | Base | 1 |
def __init__(self, expression, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expression.
ordering = (
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(expression, **extra)
self.ordering = self._parse_expressions(*ordering) | Base | 1 |
def visit_Call(self, call):
if call.func.id in INVALID_CALLS:
raise Exception("invalid function: %s" % call.func.id) | Class | 2 |
def on_permitted_domain(team: Team, request: HttpRequest) -> bool:
permitted_domains = ["127.0.0.1", "localhost"]
for url in team.app_urls:
hostname = parse_domain(url)
if hostname:
permitted_domains.append(hostname)
origin = parse_domain(request.headers.get("Origin"))
referer = parse_domain(request.headers.get("Referer"))
for permitted_domain in permitted_domains:
if "*" in permitted_domain:
pattern = "^{}$".format(permitted_domain.replace(".", "\\.").replace("*", "(.*)"))
if (origin and re.search(pattern, origin)) or (referer and re.search(pattern, referer)):
return True
else:
if permitted_domain == origin or permitted_domain == referer:
return True
return False | Base | 1 |
def get_credits(request, project=None, component=None):
"""View for credits."""
if project is None:
obj = None
kwargs = {"translation__isnull": False}
elif component is None:
obj = get_project(request, project)
kwargs = {"translation__component__project": obj}
else:
obj = get_component(request, project, component)
kwargs = {"translation__component": obj}
form = ReportsForm(request.POST)
if not form.is_valid():
show_form_errors(request, form)
return redirect_param(obj or "home", "#reports")
data = generate_credits(
None if request.user.has_perm("reports.view", obj) else request.user,
form.cleaned_data["start_date"],
form.cleaned_data["end_date"],
**kwargs,
)
if form.cleaned_data["style"] == "json":
return JsonResponse(data=data, safe=False)
if form.cleaned_data["style"] == "html":
start = "<table>"
row_start = "<tr>"
language_format = "<th>{0}</th>"
translator_start = "<td><ul>"
translator_format = '<li><a href="mailto:{0}">{1}</a> ({2})</li>'
translator_end = "</ul></td>"
row_end = "</tr>"
mime = "text/html"
end = "</table>"
else:
start = ""
row_start = ""
language_format = "* {0}\n"
translator_start = ""
translator_format = " * {1} <{0}> ({2})"
translator_end = ""
row_end = ""
mime = "text/plain"
end = ""
result = [start]
for language in data:
name, translators = language.popitem()
result.append(row_start)
result.append(language_format.format(name))
result.append(
translator_start
+ "\n".join(translator_format.format(*t) for t in translators)
+ translator_end
)
result.append(row_end)
result.append(end)
return HttpResponse("\n".join(result), content_type=f"{mime}; charset=utf-8") | Base | 1 |
def table_get_custom_enum(c_id):
ret = list()
cc = (calibre_db.session.query(db.Custom_Columns)
.filter(db.Custom_Columns.id == c_id)
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())
ret.append({'value': "", 'text': ""})
for idx, en in enumerate(cc.get_display_dict()['enum_values']):
ret.append({'value': en, 'text': en})
return json.dumps(ret) | Base | 1 |
def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
return_t = contract_sig.return_type
if return_t is None:
return ["pass"], 0, 0
return_t = calculate_type_for_external_return(return_t)
# if the abi signature has a different type than
# the vyper type, we need to wrap and unwrap the type
# so that the ABI decoding works correctly
should_unwrap_abi_tuple = return_t != contract_sig.return_type
abi_return_t = return_t.abi_type
min_return_size = abi_return_t.min_size()
max_return_size = abi_return_t.size_bound()
assert 0 < min_return_size <= max_return_size
ret_ofst = buf
ret_len = max_return_size
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
# TODO move the -1 optimization to IR optimizer
if not skip_contract_check:
ret += [["assert", ["gt", "returndatasize", min_return_size - 1]]]
# add as the last IRnode a pointer to the return data structure
# the return type has been wrapped by the calling contract;
# unwrap it so downstream code isn't confused.
# basically this expands to buf+32 if the return type has been wrapped
# in a tuple AND its ABI type is dynamic.
# in most cases, this simply will evaluate to ret.
# in the special case where the return type has been wrapped
# in a tuple AND its ABI type is dynamic, it expands to buf+32.
buf = IRnode(buf, typ=return_t, encoding=_returndata_encoding(contract_sig), location=MEMORY)
if should_unwrap_abi_tuple:
buf = get_element_ptr(buf, 0, array_bounds_check=False)
ret += [buf]
return ret, ret_ofst, ret_len | Class | 2 |
def initSession(self, expire_on_commit=True):
self.session = self.session_factory()
self.session.expire_on_commit = expire_on_commit
self.update_title_sort(self.config) | Base | 1 |
def author_list():
if current_user.check_visibility(constants.SIDEBAR_AUTHOR):
if current_user.get_view_property('author', 'dir') == 'desc':
order = db.Authors.sort.desc()
order_no = 0
else:
order = db.Authors.sort.asc()
order_no = 1
entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(text('books_authors_link.author')).order_by(order).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all()
# If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name
# starts a change session
autor_copy = copy.deepcopy(entries)
for entry in autor_copy:
entry.Authors.name = entry.Authors.name.replace('|', ',')
return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist,
title=u"Authors", page="authorlist", data='author', order=order_no)
else:
abort(404) | Base | 1 |
def _build_url(self, path, queries=()):
"""
Takes a relative path and query parameters, combines them with the
base path, and returns the result. Handles utf-8 encoding as necessary.
:param path: relative path for this request, relative to
self.base_prefix. NOTE: if this parameter starts with a
leading '/', this method will strip it and treat it as
relative. That is not a standards-compliant way to
combine path segments, so be aware.
:type path: basestring
:param queries: mapping object or a sequence of 2-element tuples,
in either case representing key-value pairs to be used
as query parameters on the URL.
:type queries: mapping object or sequence of 2-element tuples
:return: path that is a composite of self.path_prefix, path, and
queries. May be relative or absolute depending on the nature
of self.path_prefix
"""
# build the request url from the path and queries dict or tuple
if not path.startswith(self.path_prefix):
if path.startswith('/'):
path = path[1:]
path = '/'.join((self.path_prefix, path))
# Check if path is ascii and uses appropriate characters,
# else convert to binary or unicode as necessary.
try:
path = urllib.quote(str(path))
except UnicodeEncodeError:
path = urllib.quote(path.encode('utf-8'))
except UnicodeDecodeError:
path = urllib.quote(path.decode('utf-8'))
queries = urllib.urlencode(queries)
if queries:
path = '?'.join((path, queries))
return path | Base | 1 |
def home_get_preview():
vId = request.form['vId']
d = db.sentences_stats('get_preview', vId)
n = db.sentences_stats('id_networks', vId)
return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n}); | Base | 1 |
def test_level_as_none(self):
body = [ast.ImportFrom(module='time',
names=[ast.alias(name='sleep')],
level=None,
lineno=0, col_offset=0)]
mod = ast.Module(body)
code = compile(mod, 'test', 'exec')
ns = {}
exec(code, ns)
self.assertIn('sleep', ns) | Base | 1 |
def render_hot_books(page, order):
if current_user.check_visibility(constants.SIDEBAR_HOT):
if order[1] not in ['hotasc', 'hotdesc']:
# Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+
#if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or
# order[0][0].compare(func.count(ub.Downloads.book_id).asc())):
order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc'
if current_user.show_detail_random():
random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \
.order_by(func.random()).limit(config.config_random_books)
else:
random = false()
off = int(int(config.config_books_per_page) * (page - 1))
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\
.order_by(*order[0]).group_by(ub.Downloads.book_id)
hot_books = all_books.offset(off).limit(config.config_books_per_page)
entries = list()
for book in hot_books:
downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter(
db.Books.id == book.Downloads.book_id).first()
if downloadBook:
entries.append(downloadBook)
else:
ub.delete_download(book.Downloads.book_id)
numBooks = entries.__len__()
pagination = Pagination(page, config.config_books_per_page, numBooks)
return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1])
else:
abort(404) | Base | 1 |
def test_notfilelike_http10(self):
to_send = "GET /notfilelike HTTP/1.0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def deserialize(self, content, format='application/json'):
"""
Given some data and a format, calls the correct method to deserialize
the data and returns the result.
"""
desired_format = None
format = format.split(';')[0]
for short_format, long_format in self.content_types.items():
if format == long_format:
if hasattr(self, "from_%s" % short_format):
desired_format = short_format
break
if desired_format is None:
raise UnsupportedFormat("The format indicated '%s' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format)
deserialized = getattr(self, "from_%s" % desired_format)(content)
return deserialized | Class | 2 |
def from_html(self, content):
"""
Reserved for future usage.
The desire is to handle form-based (maybe Javascript?) input, making an
API available to a browser. This is on the TODO list but not currently
implemented.
"""
pass | Class | 2 |
def test_get_header_lines(self):
result = self._callFUT(b"slam\nslim")
self.assertEqual(result, [b"slam", b"slim"]) | Base | 1 |
def testOrdering(self):
import six
import random
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.int32, name='x')
pi = array_ops.placeholder(dtypes.int64, name='pi')
gi = array_ops.placeholder(dtypes.int64, name='gi')
with ops.device(test.gpu_device_name()):
stager = data_flow_ops.MapStagingArea(
[
dtypes.int32,
], shapes=[[]], ordered=True)
stage = stager.put(pi, [x], [0])
get = stager.get()
size = stager.size()
G.finalize()
n = 10
with self.session(graph=G) as sess:
# Keys n-1..0
keys = list(reversed(six.moves.range(n)))
for i in keys:
sess.run(stage, feed_dict={pi: i, x: i})
self.assertTrue(sess.run(size) == n)
# Check that key, values come out in ascending order
for i, k in enumerate(reversed(keys)):
get_key, values = sess.run(get)
self.assertTrue(i == k == get_key == values)
self.assertTrue(sess.run(size) == 0) | Base | 1 |
def __init__(self, hs):
self.server_name = hs.hostname
self.client = hs.get_http_client() | Base | 1 |
def list_users():
off = int(request.args.get("offset") or 0)
limit = int(request.args.get("limit") or 10)
search = request.args.get("search")
sort = request.args.get("sort", "id")
state = None
if sort == "state":
state = json.loads(request.args.get("state", "[]"))
else:
if sort not in ub.User.__table__.columns.keys():
sort = "id"
order = request.args.get("order", "").lower()
if sort != "state" and order:
order = text(sort + " " + order)
elif not state:
order = ub.User.id.asc()
all_user = ub.session.query(ub.User)
if not config.config_anonbrowse:
all_user = all_user.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS)
total_count = filtered_count = all_user.count()
if search:
all_user = all_user.filter(or_(func.lower(ub.User.name).ilike("%" + search + "%"),
func.lower(ub.User.kindle_mail).ilike("%" + search + "%"),
func.lower(ub.User.email).ilike("%" + search + "%")))
if state:
users = calibre_db.get_checkbox_sorted(all_user.all(), state, off, limit, request.args.get("order", "").lower())
else:
users = all_user.order_by(order).offset(off).limit(limit).all()
if search:
filtered_count = len(users)
for user in users:
if user.default_language == "all":
user.default = _("All")
else:
user.default = LC.parse(user.default_language).get_language_name(get_locale())
table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": users}
js_list = json.dumps(table_entries, cls=db.AlchemyEncoder)
response = make_response(js_list)
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response | Base | 1 |
def fetch(cls) -> "InstanceConfig":
entry = cls.get(get_instance_name())
if entry is None:
entry = cls()
entry.save()
return entry | Class | 2 |
def test_get_frontend_context_variables_safe(component):
# Set component.name to a potential XSS attack
component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
class Meta:
safe = [
"name",
]
setattr(component, "Meta", Meta())
frontend_context_variables = component.get_frontend_context_variables()
frontend_context_variables_dict = orjson.loads(frontend_context_variables)
assert len(frontend_context_variables_dict) == 1
assert (
frontend_context_variables_dict.get("name")
== '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
) | Base | 1 |
def render_POST(self, request):
"""
Register with the Identity Server
"""
send_cors(request)
args = get_args(request, ('matrix_server_name', 'access_token'))
result = yield self.client.get_json(
"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s" % (
args['matrix_server_name'], urllib.parse.quote(args['access_token']),
),
1024 * 5,
)
if 'sub' not in result:
raise Exception("Invalid response from homeserver")
user_id = result['sub']
tok = yield issueToken(self.sydent, user_id)
# XXX: `token` is correct for the spec, but we released with `access_token`
# for a substantial amount of time. Serve both to make spec-compliant clients
# happy.
defer.returnValue({
"access_token": tok,
"token": tok,
}) | Base | 1 |
def test_remote_static(app):
"""Test endpoint that serves files as a logged user"""
# GIVEN a file on disk
file = "../demo/ACC5963A1_lanes_1234_star_sorted_sj_filtered_sorted.bed.gz"
# GIVEN a running demo app
with app.test_client() as client:
# GIVEN that user is logged in
client.get(url_for("auto_login"))
with client.session_transaction() as session:
# GIVEN that resource file exists in user session
session["igv_tracks"] = [file]
# THEN the resource should be available to the user
resp = client.get(
url_for(
"alignviewers.remote_static",
file=file,
)
)
assert resp.status_code == 200 | Base | 1 |
async def initialize(self, bot):
# temporary backwards compatibility
key = await self.config.tenorkey()
if not key:
return
await bot.set_shared_api_tokens("tenor", api_key=key)
await self.config.tenorkey.clear()
| Base | 1 |
def test_http10_list(self):
body = string.ascii_letters
to_send = (
"GET /list HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: %d\n\n" % len(body)
)
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers["content-length"], str(len(body)))
self.assertEqual(headers.get("connection"), "Keep-Alive")
self.assertEqual(response_body, tobytes(body))
# remote keeps connection open because it divined the content length
# from a length-1 list
self.sock.send(to_send)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0") | Base | 1 |
def get_file(recipe):
if not recipe.link:
recipe.link = Dropbox.get_share_link(recipe)
recipe.save()
response = requests.get(recipe.link.replace('www.dropbox.', 'dl.dropboxusercontent.'))
return io.BytesIO(response.content) | Base | 1 |
def test_get_problem_responses_already_running(self):
"""
Test whether get_problem_responses returns an appropriate status
message if CSV generation is already in progress.
"""
url = reverse(
'get_problem_responses',
kwargs={'course_id': unicode(self.course.id)}
)
with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function:
error = AlreadyRunningError()
submit_task_function.side_effect = error
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertIn('already in progress', res_json['status']) | Compound | 4 |
def generate_subparsers(root, parent_parser, definitions):
action_dest = '_'.join(parent_parser.prog.split()[1:] + ['action'])
actions = parent_parser.add_subparsers(
dest=action_dest
)
for command, properties in definitions.items():
is_subparser = isinstance(properties, dict)
descr = properties.pop('help', None) if is_subparser else properties.pop(0)
command_parser = actions.add_parser(command, description=descr)
command_parser.root = root
if is_subparser:
generate_subparsers(root, command_parser, properties)
continue
for argument in properties:
command_parser.add_argument(**argument) | Class | 2 |
def opds_download_link(book_id, book_format):
# I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest
# workaround, loading the user from the request and checking it's download rights here
# in case of anonymous browsing user is None
user = load_user_from_request(request) or current_user
if not user.role_download():
return abort(403)
if "Kobo" in request.headers.get('User-Agent'):
client = "kobo"
else:
client = ""
return get_download_link(book_id, book_format.lower(), client) | Base | 1 |
def func_begin(self, name):
ctype = get_c_type(name)
self.emit("PyObject*", 0)
self.emit("ast2obj_%s(void* _o)" % (name), 0)
self.emit("{", 0)
self.emit("%s o = (%s)_o;" % (ctype, ctype), 1)
self.emit("PyObject *result = NULL, *value = NULL;", 1)
self.emit('if (!o) {', 1)
self.emit("Py_INCREF(Py_None);", 2)
self.emit('return Py_None;', 2)
self.emit("}", 1)
self.emit('', 0) | Base | 1 |
def process_response(self, request, response, spider):
if (
request.meta.get('dont_redirect', False)
or response.status in getattr(spider, 'handle_httpstatus_list', [])
or response.status in request.meta.get('handle_httpstatus_list', [])
or request.meta.get('handle_httpstatus_all', False)
):
return response
allowed_status = (301, 302, 303, 307, 308)
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['Location'])
if response.headers['Location'].startswith(b'//'):
request_scheme = urlparse(request.url).scheme
location = request_scheme + '://' + location.lstrip('/')
redirected_url = urljoin(request.url, location)
if response.status in (301, 307, 308) or request.method == 'HEAD':
redirected = request.replace(url=redirected_url)
return self._redirect(redirected, request, spider, response.status)
redirected = self._redirect_request_using_get(request, redirected_url)
return self._redirect(redirected, request, spider, response.status) | Class | 2 |
def count(cls, **kwargs):
"""Return a count of server side resources given
filtering arguments in kwargs.
"""
url = urljoin(recurly.base_uri(), cls.collection_path)
if kwargs:
url = '%s?%s' % (url, urlencode(kwargs))
return Page.count_for_url(url) | Base | 1 |
def render_prepare_search_form(cc):
# prepare data for search-form
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(text('books_tags_link.tag'))\
.order_by(db.Tags.name).all()
series = calibre_db.session.query(db.Series)\
.join(db.books_series_link)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(text('books_series_link.series'))\
.order_by(db.Series.name)\
.filter(calibre_db.common_filters()).all()
shelves = ub.session.query(ub.Shelf)\
.filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(current_user.id)))\
.order_by(ub.Shelf.name).all()
extensions = calibre_db.session.query(db.Data)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(db.Data.format)\
.order_by(db.Data.format).all()
if current_user.filter_language() == u"all":
languages = calibre_db.speaking_language()
else:
languages = None
return render_title_template('search_form.html', tags=tags, languages=languages, extensions=extensions,
series=series,shelves=shelves, title=_(u"Advanced Search"), cc=cc, page="advsearch") | Base | 1 |
def uniq(inpt):
output = []
inpt = [ " ".join(inp.split()) for inp in inpt]
for x in inpt:
if x not in output:
output.append(x)
return output | Base | 1 |
def test_auth_type_stored_in_session_file(self, httpbin):
self.config_dir = mk_config_dir()
self.session_path = self.config_dir / 'test-session.json'
class Plugin(AuthPlugin):
auth_type = 'test-saved'
auth_require = True
def get_auth(self, username=None, password=None):
return basic_auth()
plugin_manager.register(Plugin)
http('--session', str(self.session_path),
httpbin + '/basic-auth/user/password',
'--auth-type',
Plugin.auth_type,
'--auth', 'user:password',
)
updated_session = json.loads(self.session_path.read_text(encoding=UTF8))
assert updated_session['auth']['type'] == 'test-saved'
assert updated_session['auth']['raw_auth'] == "user:password"
plugin_manager.unregister(Plugin) | Class | 2 |
def test_rescore_problem_all(self, act):
""" Test rescoring for all students. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | Compound | 4 |
def __init__(self):
field_infos = [
FieldInfo.factory(key)
for key in list(request.form.keys()) + list(request.files.keys())
]
# important to sort them so they will be in expected order on command line
self.field_infos = list(sorted(field_infos))
| Compound | 4 |
def refresh(self):
"""
Security endpoint for the refresh token, so we can obtain a new
token without forcing the user to login again
---
post:
description: >-
Use the refresh token to get a new JWT access token
responses:
200:
description: Refresh Successful
content:
application/json:
schema:
type: object
properties:
access_token:
description: A new refreshed access token
type: string
401:
$ref: '#/components/responses/401'
500:
$ref: '#/components/responses/500'
security:
- jwt_refresh: []
"""
resp = {
API_SECURITY_ACCESS_TOKEN_KEY: create_access_token(
identity=get_jwt_identity(), fresh=False
)
}
return self.response(200, **resp) | Class | 2 |
def __setitem__(self, key, value):
self.dict[_hkey(key)] = [value if isinstance(value, unicode) else
str(value)] | Base | 1 |
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):
"""
Test update forum role membership.
Get unique_student_identifier, rolename and action and update forum role.
"""
url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(
url,
{
'unique_student_identifier': identifier,
'rolename': rolename,
'action': action,
}
)
# Status code should be 200.
self.assertEqual(response.status_code, 200)
user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
if action == 'allow':
self.assertIn(rolename, user_roles)
elif action == 'revoke':
self.assertNotIn(rolename, user_roles) | Compound | 4 |
def preprocess_input_exprs_arg_string(input_exprs_str):
"""Parses input arg into dictionary that maps input key to python expression.
Parses input string in the format of 'input_key=<python expression>' into a
dictionary that maps each input_key to its python expression.
Args:
input_exprs_str: A string that specifies python expression for input keys.
Each input is separated by semicolon. For each input key:
'input_key=<python expression>'
Returns:
A dictionary that maps input keys to their values.
Raises:
RuntimeError: An error when the given input string is in a bad format.
"""
input_dict = {}
for input_raw in filter(bool, input_exprs_str.split(';')):
if '=' not in input_exprs_str:
raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow'
'"<input_key>=<python expression>"' % input_exprs_str)
input_key, expr = input_raw.split('=', 1)
# ast.literal_eval does not work with numpy expressions
input_dict[input_key] = eval(expr) # pylint: disable=eval-used
return input_dict | Base | 1 |
def feed_hot():
off = request.args.get("offset") or 0
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
hot_books = all_books.offset(off).limit(config.config_books_per_page)
entries = list()
for book in hot_books:
downloadBook = calibre_db.get_book(book.Downloads.book_id)
if downloadBook:
entries.append(
calibre_db.get_filtered_book(book.Downloads.book_id)
)
else:
ub.delete_download(book.Downloads.book_id)
numBooks = entries.__len__()
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1),
config.config_books_per_page, numBooks)
return render_xml_template('feed.xml', entries=entries, pagination=pagination) | Base | 1 |
def setUp(self):
self.mock_federation = Mock()
self.mock_registry = Mock()
self.query_handlers = {}
def register_query_handler(query_type, handler):
self.query_handlers[query_type] = handler
self.mock_registry.register_query_handler = register_query_handler
hs = yield setup_test_homeserver(
self.addCleanup,
http_client=None,
resource_for_federation=Mock(),
federation_client=self.mock_federation,
federation_server=Mock(),
federation_registry=self.mock_registry,
)
self.store = hs.get_datastore()
self.frank = UserID.from_string("@1234ABCD:test")
self.bob = UserID.from_string("@4567:test")
self.alice = UserID.from_string("@alice:remote")
yield defer.ensureDeferred(self.store.create_profile(self.frank.localpart))
self.handler = hs.get_profile_handler()
self.hs = hs | Base | 1 |
def test_parse_www_authenticate_correct(data, strict):
headers, info = data
# FIXME: move strict to parse argument
httplib2.USE_WWW_AUTH_STRICT_PARSING = strict
try:
assert httplib2._parse_www_authenticate(headers) == info
finally:
httplib2.USE_WWW_AUTH_STRICT_PARSING = 0 | Class | 2 |
def render_edit_book(book_id):
cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)
if not book:
flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error")
return redirect(url_for("web.index"))
for lang in book.languages:
lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code)
book.authors = calibre_db.order_authors([book])
author_names = []
for authr in book.authors:
author_names.append(authr.name.replace('|', ','))
# Option for showing convertbook button
valid_source_formats=list()
allowed_conversion_formats = list()
kepub_possible=None
if config.config_converterpath:
for file in book.data:
if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM:
valid_source_formats.append(file.format.lower())
if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]:
kepub_possible = True
if not config.config_converterpath:
valid_source_formats.append('epub')
# Determine what formats don't already exist
if config.config_converterpath:
allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:]
for file in book.data:
if file.format.lower() in allowed_conversion_formats:
allowed_conversion_formats.remove(file.format.lower())
if kepub_possible:
allowed_conversion_formats.append('kepub')
return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc,
title=_(u"edit metadata"), page="editbook",
conversion_formats=allowed_conversion_formats,
config=config,
source_formats=valid_source_formats) | Base | 1 |
def test_invoice_payment_is_still_pending_for_registration_codes(self):
"""
test generate enrollment report
enroll a user in a course using registration code
whose invoice has not been paid yet
"""
course_registration_code = CourseRegistrationCode.objects.create(
code='abcde',
course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor,
invoice=self.sale_invoice_1,
invoice_item=self.invoice_item,
mode_slug='honor'
)
test_user1 = UserFactory()
self.register_with_redemption_code(test_user1, course_registration_code.code)
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
self.client.login(username=self.instructor.username, password='test')
url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
self.assertIn('The detailed enrollment report is being created.', response.content) | Compound | 4 |
def test_get_sale_records_features_json(self):
"""
Test that the response from get_sale_records is in json format.
"""
for i in range(5):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i),
course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor,
invoice=self.sale_invoice_1,
invoice_item=self.invoice_item,
mode_slug='honor'
)
course_registration_code.save()
url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('sale', res_json)
for res in res_json['sale']:
self.validate_sale_records_response(
res,
course_registration_code,
self.sale_invoice_1,
0,
invoice_item=self.invoice_item
) | Compound | 4 |
def __init__(self, sydent):
self.sydent = sydent
# The default endpoint factory in Twisted 14.0.0 (which we require) uses the
# BrowserLikePolicyForHTTPS context factory which will do regular cert validation
# 'like a browser'
self.agent = Agent(
self.sydent.reactor,
connectTimeout=15,
) | Class | 2 |
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None, | Class | 2 |
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) | Base | 1 |
async def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], | Base | 1 |
def prepare(self, reactor, clock, homeserver):
# make a second homeserver, configured to use the first one as a key notary
self.http_client2 = Mock()
config = default_config(name="keyclient")
config["trusted_key_servers"] = [
{
"server_name": self.hs.hostname,
"verify_keys": {
"ed25519:%s"
% (
self.hs_signing_key.version,
): signedjson.key.encode_verify_key_base64(
self.hs_signing_key.verify_key
)
},
}
]
self.hs2 = self.setup_test_homeserver(
http_client=self.http_client2, config=config
)
# wire up outbound POST /key/v2/query requests from hs2 so that they
# will be forwarded to hs1
async def post_json(destination, path, data):
self.assertEqual(destination, self.hs.hostname)
self.assertEqual(
path, "/_matrix/key/v2/query",
)
channel = FakeChannel(self.site, self.reactor)
req = SynapseRequest(channel)
req.content = BytesIO(encode_canonical_json(data))
req.requestReceived(
b"POST", path.encode("utf-8"), b"1.1",
)
channel.await_result()
self.assertEqual(channel.code, 200)
resp = channel.json_body
return resp
self.http_client2.post_json.side_effect = post_json | Base | 1 |
def remote_static():
"""Stream *large* static files with special requirements."""
file_path = request.args.get("file") or "."
# Check that user is logged in or that file extension is valid
if current_user.is_authenticated is False or file_path not in session.get("igv_tracks", []):
LOG.warning(f"{file_path} not in {session.get('igv_tracks', [])}")
return abort(403)
range_header = request.headers.get("Range", None)
if not range_header and (file_path.endswith(".bam") or file_path.endswith(".cram")):
return abort(500)
new_resp = send_file_partial(file_path)
return new_resp | Base | 1 |
def get_response(self):
token_serializer = self.token_serializer_class(
instance=self.token,
context=self.get_serializer_context(),
)
data = token_serializer.data
data['next'] = self.serializer.validated_data['code'].next
return Response(data, status=status.HTTP_200_OK) | Base | 1 |
def test_list_background_email_tasks(self, act):
"""Test list of background email tasks."""
act.return_value = self.tasks
url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks) | Compound | 4 |
def test_session_with_cookie_followed_by_another_header(self, httpbin):
"""
Make sure headers don’t get mutated — <https://github.com/httpie/httpie/issues/1126>
"""
self.start_session(httpbin)
session_data = {
"headers": {
"cookie": "...",
"zzz": "..."
}
}
session_path = self.config_dir / 'session-data.json'
session_path.write_text(json.dumps(session_data))
r = http('--session', str(session_path), 'GET', httpbin.url + '/get',
env=self.env())
assert HTTP_OK in r
assert 'Zzz' in r | Class | 2 |
def check_unrar(unrarLocation):
if not unrarLocation:
return
if not os.path.exists(unrarLocation):
return _('Unrar binary file not found')
try:
unrarLocation = [unrarLocation]
value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')
if value:
version = value.group(1)
log.debug("unrar version %s", version)
except (OSError, UnicodeDecodeError) as err:
log.error_or_exception(err)
return _('Error excecuting UnRar') | Base | 1 |
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
ImportError: if yaml module is not found.
"""
if yaml is None:
raise ImportError(
'Requires yaml module installed (`pip install pyyaml`).')
return yaml.dump(self._updated_config(), **kwargs) | Base | 1 |
def custom_logout(request, **kwargs):
if not request.user.is_authenticated:
return redirect(request.GET.get('next', reverse(settings.LOGIN_URL)))
if request.method == 'POST':
return _logout_view(request, **kwargs)
return render(request, 'spirit/user/auth/logout.html') | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.