INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
https://github.com... | def powerline():
'''Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
... |
More infos:
https://powerline.readthedocs.io/en/latest/installation/linux.html#fonts-installation
https://wiki.archlinux.org/index.php/Font_configuration
$XDG_CONFIG_HOME: http://superuser.com/a/365918 | def install_special_glyphs():
'''
More infos:
https://powerline.readthedocs.io/en/latest/installation/linux.html#fonts-installation
https://wiki.archlinux.org/index.php/Font_configuration
$XDG_CONFIG_HOME: http://superuser.com/a/365918
'''
from_dir = '~/repos/powerline/font'
run('... |
More infos:
https://powerline.readthedocs.io/en/latest/installation.html#pip-installation | def install_upgrade_powerline():
'''
More infos:
https://powerline.readthedocs.io/en/latest/installation.html#pip-installation
'''
checkup_git_repo_legacy('https://github.com/powerline/powerline.git')
path_to_powerline = os.path.expanduser('~/repos/powerline')
run(flo('pip install --user -... |
Set up the bash extension of powerline or powerline_shell (another task). | def powerline_for_bash_or_powerline_shell(bindings_dir):
'''Set up the bash extension of powerline or powerline_shell (another task).
'''
question = '\nSet up powerline-shell instead of powerline bash extension?'
if query_yes_no(question, default='yes'):
from setup import powerline_shell
... |
Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/to/page' %}...{% endifancestor}
{% ... | def ifancestor(parser, token):
"""
Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/... |
Print ping exit statistics | def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... |
static method that calls os.walk, but filters out
anything that doesn't match the filter | def _filtered_walk(path, file_filter):
"""
static method that calls os.walk, but filters out
anything that doesn't match the filter
"""
for root, dirs, files in os.walk(path):
log.debug('looking in %s', root)
log.debug('files is %s', files)
file_filter.set_root(root)
files = filter(file_filter, fi... |
Set the appropriate Cache-Control and Expires headers for the given
number of hours. | def cache_control_expires(num_hours):
"""
Set the appropriate Cache-Control and Expires headers for the given
number of hours.
"""
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *... |
The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in the weeds.
Exits:
... | def upsert(self):
"""
The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in t... |
List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | def list(self):
"""
List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_list()
int... |
Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | def smash(self):
"""
Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_smash()
try:
stack_name ... |
The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False | def _init_boto3_clients(self):
"""
The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False
"""
try:
profile = self._config.get('environment', {}... |
Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways. | def _get_ssm_parameter(self, p):
"""
Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways.
"""
try:
response = self._ssm.g... |
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist. | def _fill_parameters(self):
"""
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.
"""
... |
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist. | def _read_tags(self):
"""
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.
"""
tags = self._co... |
Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True | def _set_update(self):
"""
Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True
"""
try:
self._updateStack = Fal... |
Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version control tag or git commit hash as
the version.... | def _archive_elements(self):
"""
Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version contr... |
We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key | def _craft_s3_keys(self):
"""
We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key
... |
Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False | def poll_stack(self):
"""
Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False
"""
logging.info('polling stack status, POLL_INTERVAL={}'.format(POLL_INTERVAL))
time.sleep... |
Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md | def setup_desktop():
'''Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md
'''
run('sudo apt-get u... |
Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.m... | def setup_webserver():
'''Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your o... |
Open a server on Unix Domain Socket | def start_recv(sockfile=None):
'''Open a server on Unix Domain Socket'''
if sockfile is not None:
SOCKFILE = sockfile
else:
# default sockfile
SOCKFILE = "/tmp/snort_alert"
if os.path.exists(SOCKFILE):
os.unlink(SOCKFILE)
unsock = socket.socket(socket.AF_UNIX, socke... |
Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data. | def dump(obj, fp=None, indent=None, sort_keys=False, **kw):
"""
Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data.
"""
... |
Dump string. | def dumps(obj, indent=None, default=None, sort_keys=False, **kw):
"""Dump string."""
return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj) |
Load yaml file | def load(s, **kwargs):
"""Load yaml file"""
try:
return loads(s, **kwargs)
except TypeError:
return loads(s.read(), **kwargs) |
Load string | def loads(s, cls=None, **kwargs):
"""Load string"""
if not isinstance(s, string_types):
raise TypeError('the YAML object must be str, not {0!r}'.format(s.__class__.__name__))
cls = cls or YAMLDecoder
return cls(**kwargs).decode(s) |
The address in big-endian | def address(self):
"The address in big-endian"
_ = struct.pack('L', self.address_num)
return struct.unpack('!L', _)[0] |
add to ~/.bashrc: Export of $NVM env variable and load nvm command. | def enable_nvm():
'''add to ~/.bashrc: Export of $NVM env variable and load nvm command.'''
bash_snippet = '~/.bashrc_nvm'
install_file_legacy(path=bash_snippet)
prefix = flo('if [ -f {bash_snippet} ]; ')
enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi')
if env.host == '... |
Getting started with nvm (cf. https://github.com/creationix/nvm#usage). | def nvm_primer():
'''Getting started with nvm (cf. https://github.com/creationix/nvm#usage).
'''
print('\nDownload, compile and install the latest release of node:\n\n' +
cyan(' nvm install node'))
print('\nAnd then in any new shell:\n\n' +
cyan(' nvm use node') + ' # use the... |
some validation checks before doing anything | def validate_currency(*currencies):
""" some validation checks before doing anything """
validated_currency = []
if not currencies:
raise CurrencyException('My function need something to run, duh')
for currency in currencies:
currency = currency.upper()
if not isinstance(currency, str):
raise TypeError('Cu... |
validation checks for price argument | def validate_price(price):
""" validation checks for price argument """
if isinstance(price, str):
try:
price = int(price)
except ValueError: # fallback if convert to int failed
price = float(price)
if not isinstance(price, (int, float)):
raise TypeError('Price should be a number: ' + repr(price))
retur... |
return name of currency | def name(currency, *, plural=False):
""" return name of currency """
currency = validate_currency(currency)
if plural:
return _currencies[currency]['name_plural']
return _currencies[currency]['name'] |
return symbol of currency | def symbol(currency, *, native=True):
""" return symbol of currency """
currency = validate_currency(currency)
if native:
return _currencies[currency]['symbol_native']
return _currencies[currency]['symbol'] |
rounding currency value based on its max decimal digits | def rounding(price, currency):
""" rounding currency value based on its max decimal digits """
currency = validate_currency(currency)
price = validate_price(price)
if decimals(currency) == 0:
return round(int(price), decimals(currency))
return round(price, decimals(currency)) |
return format price with symbol. Example format(100, 'USD') return '$100'
pretty(price, currency, abbrev=True, trim=False)
abbrev:
True: print value + symbol. Symbol can either be placed before or after value
False: print value + currency code. currency code is placed behind value
trim:
True: trim float value ... | def pretty(price, currency, *, abbrev=True, trim=True):
""" return format price with symbol. Example format(100, 'USD') return '$100'
pretty(price, currency, abbrev=True, trim=False)
abbrev:
True: print value + symbol. Symbol can either be placed before or after value
False: print value + currency code. currency... |
check if last update is over 30 mins ago. if so return True to update, else False | def check_update(from_currency, to_currency):
""" check if last update is over 30 mins ago. if so return True to update, else False """
if from_currency not in ccache: # if currency never get converted before
ccache[from_currency] = {}
if ccache[from_currency].get(to_currency) is None:
ccache[from_currency][to_c... |
update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info | def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info """
if check_update(from_currency, to_currency) is True:
ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc... |
convert from from_currency to to_currency by requesting API | def convert_using_api(from_currency, to_currency):
""" convert from from_currency to to_currency by requesting API """
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, par... |
convert from from_currency to to_currency using cached info | def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... |
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses. | def wait_for_signal(self, timeout=None):
"""
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses.
"""
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) |
发送站内消息
:param recipient_list: 收件人列表
:param subject: 标题
:param body: 内容(不能超过 1024 个字符) | def send_message(self, recipient_list, subject, body):
"""发送站内消息
:param recipient_list: 收件人列表
:param subject: 标题
:param body: 内容(不能超过 1024 个字符)
"""
url = 'http://www.shanbay.com/api/v1/message/'
recipient = ','.join(recipient_list)
data = {
'r... |
回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符) | def reply_message(self, message_url, body):
"""回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符)
"""
id = re.findall(r'(\d+)/?$', message_url)[0]
api = 'http://www.shanbay.com/api/v1/message/%s/reply/'
url = api % id
data = {
... |
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated. | def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... |
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation. | def google_maps_geoloc_link(data):
"""
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation.
"""
if isinstance(data, str):
lat_lon ... |
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation. | def open_street_map_geoloc_link(data):
"""
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation.
"""
if isinstance(data, str):
... |
Chart for status codes. | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... |
Chart for most visited pages legend. | def most_visited_pages_legend_chart():
"""Chart for most visited pages legend."""
return {
'chart': {
'type': 'bar',
'height': 200,
},
'title': {
'text': _('Legend')
},
'xAxis': {
'categories': [
_('Project U... |
Chart for most visited pages. | def most_visited_pages_charts():
"""Chart for most visited pages."""
stats = most_visited_pages_stats()
charts = []
for i, stat in enumerate(stats['more_than_10']):
bound = stat['bound']
subset = stat['subset']
chart_options = {
'chart': {
'type': '... |
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``. | def add_settings(mod, allow_extras=True, settings=django_settings):
"""
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``.
"""
extras = {}
for setting in dir(mod):
... |
Get urls method.
Returns:
list: the list of url objects. | def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... |
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{% for field in form.fields %}
{% add_form_widget_attr field 'class'... | def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... |
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %} | def block_anyfilter(parser, token):
"""
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %}
"""
bits = token.co... |
Returns the thumbnail dimensions depending on the images format. | def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) |
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'mykey' as result %}
{% call myobj 'myattribute... | def call(obj, method, *args, **kwargs):
"""
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'my... |
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar". | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... |
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return. | def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... |
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format. | def get_verbose(obj, field_name=""):
"""
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format.
"""
if hasattr(obj, "_meta") and hasattr(obj._meta, "get_field_by_name"):
try:
return obj._me... |
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pairs of keys and values::
{% get_query_param... | def get_query_params(request, *args):
"""
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pa... |
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string representing a part of the URL that needs to exist
in order f... | def navactive(request, url, exact=0, use_resolver=1):
"""
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string r... |
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 items around
that page (including the page itself).
Usage::
... | def get_range_around(range_value, current_item, padding):
"""
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 item... |
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TOTAL }} | def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... |
Tag to render x-tmpl templates with Django template code. | def verbatim(parser, token):
"""Tag to render x-tmpl templates with Django template code."""
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == TOKEN_VAR:
text.append('{{ ')
elif token.token... |
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's | def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) |
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz']) | def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not a... |
:param project: should represent the canonical name for the project, generally
the same name it assigned in distutils.
:param default_config_path: the default location for the configuration file.
:param default_settings: default settings to load (think inheritence).
:param settings_initializer: a ca... | def configure_app(config_path=None, project=None, default_config_path=None,
default_settings=None, settings_initializer=None,
settings_envvar=None, initializer=None, allow_extras=True,
config_module_name=None, runner_name=None, on_configure=None):
"""
:param... |
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views. | def logs_urlpatterns(admin_view=lambda x: x):
"""
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views.
"""
return [
url(r'^$',
admin_view(Lo... |
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started | def _get(self, ip):
"""
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started
"""
# Geoloc updated up to once a week:
# http://ipinfo.io/developers/data#geoloc... |
Parses a raw datagram and return the right type of message | def parse(data):
""" Parses a raw datagram and return the right type of message """
# convert to string
data = data.decode("ascii")
if len(data) == 2 and data == "A5":
return AckMessage()
# split into bytes
raw = [data[i:i+2] for i in range(len(data)) if i % 2 == 0]
if len(raw) !... |
Returns a XOR of all the bytes specified inside of the given list | def checksum_bytes(data):
""" Returns a XOR of all the bytes specified inside of the given list """
int_values = [int(x, 16) for x in data]
int_xor = reduce(lambda x, y: x ^ y, int_values)
hex_xor = "{:X}".format(int_xor)
if len(hex_xor) % 2 != 0:
hex_xor = "0" + hex_xor
return str.enc... |
Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance) | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) |
computes the correlation coefficient between each distinct pairing of columns
preprocessing note:
any rows with missing values (in either paired column) are dropped for that pairing
categorical columns are replaced with one-hot encoded columns
any columns which have only one distinct value (... | def get_canonical_correlations(dataframe, column_types):
'''
computes the correlation coefficient between each distinct pairing of columns
preprocessing note:
any rows with missing values (in either paired column) are dropped for that pairing
categorical columns are replaced with one-hot enc... |
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param context: A dictionary of items that should be added to the
templates' contexts.
:param subject_template: A string representing the path to the template of
of the email's subject.
... | def send_email(request, context, subject_template, body_template,
from_email, recipients, priority="medium", reply_to=None,
headers=None, cc=None, bcc=None):
"""
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param co... |
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns: | def url_is_project(url, default='not_a_func'):
"""
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns:
"""
try:
u = resolve(url)
if u and u.func != de... |
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is... | def url_is(white_list):
"""
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is...
"""
def func(url):
prefixes = white_list.get('PREFIXES', ())
for prefix in prefixes:
... |
Save a collection of records | def save_records(self, records):
'''
Save a collection of records
'''
for record in records:
if not isinstance(record, Record):
record = Record(*record)
self.save_record(*record) |
Save a collection of records to the database.
Database writes are cached. | def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... |
Get the serialized value for a given key. | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... |
Get the deserialized value for a given key, and the serialized version. | def recover(self, key, value):
"""Get the deserialized value for a given key, and the serialized version."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
raise ValueError("Unknown datatype for {} and {}".format(key, value))
return self... |
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed. | def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... |
Load records. | def records():
"""Load records."""
import pkg_resources
import uuid
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from invenio_pidstore import current_pidstore
from invenio_records.api import Record
# pkg resources the demodat... |
Run a single trial of the simulation
Parameters
----------
trial_id : int | def run_trial(self, trial_id = 0, until = None, return_env = True, **opts):
"""Run a single trial of the simulation
Parameters
----------
trial_id : int
"""
# Set-up trial environment and graph
until=until or self.max_time
env=self.get_env(trial_id = tria... |
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations | def run_trial_exceptions(self, *args, **kwargs):
'''
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations
'''
try:
return self.run_trial(*args, **kwargs)
except Exception as ex:
c = ex.__cause__
... |
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from the API
Raises:
`~reques... | def search_orcid(orcid):
"""
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from ... |
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range. | def daterange(start_date, end_date):
"""
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range.
"""
for n in range(int((end_date - start_date).da... |
Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12). | def month_name_to_number(month, to_int=False):
"""
Convert a month name (MMM) to its number (01-12).
Args:
month (str): 3-letters string describing month.
to_int (bool): cast number to int or not.
Returns:
str/int: the month's number (between 01 and 12).
"""
number = {
... |
Read and parse ReSpecTh XML file metadata (file author, version, etc.)
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with file metadata | def get_file_metadata(root):
"""Read and parse ReSpecTh XML file metadata (file author, version, etc.)
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with file metadata
"""
properties = {}
file_author = getattr... |
Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information. | def get_experiment_kind(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information.
"""
properties = {}
if root... |
Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties | def get_common_properties(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with common properties
"""
properties = {}
for elem in root.iterfind('co... |
Gets ignition type and target.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition type/target information | def get_ignition_type(root):
"""Gets ignition type and target.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition type/target information
"""
properties = {}
elem = root.find('ignitionType')
if el... |
Parse datapoints with ignition delay from file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition delay data | def get_datapoints(root):
"""Parse datapoints with ignition delay from file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with ignition delay data
"""
# Shock tube experiment will have one data group, while RCM ma... |
Convert ReSpecTh XML file to ChemKED-compliant dictionary.
Args:
filename_xml (`str`): Name of ReSpecTh XML file to be converted.
file_author (`str`, optional): Name to override original file author
file_author_orcid (`str`, optional): ORCID of file author
validate (`bool`, optional... | def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False):
"""Convert ReSpecTh XML file to ChemKED-compliant dictionary.
Args:
filename_xml (`str`): Name of ReSpecTh XML file to be converted.
file_author (`str`, optional): Name to override original file auth... |
Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. | def respth2ck(argv=None):
"""Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file.
"""
parser = ArgumentParser(
description='Convert a ReSpecTh XML file to a ChemKED YAML file.'
)
parser.add_argument('-i', '--input',
type=str,
... |
Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. | def ck2respth(argv=None):
"""Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file.
"""
parser = ArgumentParser(
description='Convert a ChemKED YAML file to a ReSpecTh XML file.'
)
parser.add_argument('-i', '--input',
type=str,
... |
General function for converting between ReSpecTh and ChemKED files based on extension. | def main(argv=None):
"""General function for converting between ReSpecTh and ChemKED files based on extension.
"""
parser = ArgumentParser(
description='Convert between ReSpecTh XML file and ChemKED YAML file '
'automatically based on file extension.'
)
parser.add_arg... |
Add user details. | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email |
Send broken link emails for relevant 404 NOT FOUND responses. | def process_response(self, request, response):
"""
Send broken link emails for relevant 404 NOT FOUND responses.
"""
if response.status_code == 404 and not settings.DEBUG:
domain = request.get_host()
path = request.get_full_path()
referer = force_text(... |
Returns True if referring URL is the same domain as current request. | def is_internal_request(self, domain, referer):
"""
Returns True if referring URL is the same domain as current request.
"""
# Different subdomains are treated as different domains.
return bool(re.match("^https?://%s/" % re.escape(domain), referer)) |
Returns True if the given request *shouldn't* notify the site managers. | def is_ignorable_request(self, request, uri, domain, referer):
"""
Returns True if the given request *shouldn't* notify the site managers.
"""
# '?' in referer is identified as search engine source
if (not referer or (not self.is_internal_request(
domain, referer)... |
Parses a duration string representation
:param representation: duration as a string, example: '1d' (day),
'34minutes' (minutes), '485s' (seconds)...
:type representation: string
:returns: the parsed duration representation
:rtype: DurationRepresentat... | def parse(self, representation):
"""Parses a duration string representation
:param representation: duration as a string, example: '1d' (day),
'34minutes' (minutes), '485s' (seconds)...
:type representation: string
:returns: the parsed duration repres... |
Get or create an entry using obtained information from an IP.
Args:
ip (str): IP address xxx.xxx.xxx.xxx.
Returns:
ip_info: an instance of IPInfo. | def get_or_create_from_ip(ip):
"""
Get or create an entry using obtained information from an IP.
Args:
ip (str): IP address xxx.xxx.xxx.xxx.
Returns:
ip_info: an instance of IPInfo.
"""
data = ip_api_handler.get(ip)
if data and any(v for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.