_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35700 | ConeFlatGeometry.frommatrix | train | def frommatrix(cls, apart, dpart, src_radius, det_radius, init_matrix,
pitch=0, **kwargs):
"""Create an instance of `ConeFlatGeometry` using a matrix.
This alternative constructor uses a matrix to rotate and
translate the default configuration. It is most useful when
... | python | {
"resource": ""
} |
q35701 | linear_deform | train | def linear_deform(template, displacement, out=None):
"""Linearized deformation of a template with a displacement field.
The function maps a given template ``I`` and a given displacement
field ``v`` to the new function ``x --> I(x + v(x))``.
Parameters
----------
template : `DiscreteLpElement`
... | python | {
"resource": ""
} |
q35702 | LinDeformFixedTempl.derivative | train | def derivative(self, displacement):
"""Derivative of the operator at ``displacement``.
Parameters
----------
displacement : `domain` `element-like`
Point at which the derivative is computed.
Returns
-------
derivative : `PointwiseInner`
T... | python | {
"resource": ""
} |
q35703 | LinDeformFixedDisp.adjoint | train | def adjoint(self):
"""Adjoint of the linear operator.
Note that this implementation uses an approximation that is only
valid for small displacements.
"""
# TODO allow users to select what method to use here.
div_op = Divergence(domain=self.displacement.space, method='for... | python | {
"resource": ""
} |
q35704 | cylinders_from_ellipses | train | def cylinders_from_ellipses(ellipses):
"""Create 3d cylinders from ellipses."""
ellipses = np.asarray(ellipses)
ellipsoids = np.zeros((ellipses.shape[0], 10))
ellipsoids[:, [0, 1, 2, 4, 5, 7]] = ellipses
ellipsoids[:, 3] = 100000.0
return ellipsoids | python | {
"resource": ""
} |
q35705 | ElapsedMixIn.elapsed | train | def elapsed(self):
'''
Returns elapsed crawl time as a float in seconds.
This metric includes all the time that a site was in active rotation,
including any time it spent waiting for its turn to be brozzled.
In contrast `Site.active_brozzling_time` only counts time when a
... | python | {
"resource": ""
} |
q35706 | RethinkDbFrontier.enforce_time_limit | train | def enforce_time_limit(self, site):
'''
Raises `brozzler.ReachedTimeLimit` if appropriate.
'''
if (site.time_limit and site.time_limit > 0
and site.elapsed() > site.time_limit):
self.logger.debug(
"site FINISHED_TIME_LIMIT! time_limit=%s "
... | python | {
"resource": ""
} |
q35707 | RethinkDbFrontier.honor_stop_request | train | def honor_stop_request(self, site):
"""Raises brozzler.CrawlStopped if stop has been requested."""
site.refresh()
if (site.stop_requested
and site.stop_requested <= doublethink.utcnow()):
self.logger.info("stop requested for site %s", site.id)
raise brozzl... | python | {
"resource": ""
} |
q35708 | RethinkDbFrontier._maybe_finish_job | train | def _maybe_finish_job(self, job_id):
"""Returns True if job is finished."""
job = brozzler.Job.load(self.rr, job_id)
if not job:
return False
if job.status.startswith("FINISH"):
self.logger.warn("%s is already %s", job, job.status)
return True
... | python | {
"resource": ""
} |
q35709 | RethinkDbFrontier._merge_page | train | def _merge_page(self, existing_page, fresh_page):
'''
Utility method for merging info from `brozzler.Page` instances
representing the same url but with possibly different metadata.
'''
existing_page.priority += fresh_page.priority
existing_page.hashtags = list(set(
... | python | {
"resource": ""
} |
q35710 | behaviors | train | def behaviors(behaviors_dir=None):
"""Return list of JS behaviors loaded from YAML file.
:param behaviors_dir: Directory containing `behaviors.yaml` and
`js-templates/`. Defaults to brozzler dir.
"""
import os, yaml, string
global _behaviors
if _behaviors is None:
d = behaviors_dir ... | python | {
"resource": ""
} |
q35711 | behavior_script | train | def behavior_script(url, template_parameters=None, behaviors_dir=None):
'''
Returns the javascript behavior string populated with template_parameters.
'''
import re, logging, json
for behavior in behaviors(behaviors_dir=behaviors_dir):
if re.match(behavior['url_regex'], url):
par... | python | {
"resource": ""
} |
q35712 | thread_raise | train | def thread_raise(thread, exctype):
'''
Raises or queues the exception `exctype` for the thread `thread`.
See the documentation on the function `thread_exception_gate()` for more
information.
Adapted from http://tomerfiliba.com/recipes/Thread2/ which explains:
"The exception will be raised only... | python | {
"resource": ""
} |
q35713 | sleep | train | def sleep(duration):
'''
Sleeps for duration seconds in increments of 0.5 seconds.
Use this so that the sleep can be interrupted by thread_raise().
'''
import time
start = time.time()
while True:
elapsed = time.time() - start
if elapsed >= duration:
break
... | python | {
"resource": ""
} |
q35714 | BrowserPool.acquire_multi | train | def acquire_multi(self, n=1):
'''
Returns a list of up to `n` browsers.
Raises:
NoBrowsersAvailable if none available
'''
browsers = []
with self._lock:
if len(self._in_use) >= self.size:
raise NoBrowsersAvailable
while... | python | {
"resource": ""
} |
q35715 | BrowserPool.acquire | train | def acquire(self):
'''
Returns an available instance.
Returns:
browser from pool, if available
Raises:
NoBrowsersAvailable if none available
'''
with self._lock:
if len(self._in_use) >= self.size:
raise NoBrowsersAvail... | python | {
"resource": ""
} |
q35716 | WebsockReceiverThread._on_error | train | def _on_error(self, websock, e):
'''
Raises BrowsingException in the thread that created this instance.
'''
if isinstance(e, (
websocket.WebSocketConnectionClosedException,
ConnectionResetError)):
self.logger.error('websocket closed, did chrome die?')
... | python | {
"resource": ""
} |
q35717 | Browser.start | train | def start(self, **kwargs):
'''
Starts chrome if it's not running.
Args:
**kwargs: arguments for self.chrome.start(...)
'''
if not self.is_running():
self.websock_url = self.chrome.start(**kwargs)
self.websock = websocket.WebSocketApp(self.webs... | python | {
"resource": ""
} |
q35718 | Browser.stop | train | def stop(self):
'''
Stops chrome if it's running.
'''
try:
if (self.websock and self.websock.sock
and self.websock.sock.connected):
self.logger.info('shutting down websocket connection')
try:
self.websock... | python | {
"resource": ""
} |
q35719 | Browser.browse_page | train | def browse_page(
self, page_url, extra_headers=None,
user_agent=None, behavior_parameters=None, behaviors_dir=None,
on_request=None, on_response=None,
on_service_worker_version_updated=None, on_screenshot=None,
username=None, password=None, hashtags=None,
... | python | {
"resource": ""
} |
q35720 | Browser.url | train | def url(self, timeout=30):
'''
Returns value of document.URL from the browser.
'''
self.websock_thread.expect_result(self._command_id.peek())
msg_id = self.send_to_chrome(
method='Runtime.evaluate',
params={'expression': 'document.URL'})
se... | python | {
"resource": ""
} |
q35721 | brozzler_new_job | train | def brozzler_new_job(argv=None):
'''
Command line utility entry point for queuing a new brozzler job. Takes a
yaml brozzler job configuration file, creates job, sites, and pages objects
in rethinkdb, which brozzler-workers will look at and start crawling.
'''
argv = argv or sys.argv
arg_pars... | python | {
"resource": ""
} |
q35722 | brozzler_new_site | train | def brozzler_new_site(argv=None):
'''
Command line utility entry point for queuing a new brozzler site.
Takes a seed url and creates a site and page object in rethinkdb, which
brozzler-workers will look at and start crawling.
'''
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
... | python | {
"resource": ""
} |
q35723 | brozzler_list_captures | train | def brozzler_list_captures(argv=None):
'''
Handy utility for looking up entries in the rethinkdb "captures" table by
url or sha1.
'''
import urlcanon
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
prog=os.path.basename(argv[0]),
formatter_class=BetterA... | python | {
"resource": ""
} |
q35724 | BrozzlerEasyController._warcprox_opts | train | def _warcprox_opts(self, args):
'''
Takes args as produced by the argument parser built by
_build_arg_parser and builds warcprox arguments object suitable to pass
to warcprox.main.init_controller. Copies some arguments, renames some,
populates some with defaults appropriate for b... | python | {
"resource": ""
} |
q35725 | _reppy_rules_getitem | train | def _reppy_rules_getitem(self, agent):
'''
Find the user-agent token matching the supplied full user-agent, using
a case-insensitive substring search.
'''
lc_agent = agent.lower()
for s in self.agents:
if s in lc_agent:
return self.agents[s]
return self.agents.get('*') | python | {
"resource": ""
} |
q35726 | is_permitted_by_robots | train | def is_permitted_by_robots(site, url, proxy=None):
'''
Checks if `url` is permitted by robots.txt.
Treats any kind of error fetching robots.txt as "allow all". See
http://builds.archive.org/javadoc/heritrix-3.x-snapshot/org/archive/modules/net/CrawlServer.html#updateRobots(org.archive.modules.CrawlURI)... | python | {
"resource": ""
} |
q35727 | final_bounces | train | def final_bounces(fetches, url):
"""
Resolves redirect chains in `fetches` and returns a list of fetches
representing the final redirect destinations of the given url. There could
be more than one if for example youtube-dl hit the same url with HEAD and
then GET requests.
"""
redirects = {}
... | python | {
"resource": ""
} |
q35728 | _remember_videos | train | def _remember_videos(page, fetches, stitch_ups=None):
'''
Saves info about videos captured by youtube-dl in `page.videos`.
'''
if not 'videos' in page:
page.videos = []
for fetch in fetches or []:
content_type = fetch['response_headers'].get_content_type()
if (content_type.st... | python | {
"resource": ""
} |
q35729 | do_youtube_dl | train | def do_youtube_dl(worker, site, page):
'''
Runs youtube-dl configured for `worker` and `site` to download videos from
`page`.
Args:
worker (brozzler.BrozzlerWorker): the calling brozzler worker
site (brozzler.Site): the site we are brozzling
page (brozzler.Page): the page we are... | python | {
"resource": ""
} |
q35730 | pages | train | def pages(site_id):
"""Pages already crawled."""
start = int(flask.request.args.get("start", 0))
end = int(flask.request.args.get("end", start + 90))
reql = rr.table("pages").between(
[site_id, 1, r.minval], [site_id, r.maxval, r.maxval],
index="least_hops").order_by(index="least... | python | {
"resource": ""
} |
q35731 | check_version | train | def check_version(chrome_exe):
'''
Raises SystemExit if `chrome_exe` is not a supported browser version.
Must run in the main thread to have the desired effect.
'''
# mac$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version
# Google Chrome 64.0.3282.140
# mac$ /Applica... | python | {
"resource": ""
} |
q35732 | BrozzlerWorker._service_heartbeat_if_due | train | def _service_heartbeat_if_due(self):
'''Sends service registry heartbeat if due'''
due = False
if self._service_registry:
if not hasattr(self, "status_info"):
due = True
else:
d = doublethink.utcnow() - self.status_info["last_heartbeat"]
... | python | {
"resource": ""
} |
q35733 | BrozzlerWorker._start_browsing_some_sites | train | def _start_browsing_some_sites(self):
'''
Starts browsing some sites.
Raises:
NoBrowsersAvailable if none available
'''
# acquire_multi() raises NoBrowsersAvailable if none available
browsers = self._browser_pool.acquire_multi(
(self._browser_... | python | {
"resource": ""
} |
q35734 | tokenizer._createtoken | train | def _createtoken(self, type_, value, flags=None):
'''create a token with position information'''
pos = None
assert len(self._positions) >= 2, (type_, value)
p2 = self._positions.pop()
p1 = self._positions.pop()
pos = [p1, p2]
return token(type_, value, pos, flags) | python | {
"resource": ""
} |
q35735 | parse | train | def parse(s, strictmode=True, expansionlimit=None, convertpos=False):
'''parse the input string, returning a list of nodes
top level node kinds are:
- command - a simple command
- pipeline - a series of simple commands
- list - a series of one or more pipelines
- compound - contains constructs... | python | {
"resource": ""
} |
q35736 | split | train | def split(s):
'''a utility function that mimics shlex.split but handles more
complex shell constructs such as command substitutions inside words
>>> list(split('a b"c"\\'d\\''))
['a', 'bcd']
>>> list(split('a "b $(c)" $(d) \\'$(e)\\''))
['a', 'b $(c)', '$(d)', '$(e)']
>>> list(split('a b\\n... | python | {
"resource": ""
} |
q35737 | sleep_and_retry | train | def sleep_and_retry(func):
'''
Return a wrapped function that rescues rate limit exceptions, sleeping the
current thread until rate limit resets.
:param function func: The function to decorate.
:return: Decorated function.
:rtype: function
'''
@wraps(func)
def wrapper(*args, **kargs... | python | {
"resource": ""
} |
q35738 | RateLimitDecorator.__period_remaining | train | def __period_remaining(self):
'''
Return the period remaining for the current rate limit window.
:return: The remaing period.
:rtype: float
'''
elapsed = self.clock() - self.last_reset
return self.period - elapsed | python | {
"resource": ""
} |
q35739 | filter_lines_from_comments | train | def filter_lines_from_comments(lines):
""" Filter the lines from comments and non code lines. """
for line_nb, raw_line in enumerate(lines):
clean_line = remove_comments_from_line(raw_line)
if clean_line == '':
continue
yield line_nb, clean_line, raw_line | python | {
"resource": ""
} |
q35740 | _check_no_current_table | train | def _check_no_current_table(new_obj, current_table):
""" Raises exception if we try to add a relation or a column
with no current table. """
if current_table is None:
msg = 'Cannot add {} before adding table'
if isinstance(new_obj, Relation):
raise NoCurrentTableException(msg.for... | python | {
"resource": ""
} |
q35741 | update_models | train | def update_models(new_obj, current_table, tables, relations):
""" Update the state of the parsing. """
_update_check_inputs(current_table, tables, relations)
_check_no_current_table(new_obj, current_table)
if isinstance(new_obj, Table):
tables_names = [t.name for t in tables]
_check_not... | python | {
"resource": ""
} |
q35742 | markdown_file_to_intermediary | train | def markdown_file_to_intermediary(filename):
""" Parse a file and return to intermediary syntax. """
with open(filename) as f:
lines = f.readlines()
return line_iterator_to_intermediary(lines) | python | {
"resource": ""
} |
q35743 | check_args | train | def check_args(args):
"""Checks that the args are coherent."""
check_args_has_attributes(args)
if args.v:
non_version_attrs = [v for k, v in args.__dict__.items() if k != 'v']
print('non_version_attrs', non_version_attrs)
if len([v for v in non_version_attrs if v is not None]) != 0:
... | python | {
"resource": ""
} |
q35744 | relation_to_intermediary | train | def relation_to_intermediary(fk):
"""Transform an SQLAlchemy ForeignKey object to it's intermediary representation. """
return Relation(
right_col=format_name(fk.parent.table.fullname),
left_col=format_name(fk._column_tokens[1]),
right_cardinality='?',
left_cardinality='*',
) | python | {
"resource": ""
} |
q35745 | column_to_intermediary | train | def column_to_intermediary(col, type_formatter=format_type):
"""Transform an SQLAlchemy Column object to it's intermediary representation. """
return Column(
name=col.name,
type=type_formatter(col.type),
is_key=col.primary_key,
) | python | {
"resource": ""
} |
q35746 | table_to_intermediary | train | def table_to_intermediary(table):
"""Transform an SQLAlchemy Table object to it's intermediary representation. """
return Table(
name=table.fullname,
columns=[column_to_intermediary(col) for col in table.c._data.values()]
) | python | {
"resource": ""
} |
q35747 | metadata_to_intermediary | train | def metadata_to_intermediary(metadata):
""" Transforms SQLAlchemy metadata to the intermediary representation. """
tables = [table_to_intermediary(table) for table in metadata.tables.values()]
relationships = [relation_to_intermediary(fk) for table in metadata.tables.values() for fk in table.foreign_keys]
... | python | {
"resource": ""
} |
q35748 | name_for_scalar_relationship | train | def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
""" Overriding naming schemes. """
name = referred_cls.__name__.lower() + "_ref"
return name | python | {
"resource": ""
} |
q35749 | intermediary_to_markdown | train | def intermediary_to_markdown(tables, relationships, output):
""" Saves the intermediary representation to markdown. """
er_markup = _intermediary_to_markdown(tables, relationships)
with open(output, "w") as file_out:
file_out.write(er_markup) | python | {
"resource": ""
} |
q35750 | intermediary_to_dot | train | def intermediary_to_dot(tables, relationships, output):
""" Save the intermediary representation to dot format. """
dot_file = _intermediary_to_dot(tables, relationships)
with open(output, "w") as file_out:
file_out.write(dot_file) | python | {
"resource": ""
} |
q35751 | intermediary_to_schema | train | def intermediary_to_schema(tables, relationships, output):
""" Transforms and save the intermediary representation to the file chosen. """
dot_file = _intermediary_to_dot(tables, relationships)
graph = AGraph()
graph = graph.from_string(dot_file)
extension = output.split('.')[-1]
graph.draw(path... | python | {
"resource": ""
} |
q35752 | _intermediary_to_markdown | train | def _intermediary_to_markdown(tables, relationships):
""" Returns the er markup source in a string. """
t = '\n'.join(t.to_markdown() for t in tables)
r = '\n'.join(r.to_markdown() for r in relationships)
return '{}\n{}'.format(t, r) | python | {
"resource": ""
} |
q35753 | _intermediary_to_dot | train | def _intermediary_to_dot(tables, relationships):
""" Returns the dot source representing the database in a string. """
t = '\n'.join(t.to_dot() for t in tables)
r = '\n'.join(r.to_dot() for r in relationships)
return '{}\n{}\n{}\n}}'.format(GRAPH_BEGINNING, t, r) | python | {
"resource": ""
} |
q35754 | all_to_intermediary | train | def all_to_intermediary(filename_or_input, schema=None):
""" Dispatch the filename_or_input to the different function to produce the intermediary syntax.
All the supported classes names are in `swich_input_class_to_method`.
The input can also be a list of strings in markdown format or a filename finishing b... | python | {
"resource": ""
} |
q35755 | get_output_mode | train | def get_output_mode(output, mode):
"""
From the output name and the mode returns a the function that will transform the intermediary
representation to the output.
"""
if mode != 'auto':
try:
return switch_output_mode_auto[mode]
except KeyError:
raise ValueErro... | python | {
"resource": ""
} |
q35756 | handle_oneof | train | def handle_oneof(oneof_schema: list) -> tuple:
"""
Custom handle of `oneOf` JSON schema validator. Tried to match primitive type and see if it should be allowed
to be passed multiple timns into a command
:param oneof_schema: `oneOf` JSON schema
:return: Tuple of :class:`click.ParamType`, ``multipl... | python | {
"resource": ""
} |
q35757 | clean_data | train | def clean_data(data: dict) -> dict:
"""Removes all empty values and converts tuples into lists"""
new_data = {}
for key, value in data.items():
# Verify that only explicitly passed args get passed on
if not isinstance(value, bool) and not value:
continue
# Multiple choic... | python | {
"resource": ""
} |
q35758 | SchemaResource.schema | train | def schema(self) -> dict:
"""
A property method that'll return the constructed provider schema.
Schema MUST be an object and this method must be overridden
:return: JSON schema of the provider
"""
if not self._merged_schema:
log.debug("merging required dict i... | python | {
"resource": ""
} |
q35759 | SchemaResource._process_data | train | def _process_data(self, **data) -> dict:
"""
The main method that process all resources data. Validates schema, gets environs, validates data, prepares
it via provider requirements, merges defaults and check for data dependencies
:param data: The raw data passed by the notifiers client... | python | {
"resource": ""
} |
q35760 | is_iso8601 | train | def is_iso8601(instance: str):
"""Validates ISO8601 format"""
if not isinstance(instance, str):
return True
return ISO8601.match(instance) is not None | python | {
"resource": ""
} |
q35761 | is_rfc2822 | train | def is_rfc2822(instance: str):
"""Validates RFC2822 format"""
if not isinstance(instance, str):
return True
return email.utils.parsedate(instance) is not None | python | {
"resource": ""
} |
q35762 | is_valid_port | train | def is_valid_port(instance: int):
"""Validates data is a valid port"""
if not isinstance(instance, (int, str)):
return True
return int(instance) in range(65535) | python | {
"resource": ""
} |
q35763 | is_timestamp | train | def is_timestamp(instance):
"""Validates data is a timestamp"""
if not isinstance(instance, (int, str)):
return True
return datetime.fromtimestamp(int(instance)) | python | {
"resource": ""
} |
q35764 | func_factory | train | def func_factory(p, method: str) -> callable:
"""
Dynamically generates callback commands to correlate to provider public methods
:param p: A :class:`notifiers.core.Provider` object
:param method: A string correlating to a provider method
:return: A callback func
"""
def callback(pretty: b... | python | {
"resource": ""
} |
q35765 | _notify | train | def _notify(p, **data):
"""The callback func that will be hooked to the ``notify`` command"""
message = data.get("message")
if not message and not sys.stdin.isatty():
message = click.get_text_stream("stdin").read()
data["message"] = message
data = clean_data(data)
ctx = click.get_curre... | python | {
"resource": ""
} |
q35766 | _resource | train | def _resource(resource, pretty: bool = None, **data):
"""The callback func that will be hooked to the generic resource commands"""
data = clean_data(data)
ctx = click.get_current_context()
if ctx.obj.get("env_prefix"):
data["env_prefix"] = ctx.obj["env_prefix"]
rsp = resource(**data)
d... | python | {
"resource": ""
} |
q35767 | _resources | train | def _resources(p):
"""Callback func to display provider resources"""
if p.resources:
click.echo(",".join(p.resources))
else:
click.echo(f"Provider '{p.name}' does not have resource helpers") | python | {
"resource": ""
} |
q35768 | one_or_more | train | def one_or_more(
schema: dict, unique_items: bool = True, min: int = 1, max: int = None
) -> dict:
"""
Helper function to construct a schema that validates items matching
`schema` or an array containing items matching `schema`.
:param schema: The schema to use
:param unique_items: Flag if array... | python | {
"resource": ""
} |
q35769 | text_to_bool | train | def text_to_bool(value: str) -> bool:
"""
Tries to convert a text value to a bool. If unsuccessful returns if value is None or not
:param value: Value to check
"""
try:
return bool(strtobool(value))
except (ValueError, AttributeError):
return value is not None | python | {
"resource": ""
} |
q35770 | merge_dicts | train | def merge_dicts(target_dict: dict, merge_dict: dict) -> dict:
"""
Merges ``merge_dict`` into ``target_dict`` if the latter does not already contain a value for each of the key
names in ``merge_dict``. Used to cleanly merge default and environ data into notification payload.
:param target_dict: The targ... | python | {
"resource": ""
} |
q35771 | snake_to_camel_case | train | def snake_to_camel_case(value: str) -> str:
"""
Convert a snake case param to CamelCase
:param value: The value to convert
:return: A CamelCase value
"""
log.debug("trying to convert %s to camel case", value)
return "".join(word.capitalize() for word in value.split("_")) | python | {
"resource": ""
} |
q35772 | valid_file | train | def valid_file(path: str) -> bool:
"""
Verifies that a string path actually exists and is a file
:param path: The path to verify
:return: **True** if path exist and is a file
"""
path = Path(path).expanduser()
log.debug("checking if %s is a valid file", path)
return path.exists() and pa... | python | {
"resource": ""
} |
q35773 | NotificationHandler.init_providers | train | def init_providers(self, provider, kwargs):
"""
Inits main and fallback provider if relevant
:param provider: Provider name to use
:param kwargs: Additional kwargs
:raises ValueError: If provider name or fallback names are not valid providers, a :exc:`ValueError` will
b... | python | {
"resource": ""
} |
q35774 | provider_group_factory | train | def provider_group_factory():
"""Dynamically generate provider groups for all providers, and add all basic command to it"""
for provider in all_providers():
p = get_notifier(provider)
provider_name = p.name
help = f"Options for '{provider_name}'"
group = click.Group(name=provider... | python | {
"resource": ""
} |
q35775 | entry_point | train | def entry_point():
"""The entry that CLI is executed from"""
try:
provider_group_factory()
notifiers_cli(obj={})
except NotifierException as e:
click.secho(f"ERROR: {e.message}", bold=True, fg="red")
exit(1) | python | {
"resource": ""
} |
q35776 | Requester.request | train | def request(
self, method, endpoint=None, headers=None, use_auth=True,
_url=None, _kwargs=None, **kwargs):
"""
Make a request to the Canvas API and return the response.
:param method: The HTTP method for the request.
:type method: str
:param endpoint: The... | python | {
"resource": ""
} |
q35777 | Requester._get_request | train | def _get_request(self, url, headers, params=None):
"""
Issue a GET request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param params: dict
"""
return self._session.get(url, headers=headers, params=params) | python | {
"resource": ""
} |
q35778 | Requester._post_request | train | def _post_request(self, url, headers, data=None):
"""
Issue a POST request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
# Grab file from data.
files = None
for field, value in data:... | python | {
"resource": ""
} |
q35779 | Requester._delete_request | train | def _delete_request(self, url, headers, data=None):
"""
Issue a DELETE request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
return self._session.delete(url, headers=headers, data=data) | python | {
"resource": ""
} |
q35780 | Requester._put_request | train | def _put_request(self, url, headers, data=None):
"""
Issue a PUT request to the specified endpoint with the data provided.
:param url: str
:pararm headers: dict
:param data: dict
"""
return self._session.put(url, headers=headers, data=data) | python | {
"resource": ""
} |
q35781 | Uploader.request_upload_token | train | def request_upload_token(self, file):
"""
Request an upload token.
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
and the JSON response from the API.
:rtype: tuple
"""
s... | python | {
"resource": ""
} |
q35782 | Uploader.upload | train | def upload(self, response, file):
"""
Upload the file.
:param response: The response from the upload request.
:type response: dict
:param file: A file handler pointing to the file to upload.
:returns: True if the file uploaded successfully, False otherwise, \
... | python | {
"resource": ""
} |
q35783 | CanvasObject.set_attributes | train | def set_attributes(self, attributes):
"""
Load this object with attributes.
This method attempts to detect special types based on the field's content
and will create an additional attribute of that type.
Consider a JSON response with the following fields::
{
... | python | {
"resource": ""
} |
q35784 | Canvas.create_account | train | def create_account(self, **kwargs):
"""
Create a new root account.
:calls: `POST /api/v1/accounts \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_
:rtype: :class:`canvasapi.account.Account`
"""
response = self.__requester.request... | python | {
"resource": ""
} |
q35785 | Canvas.get_account | train | def get_account(self, account, use_sis_id=False, **kwargs):
"""
Retrieve information on an individual account.
:calls: `GET /api/v1/accounts/:id \
<https://canvas.instructure.com/doc/api/accounts.html#method.accounts.show>`_
:param account: The object or ID of the account to re... | python | {
"resource": ""
} |
q35786 | Canvas.get_accounts | train | def get_accounts(self, **kwargs):
"""
List accounts that the current user can view or manage.
Typically, students and teachers will get an empty list in
response. Only account admins can view the accounts that they
are in.
:calls: `GET /api/v1/accounts \
<https:... | python | {
"resource": ""
} |
q35787 | Canvas.get_course | train | def get_course(self, course, use_sis_id=False, **kwargs):
"""
Retrieve a course by its ID.
:calls: `GET /api/v1/courses/:id \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.show>`_
:param course: The object or ID of the course to retrieve.
:type cou... | python | {
"resource": ""
} |
q35788 | Canvas.get_user | train | def get_user(self, user, id_type=None):
"""
Retrieve a user by their ID. `id_type` denotes which endpoint to try as there are
several different IDs that can pull the same user record from Canvas.
Refer to API documentation's
`User <https://canvas.instructure.com/doc/api/users.ht... | python | {
"resource": ""
} |
q35789 | Canvas.get_courses | train | def get_courses(self, **kwargs):
"""
Return a list of active courses for the current user.
:calls: `GET /api/v1/courses \
<https://canvas.instructure.com/doc/api/courses.html#method.courses.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`... | python | {
"resource": ""
} |
q35790 | Canvas.get_section | train | def get_section(self, section, use_sis_id=False, **kwargs):
"""
Get details about a specific section.
:calls: `GET /api/v1/sections/:id \
<https://canvas.instructure.com/doc/api/sections.html#method.sections.show>`_
:param section: The object or ID of the section to get.
... | python | {
"resource": ""
} |
q35791 | Canvas.set_course_nickname | train | def set_course_nickname(self, course, nickname):
"""
Set a nickname for the given course. This will replace the
course's name in the output of subsequent API calls, as
well as in selected places in the Canvas web user interface.
:calls: `PUT /api/v1/users/self/course_nicknames/:... | python | {
"resource": ""
} |
q35792 | Canvas.search_accounts | train | def search_accounts(self, **kwargs):
"""
Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.... | python | {
"resource": ""
} |
q35793 | Canvas.get_group | train | def get_group(self, group, use_sis_id=False, **kwargs):
"""
Return the data for a single group. If the caller does not
have permission to view the group a 401 will be returned.
:calls: `GET /api/v1/groups/:group_id \
<https://canvas.instructure.com/doc/api/groups.html#method.gro... | python | {
"resource": ""
} |
q35794 | Canvas.get_group_category | train | def get_group_category(self, category):
"""
Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
... | python | {
"resource": ""
} |
q35795 | Canvas.create_conversation | train | def create_conversation(self, recipients, body, **kwargs):
"""
Create a new Conversation.
:calls: `POST /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.create>`_
:param recipients: An array of recipient ids.
Th... | python | {
"resource": ""
} |
q35796 | Canvas.get_conversation | train | def get_conversation(self, conversation, **kwargs):
"""
Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
... | python | {
"resource": ""
} |
q35797 | Canvas.get_conversations | train | def get_conversations(self, **kwargs):
"""
Return list of conversations for the current user, most resent ones first.
:calls: `GET /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_
:rtype: :class:`canvasapi.paginate... | python | {
"resource": ""
} |
q35798 | Canvas.create_calendar_event | train | def create_calendar_event(self, calendar_event, **kwargs):
"""
Create a new Calendar Event.
:calls: `POST /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.create>`_
:param calendar_event: The attributes of the cal... | python | {
"resource": ""
} |
q35799 | Canvas.get_calendar_events | train | def get_calendar_events(self, **kwargs):
"""
List calendar events.
:calls: `GET /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:cla... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.