INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 to wrap.
Returns:
list of pairs: [event_index, value... | 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.
Args:
engine (Engine): engine object.
log_handler (callable): a logging handler to execute
event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.eng... | 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.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should start (reset) the timer.
pause (Events):
Event which should pause 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.
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, y-axis value
event_name: Event name which is used to setup x-axis l... | 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.
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'). | 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
@param path: Path to normalize.
@type path: st... | 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.
@param url: URL to clean.
@type url: str
@return: Cleaned URL.
@rtype: str | 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.
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
seen any update in the last 30 days or more. ... | 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.
@param destination: Destination dictionary that will be extended.
@type destination: @see CourseraOnDemand._extract_links_from_text
... | 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.
@param args: Command-line arguments.
@type args: namedtuple | 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.
@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) | 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.
@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) | 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.
@param session: Requests session.
@type session: requests.Session
@param include_cauth: Flag that indicates whether CAUTH cookies should be
included as well.
@type include_cauth:... | 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.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag | 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.
To access the class pages we need two cookies on class.coursera.org:
csrf_token, session | 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.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string. | 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.
This prevents us from repeated authentications on the
accounts.coursera.org and class.coursera.org/class_name sites. | 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.
We do not validate the cookies if they are loaded from a cookies file
because this is intended for debugging purposes or if the coursera
authentication process has changed. | 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.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whet... | 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.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whether POST request should be sent.
@type post: bool
@param data:... | 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.
@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 otherwise.
@rtype bool | 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.
In case of errors, we show a message having the error that we got and
exit the program. | 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.
If it's a specialization, expand the list of class names with the child
class names. | 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.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | 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.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | 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.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | 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.
@param session: Requests session.
@type session: requests.Session
@param course_name: Course name (slug) from course json.
@type course_name: str
@return: Instance of OnDemandCourseMaterialItems
@rtype: OnDemandCour... | 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.
@return: List of enrolled courses.
@rtype: [str] | 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.
@param video_id: Video ID.
@type video_id: str
@param subtitle_language: Subtitle language.
@type subtitle_language: str
@param resolution: Preferred video resolution.
@type resolution: str
@return: @see Cour... | 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 chara... | 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.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text | 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.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
@rtype [{
'name': '<filename.ext>'
... | 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.
@param element_id: Element ID to extract files from.
@type element_id: str
@return: @see CourseraOnDemand._extract_links_from_text | 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.
@return: @see CourseraOnDemand._extract_links_from_text | 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.
@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: {
'<id>': {
'name': '<name>',
... | 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.
@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': '<url>'
}] | 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.
@return: @see CourseraOnDemand._extract_links_from_text | 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).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str] | 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).
@param element_id: Element id to extract notebook links.
@type element_id: str
@return: Notebook URL.
@rtype: [str] | 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).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str] | 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).
@param element_id: Element id to extract peer assignment instructions from.
@type element_id: str
@return: List of peer assignment text (instructions).
@rtype: [str] | 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)
@param text: HTML text.
@type text: str
... | 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.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text | 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.
@param text: HTML text.
@type text: str
@return: Dictionary with supplement links grouped by extension.
@rtype: {
'<extension1>': [
('<link1>', '<title1>'),
... | 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.
@param section_dir: Path where to scan for *.mp4 files.
@type section_dir: str | 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.
@return: List of enrolled courses.
@rtype: [str] | 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.
@return: Tuple of (bool, list), where bool indicates whether
there was at least on error while parsing syllabus, the list
is a list of parsed modules.
@rtype: (bool, list) | 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.
@param url: URL of the resource.
@type url: str
@param fmt: Format of the resource (pdf, csv, etc)
@type fmt: str
@param lecture_filename: File name of the lecture.
@type... | 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.
@param combined_section_lectures_nums: Flag that indicates whether
section lectures should have combined numbering.
@type combined_section_lectures_nums: bool
@param section_dir: Path to current section directory.
@type section_dir: str
@param secnu... | 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.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way" of doing
things.
A brief recap of the situation (all fil... | 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.
Raises CredentialsError if no valid netrc file is found. | 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.
Raises CredentialsError if username or password is missing. | 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)
... |
The mimetype (content type without charset etc.) | def mimetype(self):
"""The mimetype (content type without charset etc.)"""
ct = self.headers.get("content-type")
if ct:
return ct.split(";")[0].strip() |
The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5 | def mimetype_params(self):
"""The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
"""
def on_update(d):
self.headers["Content-Type"] = dump_optio... |
Index of all pages. | def page_index(request):
"""Index of all pages."""
letters = {}
for page in Page.query.order_by(Page.name):
letters.setdefault(page.name.capitalize()[0], []).append(page)
return Response(
generate_template("page_index.html", letters=sorted(letters.items()))
) |
Display the recent changes. | def recent_changes(request):
"""Display the recent changes."""
page = max(1, request.args.get("page", type=int))
query = RevisionedPage.query.order_by(RevisionedPage.revision_id.desc())
return Response(
generate_template(
"recent_changes.html",
pagination=Pagination(query... |
Helper function that creates a plnt app. | def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app |
Initialize the database | def initdb():
"""Initialize the database"""
from plnt.database import Blog, session
make_app().init_database()
# and now fill in some python blogs everybody should read (shamelessly
# added my own blog too)
blogs = [
Blog(
"Armin Ronacher",
"http://lucumr.pocoo.o... |
Start a new development server. | def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
"""Start a new development server."""
app = make_app()
reloader = not no_reloader
evalex = not no_evalex
run_simple(
hostname,
port,
app,
use_reloader=reloader,
use_debugger=... |
Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures. | def iter_multi_items(mapping):
"""Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures.
"""
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
yield item
elif isinstance(mapping, dict):
... |
Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the default as if the value was not
found:
>>... | def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the de... |
Used internally by the accessor properties. | def _get_cache_value(self, key, empty, type):
"""Used internally by the accessor properties."""
if type is bool:
return key in self
if key in self:
value = self[key]
if value is None:
return empty
elif type is not None:
... |
Used internally by the accessor properties. | def _set_cache_value(self, key, value, type):
"""Used internally by the accessor properties."""
if type is bool:
if value:
self[key] = None
else:
self.pop(key, None)
else:
if value is None:
self.pop(key)
... |
Remove a header from the set. This raises an :exc:`KeyError` if the
header is not in the set.
.. versionchanged:: 0.5
In older versions a :exc:`IndexError` was raised instead of a
:exc:`KeyError` if the object was missing.
:param header: the header to be removed. | def remove(self, header):
"""Remove a header from the set. This raises an :exc:`KeyError` if the
header is not in the set.
.. versionchanged:: 0.5
In older versions a :exc:`IndexError` was raised instead of a
:exc:`KeyError` if the object was missing.
:param he... |
Add all the headers from the iterable to the set.
:param iterable: updates the set with the items from the iterable. | def update(self, iterable):
"""Add all the headers from the iterable to the set.
:param iterable: updates the set with the items from the iterable.
"""
inserted_any = False
for header in iterable:
key = header.lower()
if key not in self._set:
... |
Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up. | def find(self, header):
"""Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up.
"""
header = header.lower()
for idx, item in enumerate(self._headers):
if item.lower() == header:
return idx
... |
Return the index of the header in the set or raise an
:exc:`IndexError`.
:param header: the header to be looked up. | def index(self, header):
"""Return the index of the header in the set or raise an
:exc:`IndexError`.
:param header: the header to be looked up.
"""
rv = self.find(header)
if rv < 0:
raise IndexError(header)
return rv |
Clear the set. | def clear(self):
"""Clear the set."""
self._set.clear()
del self._headers[:]
if self.on_update is not None:
self.on_update(self) |
Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the original case like in the
:... | def as_set(self, preserve_casing=False):
"""Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the origina... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.