INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculates Intersection over Union | def IoU(cm, ignore_index=None):
"""Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
trai... |
Calculates accuracy using: class: ~ignite. metrics. ConfusionMatrix metric. Args: cm ( ConfusionMatrix ): instance of confusion matrix metric | def cmAccuracy(cm):
"""
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda
"""
# Increase floating point precision
cm = cm.type(torch.float64)
return cm.diag().... |
Calculates precision using: class: ~ignite. metrics. ConfusionMatrix metric. Args: cm ( ConfusionMatrix ): instance of confusion matrix metric average ( bool optional ): if True metric value is averaged over all classes Returns: MetricsLambda | def cmPrecision(cm, average=True):
"""
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
... |
Calculates recall using: class: ~ignite. metrics. ConfusionMatrix metric. Args: cm ( ConfusionMatrix ): instance of confusion matrix metric average ( bool optional ): if True metric value is averaged over all classes Returns: MetricsLambda | def cmRecall(cm, average=True):
"""
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
"""
... |
Move tensors to relevant device. | def convert_tensor(input_, device=None, non_blocking=False):
"""Move tensors to relevant device."""
def _func(tensor):
return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
return apply_to_tensor(input_, _func) |
Apply a function on a object of input_type or mapping or sequence of objects of input_type. | def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
elif isinstance(input_, string_classes):
return input_
elif isinstance(input_, c... |
Convert a tensor of indices of any shape ( N... ) to a tensor of one - hot indicators of shape ( N num_classes... ). | def to_onehot(indices, num_classes):
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`.
"""
onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device)
return onehot.scatter_(1, indices.unsquee... |
Attaches the progress bar to an engine object. | def attach(self, engine, metric_names=None, output_transform=None,
event_name=Events.ITERATION_COMPLETED,
closing_event_name=Events.EPOCH_COMPLETED):
"""
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
me... |
Create a trainer for truncated backprop through time supervised models. | def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computation... |
Prepare batch for training: pass to a device with options. | def _prepare_batch(batch, device=None, non_blocking=False):
"""Prepare batch for training: pass to a device with options.
"""
x, y = batch
return (convert_tensor(x, device=device, non_blocking=non_blocking),
convert_tensor(y, device=device, non_blocking=non_blocking)) |
Factory function for creating a trainer for supervised models. | def create_supervised_trainer(model, optimizer, loss_fn,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred, loss: loss.item()):
"""
Factory function for creating a trainer ... |
Factory function for creating an evaluator for supervised models. | def create_supervised_evaluator(model, metrics=None,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred: (y_pred, y,)):
"""
Factory function for creating an evaluator ... |
Helper method to create a LR scheduler with a linear warm - up. | def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... |
Method to simulate scheduled values during num_events events. | def simulate_values(cls, num_events, **scheduler_kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
... |
Method to get current optimizer s parameter value | def get_param(self):
"""Method to get current optimizer's parameter value
"""
cycle_progress = self.event_index / self.cycle_size
return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress)) |
Method to simulate scheduled values during num_events events. | def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedu... |
Method to get current optimizer s parameter value | def get_param(self):
"""Method to get current optimizer's parameter value
"""
lr_list = self.lr_scheduler.get_lr()
if len(lr_list) > 1:
raise ValueError("Optimizer passed to lr_scheduler should have a single param group, "
"but currently there are... |
Method to simulate scheduled values during num_events events. | def simulate_values(cls, num_events, lr_scheduler, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object ... |
If manual seed is not specified choose a random one and communicate it to the user. | def check_manual_seed(seed):
""" If manual seed is not specified, choose a random one and communicate it to the user.
"""
seed = seed or random.randint(1, 10000)
random.seed(seed)
torch.manual_seed(seed)
print('Using manual seed: {seed}'.format(seed=seed)) |
Attach the logger to the engine and execute log_handler function at event_name events. | def attach(self, engine, log_handler, event_name):
"""Attach the logger to the engine and execute `log_handler` function at `event_name` events.
Args:
engine (Engine): engine object.
log_handler (callable): a logging handler to execute
event_name: event to attach the... |
Helper method to setup metrics to log | def _setup_output_metrics(self, engine):
"""Helper method to setup metrics to log
"""
metrics = {}
if self.metric_names is not None:
for name in self.metric_names:
if name not in engine.state.metrics:
warnings.warn("Provided metric name '{}... |
Register callbacks to control the timer. | def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):
""" Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should star... |
Helper method to log a scalar with VisdomLogger. | def add_scalar(self, logger, k, v, event_name, global_step):
"""
Helper method to log a scalar with VisdomLogger.
Args:
logger (VisdomLogger): visdom logger
k (str): scalar name which is used to set window title and y-axis label
v (int or float): scalar value... |
Convert seconds to hours mins and seconds. | def _to_hours_mins_secs(time_taken):
"""Convert seconds to hours, mins, and seconds."""
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return hours, mins, secs |
Parse the arguments/ options passed to the program on the command line. | def parse_args(args=None):
"""
Parse the arguments/options passed to the program on the command line.
"""
parse_kwargs = {
"description": 'Download Coursera.org lecture material and resources.'
}
conf_file_path = os.path.join(os.getcwd(), LOCAL_CONF_FILE_NAME)
if os.path.isfile(co... |
Return a pseudo - random string of specified length. | def random_string(length):
"""
Return a pseudo-random string of specified length.
"""
valid_chars = string_ascii_letters + string_digits
return ''.join(random.choice(valid_chars) for i in range(length)) |
Sanitize a string to be used as a filename. | def clean_filename(s, minimal_change=False):
"""
Sanitize a string to be used as a filename.
If minimal_change is set to true, then we only strip the bare minimum of
characters that are problematic for filesystems (namely, ':', '/' and
'\x00', '\n').
"""
# First, deal with URL encoded stri... |
Normalizes path on Windows OS. This means prepending <backslash > <backslash > ?<backslash > to the path to get access to Win32 device namespace instead of Win32 file namespace. See https:// msdn. microsoft. com/ en - us/ library/ aa365247%28v = vs. 85%29. aspx#maxpath | def normalize_path(path):
"""
Normalizes path on Windows OS. This means prepending
<backslash><backslash>?<backslash> to the path to get access to
Win32 device namespace instead of Win32 file namespace.
See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
@param path:... |
Extract the resource file - type format from the anchor. | def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=txt" or "...download.mp4?..."
fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
return fmt.group(1) if fmt else None |
Remove params query and fragment parts from URL so that os. path. basename and os. path. splitext can work correctly. | def clean_url(url):
"""
Remove params, query and fragment parts from URL so that `os.path.basename`
and `os.path.splitext` can work correctly.
@param url: URL to clean.
@type url: str
@return: Cleaned URL.
@rtype: str
"""
parsed = urlparse(url.strip())
reconstructed = ParseResu... |
Strip whitespace characters from the beginning and the end of the url and add a default scheme. | def fix_url(url):
"""
Strip whitespace characters from the beginning and the end of the url
and add a default scheme.
"""
if url is None:
return None
url = url.strip()
if url and not urlparse(url).scheme:
url = "http://" + url
return url |
Determine is the course is likely to have been terminated or not. | def is_course_complete(last_update):
"""
Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
... |
If given url is relative adds coursera netloc otherwise returns it without any changes. | def make_coursera_absolute_url(url):
"""
If given url is relative adds coursera netloc,
otherwise returns it without any changes.
"""
if not bool(urlparse(url).netloc):
return urljoin(COURSERA_URL, url)
return url |
Extends ( merges ) destination dictionary with supplement_links from source dictionary. Values are expected to be lists or any data structure that has extend method. | def extend_supplement_links(destination, source):
"""
Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type de... |
Print SSLError message with URL to instructions on how to fix it. | def print_ssl_error_message(exception):
"""
Print SSLError message with URL to instructions on how to fix it.
"""
message = """
#####################################################################
# ATTENTION! PLEASE READ THIS!
#
# The following error has just occurred:
# %s %s
#
# Please read instruct... |
List enrolled courses. | def list_courses(args):
"""
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
"""
session = get_session()
login(session, args.username, args.password)
extractor = CourseraExtractor(session)
courses = extractor.list_courses()
logging.info('Found %... |
Download all requested resources from the on - demand class given in class_name. | def download_on_demand_class(session, args, class_name):
"""
Download all requested resources from the on-demand class given
in class_name.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether th... |
Try to download on - demand class. | def download_class(session, args, class_name):
"""
Try to download on-demand class.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether the course appears to be completed.
@rtype: (bool, bool)
... |
Main entry point for execution as a program ( instead of as a module ). | def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %s', __version__)
completed_classes = []
classes_with_errors = []
mkdir_p(PATH_CACHE, 0o700)
if args.clear_cache:
shutil.rmtree(PA... |
This function prepares headers with CSRF/ CAUTH tokens that can be used in POST requests such as login/ get_quiz. | def prepare_auth_headers(session, include_cauth=False):
"""
This function prepares headers with CSRF/CAUTH tokens that can
be used in POST requests such as login/get_quiz.
@param session: Requests session.
@type session: requests.Session
@param include_cauth: Flag that indicates whether CAUTH ... |
Login on coursera. org with the given credentials. | def login(session, username, password, class_name=None):
"""
Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag
"""
logging.debug('Initiating login.')
try:
session.cookies.clear('.course... |
Authenticate on class. coursera. org | def down_the_wabbit_hole(session, class_name):
"""
Authenticate on class.coursera.org
"""
auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name)
r = session.get(auth_redirector_url)
logging.debug('Following %s to authenticate on class.coursera.org.',
auth_redir... |
Get the necessary cookies to authenticate on class. coursera. org. | def get_authentication_cookies(session, class_name, username, password):
"""
Get the necessary cookies to authenticate on class.coursera.org.
To access the class pages we need two cookies on class.coursera.org:
csrf_token, session
"""
# First, check if we already have the .coursera.org coo... |
Check whether we have all the required cookies to authenticate on class. coursera. org. | def do_we_have_enough_cookies(cj, class_name):
"""
Check whether we have all the required cookies
to authenticate on class.coursera.org.
"""
domain = 'class.coursera.org'
path = "/" + class_name
return cj.get('csrf_token', domain=domain, path=path) is not None |
Checks whether we have all the required cookies to authenticate on class. coursera. org. Also check for and remove stale session. | def validate_cookies(session, class_name):
"""
Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session.
"""
if not do_we_have_enough_cookies(session.cookies, class_name):
return False
url = CLASS_URL.format(class... |
Makes a string of cookie keys and values. Can be used to set a Cookie header. | def make_cookie_values(cj, class_name):
"""
Makes a string of cookie keys and values.
Can be used to set a Cookie header.
"""
path = "/" + class_name
cookies = [c.name + '=' + c.value
for c in cj
if c.domain == "class.coursera.org"
and c.path == path... |
Return a RequestsCookieJar containing the cookies for. coursera. org and class. coursera. org found in the given cookies_file. | def find_cookies_for_class(cookies_file, class_name):
"""
Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file.
"""
path = "/" + class_name
def cookies_filter(c):
return c.domain == ".coursera.org" \
or (... |
Load cookies file. | def load_cookies_file(cookies_file):
"""
Load cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string.
"""
logging.debug('Loading cookie file %s into memory.', cookies_file)
cookies = StringIO()
cookies.write('... |
Returns a RequestsCookieJar containing the cached cookies for the given user. | def get_cookies_from_cache(username):
"""
Returns a RequestsCookieJar containing the cached cookies for the given
user.
"""
logging.debug('Trying to get cookies from the cache.')
path = get_cookies_cache_path(username)
cj = requests.cookies.RequestsCookieJar()
try:
cached_cj = ... |
Save RequestsCookieJar to disk in Mozilla s cookies. txt file format. | def write_cookies_to_cache(cj, username):
"""
Save RequestsCookieJar to disk in Mozilla's cookies.txt file format.
This prevents us from repeated authentications on the
accounts.coursera.org and class.coursera.org/class_name sites.
"""
mkdir_p(PATH_COOKIES, 0o700)
path = get_cookies_cache_p... |
Get the cookies for the given class. | def get_cookies_for_class(session, class_name,
cookies_file=None,
username=None,
password=None):
"""
Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is i... |
Download an HTML page using the requests session. Low - level function that allows for flexible request configuration. | def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with... |
Download an HTML page using the requests session. | def get_page(session,
url,
json=False,
post=False,
data=None,
headers=None,
quiet=False,
**kwargs):
"""
Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.... |
Download an HTML page using the requests session and return the final URL after following redirects. | def get_page_and_url(session, url):
"""
Download an HTML page using the requests session and return
the final URL after following redirects.
"""
reply = get_reply(session, url)
return reply.text, reply.url |
Checks whether a give format/ url should be skipped and not downloaded. | def skip_format_url(format_, url):
"""
Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False oth... |
Select formats to download. | def find_resources_to_get(lecture, file_formats, resource_filter, ignored_formats=None):
"""
Select formats to download.
"""
resources_to_get = []
if ignored_formats is None:
ignored_formats = []
if len(ignored_formats):
logging.info("The following file formats will be ignored:... |
Generate README. rst from README. md via pandoc. | def generate_readme_rst():
"""
Generate README.rst from README.md via pandoc.
In case of errors, we show a message having the error that we got and
exit the program.
"""
pandoc_cmd = [
'pandoc',
'--from=markdown',
'--to=rst',
'--output=README.rst',
'READ... |
Read the contents of filename or give an alternative result instead. | def read_file(filename, alt=None):
"""
Read the contents of filename or give an alternative result instead.
"""
lines = None
try:
with open(filename, encoding='utf-8') as f:
lines = f.read()
except IOError:
lines = [] if alt is None else alt
return lines |
Check if there is a Git tag already in place | def release_check():
"""Check if there is a Git tag already in place"""
tags = local("git tag", capture=True)
tags = set(tags.splitlines())
if env.version in tags:
raise Exception("Already released v. %r" % env.version) |
Release a new version | def release():
"""Release a new version"""
release_check()
build()
print("Releasing %s version %s." % (env.projname, env.version))
local("git tag %s" % env.version)
local('gpg --detach-sign --armor dist/coursera-*.tar.gz*')
local('twine upload dist/coursera-*.tar.gz*')
local("git push")
... |
Checks whether any given name is not a class but a specialization. | def expand_specializations(session, class_names):
"""
Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names.
"""
result = []
for class_name in class_names:
specialization = Specializatio... |
Perform basic conversion of instructions markup. This includes replacement of several textual markup tags with their HTML equivalents. | def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta char... |
Convert images of instructions markup. Images are downloaded base64 - encoded and inserted into <img > tags. | def _convert_markup_images(self, soup):
"""
Convert images of instructions markup. Images are downloaded,
base64-encoded and inserted into <img> tags.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 6. Replace <img> assets with actual image c... |
Convert audios of instructions markup. Audios are downloaded base64 - encoded and inserted as <audio controls > <source > tag. | def _convert_markup_audios(self, soup):
"""
Convert audios of instructions markup. Audios are downloaded,
base64-encoded and inserted as <audio controls> <source> tag.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 7. Replace <asset> audio a... |
Create an instance using a session and a course_name. | def create(session, course_name):
"""
Create an instance using a session and a course_name.
@param session: Requests session.
@type session: requests.Session
@param course_name: Course name (slug) from course json.
@type course_name: str
@return: Instance of On... |
List enrolled courses. | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
reply = get_page(self._session, OPENCOURSE_MEMBERSHIPS, json=True)
course_list = reply['linked']['courses.v1']
slugs = [element['slug'] for element in ... |
Return the download URLs of on - demand course video. | def extract_links_from_lecture(self, course_id,
video_id, subtitle_language='en',
resolution='540p'):
"""
Return the download URLs of on-demand course video.
@param video_id: Video ID.
@type video_id: str
@pa... |
Obtain a list of asset ids from a lecture. | def _get_lecture_asset_ids(self, course_id, video_id):
"""
Obtain a list of asset ids from a lecture.
"""
dom = get_page(self._session, OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL,
json=True, course_id=course_id, video_id=video_id)
# Note that we extract here "i... |
Perform asset normalization. For some reason assets that are sometimes present in lectures have @1 at the end of their id. Such uncut asset id when fed to OPENCOURSE_ASSETS_URL results in error that says: Routing error: get - all not implemented. To avoid that the last two characters from asset id are cut off and after... | def _normalize_assets(self, assets):
"""
Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' no... |
Extract links to files of the asset ids. | def _extract_links_from_lecture_assets(self, asset_ids):
"""
Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text
"""
links = {}
def _add_asset(name,... |
Get list of asset urls and file names. This method may internally use AssetRetriever to extract asset element types. | def _get_asset_urls(self, asset_id):
"""
Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
... |
Return a dictionary with links to supplement files ( pdf csv zip ipynb html and so on ) extracted from peer assignment. | def extract_links_from_peer_assignment(self, element_id):
"""
Return a dictionary with links to supplement files (pdf, csv, zip,
ipynb, html and so on) extracted from peer assignment.
@param element_id: Element ID to extract files from.
@type element_id: str
@return: @s... |
Return a dictionary with supplement files ( pdf csv zip ipynb html and so on ) extracted from supplement page. | def extract_links_from_supplement(self, element_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug(
'Gathering sup... |
Extract asset tags from text into a convenient form. | def _extract_asset_tags(self, text):
"""
Extract asset tags from text into a convenient form.
@param text: Text to extract asset tags from. This text contains HTML
code that is parsed by BeautifulSoup.
@type text: str
@return: Asset map.
@rtype: {
... |
Extract asset URLs along with asset ids. | def _extract_asset_urls(self, asset_ids):
"""
Extract asset URLs along with asset ids.
@param asset_ids: List of ids to get URLs for.
@type assertn: [str]
@return: List of dictionaries with asset URLs and ids.
@rtype: [{
'id': '<id>',
'url': '<ur... |
Return a dictionary with supplement files ( pdf csv zip ipynb html and so on ) extracted from supplement page. | def extract_links_from_reference(self, short_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug('Gathering resource URLs for s... |
Extract assignment text ( instructions ). | def _extract_programming_immediate_instructions_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str... |
Extract notebook text ( instructions ). | def _extract_notebook_text(self, element_id):
"""
Extract notebook text (instructions).
@param element_id: Element id to extract notebook links.
@type element_id: str
@return: Notebook URL.
@rtype: [str]
"""
headers = self._auth_headers_with_json()
... |
Extract assignment text ( instructions ). | def _extract_assignment_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str]
"""
do... |
Extract peer assignment text ( instructions ). | def _extract_peer_assignment_text(self, element_id):
"""
Extract peer assignment text (instructions).
@param element_id: Element id to extract peer assignment instructions from.
@type element_id: str
@return: List of peer assignment text (instructions).
@rtype: [str]
... |
Extract supplement links from the html text. Links may be provided in two ways: 1. <a > tags with href attribute 2. <asset > tags with id attribute ( requires additional request to get the direct URL to the asset file ) | def _extract_links_from_text(self, text):
"""
Extract supplement links from the html text. Links may be provided
in two ways:
1. <a> tags with href attribute
2. <asset> tags with id attribute (requires additional request
to get the direct URL to the asset f... |
Scan the text and extract asset tags and links to corresponding files. | def _extract_links_from_asset_tags_in_text(self, text):
"""
Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text
"""
# Extract asset tags fr... |
Extract supplement links from the html text that contains <a > tags with href attribute. | def _extract_links_from_a_tags_in_text(self, text):
"""
Extract supplement links from the html text that contains <a> tags
with href attribute.
@param text: HTML text.
@type text: str
@return: Dictionary with supplement links grouped by extension.
@rtype: {
... |
Create M3U playlist with contents of section_dir/ *. mp4. The playlist will be created in that directory. | def create_m3u_playlist(section_dir):
"""
Create M3U playlist with contents of `section_dir`/*.mp4. The playlist
will be created in that directory.
@param section_dir: Path where to scan for *.mp4 files.
@type section_dir: str
"""
path_to_return = os.getcwd()
for (_path, subdirs, files... |
List enrolled courses. | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
course = CourseraOnDemand(session=self._session,
course_id=None,
course_name=None)
return c... |
Get the on - demand course listing webpage. | def _get_on_demand_syllabus(self, class_name):
"""
Get the on-demand course listing webpage.
"""
url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format(
class_name=class_name)
page = get_page(self._session, url)
logging.debug('Downloaded %s (%d bytes)', url, le... |
Parse a Coursera on - demand course listing/ syllabus page. | def _parse_on_demand_syllabus(self, course_name, page, reverse=False,
unrestricted_filenames=False,
subtitle_language='en',
video_resolution=None,
download_quizzes=False,
... |
This huge function generates a hierarchy with hopefully more clear structure of modules/ sections/ lectures. | def _iter_modules(modules, class_name, path, ignored_formats, args):
"""
This huge function generates a hierarchy with hopefully more
clear structure of modules/sections/lectures.
"""
file_formats = args.file_formats
lecture_filter = args.lecture_filter
resource_filter = args.resource_filter... |
Helper generator that traverses modules in returns a flattened iterator. | def _walk_modules(modules, class_name, path, ignored_formats, args):
"""
Helper generator that traverses modules in returns a flattened
iterator.
"""
for module in _iter_modules(modules=modules,
class_name=class_name,
path=path,
... |
Handle resource. This function builds up resource file name and downloads it if necessary. | def _handle_resource(self, url, fmt, lecture_filename, callback, last_update):
"""
Handle resource. This function builds up resource file name and
downloads it if necessary.
@param url: URL of the resource.
@type url: str
@param fmt: Format of the resource (pdf, csv, et... |
Prepare a destination lecture filename. | def get_lecture_filename(combined_section_lectures_nums,
section_dir,
secnum,
lecnum,
lecname,
title,
fmt):
"""
Prepare a destination lecture filename.
@para... |
Get human readable version of given bytes. Ripped from https:// github. com/ rg3/ youtube - dl | def format_bytes(bytes):
"""
Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl
"""
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent = int(math.log... |
Decides which downloader to use. | def get_downloader(session, class_name, args):
"""
Decides which downloader to use.
"""
external = {
'wget': WgetDownloader,
'curl': CurlDownloader,
'aria2': Aria2Downloader,
'axel': AxelDownloader,
}
for bin, class_ in iteritems(external):
if getattr(ar... |
Download the given url to the given file. When the download is aborted by the user the partially downloaded file is also removed. | def download(self, url, filename, resume=False):
"""
Download the given url to the given file. When the download
is aborted by the user, the partially downloaded file is also removed.
"""
try:
self._start_download(url, filename, resume)
except KeyboardInterru... |
Extract cookies from the requests session and add them to the command | def _prepare_cookies(self, command, url):
"""
Extract cookies from the requests session and add them to the command
"""
req = requests.models.Request()
req.method = 'GET'
req.url = url
cookie_values = requests.cookies.get_cookie_header(
self.session.... |
Report download progress. | def report_progress(self):
"""Report download progress."""
percent = self.calc_percent()
total = format_bytes(self._total)
speed = self.calc_speed()
total_speed_report = '{0} at {1}'.format(total, speed)
report = '\r{0: <56} {1: >30}'.format(percent, total_speed_report)... |
Actual download call. Calls the underlying file downloader catches all exceptions and returns the result. | def _download_wrapper(self, url, *args, **kwargs):
"""
Actual download call. Calls the underlying file downloader,
catches all exceptions and returns the result.
"""
try:
return url, self._file_downloader.download(url, *args, **kwargs)
except Exception as e:
... |
Return a list of config files paths to try in order given config file name and possibly a user - specified path. | def get_config_paths(config_name): # pragma: no test
"""
Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way"... |
Return the tuple user/ password given a path for the. netrc file. | def authenticate_through_netrc(path=None):
"""
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
"""
errors = []
netrc_machine = 'coursera-dl'
paths = [path] if path else get_config_paths("netrc")
for path in path... |
Return valid username password tuple. | def get_credentials(username=None, password=None, netrc=None, use_keyring=False):
"""
Return valid username, password tuple.
Raises CredentialsError if username or password is missing.
"""
if netrc:
path = None if netrc is True else netrc
return authenticate_through_netrc(path)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.