_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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(
|
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_)
gc.set_stroke_color(self.pen.color_)
gc.set_line_width(self.pen.line_width)
# Draw the path.
gc.begin_path()
# x0 = self.points[0][0] - self.x
#
|
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)
|
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(self.pen.color_)
gc.begin_path()
start_x, start_y = self.points[0]
gc.move_to(start_x, start_y)
for triple in nsplit(self.points[1:], 3):
|
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
|
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 = self.in_queue.get(timeout=5)
except queue.Empty:
|
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,
)
|
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)
|
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):
|
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 ``available``) and the
pattern that it matched (from ``requested``)
:rtype: :class:`tuple` of :class:`.ContentType` instances
:raises: :class:`.NoMatch` when a suitable match was not found
This function implements the *Proactive Content Negotiation*
algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
The input is the `Accept`_ header as parsed by
:func:`.parse_http_accept_header` and a list of
parsed :class:`.ContentType` instances. The ``available`` sequence
should be a sequence of content types that the server is capable of
producing. The selected value should ultimately be used as the
`Content-Type`_ header in the generated response.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
.. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5
"""
class Match(object):
"""Sorting assistant.
Sorting matches is a tricky business. We need a way to
prefer content types by *specificity*. The definition of
*more specific* is a little less than clear. This class
treats the strength of a match as the most important thing.
Wild cards are less specific in all cases. This is tracked
by the ``match_type`` attribute.
If we the candidate and pattern differ only by parameters,
then the strength is based on the number of pattern parameters
that match parameters from the candidate. The easiest way to
track this is to count the number of candidate parameters that
are matched by the pattern. This is what ``parameter_distance``
tracks.
The final key to the solution is to order the result set such
that the most specific matches are first in the list. This
is done by carefully choosing values for ``match_type`` such
that full matches bubble up to the front. We also need a
scheme of counting matching parameters that pushes stronger
matches to the front of the list. The ``parameter_distance``
attribute starts at the number of candidate parameters and
decreases for each matching parameter - the lesser the value,
the stronger the match.
"""
WILDCARD, PARTIAL, FULL_TYPE, = 2, 1, 0
def __init__(self, candidate, pattern):
|
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 portion of the URL.
:keyword str host: if specified, this keyword sets the host
portion of the network location. A value of :data:`None`
will remove the network location portion of the URL.
:keyword str password: if specified, this keyword sets the
password portion of the URL. A value of :data:`None` will
remove the password from the URL.
:keyword str path: if specified, this keyword sets the path
portion of the URL. A value of :data:`None` will remove
the path from the URL.
:keyword int port: if specified, this keyword sets the port
portion of the network location. A value of :data:`None`
will remove the port from the URL.
:keyword query: if specified, this keyword sets the query portion
of the URL. See the comments for a description of this
parameter.
:keyword str scheme: if specified, this keyword sets the scheme
portion of the URL. A value of :data:`None` will remove
the scheme. Note that this will make the URL relative and
may have unintended consequences.
:keyword str user: if specified, this keyword sets the user
portion of the URL. A value of :data:`None` will remove
the user and password portions.
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:return: the modified URL
:raises ValueError: when a keyword parameter is given an invalid
value
If the `host` parameter is specified and not :data:`None`, then
it will be processed as an Internationalized Domain Name (IDN)
if the scheme appears in :data:`IDNA_SCHEMES`. Otherwise, it
will be encoded as UTF-8 and percent encoded.
The handling of the `query` parameter requires some additional
explanation. You can specify a query value in three different
ways - as a *mapping*, as a *sequence*
|
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`.
>>> auth, sanitized = remove_url_auth('http://foo:[email protected]')
>>> auth
('foo', 'bar')
>>> sanitized
'http://example.com'
The return value from this function is simple named tuple with the
following fields:
- *auth* the username and password as a tuple
- *username* the username portion of the URL or :data:`None`
- *password* the password portion of the URL or :data:`None`
- *url* the sanitized
|
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)
if password:
|
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 restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
|
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 strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
"""
found
|
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 representing
discovered module names, not the
|
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 correctly.
:param mname: the module name to descend into
|
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
parameter. This filter's return value must be interpretable as a
|
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 must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
|
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)
|
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."""
|
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 &
|
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 environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
with open(os.devnull, 'w') as err_out:
out = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
|
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_name != self.module_name:
raise LoaderError(
'Requesting a module that the loader is unaware of.')
if module_name in sys.modules:
return sys.modules[module_name]
|
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
|
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
package.__path__ for submodules and subpackages (unused)
"""
module_path = os.path.join(*module_name.split(MODULE_PATH_SEP))
for search_root in self.paths:
target_path = os.path.join(search_root, module_path)
is_pkg = False
# If the target references a directory, try to load it as
|
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 desired line length
:return: A list of lines
"""
if len(line) <= max_line_length:
# No need to split!
return [line]
# First work out the indentation on the beginning of the line
indent = 0
while line[indent] == ' ' and indent < len(line):
indent += 1
# Try to split the line
# Start looking for a space at character max_line_length working backwards
i = max_line_length
split_point = None
while i > min_line_length:
if line[i] == ' ':
split_point = i
break
i -= 1
if split_point is None:
# We didn't find a split point - search beyond the end of the line
|
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('}')
|
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
whether to check the special 'package' version for consistency
(default False)
strictness: str
"""
keys_to_check = list(self.versions.keys())
if not include_package and 'package' in keys_to_check:
keys_to_check.remove('package')
if desired_version is None:
# if we have to guess, we trust setup.py
try:
desired_version = self.versions['setup.py']
except KeyError:
desired_version = self.versions[keys_to_check[0]]
if strictness is None:
strictness = self.strictness
desired = self._version(desired_version, strictness)
|
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
|
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:
|
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:
|
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:
kwargs["token"]
|
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.method
endpoint = request.endpoint
# Obscure password field and prettify a little bit
form_dict = dict(request.form)
for key in form_dict:
if key.lower() in _error_reporting_obscured_fields:
form_dict[key] = '******'
elif len(form_dict[key]) == 1:
form_dict[key] = form_dict[key][0]
form = pprint.pformat(form_dict).replace('\n', '\n ')
msg = '%s\nRequest:\n\nurl: %s\nmethod: %s\nendpoint: %s\nform: %s\n' % \
(msg, url, method, endpoint, form)
|
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 - 60
new_rate_limiter = [x for x in self.rate_limiter if x > one_minute_ago]
log.debug('Rate limiter %s -> %s' % (len(self.rate_limiter), len(new_rate_limiter)))
self.rate_limiter = new_rate_limiter
# Now, get the number of emails sent in the last minute. If it's less than the threshold, add another
# entry to the rate limiter list
recent_sends = len(self.rate_limiter)
send_email = recent_sends < self.max_sends_per_minute
if send_email:
self.rate_limiter.append(now)
msg = self.format(record)
msg = self.add_details(msg)
# Finally send the message!
|
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)
|
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:
self.attempts[key] += 1
if self.attempts[key] >= self.max_attempts:
|
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:
|
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.workers:
for _ in range(workers_per_task):
self.workers.append(Worker(self._download, self.queues['download'], self.queues['convert'], self.stopper))
self.workers.append(Worker(self._convert, self.queues['convert'], self.queues['upload'], self.stopper))
|
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))
|
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
|
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 not wait_index:
params['index'] = self.index(k, recursive=True)
else:
params['index'] = wait_index
r = requests.get(url, params=params)
if r.status_code == 404:
raise KeyDoesNotExist("Key " +
|
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)
|
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'] =
|
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 will be used for clustering
'''
sns.set(color_codes=True)
df = feature_importance_report(X, y)
df_sns = pd.DataFrame().from_records(X)[df[:top_n].index].T
|
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
years += 1
# month = timestamp.month
year = timestamp.year + years
try:
return datetime.datetime(year, new_month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
|
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
year = date.year + years
try:
return datetime.date(year, new_month, date.day)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
|
python
|
{
"resource": ""
}
|
q276848
|
is_christmas_period
|
test
|
def is_christmas_period():
"""Is this the christmas period?"""
now = datetime.date.today()
|
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[service_name]
except KeyError:
if service_name == 'youtube':
self.music_services['youtube'] = Youtube()
self.current_music = self.music_services['youtube']
|
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 (optional, and must already exist, use absolute paths only)
"""
try:
self.current_storage = self.storage_services[service_name]
except KeyError:
if service_name == 'google drive':
self.storage_services['google drive'] = GoogleDrive()
self.current_storage = self.storage_services['google drive']
|
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')
|
python
|
{
"resource": ""
}
|
q276852
|
SkUtilsIO.from_json
|
test
|
def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
|
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.
'''
|
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
|
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'):
'''
Provide signifance for features in dataset with anova using multiple hypostesis testing
:param X: List of dict with key as feature names and values as features
:param y: Labels
:param threshold: Low-variens threshold to eliminate low varience features
:param correcting_multiple_hypotesis: corrects p-val with multiple hypotesis testing
:param method: method of multiple hypotesis testing
:param alpha: alpha of multiple hypotesis testing
:param sort_by: sorts output dataframe by pval or F
:return: DataFrame with F and pval for each feature with their average values
|
python
|
{
"resource": ""
}
|
q276857
|
SessionData.restore_data
|
test
|
def restore_data(self, data_dict):
"""
Restore the data dict - update the flask session and this object
"""
|
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):
|
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, **kwargs):
|
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:
|
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.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's sizedimage module.
try:
before_import_block_registry = copy.copy(
block_registry._registry
)
import_module('{}.registered_blocks'.format(app))
except:
# Reset the block_registry to the state before the last
|
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 unregister that block before trying "
"to register this block under a different `block_type`".format(
block_type
)
|
python
|
{
"resource": ""
}
|
q276863
|
RegisteredBlockStreamFieldRegistry.register_block
|
test
|
def register_block(self, block_type, block):
"""
Registers `block` to `block_type` in the registry.
"""
|
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.
"""
|
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: Filename of the new file in local storage
"""
file = os.path.splitext(file_name)
if file[1] == '.mp3':
log.info(f"{file_name} is already a MP3 file, no conversion needed.")
return file_name
new_file_name = file[0] + '.mp3'
ff = FFmpeg(
inputs={file_name: None},
outputs={new_file_name: None}
)
log.info(f"Conversion for {file_name} has started")
|
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 version name
"""
try:
desired_version = desired_version.base_version
except:
pass
(new_major, new_minor, new_patch) = \
map(int, desired_version.split('.'))
tag_versions = self._versions_from_tags()
if not tag_versions:
# no tags yet, and legal version is legal!
|
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', 'filemanager.static']:
needs_ssl = False
ssl_enabled = False
view_function = current_app.view_functions[request.endpoint]
if request.endpoint.startswith('admin.') or \
(hasattr(view_function, 'ssl_required') and view_function.ssl_required):
|
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,
|
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<[email protected]>, [email protected]"
:param from_address: Who the email is from i.e. "Stephen Brown <[email protected]>"
:param subject: The email subject
|
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
named ``quality``.
``Accept`` is a class of headers that contain a list of values
and an associated preference value. The ever present `Accept`_
header is a perfect example. It is a list of content types and
an optional parameter named ``q`` that indicates the relative
weight of a particular type. The most basic example is::
Accept: audio/*;q=0.2, audio/basic
Which states that I prefer the ``audio/basic`` content type
|
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.
:param str header_value: ``Cache-Control`` header value to parse
:return: the parsed ``Cache-Control`` header values
:rtype: dict
.. _Cache-Control: https://tools.ietf.org/html/rfc7234#section-5.2
"""
directives = {}
for segment in parse_list(header_value):
name, sep, value = segment.partition('=')
if sep != '=':
directives[name] = None
elif sep
|
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 parameter values are case preserving.
:return: a :class:`~ietfparse.datastructures.ContentType` instance
"""
parts = _remove_comments(content_type).split(';')
content_type, content_subtype = parts.pop(0).split('/')
if '+' in content_subtype:
|
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 in :exc:`~ietfparse.errors.StrictHeaderParsingFailure`
:return: an ordered :class:`list` of :class:`dict` instances
:raises: :exc:`ietfparse.errors.StrictHeaderParsingFailure` is
raised if `only_standard_parameters` is enabled and a non-standard
parameter name is encountered
This function parses
|
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 =
|
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_list: sequence of string values to parse
:keyword bool normalize_parameter_names: if specified and *truthy*
then parameter names will be case-folded to lower case
:keyword bool normalize_parameter_values: if omitted or specified
as *truthy*, then parameter values are case-folded to lower case
:keyword bool normalized_parameter_values: alternate way to spell
``normalize_parameter_values`` -- this one is deprecated
|
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
|
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
is detected
This method implements most of the validation mentioned in
sections 5.3 and 5.4 of :rfc:`5988`. The ``_rfc_values``
dictionary contains the appropriate values for the attributes
that get special handling. If *strict mode* is enabled, then
only values that are acceptable will be added to ``_values``.
"""
try:
|
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 RegexMatchError:
log.error(f"Cannot download file at {url}")
else:
stream = yt.streams.first()
log.info(f"Download for {stream.default_filename} has started")
|
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()
if not creds or creds.invalid:
try:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
except InvalidClientSecretsError:
log.error('ERROR: Could not find client_secret.json in current directory, please obtain it from the API console.')
return
creds = tools.run_flow(flow, store)
self.connection = build('drive', 'v3', http=creds.authorize(Http()))
|
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 queue)
"""
response = self.connection.files().list(q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
folder_id = response.get('files', [])[0]['id']
file_metadata = {'name': file_name, 'parents': [folder_id]}
|
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')
|
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(self.verbose) + '\n')
f.write('band_count= ' + str(self.num_bands) + '\n')
f.write('band_centres_data= ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition= ' + self.partition + '\n')
f.write('vn= ' + str(self.vn) + '\n')
f.write('hn= ' + str(self.hn) + '\n')
f.write('rdif= ' + str(self.sky_r_dif) + '\n')
f.write('theta_points= ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
|
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:
|
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:
|
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:
|
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:
|
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 interpolating to ' + str(self.wavelengths))
if os.path.isfile(file_name):
iop_reader = csv.reader(open(file_name), delimiter=',', quotechar='"')
wave = iop_reader.next()
iop = iop_reader.next()
else:
lg.exception('Problem
|
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
|
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
"""
|
python
|
{
"resource": ""
}
|
q276891
|
BioOpticalParameters.build_a
|
test
|
def build_a(self):
"""Calculates the total absorption from water, phytoplankton and CDOM
|
python
|
{
"resource": ""
}
|
q276892
|
BioOpticalParameters.build_c
|
test
|
def build_c(self):
"""Calculates the total attenuation from the total absorption and total
|
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
|
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
|
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_dict.keys():
|
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:
|
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 the report
"""
done = False
f = open(filename)
while f:
#for line in open(filename):
line = f.readline()
if not line:
done = True
break
if "# Quad solid angle mean point theta table (rows are horizontal, columns are vertical):" in line.strip():
# read in the bunch of lines.
tmp = []
for i_iter in range(0, len(self.data_dictionary['theta_points_deg']) - 2):
tmp.append(f.readline())
self.data_dictionary['Quad_solid_angle_mean_point_theta'] = tmp
elif '#' not in line or not line.strip():
element = line.split(',')
self.data_dictionary[element[0]] = element[1:]
|
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:
|
python
|
{
"resource": ""
}
|
q276899
|
SignalHandler.pseudo_handler
|
test
|
def pseudo_handler(self, signum, frame):
""" Pseudo handler placeholder while signal is beind processed """
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.