_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q276800 | highlight_info | test | def highlight_info(ctx, style):
"""Outputs the CSS which can be customized for highlighted code"""
click.secho("The following styles are available to choose from:", fg="green")
click.echo(list(pygments.styles.get_all_styles()))
click.echo()
click.secho(
f'The following CSS for the "{style}" ... | python | {
"resource": ""
} |
q276801 | Polygon._draw_mainlayer | test | def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws a closed polygon """
gc.save_state()
try:
# self._draw_bounds(gc)
if len(self.points) >= 2:
# Set the drawing parameters.
gc.set_fill_color(self.pen.fill_color_)
... | python | {
"resource": ""
} |
q276802 | Polygon.is_in | test | def is_in(self, point_x, point_y):
""" Test if a point is within this polygonal region """
point_array = array(((point_x, point_y),))
vertices = array(self.points)
winding = self.inside_rule == "winding"
result = points_in_polygon(point_array, vertices, winding)
return r... | python | {
"resource": ""
} |
q276803 | BSpline._draw_mainlayer | test | def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the Bezier component """
if not self.points: return
gc.save_state()
try:
gc.set_fill_color(self.pen.fill_color_)
gc.set_line_width(self.pen.line_width)
gc.set_stroke_color(sel... | python | {
"resource": ""
} |
q276804 | DatabaseExtension._handle_event | test | def _handle_event(self, event, *args, **kw):
"""Broadcast an event to the database connections registered."""
for engine in self.engines.values():
if hasattr(engine, event):
getattr(engine, event)(*args, **kw) | python | {
"resource": ""
} |
q276805 | Worker.run | test | def run(self):
"""
Method that gets run when the Worker thread is started.
When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue.
"""
while not self.stopper.is_set():
try:
item =... | python | {
"resource": ""
} |
q276806 | Pager.get_full_page_url | test | def get_full_page_url(self, page_number, scheme=None):
"""Get the full, external URL for this page, optinally with the passed in URL scheme"""
args = dict(
request.view_args,
_external=True,
)
if scheme is not None:
args['_scheme'] = scheme
... | python | {
"resource": ""
} |
q276807 | Pager.render_prev_next_links | test | def render_prev_next_links(self, scheme=None):
"""Render the rel=prev and rel=next links to a Markup object for injection into a template"""
output = ''
if self.has_prev:
output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme))
... | python | {
"resource": ""
} |
q276808 | Pager.render_seo_links | test | def render_seo_links(self, scheme=None):
"""Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template"""
out = self.render_prev_next_links(scheme=scheme)
if self.total_pages == 1:
out += self.render_canonical_link(scheme=scheme)
... | python | {
"resource": ""
} |
q276809 | _content_type_matches | test | def _content_type_matches(candidate, pattern):
"""Is ``candidate`` an exact match or sub-type of ``pattern``?"""
def _wildcard_compare(type_spec, type_pattern):
return type_pattern == '*' or type_spec == type_pattern
return (
_wildcard_compare(candidate.content_type, pattern.content_type) a... | python | {
"resource": ""
} |
q276810 | select_content_type | test | def select_content_type(requested, available):
"""Selects the best content type.
:param requested: a sequence of :class:`.ContentType` instances
:param available: a sequence of :class:`.ContentType` instances
that the server is capable of producing
:returns: the selected content type (from ``a... | python | {
"resource": ""
} |
q276811 | rewrite_url | test | def rewrite_url(input_url, **kwargs):
"""
Create a new URL from `input_url` with modifications applied.
:param str input_url: the URL to modify
:keyword str fragment: if specified, this keyword sets the
fragment portion of the URL. A value of :data:`None`
will remove the fragment port... | python | {
"resource": ""
} |
q276812 | remove_url_auth | test | def remove_url_auth(url):
"""
Removes the user & password and returns them along with a new url.
:param str url: the URL to sanitize
:return: a :class:`tuple` containing the authorization portion and
the sanitized URL. The authorization is a simple user & password
:class:`tuple`.
... | python | {
"resource": ""
} |
q276813 | _create_url_identifier | test | def _create_url_identifier(user, password):
"""
Generate the user+password portion of a URL.
:param str user: the user name or :data:`None`
:param str password: the password or :data:`None`
"""
if user is not None:
user = parse.quote(user.encode('utf-8'), safe=USERINFO_SAFE_CHARS)
... | python | {
"resource": ""
} |
q276814 | _normalize_host | test | def _normalize_host(host, enable_long_host=False, encode_with_idna=None,
scheme=None):
"""
Normalize a host for a URL.
:param str host: the host name to normalize
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length ... | python | {
"resource": ""
} |
q276815 | discover_modules | test | def discover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function searches the top-level of the directory
tree for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strin... | python | {
"resource": ""
} |
q276816 | rdiscover_modules | test | def rdiscover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function recursively searches the directory tree
for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings r... | python | {
"resource": ""
} |
q276817 | rlist_modules | test | def rlist_modules(mname):
"""
Attempts to the submodules under a module recursively. This function
works for modules located in the default path as well as extended paths
via the sys.meta_path hooks.
This function carries the expectation that the hidden module variable
'__path__' has been set c... | python | {
"resource": ""
} |
q276818 | list_classes | test | def list_classes(mname, cls_filter=None):
"""
Attempts to list all of the classes within a specified module. This
function works for modules located in the default path as well as
extended paths via the sys.meta_path hooks.
If a class filter is set, it will be called with each class as its
para... | python | {
"resource": ""
} |
q276819 | rlist_classes | test | def rlist_classes(module, cls_filter=None):
"""
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value... | python | {
"resource": ""
} |
q276820 | ensure_dir | test | def ensure_dir(path):
"""Ensure that a needed directory exists, creating it if it doesn't"""
try:
log.info('Ensuring directory exists: %s' % path)
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise | python | {
"resource": ""
} |
q276821 | AzureStorageBroker.put_text | test | def put_text(self, key, contents):
"""Store the given text contents so that they are later retrievable by
the given key."""
self._blobservice.create_blob_from_text(
self.uuid,
key,
contents
) | python | {
"resource": ""
} |
q276822 | luhn_check | test | def luhn_check(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit *... | python | {
"resource": ""
} |
q276823 | get_git_version | test | def get_git_version():
"""
Return the git hash as a string.
Apparently someone got this from numpy's setup.py. It has since been
modified a few times.
"""
# Return the git revision as a string
# copied from numpy setup.py
def _minimal_ext_cmd(cmd):
# construct minimal environmen... | python | {
"resource": ""
} |
q276824 | ModuleLoader.load_module | test | def load_module(self, module_name):
"""
Loads a module's code and sets the module's expected hidden
variables. For more information on these variables and what they
are for, please see PEP302.
:param module_name: the full name of the module to load
"""
if module_... | python | {
"resource": ""
} |
q276825 | ModuleFinder.add_path | test | def add_path(self, path):
"""
Adds a path to search through when attempting to look up a module.
:param path: the path the add to the list of searchable paths
"""
if path not in self.paths:
self.paths.append(path) | python | {
"resource": ""
} |
q276826 | ModuleFinder.find_module | test | def find_module(self, module_name, path=None):
"""
Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
... | python | {
"resource": ""
} |
q276827 | split_line | test | def split_line(line, min_line_length=30, max_line_length=100):
"""
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
:param line: The line to split
:param min_line_length: The minimum desired line length
:param max_line_length: The maximum desire... | python | {
"resource": ""
} |
q276828 | remove_namespaces | test | def remove_namespaces(root):
"""Call this on an lxml.etree document to remove all namespaces"""
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'):
continue
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i + 1:]
objectify.deannotate(root... | python | {
"resource": ""
} |
q276829 | VersionReleaseChecks.consistency | test | def consistency(self, desired_version=None, include_package=False,
strictness=None):
"""Checks that the versions are consistent
Parameters
----------
desired_version: str
optional; the version that all of these should match
include_package: bool
... | python | {
"resource": ""
} |
q276830 | Rule.from_yaml | test | def from_yaml(cls, **kwargs):
"""Creates a new instance of a rule in relation to the config file.
This updates the dictionary of the class with the added details, which
allows for flexibility in the configuation file.
Only called when parsing the default configuation file.
"""
... | python | {
"resource": ""
} |
q276831 | Rule.merge | test | def merge(self, new_dict):
"""Merges a dictionary into the Rule object."""
actions = new_dict.pop("actions")
for action in actions:
self.add_action(action)
self.__dict__.update(new_dict) | python | {
"resource": ""
} |
q276832 | Rule.execute_actions | test | def execute_actions(self, cwd):
"""Iterates over the actions and executes them in order."""
self._execute_globals(cwd)
for action in self.actions:
logger.info("executing {}".format(action))
p = subprocess.Popen(action, shell=True, cwd=cwd)
p.wait() | python | {
"resource": ""
} |
q276833 | CommandSet.from_yaml | test | def from_yaml(cls, defaults, **kwargs):
"""Creates a new instance of a rule by merging two dictionaries.
This allows for independant configuration files to be merged
into the defaults."""
# TODO: I hate myself for this. Fix it later mmkay?
if "token" not in defaults:
... | python | {
"resource": ""
} |
q276834 | LfsSmtpHandler.add_details | test | def add_details(self, message):
"""
Add extra details to the message. Separate so that it can be overridden
"""
msg = message
# Try to append Flask request details
try:
from flask import request
url = request.url
method = request.metho... | python | {
"resource": ""
} |
q276835 | LfsSmtpHandler.emit | test | def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
# First, remove all records from the rate limiter list that are over a minute old
now = timetool.unix_time()
one_minute_ago = now - ... | python | {
"resource": ""
} |
q276836 | RenditionAwareStructBlock.get_context | test | def get_context(self, value):
"""Ensure `image_rendition` is added to the global context."""
context = super(RenditionAwareStructBlock, self).get_context(value)
context['image_rendition'] = self.rendition.\
image_rendition or 'original'
return context | python | {
"resource": ""
} |
q276837 | AttackProtect.log_attempt | test | def log_attempt(self, key):
"""
Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to
the lock table
"""
with self.lock:
if key not in self.attempts:
self.attempts[key] = 1
else:
... | python | {
"resource": ""
} |
q276838 | Music2Storage.add_to_queue | test | def add_to_queue(self, url):
"""
Adds an URL to the download queue.
:param str url: URL to the music service track
"""
if self.connection_handler.current_music is None:
log.error('Music service is not initialized. URL was not added to queue.')
elif self.conn... | python | {
"resource": ""
} |
q276839 | Music2Storage.start_workers | test | def start_workers(self, workers_per_task=1):
"""
Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received.
:param int workers_per_task: Number of workers to create for each task in the pipeline
"""
if not self.... | python | {
"resource": ""
} |
q276840 | Client.set | test | def set(self, k, v):
"""Add or update a key, value pair to the database"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
r = requests.put(url, data=str(v))
if r.status_code != 200 or r.json() is not True:
raise KVStoreError('PUT returned {}'.format(r.status... | python | {
"resource": ""
} |
q276841 | Client.get | test | def get(self, k, wait=False, wait_index=False, timeout='5m'):
"""Get the value of a given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if wait:
params['index'] = wait_index
params['wait'] = timeout
r = requests.get(ur... | python | {
"resource": ""
} |
q276842 | Client.recurse | test | def recurse(self, k, wait=False, wait_index=None, timeout='5m'):
"""Recursively get the tree below the given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
params['recurse'] = 'true'
if wait:
params['wait'] = timeout
if... | python | {
"resource": ""
} |
q276843 | Client.index | test | def index(self, k, recursive=False):
"""Get the current index of the key or the subtree.
This is needed for later creating long polling requests
"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ... | python | {
"resource": ""
} |
q276844 | Client.delete | test | def delete(self, k, recursive=False):
"""Delete a given key or recursively delete the tree below it"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.delete(url, params=params)
if ... | python | {
"resource": ""
} |
q276845 | plot_heatmap | test | def plot_heatmap(X, y, top_n=10, metric='correlation', method='complete'):
'''
Plot heatmap which shows features with classes.
:param X: list of dict
:param y: labels
:param top_n: most important n feature
:param metric: metric which will be used for clustering
:param method: method which w... | python | {
"resource": ""
} |
q276846 | add_months | test | def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
y... | python | {
"resource": ""
} |
q276847 | add_months_to_date | test | def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
... | python | {
"resource": ""
} |
q276848 | is_christmas_period | test | def is_christmas_period():
"""Is this the christmas period?"""
now = datetime.date.today()
if now.month != 12:
return False
if now.day < 15:
return False
if now.day > 27:
return False
return True | python | {
"resource": ""
} |
q276849 | ConnectionHandler.use_music_service | test | def use_music_service(self, service_name, api_key):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
try:
self.current_music = self.music_services[ser... | python | {
"resource": ""
} |
q276850 | ConnectionHandler.use_storage_service | test | def use_storage_service(self, service_name, custom_path):
"""
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage ... | python | {
"resource": ""
} |
q276851 | SkUtilsIO.from_csv | test | def from_csv(self, label_column='labels'):
'''
Read dataset from csv.
'''
df = pd.read_csv(self.path, header=0)
X = df.loc[:, df.columns != label_column].to_dict('records')
X = map_dict_list(X, if_func=lambda k, v: v and math.isfinite(v))
y = list(df[label_column]... | python | {
"resource": ""
} |
q276852 | SkUtilsIO.from_json | test | def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
'rt') if self.gz else open(self.path) as file:
return list(map(list, zip(*json.load(file))))[::-1] | python | {
"resource": ""
} |
q276853 | SkUtilsIO.to_json | test | def to_json(self, X, y):
'''
Reads dataset to csv.
:param X: dataset as list of dict.
:param y: labels.
'''
with gzip.open('%s.gz' % self.path, 'wt') if self.gz else open(
self.path, 'w') as file:
json.dump(list(zip(y, X)), file) | python | {
"resource": ""
} |
q276854 | filter_by_label | test | def filter_by_label(X, y, ref_label, reverse=False):
'''
Select items with label from dataset.
:param X: dataset
:param y: labels
:param ref_label: reference label
:param bool reverse: if false selects ref_labels else eliminates
'''
check_reference_label(y, ref_label)
return list(z... | python | {
"resource": ""
} |
q276855 | average_by_label | test | def average_by_label(X, y, ref_label):
'''
Calculates average dictinary from list of dictionary for give label
:param List[Dict] X: dataset
:param list y: labels
:param ref_label: reference label
'''
# TODO: consider to delete defaultdict
return defaultdict(float,
... | python | {
"resource": ""
} |
q276856 | feature_importance_report | test | def feature_importance_report(X,
y,
threshold=0.001,
correcting_multiple_hypotesis=True,
method='fdr_bh',
alpha=0.1,
sort_by='pval'):
''... | python | {
"resource": ""
} |
q276857 | SessionData.restore_data | test | def restore_data(self, data_dict):
"""
Restore the data dict - update the flask session and this object
"""
session[self._base_key] = data_dict
self._data_dict = session[self._base_key] | python | {
"resource": ""
} |
q276858 | _mergedict | test | def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a | python | {
"resource": ""
} |
q276859 | multi | test | def multi(dispatch_fn, default=None):
"""A decorator for a function to dispatch on.
The value returned by the dispatch function is used to look up the
implementation function based on its dispatch key.
The dispatch function is available using the `dispatch_fn` function.
"""
def _inner(*args, ... | python | {
"resource": ""
} |
q276860 | method | test | def method(dispatch_fn, dispatch_key=None):
"""A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function.
"""
def apply_decorator(fn):
if dispatch_key is None:
# Default case
... | python | {
"resource": ""
} |
q276861 | find_blocks | test | def find_blocks():
"""
Auto-discover INSTALLED_APPS registered_blocks.py modules and fail
silently when not present. This forces an import on them thereby
registering their blocks.
This is a near 1-to-1 copy of how django's admin application registers
models.
"""
for app in settings.IN... | python | {
"resource": ""
} |
q276862 | RegisteredBlockStreamFieldRegistry._verify_block | test | def _verify_block(self, block_type, block):
"""
Verifies a block prior to registration.
"""
if block_type in self._registry:
raise AlreadyRegistered(
"A block has already been registered to the {} `block_type` "
"in the registry. Either unregis... | python | {
"resource": ""
} |
q276863 | RegisteredBlockStreamFieldRegistry.register_block | test | def register_block(self, block_type, block):
"""
Registers `block` to `block_type` in the registry.
"""
self._verify_block(block_type, block)
self._registry[block_type] = block | python | {
"resource": ""
} |
q276864 | RegisteredBlockStreamFieldRegistry.unregister_block | test | def unregister_block(self, block_type):
"""
Unregisters the block associated with `block_type` from the registry.
If no block is registered to `block_type`, NotRegistered will raise.
"""
if block_type not in self._registry:
raise NotRegistered(
'There... | python | {
"resource": ""
} |
q276865 | convert_to_mp3 | test | def convert_to_mp3(file_name, delete_queue):
"""
Converts the file associated with the file_name passed into a MP3 file.
:param str file_name: Filename of the original file in local storage
:param Queue delete_queue: Delete queue to add the original file to after conversion is done
:return str: Fil... | python | {
"resource": ""
} |
q276866 | GitReleaseChecks.reasonable_desired_version | test | def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next ve... | python | {
"resource": ""
} |
q276867 | handle_ssl_redirect | test | def handle_ssl_redirect():
"""
Check if a route needs ssl, and redirect it if not. Also redirects back to http for non-ssl routes. Static routes
are served as both http and https
:return: A response to be returned or None
"""
if request.endpoint and request.endpoint not in ['static', 'fileman... | python | {
"resource": ""
} |
q276868 | init_celery | test | def init_celery(app, celery):
"""
Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance
"""
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
... | python | {
"resource": ""
} |
q276869 | queue_email | test | def queue_email(to_addresses, from_address, subject, body, commit=True, html=True, session=None):
"""
Add a mail to the queue to be sent.
WARNING: Commits by default!
:param to_addresses: The names and addresses to send the email to, i.e. "Steve<steve@fig14.com>, info@fig14.com"
:param from_addres... | python | {
"resource": ""
} |
q276870 | parse_accept | test | def parse_accept(header_value):
"""Parse an HTTP accept-like header.
:param str header_value: the header value to parse
:return: a :class:`list` of :class:`.ContentType` instances
in decreasing quality order. Each instance is augmented
with the associated quality as a ``float`` property
... | python | {
"resource": ""
} |
q276871 | parse_cache_control | test | def parse_cache_control(header_value):
"""
Parse a `Cache-Control`_ header, returning a dictionary of key-value pairs.
Any of the ``Cache-Control`` parameters that do not have directives, such
as ``public`` or ``no-cache`` will be returned with a value of ``True``
if they are set in the header.
... | python | {
"resource": ""
} |
q276872 | parse_content_type | test | def parse_content_type(content_type, normalize_parameter_values=True):
"""Parse a content type like header.
:param str content_type: the string to parse as a content type
:param bool normalize_parameter_values:
setting this to ``False`` will enable strict RFC2045 compliance
in which content... | python | {
"resource": ""
} |
q276873 | parse_forwarded | test | def parse_forwarded(header_value, only_standard_parameters=False):
"""
Parse RFC7239 Forwarded header.
:param str header_value: value to parse
:keyword bool only_standard_parameters: if this keyword is specified
and given a *truthy* value, then a non-standard parameter name
will result ... | python | {
"resource": ""
} |
q276874 | parse_list | test | def parse_list(value):
"""
Parse a comma-separated list header.
:param str value: header value to split into elements
:return: list of header elements as strings
"""
segments = _QUOTED_SEGMENT_RE.findall(value)
for segment in segments:
left, match, right = value.partition(segment)
... | python | {
"resource": ""
} |
q276875 | _parse_parameter_list | test | def _parse_parameter_list(parameter_list,
normalized_parameter_values=_DEF_PARAM_VALUE,
normalize_parameter_names=False,
normalize_parameter_values=True):
"""
Parse a named parameter list in the "common" format.
:param parameter_... | python | {
"resource": ""
} |
q276876 | resize_image_to_fit_width | test | def resize_image_to_fit_width(image, dest_w):
"""
Resize and image to fit the passed in width, keeping the aspect ratio the same
:param image: PIL.Image
:param dest_w: The desired width
"""
scale_factor = dest_w / image.size[0]
dest_h = image.size[1] * scale_factor
scaled_image = i... | python | {
"resource": ""
} |
q276877 | ParameterParser.add_value | test | def add_value(self, name, value):
"""
Add a new value to the list.
:param str name: name of the value that is being parsed
:param str value: value that is being parsed
:raises ietfparse.errors.MalformedLinkValue:
if *strict mode* is enabled and a validation error
... | python | {
"resource": ""
} |
q276878 | Youtube.download | test | def download(self, url):
"""
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
"""
try:
yt = YouTube(url)
except Rege... | python | {
"resource": ""
} |
q276879 | GoogleDrive.connect | test | def connect(self):
"""Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist."""
SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('drive_credentials.json')
creds = store.get()
... | python | {
"resource": ""
} |
q276880 | GoogleDrive.upload | test | def upload(self, file_name):
"""
Uploads the file associated with the file_name passed to Google Drive in the Music folder.
:param str file_name: Filename of the file to be uploaded
:return str: Original filename passed as an argument (in order for the worker to send it to the delete qu... | python | {
"resource": ""
} |
q276881 | LocalStorage.connect | test | def connect(self):
"""Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist."""
if self.music_folder is None:
music_folder = os.path.join(os.path.expanduser('~'), 'Music')
if not os.path.exists(music_folder)... | python | {
"resource": ""
} |
q276882 | RunParameters.write_sky_params_to_file | test | def write_sky_params_to_file(self):
"""Writes the params to file that skytool_Free needs to generate the sky radiance distribution."""
inp_file = self.sky_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
f = open(inp_file, 'w')
f.write('verbose= ' + str(sel... | python | {
"resource": ""
} |
q276883 | RunParameters.update_filenames | test | def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
... | python | {
"resource": ""
} |
q276884 | BioOpticalParameters.read_aphi_from_file | test | def read_aphi_from_file(self, file_name):
"""Read the phytoplankton absorption file from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading ahpi absorption')
try:
self.a_phi = self._read_iop_from_file(file_name)
exce... | python | {
"resource": ""
} |
q276885 | BioOpticalParameters.scale_aphi | test | def scale_aphi(self, scale_parameter):
"""Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
"""
lg.info('Scaling a_phi by :: ' + str(scale_parameter))
try:
self.a_phi = self.a_phi * scale_parameter
except:... | python | {
"resource": ""
} |
q276886 | BioOpticalParameters.read_pure_water_absorption_from_file | test | def read_pure_water_absorption_from_file(self, file_name):
"""Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water absorption from file')
try:
self.a_water = self._read_iop_from_file(f... | python | {
"resource": ""
} |
q276887 | BioOpticalParameters.read_pure_water_scattering_from_file | test | def read_pure_water_scattering_from_file(self, file_name):
"""Read the pure water scattering from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water scattering from file')
try:
self.b_water = self._read_iop_from_file(f... | python | {
"resource": ""
} |
q276888 | BioOpticalParameters._read_iop_from_file | test | def _read_iop_from_file(self, file_name):
"""
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor
:param file_name: filename and path of the csv file
:returns interpolated iop
"""
lg.info('Reading :: ' + file_name + ' :: and ... | python | {
"resource": ""
} |
q276889 | BioOpticalParameters._write_iop_to_file | test | def _write_iop_to_file(self, iop, file_name):
"""Generic iop file writer
:param iop numpy array to write to file
:param file_name the file and path to write the IOP to
"""
lg.info('Writing :: ' + file_name)
f = open(file_name, 'w')
for i in scipy.nditer(iop):
... | python | {
"resource": ""
} |
q276890 | BioOpticalParameters.build_b | test | def build_b(self, scattering_fraction=0.01833):
"""Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
"""
lg.info('Building b with scatteri... | python | {
"resource": ""
} |
q276891 | BioOpticalParameters.build_a | test | def build_a(self):
"""Calculates the total absorption from water, phytoplankton and CDOM
a = awater + acdom + aphi
"""
lg.info('Building total absorption')
self.a = self.a_water + self.a_cdom + self.a_phi | python | {
"resource": ""
} |
q276892 | BioOpticalParameters.build_c | test | def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
"""
lg.info('Building total attenuation C')
self.c = self.a + self.b | python | {
"resource": ""
} |
q276893 | BioOpticalParameters.build_all_iop | test | def build_all_iop(self):
"""Meta method that calls all of the build methods in the correct order
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
"""
lg.info('Building all b and c from IOPs')
self.build_a()
self.build_bb()
sel... | python | {
"resource": ""
} |
q276894 | BatchRun.batch_parameters | test | def batch_parameters(self, saa, sza, p, x, y, g, s, z):
"""Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> Sc... | python | {
"resource": ""
} |
q276895 | FileTools.read_param_file_to_dict | test | def read_param_file_to_dict(file_name):
"""Loads a text file to a python dictionary using '=' as the delimiter
:param file_name: the name and path of the text file
"""
data = loadtxt(file_name, delimiter='=', dtype=scipy.string0)
data_dict = dict(data)
for key in data_di... | python | {
"resource": ""
} |
q276896 | HelperMethods.string_to_float_list | test | def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']'... | python | {
"resource": ""
} |
q276897 | ReportTools.read_pr_report | test | def read_pr_report(self, filename):
"""Reads in a PlanarRad generated report
Saves the single line reported parameters as a python dictionary
:param filename: The name and path of the PlanarRad generated file
:returns self.data_dictionary: python dictionary with the key and values from... | python | {
"resource": ""
} |
q276898 | SignalHandler.set_handler | test | def set_handler(self, signals, handler=signal.SIG_DFL):
""" Takes a list of signals and sets a handler for them """
for sig in signals:
self.log.debug("Creating handler for signal: {0}".format(sig))
signal.signal(sig, handler) | python | {
"resource": ""
} |
q276899 | SignalHandler.pseudo_handler | test | def pseudo_handler(self, signum, frame):
""" Pseudo handler placeholder while signal is beind processed """
self.log.warn("Received sigal {0} but system is already busy processing a previous signal, current frame: {1}".format(signum, str(frame))) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.