_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15300 | setup | train | def setup(service_manager, conf, reload_method="reload"):
"""Load services configuration from oslo config object.
It reads ServiceManager and Service configuration options from an
oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to
reload the configuration file on reload in the ... | python | {
"resource": ""
} |
q15301 | ServiceManager.register_hooks | train | def register_hooks(self, on_terminate=None, on_reload=None,
on_new_worker=None, on_dead_worker=None):
"""Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will ... | python | {
"resource": ""
} |
q15302 | ServiceManager.add | train | def add(self, service, workers=1, args=None, kwargs=None):
"""Add a new service to the ServiceManager
:param service: callable that return an instance of :py:class:`Service`
:type service: callable
:param workers: number of processes/workers for this service
:type workers: int
... | python | {
"resource": ""
} |
q15303 | ServiceManager.reconfigure | train | def reconfigure(self, service_id, workers):
"""Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError
""... | python | {
"resource": ""
} |
q15304 | ServiceManager.run | train | def run(self):
"""Start and supervise services workers
This method will start and supervise all children processes
until the master process asked to shutdown by a SIGTERM.
All spawned processes are part of the same unix process group.
"""
self._systemd_notify_once()
... | python | {
"resource": ""
} |
q15305 | ServiceManager._reload | train | def _reload(self):
"""reload all children
posix only
"""
self._run_hooks('reload')
# Reset forktimes to respawn services quickly
self._forktimes = []
signal.signal(signal.SIGHUP, signal.SIG_IGN)
os.killpg(0, signal.SIGHUP)
signal.signal(signal.SI... | python | {
"resource": ""
} |
q15306 | ServiceManager._get_last_worker_died | train | def _get_last_worker_died(self):
"""Return the last died worker information or None"""
for service_id in list(self._running_services.keys()):
# We copy the list to clean the orignal one
processes = list(self._running_services[service_id].items())
for process, worker_i... | python | {
"resource": ""
} |
q15307 | ServiceManager._systemd_notify_once | train | def _systemd_notify_once():
"""Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
not... | python | {
"resource": ""
} |
q15308 | accepts | train | def accepts(*argtypes, **kwargtypes):
"""A function decorator to specify argument types of the function.
Types may be specified either in the order that they appear in the
function or via keyword arguments (just as if you were calling the
function).
Example usage:
| @accepts(Positive0)
... | python | {
"resource": ""
} |
q15309 | returns | train | def returns(returntype):
"""A function decorator to specify return type of the function.
Example usage:
| @accepts(Positive0)
| @returns(Positive0)
| def square_root(x):
| ...
"""
returntype = T.TypeFactory(returntype)
def _decorator(func):
# @returns decorator
... | python | {
"resource": ""
} |
q15310 | requires | train | def requires(condition):
"""A function decorator to specify entry conditions for the function.
Entry conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name.
The special syntax "-->" and "<-->" may be used to mean "if" and
... | python | {
"resource": ""
} |
q15311 | ensures | train | def ensures(condition):
"""A function decorator to specify exit conditions for the function.
Exit conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name. The return value of the function may be accessed using the
special vari... | python | {
"resource": ""
} |
q15312 | paranoidclass | train | def paranoidclass(cls):
"""A class decorator to specify that class methods contain paranoid decorators.
Example usage:
| @paranoidclass
| class Point:
| def __init__(self, x, y):
| ...
| @returns(Number)
| def distance_from_zero():
| ...
... | python | {
"resource": ""
} |
q15313 | paranoidconfig | train | def paranoidconfig(**kwargs):
"""A function decorator to set a local setting.
Settings may be set either globally (using
settings.Settings.set()) or locally using this decorator. The
setting name should be passed as a keyword argument, and the value
to assign the setting should be passed as the va... | python | {
"resource": ""
} |
q15314 | TypeFactory | train | def TypeFactory(v):
"""Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.... | python | {
"resource": ""
} |
q15315 | profile_v3_to_proofs | train | def profile_v3_to_proofs(profile, fqdn, refresh=False, address = None):
"""
Convert profile format v3 to proofs
"""
proofs = []
try:
test = profile.items()
except:
return proofs
if 'account' in profile:
accounts = profile['account']
else:
return pro... | python | {
"resource": ""
} |
q15316 | has_fun_prop | train | def has_fun_prop(f, k):
"""Test whether function `f` has property `k`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` is an unannotated function, this returns
False. If `f` has the property na... | python | {
"resource": ""
} |
q15317 | get_fun_prop | train | def get_fun_prop(f, k):
"""Get the value of property `k` from function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` does not have a property named `k`, this
throws an error. If `f` has ... | python | {
"resource": ""
} |
q15318 | set_fun_prop | train | def set_fun_prop(f, k, v):
"""Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
... | python | {
"resource": ""
} |
q15319 | Settings.set | train | def set(**kwargs):
"""Set configuration parameters.
Pass keyword arguments for the parameters you would like to
set.
This function is particularly useful to call at the head of
your script file to disable particular features. For example,
>>> from paranoid.settings ... | python | {
"resource": ""
} |
q15320 | Settings._set | train | def _set(name, value, function=None):
"""Internally set a config parameter.
If you call it with no function, it sets the global parameter.
If you call it with a function argument, it sets the value for
the specified function. Normally, this should only be called
with a function... | python | {
"resource": ""
} |
q15321 | Settings.get | train | def get(name, function=None):
"""Get a setting.
`name` should be the name of the setting to look for. If the
optional argument `function` is passed, this will look for a
value local to the function before retrieving the global
value.
"""
if function is not None:... | python | {
"resource": ""
} |
q15322 | Demon.__read_graph | train | def __read_graph(self, network_filename):
"""
Read .ncol network file
:param network_filename: complete path for the .ncol file
:return: an undirected network
"""
self.g = nx.read_edgelist(network_filename, nodetype=int) | python | {
"resource": ""
} |
q15323 | Demon.execute | train | def execute(self):
"""
Execute Demon algorithm
"""
for n in self.g.nodes():
self.g.node[n]['communities'] = [n]
all_communities = {}
for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'):
ego_minus_ego = nx.ego_grap... | python | {
"resource": ""
} |
q15324 | get_declared_enums | train | def get_declared_enums(metadata, schema, default):
"""
Return a dict mapping SQLAlchemy enumeration types to the set of their
declared values.
:param metadata:
...
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "... | python | {
"resource": ""
} |
q15325 | compare_enums | train | def compare_enums(autogen_context, upgrade_ops, schema_names):
"""
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared versio... | python | {
"resource": ""
} |
q15326 | Memoizer.get | train | def get(self, key, func=None, args=(), kwargs=None, **opts):
"""Manually retrieve a value from the cache, calculating as needed.
Params:
key -> string to store/retrieve value from.
func -> callable to generate value if it does not exist, or has
expired.
... | python | {
"resource": ""
} |
q15327 | Memoizer.expire_at | train | def expire_at(self, key, expiry, **opts):
"""Set the explicit unix expiry time of a key."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
if data is not None:
data = list(data)
data[EXPIRY_INDEX] = expiry
store[key] = tuple(data)
... | python | {
"resource": ""
} |
q15328 | Memoizer.expire | train | def expire(self, key, max_age, **opts):
"""Set the maximum age of a given key, in seconds."""
self.expire_at(key, time() + max_age, **opts) | python | {
"resource": ""
} |
q15329 | Memoizer.ttl | train | def ttl(self, key, **opts):
"""Get the time-to-live of a given key; None if not set."""
key, store = self._expand_opts(key, opts)
if hasattr(store, 'ttl'):
return store.ttl(key)
data = store.get(key)
if data is None:
return None
expiry = data[EXPIR... | python | {
"resource": ""
} |
q15330 | Memoizer.exists | train | def exists(self, key, **opts):
"""Return if a key exists in the cache."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
# Note that we do not actually delete the thing here as the max_age
# just for this call may have triggered a False.
if not data or se... | python | {
"resource": ""
} |
q15331 | WindowCursor._destroy | train | def _destroy(self):
"""Destruction code to decrement counters"""
self.unuse_region()
if self._rlist is not None:
# Actual client count, which doesn't include the reference kept by the manager, nor ours
# as we are about to be deleted
try:
if l... | python | {
"resource": ""
} |
q15332 | WindowCursor._copy_from | train | def _copy_from(self, rhs):
"""Copy all data from rhs into this instance, handles usage count"""
self._manager = rhs._manager
self._rlist = type(rhs._rlist)(rhs._rlist)
self._region = rhs._region
self._ofs = rhs._ofs
self._size = rhs._size
for region in self._rlis... | python | {
"resource": ""
} |
q15333 | WindowCursor.use_region | train | def use_region(self, offset=0, size=0, flags=0):
"""Assure we point to a window which allows access to the given offset into the file
:param offset: absolute offset in bytes into the file
:param size: amount of bytes to map. If 0, all available bytes will be mapped
:param flags: additio... | python | {
"resource": ""
} |
q15334 | StaticWindowMapManager.num_open_files | train | def num_open_files(self):
"""Amount of opened files in the system"""
return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0) | python | {
"resource": ""
} |
q15335 | align_to_mmap | train | def align_to_mmap(num, round_up):
"""
Align the given integer number to the closest page offset, which usually is 4096 bytes.
:param round_up: if True, the next higher multiple of page size is used, otherwise
the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0)
... | python | {
"resource": ""
} |
q15336 | MapWindow.align | train | def align(self):
"""Assures the previous window area is contained in the new one"""
nofs = align_to_mmap(self.ofs, 0)
self.size += self.ofs - nofs # keep size constant
self.ofs = nofs
self.size = align_to_mmap(self.size, 1) | python | {
"resource": ""
} |
q15337 | MapWindow.extend_left_to | train | def extend_left_to(self, window, max_size):
"""Adjust the offset to start where the given window on our left ends if possible,
but don't make yourself larger than max_size.
The resize will assure that the new window still contains the old window area"""
rofs = self.ofs - window.ofs_end()... | python | {
"resource": ""
} |
q15338 | MapWindow.extend_right_to | train | def extend_right_to(self, window, max_size):
"""Adjust the size to make our window end where the right window begins, but don't
get larger than max_size"""
self.size = min(self.size + (window.ofs - self.ofs_end()), max_size) | python | {
"resource": ""
} |
q15339 | SlidingWindowMapBuffer.begin_access | train | def begin_access(self, cursor=None, offset=0, size=sys.maxsize, flags=0):
"""Call this before the first use of this instance. The method was already
called by the constructor in case sufficient information was provided.
For more information no the parameters, see the __init__ method
:pa... | python | {
"resource": ""
} |
q15340 | make_parser | train | def make_parser():
"""
Returns an argparse instance for this script.
"""
parser = argparse.ArgumentParser(description="generate HTML from crawler JSON")
parser.add_argument(
"--data-dir", default="data",
help=u"Directory containing JSON data from crawler [%(default)s]"
)
pars... | python | {
"resource": ""
} |
q15341 | render_template | train | def render_template(env, html_path, template_filename, context):
"""
Render a template file into the given output location.
"""
template = env.get_template(template_filename)
rendered_html = template.render(**context) # pylint: disable=no-member
html_path.write_text(rendered_html, encoding='utf... | python | {
"resource": ""
} |
q15342 | render_html | train | def render_html(data_dir, output_dir):
"""
The main workhorse of this script. Finds all the JSON data files
from pa11ycrawler, and transforms them into HTML files via Jinja2 templating.
"""
env = Environment(loader=PackageLoader('pa11ycrawler', 'templates'))
env.globals["wcag_refs"] = wcag_refs
... | python | {
"resource": ""
} |
q15343 | ignore_rules_for_url | train | def ignore_rules_for_url(spider, url):
"""
Returns a list of ignore rules from the given spider,
that are relevant to the given URL.
"""
ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {}
return itertools.chain.from_iterable(
rule_list
for url_glob, rule_list
... | python | {
"resource": ""
} |
q15344 | load_pa11y_results | train | def load_pa11y_results(stdout, spider, url):
"""
Load output from pa11y, filtering out the ignored messages.
The `stdout` parameter is a bytestring, not a unicode string.
"""
if not stdout:
return []
results = json.loads(stdout.decode('utf8'))
ignore_rules = ignore_rules_for_url(sp... | python | {
"resource": ""
} |
q15345 | write_pa11y_config | train | def write_pa11y_config(item):
"""
The only way that pa11y will see the same page that scrapy sees
is to make sure that pa11y requests the page with the same headers.
However, the only way to configure request headers with pa11y is to
write them into a config file.
This function will create a co... | python | {
"resource": ""
} |
q15346 | write_pa11y_results | train | def write_pa11y_results(item, pa11y_results, data_dir):
"""
Write the output from pa11y into a data file.
"""
data = dict(item)
data['pa11y'] = pa11y_results
# it would be nice to use the URL as the filename,
# but that gets complicated (long URLs, special characters, etc)
# so we'll ma... | python | {
"resource": ""
} |
q15347 | Pa11yPipeline.process_item | train | def process_item(self, item, spider):
"""
Use the Pa11y command line tool to get an a11y report.
"""
config_file = write_pa11y_config(item)
args = [
self.pa11y_path,
item["url"],
'--config={file}'.format(file=config_file.name),
]
... | python | {
"resource": ""
} |
q15348 | watched_extension | train | def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False | python | {
"resource": ""
} |
q15349 | _watch_folder | train | def _watch_folder(folder, destination, compiler_args):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
# Ignore filenames starting with ".#" for Emacs compatibil... | python | {
"resource": ""
} |
q15350 | compile_file | train | def compile_file(fullpath, outfile_name, compiler_args):
"""Calls HamlPy compiler."""
if Options.VERBOSE:
print '%s %s -> %s' % (strftime("%H:%M:%S"), fullpath, outfile_name)
try:
if Options.DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.... | python | {
"resource": ""
} |
q15351 | DuplicatesPipeline.process_item | train | def process_item(self, item, spider): # pylint: disable=unused-argument
"""
Stops processing item if we've already seen this URL before.
"""
url = self.clean_url(item["url"])
if self.is_sequence_start_page(url):
url = url.parent
if url in self.urls_seen:
... | python | {
"resource": ""
} |
q15352 | DropDRFPipeline.process_item | train | def process_item(self, item, spider): # pylint: disable=unused-argument
"Check for DRF urls."
url = URLObject(item["url"])
if url.path.startswith("/api/"):
raise DropItem(u"Dropping DRF url {url}".format(url=url))
else:
return item | python | {
"resource": ""
} |
q15353 | get_csrf_token | train | def get_csrf_token(response):
"""
Extract the CSRF token out of the "Set-Cookie" header of a response.
"""
cookie_headers = [
h.decode('ascii') for h in response.headers.getlist("Set-Cookie")
]
if not cookie_headers:
return None
csrf_headers = [
h for h in cookie_head... | python | {
"resource": ""
} |
q15354 | load_pa11y_ignore_rules | train | def load_pa11y_ignore_rules(file=None, url=None): # pylint: disable=redefined-builtin
"""
Load the pa11y ignore rules from the given file or URL.
"""
if not file and not url:
return None
if file:
file = Path(file)
if not file.isfile():
msg = (
u"... | python | {
"resource": ""
} |
q15355 | EdxSpider.handle_error | train | def handle_error(self, failure):
"""
Provides basic error information for bad requests.
If the error was an HttpError or DNSLookupError, it
prints more specific information.
"""
self.logger.error(repr(failure))
if failure.check(HttpError):
response = ... | python | {
"resource": ""
} |
q15356 | EdxSpider.parse_item | train | def parse_item(self, response):
"""
Get basic information about a page, so that it can be passed to the
`pa11y` tool for further testing.
@url https://www.google.com/
@returns items 1 1
@returns requests 0 0
@scrapes url request_headers accessed_at page_title
... | python | {
"resource": ""
} |
q15357 | EdxSpider.handle_unexpected_redirect_to_login_page | train | def handle_unexpected_redirect_to_login_page(self, response):
"""
This method is called if the crawler has been unexpectedly logged out.
If that happens, and the crawler requests a page that requires a
logged-in user, the crawler will be redirected to a login page,
with the origi... | python | {
"resource": ""
} |
q15358 | Element._escape_attribute_quotes | train | def _escape_attribute_quotes(self, v):
'''
Escapes quotes with a backslash, except those inside a Django tag
'''
escaped = []
inside_tag = False
for i, _ in enumerate(v):
if v[i:i + 2] == '{%':
inside_tag = True
elif v[i:i + 2] == '... | python | {
"resource": ""
} |
q15359 | RootNode.add_child | train | def add_child(self, child):
'''Add child node, and copy all options to it'''
super(RootNode, self).add_child(child)
child.attr_wrapper = self.attr_wrapper | python | {
"resource": ""
} |
q15360 | ElementNode._render_before | train | def _render_before(self, element):
'''Render opening tag and inline content'''
start = ["%s<%s" % (self.spaces, element.tag)]
if element.id:
start.append(" id=%s" % self.element.attr_wrap(self.replace_inline_variables(element.id)))
if element.classes:
start.append... | python | {
"resource": ""
} |
q15361 | ElementNode._render_after | train | def _render_after(self, element):
'''Render closing tag'''
if element.inline_content:
return "</%s>%s" % (element.tag, self.render_newlines())
elif element.self_close:
return self.render_newlines()
elif self.children:
return "%s</%s>\n" % (self.spaces,... | python | {
"resource": ""
} |
q15362 | Simplenote.authenticate | train | def authenticate(self, user, password):
""" Method to get simplenote auth token
Arguments:
- user (string): simplenote email address
- password (string): simplenote password
Returns:
Simplenote API token as string
"""
reques... | python | {
"resource": ""
} |
q15363 | Simplenote.get_token | train | def get_token(self):
""" Method to retrieve an auth token.
The cached global token is looked up and returned if it exists. If it
is `None` a new one is requested and returned.
Returns:
Simplenote API token as string
"""
if self.token == None:
se... | python | {
"resource": ""
} |
q15364 | Simplenote.get_note | train | def get_note(self, noteid, version=None):
""" Method to get a specific note
Arguments:
- noteid (string): ID of the note to get
- version (int): optional version of the note to get
Returns:
A tuple `(note, status)`
- note (dict): note object
... | python | {
"resource": ""
} |
q15365 | Simplenote.update_note | train | def update_note(self, note):
""" Method to update a specific note object, if the note object does not
have a "key" field, a new note is created
Arguments
- note (dict): note object to update
Returns:
A tuple `(note, status)`
- note (dict): note objec... | python | {
"resource": ""
} |
q15366 | Simplenote.add_note | train | def add_note(self, note):
""" Wrapper method to add a note
The method can be passed the note as a dict with the `content`
property set, which is then directly send to the web service for
creation. Alternatively, only the body as string can also be passed. In
this case the parame... | python | {
"resource": ""
} |
q15367 | Simplenote.get_note_list | train | def get_note_list(self, data=True, since=None, tags=[]):
""" Method to get the note list
The method can be passed optional arguments to limit the list to
notes containing a certain tag, or only updated since a certain
Simperium cursor. If omitted a list of all notes is returned.
... | python | {
"resource": ""
} |
q15368 | Simplenote.trash_note | train | def trash_note(self, note_id):
""" Method to move a note to the trash
Arguments:
- note_id (string): key of the note to trash
Returns:
A tuple `(note, status)`
- note (dict): the newly created note or an error message
- status (int): 0 on succes... | python | {
"resource": ""
} |
q15369 | Simplenote.delete_note | train | def delete_note(self, note_id):
""" Method to permanently delete a note
Arguments:
- note_id (string): key of the note to trash
Returns:
A tuple `(note, status)`
- note (dict): an empty dict or an error message
- status (int): 0 on success and -... | python | {
"resource": ""
} |
q15370 | BearerAuthentication.authenticate_credentials | train | def authenticate_credentials(self, token):
"""
Validate the bearer token against the OAuth provider.
Arguments:
token (str): Access token to validate
Returns:
(tuple): tuple containing:
user (User): User associated with the access token
... | python | {
"resource": ""
} |
q15371 | BearerAuthentication.get_user_info | train | def get_user_info(self, token):
"""
Retrieves the user info from the OAuth provider.
Arguments:
token (str): OAuth2 access token.
Returns:
dict
Raises:
UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.
""... | python | {
"resource": ""
} |
q15372 | BearerAuthentication.process_user_info_response | train | def process_user_info_response(self, response):
"""
Process the user info response data.
By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your
provider returns different fields, you should sub-class this class and override this metho... | python | {
"resource": ""
} |
q15373 | JwtAuthentication.authenticate_credentials | train | def authenticate_credentials(self, payload):
"""Get or create an active user with the username contained in the payload."""
username = payload.get('preferred_username') or payload.get('username')
if username is None:
raise exceptions.AuthenticationFailed('JWT must include a preferre... | python | {
"resource": ""
} |
q15374 | EnsureJWTAuthSettingsMiddleware._includes_base_class | train | def _includes_base_class(self, iter_classes, base_class):
"""
Returns whether any class in iter_class is a subclass of the given base_class.
"""
return any(
issubclass(auth_class, base_class) for auth_class in iter_classes,
) | python | {
"resource": ""
} |
q15375 | EnsureJWTAuthSettingsMiddleware._add_missing_jwt_permission_classes | train | def _add_missing_jwt_permission_classes(self, view_class):
"""
Adds permissions classes that should exist for Jwt based authentication,
if needed.
"""
view_permissions = list(getattr(view_class, 'permission_classes', []))
# Not all permissions are classes, some will be C... | python | {
"resource": ""
} |
q15376 | JwtAuthCookieMiddleware.process_request | train | def process_request(self, request):
"""
Reconstitute the full JWT and add a new cookie on the request object.
"""
use_jwt_cookie_requested = request.META.get(USE_JWT_COOKIE_HEADER)
header_payload_cookie = request.COOKIES.get(jwt_cookie_header_payload_name())
signature_coo... | python | {
"resource": ""
} |
q15377 | _set_token_defaults | train | def _set_token_defaults(token):
"""
Returns an updated token that includes default values for
fields that were introduced since the token was created
by checking its version number.
"""
def _verify_version(jwt_version):
supported_version = Version(
settings.JWT_AUTH.get('JWT_... | python | {
"resource": ""
} |
q15378 | _get_signing_jwk_key_set | train | def _get_signing_jwk_key_set(jwt_issuer):
"""
Returns a JWK Keyset containing all active keys that are configured
for verifying signatures.
"""
key_set = KEYS()
# asymmetric keys
signing_jwk_set = settings.JWT_AUTH.get('JWT_PUBLIC_SIGNING_JWK_SET')
if signing_jwk_set:
key_set.lo... | python | {
"resource": ""
} |
q15379 | paginate_search_results | train | def paginate_search_results(object_class, search_results, page_size, page):
"""
Takes edx-search results and returns a Page object populated
with db objects for that page.
:param object_class: Model class to use when querying the db for objects.
:param search_results: edX-search results.
:param... | python | {
"resource": ""
} |
q15380 | DefaultPagination.get_paginated_response | train | def get_paginated_response(self, data):
"""
Annotate the response with pagination information.
"""
return Response({
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.page.paginator.count,
'num_pages': self.p... | python | {
"resource": ""
} |
q15381 | NamespacedPageNumberPagination.get_paginated_response | train | def get_paginated_response(self, data):
"""
Annotate the response with pagination information
"""
metadata = {
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.get_result_count(),
'num_pages': self.get_num_p... | python | {
"resource": ""
} |
q15382 | get_decoded_jwt | train | def get_decoded_jwt(request):
"""
Grab jwt from jwt cookie in request if possible.
Returns a decoded jwt dict if it can be found.
Returns None if the jwt is not found.
"""
jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None)
if not jwt_cookie:
return None
return jwt_decode... | python | {
"resource": ""
} |
q15383 | SessionAuthenticationAllowInactiveUser.authenticate | train | def authenticate(self, request):
"""Authenticate the user, requiring a logged-in account and CSRF.
This is exactly the same as the `SessionAuthentication` implementation,
with the `user.is_active` check removed.
Args:
request (HttpRequest)
Returns:
Tupl... | python | {
"resource": ""
} |
q15384 | JwtHasContentOrgFilterForRequestedCourse.has_permission | train | def has_permission(self, request, view):
"""
Ensure that the course_id kwarg provided to the view contains one
of the organizations specified in the content provider filters
in the JWT used to authenticate.
"""
course_key = CourseKey.from_string(view.kwargs.get('course_id... | python | {
"resource": ""
} |
q15385 | JwtHasUserFilterForRequestedUser.has_permission | train | def has_permission(self, request, view):
"""
If the JWT has a user filter, verify that the filtered
user value matches the user in the URL.
"""
user_filter = self._get_user_filter(request)
if not user_filter:
# no user filters are present in the token to limit... | python | {
"resource": ""
} |
q15386 | RequestMetricsMiddleware.process_response | train | def process_response(self, request, response):
"""
Add metrics for various details of the request.
"""
self._set_request_auth_type_metric(request)
self._set_request_user_agent_metrics(request)
self._set_request_referer_metric(request)
self._set_request_user_id_met... | python | {
"resource": ""
} |
q15387 | RequestMetricsMiddleware._set_request_user_id_metric | train | def _set_request_user_id_metric(self, request):
"""
Add request_user_id metric
Metrics:
request_user_id
"""
if hasattr(request, 'user') and hasattr(request.user, 'id') and request.user.id:
monitoring.set_custom_metric('request_user_id', request.user.id) | python | {
"resource": ""
} |
q15388 | RequestMetricsMiddleware._set_request_referer_metric | train | def _set_request_referer_metric(self, request):
"""
Add metric 'request_referer' for http referer.
"""
if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']:
monitoring.set_custom_metric('request_referer', request.META['HTTP_REFERER']) | python | {
"resource": ""
} |
q15389 | RequestMetricsMiddleware._set_request_user_agent_metrics | train | def _set_request_user_agent_metrics(self, request):
"""
Add metrics for user agent for python.
Metrics:
request_user_agent
request_client_name: The client name from edx-rest-api-client calls.
"""
if 'HTTP_USER_AGENT' in request.META and request.META['HT... | python | {
"resource": ""
} |
q15390 | RequestMetricsMiddleware._set_request_auth_type_metric | train | def _set_request_auth_type_metric(self, request):
"""
Add metric 'request_auth_type' for the authentication type used.
NOTE: This is a best guess at this point. Possible values include:
no-user
unauthenticated
jwt/bearer/other-token-type
session-... | python | {
"resource": ""
} |
q15391 | jsonrpc_request | train | def jsonrpc_request(method, identifier, params=None):
"""Produce a JSONRPC request."""
return '{}\r\n'.format(json.dumps({
'id': identifier,
'method': method,
'params': params or {},
'jsonrpc': '2.0'
})).encode() | python | {
"resource": ""
} |
q15392 | SnapcastProtocol.handle_data | train | def handle_data(self, data):
"""Handle JSONRPC data."""
if 'id' in data:
self.handle_response(data)
else:
self.handle_notification(data) | python | {
"resource": ""
} |
q15393 | SnapcastProtocol.handle_response | train | def handle_response(self, data):
"""Handle JSONRPC response."""
identifier = data.get('id')
self._buffer[identifier]['data'] = data.get('result')
self._buffer[identifier]['flag'].set() | python | {
"resource": ""
} |
q15394 | SnapcastProtocol.handle_notification | train | def handle_notification(self, data):
"""Handle JSONRPC notification."""
if data.get('method') in self._callbacks:
self._callbacks.get(data.get('method'))(data.get('params')) | python | {
"resource": ""
} |
q15395 | SnapcastProtocol.request | train | def request(self, method, params):
"""Send a JSONRPC request."""
identifier = random.randint(1, 1000)
self._transport.write(jsonrpc_request(method, identifier, params))
self._buffer[identifier] = {'flag': asyncio.Event()}
yield from self._buffer[identifier]['flag'].wait()
... | python | {
"resource": ""
} |
q15396 | Snapserver.start | train | def start(self):
"""Initiate server connection."""
yield from self._do_connect()
_LOGGER.info('connected to snapserver on %s:%s', self._host, self._port)
status = yield from self.status()
self.synchronize(status)
self._on_server_connect() | python | {
"resource": ""
} |
q15397 | Snapserver._do_connect | train | def _do_connect(self):
"""Perform the connection to the server."""
_, self._protocol = yield from self._loop.create_connection(
lambda: SnapcastProtocol(self._callbacks), self._host, self._port) | python | {
"resource": ""
} |
q15398 | Snapserver._reconnect_cb | train | def _reconnect_cb(self):
"""Callback to reconnect to the server."""
@asyncio.coroutine
def try_reconnect():
"""Actual coroutine ro try to reconnect or reschedule."""
try:
yield from self._do_connect()
except IOError:
self._loop.... | python | {
"resource": ""
} |
q15399 | Snapserver._transact | train | def _transact(self, method, params=None):
"""Wrap requests."""
result = yield from self._protocol.request(method, params)
return result | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.