INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Get score of core-periphery pairs.
Parameters
----------
G : Graph object.
c : Dict object, the keys and values of which are the name of node and its ID of belonging core-periphery pair.
Returns
-------
q : List. q[i] is the quality of core-periphery pair i. | def score(*args):
"""Get score of core-periphery pairs.
Parameters
----------
G : Graph object.
c : Dict object, the keys and values of which are the name of node and its ID of belonging core-periphery pair.
Returns
-------
q : List. q[i] is the quality of core-periphery pair i.
"""... |
Extract the identifier out of this construct: ${mylist}: mylist | def getSource(self):
"""Extract the identifier out of this construct: ${mylist}: mylist
"""
bracket = self.next()
# we should only be here because that was a bracket
if not bracket == u'{':
raise Exception(u"parse error getting source")
c = u''
identif... |
Get a character set with individual members or ranges.
Current index is on '[', the start of the character set. | def getCharacterSet(self):
'''Get a character set with individual members or ranges.
Current index is on '[', the start of the character set.
'''
chars = u''
c = None
cnt = 1
start = 0
while True:
escaped_slash = False
c... |
Get a sequence of non-special characters. | def getLiteral(self):
'''Get a sequence of non-special characters.'''
# we are on the first non-special character
chars = u''
c = self.current()
while True:
if c and c == u"\\":
c = self.next()
if c:
chars += c
... |
Get a sequence of nodes. | def getSequence(self, level=0):
'''Get a sequence of nodes.'''
seq = []
op = ''
left_operand = None
right_operand = None
sequence_closed = False
while True:
c = self.next()
if not c:
break
if c and c not in self... |
Print the parse tree and then call render for an example. | def dump(self, **kwargs):
import sys
'''Print the parse tree and then call render for an example.'''
if not self.seq:
self.seq = self.getSequence()
print("StringGenerator version: %s" % (__version__))
print("Python version: %s" % sys.version)
# this doesn't wo... |
Return a list of generated strings.
Args:
cnt (int): length of list
unique (bool): whether to make entries unique
Returns:
list.
We keep track of total attempts because a template may
specify something impossible to attain, like [1-9]{} with cnt==10... | def render_list(self, cnt, unique=False, progress_callback=None, **kwargs):
'''Return a list of generated strings.
Args:
cnt (int): length of list
unique (bool): whether to make entries unique
Returns:
list.
We keep track of total attempts because a... |
Establish the connection. This is done automatically for you.
If you lose the connection, you can manually run this to be re-connected. | def connect(self):
"""
Establish the connection. This is done automatically for you.
If you lose the connection, you can manually run this to be re-connected.
"""
self.conn = boto.connect_s3(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL)
... |
Connect to Cloud Front. This is done automatically for you when needed. | def connect_cloudfront(self):
"Connect to Cloud Front. This is done automatically for you when needed."
self.conn_cloudfront = connect_cloudfront(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL) |
Create a folder on S3.
Examples
--------
>>> s3utils.mkdir("path/to/my_folder")
Making directory: path/to/my_folder | def mkdir(self, target_folder):
"""
Create a folder on S3.
Examples
--------
>>> s3utils.mkdir("path/to/my_folder")
Making directory: path/to/my_folder
"""
self.printv("Making directory: %s" % target_folder)
self.k.key = re.sub(r"^/|/$", "... |
Delete the path and anything under the path.
Example
-------
>>> s3utils.rm("path/to/file_or_folder") | def rm(self, path):
"""
Delete the path and anything under the path.
Example
-------
>>> s3utils.rm("path/to/file_or_folder")
"""
list_of_files = list(self.ls(path))
if list_of_files:
if len(list_of_files) == 1:
self.buck... |
Copy a file to s3. | def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"):
"""Copy a file to s3."""
action_word = "moving" if del_after_upload else "copying"
try:
self.k.key = target_file # setting the path (key) of file in the conta... |
Copy a file or folder from local to s3.
Parameters
----------
local_path : string
Path to file or folder. Or if you want to copy only the contents of folder, add /* at the end of folder name
target_path : string
Target path on S3 bucket.
acl : string, ... | def cp(self, local_path, target_path, acl='public-read',
del_after_upload=False, overwrite=True, invalidate=False):
"""
Copy a file or folder from local to s3.
Parameters
----------
local_path : string
Path to file or folder. Or if you want to copy only t... |
Similar to Linux mv command.
Move the file to the S3 and deletes the local copy
It is basically s3utils.cp that has del_after_upload=True
Examples
--------
>>> s3utils.mv("path/to/folder","/test/")
moving /path/to/myfolder/test2.txt to test/myfolder/test2.txt
... | def mv(self, local_file, target_file, acl='public-read', overwrite=True, invalidate=False):
"""
Similar to Linux mv command.
Move the file to the S3 and deletes the local copy
It is basically s3utils.cp that has del_after_upload=True
Examples
--------
>>> s... |
Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images.
S3utils was originally written to put cropduster images on S3 bucket.
Extra Items in your Django Settings
-----------------------------------
MEDIA_ROOT : string
Django m... | def cp_cropduster_image(self, the_image_path, del_after_upload=False, overwrite=False, invalidate=False):
"""
Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images.
S3utils was originally written to put cropduster images on S3 bucket.
Ext... |
Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
options:
- private: Owner gets FULL_CONTROL. No one else has any ac... | def __get_grants(self, target_file, all_grant_data):
"""
Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
option... |
sets permissions for a file on S3
Parameters
----------
target_file : string
Path to file on S3
acl : string, optional
File permissions on S3. Default is public-read
options:
- private: Owner gets FULL_CONTROL. No one else has any a... | def chmod(self, target_file, acl='public-read'):
"""
sets permissions for a file on S3
Parameters
----------
target_file : string
Path to file on S3
acl : string, optional
File permissions on S3. Default is public-read
options:
... |
gets the list of file names (keys) in a s3 folder
Parameters
----------
folder : string
Path to file on S3
num: integer, optional
number of results to return, by default it returns all results.
begin_from_file: string, optional
which file t... | def ls(self, folder="", begin_from_file="", num=-1, get_grants=False, all_grant_data=False):
"""
gets the list of file names (keys) in a s3 folder
Parameters
----------
folder : string
Path to file on S3
num: integer, optional
number of results ... |
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
num: integer, optional
number of results to return, by default it returns ... | def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... |
Invalidate the CDN (distribution) cache for a certain file of files. This might take up to 15 minutes to be effective.
You can check for the invalidation status using check_invalidation_request.
Examples
--------
>>> from s3utils import S3utils
>>> s3utils = S3utils(
... | def invalidate(self, files_to_be_invalidated):
"""
Invalidate the CDN (distribution) cache for a certain file of files. This might take up to 15 minutes to be effective.
You can check for the invalidation status using check_invalidation_request.
Examples
--------
>... |
Parses a tag that's supposed to be in this format: {% anchor field title %} | def anchor(parser, token):
"""
Parses a tag that's supposed to be in this format: {% anchor field title %}
"""
bits = [b.strip('"\'') for b in token.split_contents()]
if len(bits) < 2:
raise TemplateSyntaxError, "anchor tag takes at least 1 argument"
try:
title = bits[2]
... |
Get the path from a given url, including the querystring.
Args:
url (str)
Returns:
str | def get_path(url):
"""
Get the path from a given url, including the querystring.
Args:
url (str)
Returns:
str
"""
url = urlsplit(url)
path = url.path
if url.query:
path += "?{}".format(url.query)
return path |
Reads data from disk and generates CSV files. | def run(self):
"""Reads data from disk and generates CSV files."""
# Try to create the directory
if not os.path.exists(self.output):
try:
os.mkdir(self.output)
except:
print 'failed to create output directory %s' % self.output
# Be... |
Process a list of simple string field definitions and assign their order based on prefix. | def process_fields(self, fields):
"""Process a list of simple string field definitions and assign their order based on prefix."""
result = []
strip = ''.join(self.PREFIX_MAP)
for field in fields:
direction = self.PREFIX_MAP['']
if field[0] in self.PREFIX_MAP:
direction = self.PREFIX_MAP[fiel... |
Create this index in the specified collection; keyword arguments are passed to PyMongo.
http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_index | def create(self, collection, **kw):
"""Create this index in the specified collection; keyword arguments are passed to PyMongo.
http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_index
"""
options = dict(
name = self.__name__,
unique = self.unique... |
Rubrics search
http://api.2gis.ru/doc/firms/list/rubricator/ | def rubricator(self, **kwargs):
"""Rubrics search
http://api.2gis.ru/doc/firms/list/rubricator/
"""
# `show_children' parameter must be an integer
kwargs['show_children'] = int(kwargs.pop('show_children', False))
return self._rubricator(**kwargs) |
Firms search
http://api.2gis.ru/doc/firms/searches/search/ | def search(self, **kwargs):
"""Firms search
http://api.2gis.ru/doc/firms/searches/search/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % (point[0], point[1])
bound = kwargs.pop('bound', False)
if bound:
kwar... |
Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/ | def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... |
Geo search
http://api.2gis.ru/doc/geo/search/ | def geo_search(self, **kwargs):
"""Geo search
http://api.2gis.ru/doc/geo/search/
"""
if 'types' in kwargs:
kwargs['types'] = ','.join(kwargs['types'])
bound = kwargs.pop('bound', False)
if bound:
kwargs['bound[point1]'] = bound[0]
kw... |
Refresh the list and the screen | def refresh(self):
'''
Refresh the list and the screen
'''
self._screen.force_update()
self._screen.refresh()
self._update(1) |
Mark an action as started
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action` | def start(self, activity, action):
'''
Mark an action as started
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._start_actio... |
Mark a task as completed
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action` | def stop(self, activity, action):
'''
Mark a task as completed
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._remove_runnin... |
Move laggard tasks over
:param activity: The virtualenv status
:type activity: ``str`` | def finish(self, status):
'''
Move laggard tasks over
:param activity: The virtualenv status
:type activity: ``str``
'''
retox_log.info("Completing %s with status %s" % (self.name, status))
result = Screen.COLOUR_GREEN if not status else Screen.COLOUR_RED
... |
Reset the frame between jobs | def reset(self):
'''
Reset the frame between jobs
'''
self.palette['title'] = (Screen.COLOUR_WHITE, Screen.A_BOLD, Screen.COLOUR_BLUE)
self._completed_view.options = []
self._task_view.options = []
self.refresh() |
Returns the available kwargs of the called class | def default_arguments(cls):
"""Returns the available kwargs of the called class"""
func = cls.__init__
args = func.__code__.co_varnames
defaults = func.__defaults__
index = -len(defaults)
return {k: v for k, v in zip(args[index:], defaults)} |
Recreate the class based in your args, multiple uses | def recreate(cls, *args, **kwargs):
"""Recreate the class based in your args, multiple uses"""
cls.check_arguments(kwargs)
first_is_callable = True if any(args) and callable(args[0]) else False
signature = cls.default_arguments()
allowed_arguments = {k: v for k, v in kwargs.items... |
Put warnings of arguments whose can't be handle by the class | def check_arguments(cls, passed):
"""Put warnings of arguments whose can't be handle by the class"""
defaults = list(cls.default_arguments().keys())
template = ("Pass arg {argument:!r} in {cname:!r}, can be a typo? "
"Supported key arguments: {defaults}")
fails = []
... |
process the specified type then process its children | def process(self, data, type, history):
""" process the specified type then process its children """
if type in history:
return
if type.enum():
return
history.append(type)
resolved = type.resolve()
value = None
if type.multi_occurrence():
... |
get whether or not to skip the specified child | def skip_child(self, child, ancestry):
""" get whether or not to skip the specified child """
if child.any(): return True
for x in ancestry:
if x.choice():
return True
return False |
Signal endpoint that actually sends knocks whenever an instance is created / saved | def notify_items(**kwargs):
"""
Signal endpoint that actually sends knocks whenever an instance is created / saved
"""
instance = kwargs.get('instance')
created = kwargs.get('created', False)
if hasattr(instance, 'send_knock') and active_knocks(instance):
try:
# This is a stu... |
Checks whether knocks are enabled for the model given as argument
:param obj: model instance
:return True if knocks are active | def active_knocks(obj):
"""
Checks whether knocks are enabled for the model given as argument
:param obj: model instance
:return True if knocks are active
"""
if not hasattr(_thread_locals, 'knock_enabled'):
return True
return _thread_locals.knock_enabled.get(obj.__class__, True) |
Context manager to suspend sending knocks for the given model
:param obj: model instance | def pause_knocks(obj):
"""
Context manager to suspend sending knocks for the given model
:param obj: model instance
"""
if not hasattr(_thread_locals, 'knock_enabled'):
_thread_locals.knock_enabled = {}
obj.__class__._disconnect()
_thread_locals.knock_enabled[obj.__class__] = False
... |
Loop over the report progress | def _loopreport(self):
'''
Loop over the report progress
'''
while 1:
eventlet.sleep(0.2)
ac2popenlist = {}
for action in self.session._actions:
for popen in action._popenlist:
if popen.poll() is None:
... |
Send markdown email
Args:
email (str/obj): A markdown string or EmailContent object
subject (str): subject line
from_email (str): sender email address
to_email (str/list): recipient email addresses
cc (str/list): CC email addresses (string or a list)
bcc (str/list):... | def send(email, subject=None,
from_email=None, to_email=None,
cc=None, bcc=None, reply_to=None,
smtp=None):
"""Send markdown email
Args:
email (str/obj): A markdown string or EmailContent object
subject (str): subject line
from_email (str): sender email addre... |
Process timezone casting and conversion. | def _process_tz(self, dt, naive, tz):
"""Process timezone casting and conversion."""
def _tz(t):
if t in (None, 'naive'):
return t
if t == 'local':
if __debug__ and not localtz:
raise ValueError("Requested conversion to local timezone, but `localtz` not installed.")
t = localtz
... |
Trigger assignment of default values. | def _prepare_defaults(self):
"""Trigger assignment of default values."""
for name, field in self.__fields__.items():
if field.assign:
getattr(self, name) |
Convert data coming in from the MongoDB wire driver into a Document instance. | def from_mongo(cls, doc):
"""Convert data coming in from the MongoDB wire driver into a Document instance."""
if doc is None: # To support simplified iterative use, None should return None.
return None
if isinstance(doc, Document): # No need to perform processing on existing Document instances.
retu... |
Retrieve and remove a value from the backing store, optionally with a default. | def pop(self, name, default=SENTINEL):
"""Retrieve and remove a value from the backing store, optionally with a default."""
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default) |
A basic operation operating on a single value. | def _op(self, operation, other, *allowed):
"""A basic operation operating on a single value."""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self._combining,
(q._op(operation, other, *allowed) for q in f)) # pylint:disable=pr... |
An iterative operation operating on multiple values.
Consumes iterators to construct a concrete list at time of execution. | def _iop(self, operation, other, *allowed):
"""An iterative operation operating on multiple values.
Consumes iterators to construct a concrete list at time of execution.
"""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self.... |
Allow for the projection (and update) of nested values contained within the single match of an array.
Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_
Array update operator: https://docs.mongodb.com/manual/reference/operator/update/positional/ | def S(self):
"""Allow for the projection (and update) of nested values contained within the single match of an array.
Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_
Array update operator: https://docs.mongodb.com/manual/reference/operator/update/position... |
Matches string values against a regular expression compiled of individual parts.
Document.field.re(r'^', variable_part, r'\\.')
Regex operator: {$regex: value}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/ | def re(self, *parts):
"""Matches string values against a regular expression compiled of individual parts.
Document.field.re(r'^', variable_part, r'\\.')
Regex operator: {$regex: value}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/
"""
if self._combining: # We are ... |
Selects documents if element in the array field matches all the specified conditions.
Document.field.match(...)
Array operator: {$elemMatch: value}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch | def match(self, q):
"""Selects documents if element in the array field matches all the specified conditions.
Document.field.match(...)
Array operator: {$elemMatch: value}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch
"""
if self._combining: # W... |
Matches values that are between a minimum and maximum value, semi-inclusive.
Document.field.range(4, 12)
This will find documents with a field whose value is greater than or equal to 4, and less than 12.
Comparison operator: {$gte: gte, $lt: lt} | def range(self, gte, lt):
"""Matches values that are between a minimum and maximum value, semi-inclusive.
Document.field.range(4, 12)
This will find documents with a field whose value is greater than or equal to 4, and less than 12.
Comparison operator: {$gte: gte, $lt: lt}
"""
if self._combini... |
Selects documents if the array field is a specified size.
Document.field.size(5)
Array operator: {$size: value}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/size/#op._S_size | def size(self, value):
"""Selects documents if the array field is a specified size.
Document.field.size(5)
Array operator: {$size: value}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/size/#op._S_size
"""
if self._combining: # We are a field-compound query fragment, e.g.... |
Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type | def of_type(self, *kinds):
"""Selects documents if a field is of the correct type.
Document.field.of_type()
Document.field.of_type('string')
Element operator: {$type: self.__foreign__}
Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
"""
if self._combinin... |
Order results by their distance from the given point, optionally with range limits in meters.
Geospatial operator: {$near: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near
{
$near: {
$geometry: <center; Point or (long, lat)>,
$minDistance: <min; ... | def near(self, center, sphere=False, min=None, max=None):
"""Order results by their distance from the given point, optionally with range limits in meters.
Geospatial operator: {$near: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near
{
$near: {
$geom... |
Select geometries within a bounding GeoJSON geometry.
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin
Geospatial operator: {$geoWithin: {$geometry: ...}}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geometry/#op._S_geometry
... | def within(self, geometry=None, center=None, sphere=None, radius=None, box=None, polygon=None, crs=None):
"""Select geometries within a bounding GeoJSON geometry.
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin
Geospatial operator: {$geoWithin: {$geometry: ... |
Select geometries that intersect with a GeoJSON geometry.
Geospatial operator: {$geoIntersects: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects
{
$geoIntersects: { $geometry: <geometry; a GeoJSON object> }
} | def intersects(self, geometry, crs=None):
"""Select geometries that intersect with a GeoJSON geometry.
Geospatial operator: {$geoIntersects: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects
{
$geoIntersects: { $geometry: <geometry; a Ge... |
we recursively run dfs on each vertices in free_vertex,
:param v: vertices in free_vertex
:return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k)
and false otherwise. | def __dfs(self, v, index, layers):
"""
we recursively run dfs on each vertices in free_vertex,
:param v: vertices in free_vertex
:return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k)
and false otherwise.
"""
if in... |
Gets (and create if not exists) as named symbol.
Optionally, you can specify a binding power (bp) value, which will be used
to control operator presedence; the higher the value, the tighter a token
binds to the tokens that follow. | def symbol(self, ident, bp=0):
'''
Gets (and create if not exists) as named symbol.
Optionally, you can specify a binding power (bp) value, which will be used
to control operator presedence; the higher the value, the tighter a token
binds to the tokens that follow.
'''
... |
Symbol decorator. | def method(self, symbol):
'''
Symbol decorator.
'''
assert issubclass(symbol, SymbolBase)
def wrapped(fn):
setattr(symbol, fn.__name__, fn)
return wrapped |
Simple date parsing function | def _simpleparsefun(date):
"""Simple date parsing function"""
if hasattr(date, 'year'):
return date
try:
date = datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
return date |
Check if a given date is a work date, ignoring holidays.
Args:
date (date, datetime or str): Date to be checked.
Returns:
bool: True if the date is a work date, False otherwise. | def isworkday(self, date):
"""
Check if a given date is a work date, ignoring holidays.
Args:
date (date, datetime or str): Date to be checked.
Returns:
bool: True if the date is a work date, False otherwise.
"""
date = parsefun(date)
... |
Check if a given date is a holiday.
Args:
date (date, datetime or str): Date to be checked.
Returns:
bool: True if the date is a holiday, False otherwise. | def isholiday(self, date):
"""
Check if a given date is a holiday.
Args:
date (date, datetime or str): Date to be checked.
Returns:
bool: True if the date is a holiday, False otherwise.
"""
date = parsefun(date)
if self.holiday... |
Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it is returned unchanged.
How to use the ad... | def adjust(self, date, mode):
"""
Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it i... |
Add work days to a given date, ignoring holidays.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a work date. An offset of 1
represents the next work date, regardless of date being a work
date or not.
... | def addworkdays(self, date, offset):
"""
Add work days to a given date, ignoring holidays.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a work date. An offset of 1
represents the next work date, rega... |
Add business days to a given date, taking holidays into consideration.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a business date. An offset of 1
represents the next business date, regardless of date being a
... | def addbusdays(self, date, offset):
"""
Add business days to a given date, taking holidays into consideration.
Note:
By definition, a zero offset causes the function to return the
initial date, even it is not a business date. An offset of 1
represents ... |
(PRIVATE) Count work days between two dates, ignoring holidays. | def _workdaycount(self, date1, date2):
"""
(PRIVATE) Count work days between two dates, ignoring holidays.
"""
assert date2 >= date1
date1wd = date1.weekday()
date2wd = date2.weekday()
if not self.weekdaymap[date2wd].isworkday:
date2 += datetim... |
Count work days between two dates, ignoring holidays.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval.
Note:
The adopted notation is COB to COB, so effectively date1 is not
included... | def workdaycount(self, date1, date2):
"""
Count work days between two dates, ignoring holidays.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval.
Note:
The adopted notation is C... |
Count business days between two dates (private), taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval.
Note:
The adopted notation is COB to COB, so effect... | def busdaycount(self, date1, date2):
"""
Count business days between two dates (private), taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval.
Note:... |
Adjust date to last day of the month, regardless of work days.
Args:
date (date, datetime or str): Date to be adjusted.
Returns:
datetime: Adjusted date. | def caleom(date):
"""
Adjust date to last day of the month, regardless of work days.
Args:
date (date, datetime or str): Date to be adjusted.
Returns:
datetime: Adjusted date.
"""
date = parsefun(date)
date += datetime.timedelt... |
Generate business days between two dates, taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval, not included.
Note:
All business days between date1 (inc) ... | def range(self, date1, date2):
"""
Generate business days between two dates, taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval, not included.
Note... |
Connect signal to current model | def _connect(cls):
"""
Connect signal to current model
"""
post_save.connect(
notify_items, sender=cls,
dispatch_uid='knocker_{0}'.format(cls.__name__)
) |
Disconnect signal from current model | def _disconnect(cls):
"""
Disconnect signal from current model
"""
post_save.disconnect(
notify_items, sender=cls,
dispatch_uid='knocker_{0}'.format(cls.__name__)
) |
Returns a dictionary with the knock data built from _knocker_data | def as_knock(self, created=False):
"""
Returns a dictionary with the knock data built from _knocker_data
"""
knock = {}
if self.should_knock(created):
for field, data in self._retrieve_data(None, self._knocker_data):
knock[field] = data
return ... |
Send the knock in the associated channels Group | def send_knock(self, created=False):
"""
Send the knock in the associated channels Group
"""
knock = self.as_knock(created)
if knock:
gr = Group('knocker-{0}'.format(knock['language']))
gr.send({'text': json.dumps(knock)}) |
Colorize some message with ANSI colors specification
:param printable: interface whose has __str__ or __repr__ method
:param color: the colors defined in COLOR_MAP to colorize the text
:style: can be 'normal', 'bold' or 'underline'
:returns: the 'printable' colorized with style | def colorize(printable, color, style='normal', autoreset=True):
"""Colorize some message with ANSI colors specification
:param printable: interface whose has __str__ or __repr__ method
:param color: the colors defined in COLOR_MAP to colorize the text
:style: can be 'normal', 'bold' or 'underline'
... |
Function: cache
Summary: Decorator used to cache the input->output
Examples: An fib memoized executes at O(1) time
instead O(e^n)
Attributes:
@param (function): function
Returns: wrapped function
TODO: Give support to functions with kwargs | def cache(function):
"""
Function: cache
Summary: Decorator used to cache the input->output
Examples: An fib memoized executes at O(1) time
instead O(e^n)
Attributes:
@param (function): function
Returns: wrapped function
TODO: Give support to functions with kwargs
... |
Change text color for the linux terminal, defaults to green.
Set "warning=True" for red. | def color(string, status=True, warning=False, bold=True):
"""
Change text color for the linux terminal, defaults to green.
Set "warning=True" for red.
"""
attr = []
if status:
# green
attr.append('32')
if warning:
# red
attr.append('31')
if bold:
a... |
A generator which will block and yield entries as they are added to a capped collection.
Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an
integer or floating point number of seconds, indicating how long to wait for a result. Correct operation requires... | def tail(collection, filter=None, projection=None, limit=0, timeout=None, aggregate=False):
"""A generator which will block and yield entries as they are added to a capped collection.
Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an
integer or floati... |
Patch pymongo's Collection object to add a tail method.
While not nessicarily recommended, you can use this to inject `tail` as a method into Collection, making it
generally accessible. | def _patch():
"""Patch pymongo's Collection object to add a tail method.
While not nessicarily recommended, you can use this to inject `tail` as a method into Collection, making it
generally accessible.
"""
if not __debug__: # pragma: no cover
import warnings
warnings.warn("A catgirl has died.", ImportWar... |
Process arguments to query methods. For internal use only.
Positional arguments are treated as query components, combined using boolean AND reduction.
Keyword arguments are processed depending on the passed in mapping and set of valid options, with non-
option arguments treated as parametric query component... | def _prepare_query(cls, mapping, valid, *args, **kw):
"""Process arguments to query methods. For internal use only.
Positional arguments are treated as query components, combined using boolean AND reduction.
Keyword arguments are processed depending on the passed in mapping and set of valid options, with no... |
Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring. | def _prepare_find(cls, *args, **kw):
"""Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
"""
cls, collection, query, options = cls._prepare_query(
... |
Generate and execute an aggregate query pipline using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
This provides a find-like interface for generating aggregate pipelines with a few shortcuts that make
ag... | def _prepare_aggregate(cls, *args, **kw):
"""Generate and execute an aggregate query pipline using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
This provides a find-like interface for generating aggregat... |
Query the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed along with minor transformation.
... | def find(cls, *args, **kw):
"""Query the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed al... |
Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed along with min... | def find_one(cls, *args, **kw):
"""Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyw... |
Return a QuerySet iterating the results of a query in a defined order. Technically an aggregate.
To be successful one must be running MongoDB 3.4 or later. Document order will not be represented otherwise.
Based on the technique described here: http://s.webcore.io/2O3i0N2E3h0r
See also: https://jira.mongodb... | def find_in_sequence(cls, field, order, *args, **kw):
"""Return a QuerySet iterating the results of a query in a defined order. Technically an aggregate.
To be successful one must be running MongoDB 3.4 or later. Document order will not be represented otherwise.
Based on the technique described here: http:/... |
Reload the entire document from the database, or refresh specific named top-level fields. | def reload(self, *fields, **kw):
"""Reload the entire document from the database, or refresh specific named top-level fields."""
Doc, collection, query, options = self._prepare_find(id=self.id, projection=fields, **kw)
result = collection.find_one(query, **options)
if fields: # Refresh only the requested... |
Get values gathered from the previously set hierarchy.
Respects the order in which sources are set, the first source set
has the highest priority, overrides values with the same key that
exist in sources with lower priority.
Returns:
dict: The dictionary containing values g... | def get(cls):
"""Get values gathered from the previously set hierarchy.
Respects the order in which sources are set, the first source set
has the highest priority, overrides values with the same key that
exist in sources with lower priority.
Returns:
dict: The dicti... |
Set command line arguments as a source
Parses the command line arguments described by the parameters.
Args:
name: the long name of the argument (foo)
short_name: the optional short name of the argument (f)
type: the optional type of the argument, defaults to bool
... | def argv(cls, name, short_name=None, type=None, help=None):
""" Set command line arguments as a source
Parses the command line arguments described by the parameters.
Args:
name: the long name of the argument (foo)
short_name: the optional short name of the argument (f)
... |
Set environment variables as a source.
By default all environment variables available to the process are used.
This can be narrowed by the args.
Args:
separator: Keys are split along this character, the resulting
splits are considered nested values.
matc... | def env(cls, separator=None, match=None, whitelist=None, parse_values=None, to_lower=None, convert_underscores=None):
"""Set environment variables as a source.
By default all environment variables available to the process are used.
This can be narrowed by the args.
Args:
se... |
Set a file as a source.
File are parsed as literal python dicts by default, this behaviour
can be configured.
Args:
path: The path to the file to be parsed
encoding: The encoding of the file.
Defaults to 'raw'. Available built-in values: 'ini', 'json', '... | def file(cls, path, encoding=None, parser=None):
"""Set a file as a source.
File are parsed as literal python dicts by default, this behaviour
can be configured.
Args:
path: The path to the file to be parsed
encoding: The encoding of the file.
De... |
Generate a MongoDB projection dictionary using the Django ORM style. | def P(Document, *fields, **kw):
"""Generate a MongoDB projection dictionary using the Django ORM style."""
__always__ = kw.pop('__always__', set())
projected = set()
omitted = set()
for field in fields:
if field[0] in ('-', '!'):
omitted.add(field[1:])
elif field[0] == '+':
projected.add(field[1:])
... |
Performs a login handshake with a user on the command-line. This method
will handle all of the follow-up requests (e.g. capcha or two-factor). A
login that requires two-factor looks like this::
>>> import mwapi.cli
>>> import mwapi
>>> mwapi.cli.do_login(mwapi.Session("https://en.wiki... | def do_login(session, for_what):
"""
Performs a login handshake with a user on the command-line. This method
will handle all of the follow-up requests (e.g. capcha or two-factor). A
login that requires two-factor looks like this::
>>> import mwapi.cli
>>> import mwapi
>>> mwap... |
Identify if the given session ID is currently valid.
Return True if valid, False if explicitly invalid, None if unknown. | def is_valid(self, context, sid):
"""Identify if the given session ID is currently valid.
Return True if valid, False if explicitly invalid, None if unknown.
"""
record = self._Document.find_one(sid, project=('expires', ))
if not record:
return
return not record._expired |
Immediately expire a session from the backing store. | def invalidate(self, context, sid):
"""Immediately expire a session from the backing store."""
result = self._Document.get_collection().delete_one({'_id': sid})
return result.deleted_count == 1 |
Update or insert the session document into the configured collection | def persist(self, context):
"""Update or insert the session document into the configured collection"""
D = self._Document
document = context.session[self.name]
D.get_collection().replace_one(D.id == document.id, document, True) |
Channels connection setup.
Register the current client on the related Group according to the language | def ws_connect(message):
"""
Channels connection setup.
Register the current client on the related Group according to the language
"""
prefix, language = message['path'].strip('/').split('/')
gr = Group('knocker-{0}'.format(language))
gr.add(message.reply_channel)
message.channel_session... |
Channels connection close.
Deregister the client | def ws_disconnect(message):
"""
Channels connection close.
Deregister the client
"""
language = message.channel_session['knocker']
gr = Group('knocker-{0}'.format(language))
gr.discard(message.reply_channel) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.