code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def inherit_docstrings(cls):
@functools.wraps(cls)
def _inherit_docstrings(cls):
if not isinstance(cls, (type, colorise.compat.ClassType)):
raise RuntimeError("Type is not a class")
for name, value in colorise.compat.iteritems(vars(cls)):
if isinstance(getattr(cls, ... | Class decorator for inheriting docstrings.
Automatically inherits base class doc-strings if not present in the
derived class. |
def upload(config):
token = get_keeper_token(config['keeper_url'],
config['keeper_user'],
config['keeper_password'])
build_resource = register_build(config, token)
ltdconveyor.upload_dir(
build_resource['bucket_name'],
build_res... | Upload the build documentation site to LSST the Docs.
Parameters
----------
config : `lander.config.Configuration`
Site configuration, which includes upload information and credentials. |
def get_keeper_token(base_url, username, password):
token_endpoint = base_url + '/token'
r = requests.get(token_endpoint, auth=(username, password))
if r.status_code != 200:
raise RuntimeError('Could not authenticate to {0}: error {1:d}\n{2}'.
format(base_url, r.statu... | Get a temporary auth token from LTD Keeper. |
def get_product(config):
product_url = config['keeper_url'] + '/products/{p}'.format(
p=config['ltd_product'])
r = requests.get(product_url)
if r.status_code != 200:
raise RuntimeError(r.json())
product_info = r.json()
return product_info | Get the /product/<product> resource from LTD Keeper. |
def install(
board_id='atmega88',
mcu='atmega88',
f_cpu=20000000,
upload='usbasp',
core='arduino',
replace_existing=True,
):
board = AutoBunch()
board.name = TEMPL.format(mcu=mcu, f_cpu=f_cpu, upload=upload)
board.upload.using = upload
board.upload.maximum_size = 8 * 1024
... | install atmega88 board. |
def _compute_bgid(self, bg=None):
if bg is None:
bg = self._bgdata
if isinstance(bg, qpimage.QPImage):
# Single QPImage
if "identifier" in bg:
return bg["identifier"]
else:
data = [bg.amp, bg.pha]
fo... | Return a unique identifier for the background data |
def identifier(self):
if self.background_identifier is None:
idsum = self._identifier_data()
else:
idsum = hash_obj([self._identifier_data(),
self.background_identifier])
return idsum | Return a unique identifier for the given data set |
def get_time(self, idx):
# raw data
qpi = self.get_qpimage_raw(idx)
if "time" in qpi.meta:
thetime = qpi.meta["time"]
else:
thetime = np.nan
return thetime | Return time of data at index `idx`
Returns nan if the time is not defined |
def get_qpimage(self, idx):
# raw data
qpi = self.get_qpimage_raw(idx)
if "identifier" not in qpi:
msg = "`get_qpimage_raw` does not set 'identifier' " \
+ "in class '{}'!".format(self.__class__)
raise KeyError(msg)
# bg data
if ... | Return background-corrected QPImage of data at index `idx` |
def set_bg(self, dataset):
if isinstance(dataset, qpimage.QPImage):
# Single QPImage
self._bgdata = [dataset]
elif (isinstance(dataset, list) and
len(dataset) == len(self) and
isinstance(dataset[0], qpimage.QPImage)):
# List of QPI... | Set background data
Parameters
----------
dataset: `DataSet`, `qpimage.QPImage`, or int
If the ``len(dataset)`` matches ``len(self)``,
then background correction is performed
element-wise. Otherwise, ``len(dataset)``
must be one and is used for al... |
def get_time(self, idx=0):
thetime = super(SingleData, self).get_time(idx=0)
return thetime | Time of the data
Returns nan if the time is not defined |
def do(self, fn, message=None, *args, **kwargs):
self.items.put(ChainItem(fn, self.do, message, *args, **kwargs))
return self | Add a 'do' action to the steps. This is a function to execute
:param fn: A function
:param message: Message indicating what this function does (used for debugging if assertions fail) |
def expect(self, value, message='Failed: "{actual} {operator} {expected}" after step "{step}"', operator='=='):
if operator not in self.valid_operators:
raise ValueError('Illegal operator specified for ')
self.items.put(ChainItem(value, self.expect, message, operator=operator))
... | Add an 'assertion' action to the steps. This will evaluate the return value of the last 'do' step and
compare it to the value passed here using the specified operator.
Checks that the first function will return 2
>>> AssertionChain().do(lambda: 1 + 1, 'add 1 + 1').expect(2)
This will c... |
def perform(self):
last_value = None
last_step = None
while self.items.qsize():
item = self.items.get()
if item.flag == self.do:
last_value = item.item(*item.args, **item.kwargs)
last_step = item.message
elif item.fl... | Runs through all of the steps in the chain and runs each of them in sequence.
:return: The value from the lat "do" step performed |
def get_volumes(self):
vols = [self.find_volume(name) for name in self.virsp.listVolumes()]
return vols | Return a list of all Volumes in this Storage Pool |
def create_backed_vol(self, name, backer, _format='qcow2'):
vol_xml = ElementTree.Element('volume')
vol_name = ElementTree.SubElement(vol_xml, 'name')
name = '{0}.{1}'.format(name, _format)
vol_name.text = name
target = ElementTree.SubElement(vol_xml, 'target')
... | TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do this in libvirt, the
best way I've found is to just create some xml and... |
def find_volume(self, name):
try:
return Volume(self.virsp.storageVolLookupByName(name), self)
except libvirtError:
return None | Find a storage volume by its name
:param name: The name of the volume
:type name: str |
def install(replace_existing=False):
bunch = AutoBunch()
bunch.name = 'DAPA'
bunch.protocol = 'dapa'
bunch.force = 'true'
# bunch.delay=200
install_programmer('dapa', bunch, replace_existing=replace_existing) | install dapa programmer. |
def get_terminal_converted(self, attr):
value = self.data.get(attr.repr_name)
return self.converter_registry.convert_to_representation(
value,
attr.value_type) | Returns the value of the specified attribute converted to a
representation value.
:param attr: Attribute to retrieve.
:type attr: :class:`everest.representers.attributes.MappedAttribute`
:returns: Representation string. |
def set_terminal_converted(self, attr, repr_value):
value = self.converter_registry.convert_from_representation(
repr_value,
attr.value_type)
self.data[attr.repr_name] = value | Converts the given representation value and sets the specified
attribute value to the converted value.
:param attr: Attribute to set.
:param str repr_value: String value of the attribute to set. |
def load(self, filename, offset):
try:
self.offset = offset
# self.fd = open(filename, 'rb')
# self.fd.close()
except IOError:
self.logger.error('Unable to load EfiSystem volume') | Will eventually load information for Apple_Boot volume. \
Not yet implemented |
def send(self, filenames=None):
try:
with self.ssh_client.connect() as ssh_conn:
with self.sftp_client.connect(ssh_conn) as sftp_conn:
for filename in filenames:
sftp_conn.copy(filename=filename)
self.archiv... | Sends the file to the remote host and archives
the sent file locally. |
def compile(self, name, folder=None, data=None):
template_name = name.replace(os.sep, "")
if folder is None:
folder = ""
full_name = os.path.join(
folder.strip(os.sep), template_name)
if data is None:
data = {}
try:
... | renders template_name + self.extension file with data using jinja |
def create_token(self, data, token_valid_for=180) -> str:
jwt_token = jwt.encode({
'data': data,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret)
return Security.encrypt(jwt_token) | Create encrypted JWT |
def verify_token(self, token) -> bool:
try:
self.data = jwt.decode(Security.decrypt(token), self.app_secret)
return True
except (Exception, BaseException) as error:
self.errors.append(error)
return False
return False | Verify encrypted JWT |
def verify_http_auth_token(self) -> bool:
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
... | Use request information to validate JWT |
def create_token_with_refresh_token(self, data, token_valid_for=180,
refresh_token_valid_for=86400):
refresh_token = None
refresh_token = jwt.encode({
'exp':
datetime.utcnow() +
timedelta(seconds=refresh_... | Create an encrypted JWT with a refresh_token |
def verify_refresh_token(self, expired_token) -> bool:
try:
decoded_token = jwt.decode(
Security.decrypt(expired_token),
self.app_secret,
options={'verify_exp': False})
if 'refresh_token' in decoded_token and \
... | Use request information to validate refresh JWT |
def verify_http_auth_refresh_token(self) -> bool:
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_refresh_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
... | Use expired token to check refresh token information |
def autocomplete(input_list):
if input_list[0] in ['modulehelp', 'enable', 'disable']:
commands = []
for modulename in seash_modules.module_data.keys():
commands.append(input_list[0] + ' ' + modulename)
return commands
return [] | <Purpose>
Returns all valid input completions for the specified command line input.
<Arguments>
input_list: A list of tokens.
<Side Effects>
None
<Exceptions>
None
<Returns>
A list of strings representing valid completions. |
def status(self, status_code=None):
if status_code is not None:
self.response_model.status = status_code
# return string for response support
return str(self.response_model.status) | Set status or Get Status |
def message(self, message=None):
if message is not None:
self.response_model.message = message
return self.response_model.message | Set response message |
def data(self, data=None):
if data is not None:
self.response_model.data = data
return self.response_model.data | Set response data |
def quick_response(self, status_code):
translator = Translator(environ=self.environ)
if status_code == 404:
self.status(404)
self.message(translator.trans('http_messages.404'))
elif status_code == 401:
self.status(401)
self.message... | Quickly construct response using a status code |
def memoize(func):
cache = {}
def memoizer():
if 0 not in cache:
cache[0] = func()
return cache[0]
return functools.wraps(func)(memoizer) | Cache forever. |
def getpreferredencoding():
encoding = locale.getpreferredencoding(False)
if sys.platform == 'darwin' and encoding.startswith('mac-'):
# Upgrade ancient MacOS encodings in Python < 2.7
encoding = 'utf-8'
return encoding | Return preferred encoding for text I/O. |
def getinputencoding(stream=None):
if stream is None:
stream = sys.stdin
encoding = stream.encoding
if not encoding:
encoding = getpreferredencoding()
return encoding | Return preferred encoding for reading from ``stream``.
``stream`` defaults to sys.stdin. |
def getoutputencoding(stream=None):
if stream is None:
stream = sys.stdout
encoding = stream.encoding
if not encoding:
encoding = getpreferredencoding()
return encoding | Return preferred encoding for writing to ``stream``.
``stream`` defaults to sys.stdout. |
def decode(string, encoding=None, errors=None):
if encoding is None:
encoding = getpreferredencoding()
if errors is None:
errors = getpreferrederrors()
return string.decode(encoding, errors) | Decode from specified encoding.
``encoding`` defaults to the preferred encoding.
``errors`` defaults to the preferred error handler. |
def encode(string, encoding=None, errors=None):
if encoding is None:
encoding = getpreferredencoding()
if errors is None:
errors = getpreferrederrors()
return string.encode(encoding, errors) | Encode to specified encoding.
``encoding`` defaults to the preferred encoding.
``errors`` defaults to the preferred error handler. |
def _get_response_mime_type(self):
view_name = self.request.view_name
if view_name != '':
mime_type = get_registered_mime_type_for_name(view_name)
else:
mime_type = None
acc = None
for acc in self.request.accept:
if acc == ... | Returns the reponse MIME type for this view.
:raises: :class:`pyramid.httpexceptions.HTTPNotAcceptable` if the
MIME content type(s) the client specified can not be handled by
the view. |
def _get_response_body_mime_type(self):
mime_type = self._get_response_mime_type()
if mime_type is AtomMime:
# FIXME: This cements using XML as the representation to use in
# ATOM bodies (which is perhaps not too worrisome).
mime_type = XmlMime
... | Returns the response body MIME type. This might differ from the
overall response mime type e.g. in ATOM responses where the body
MIME type is XML. |
def _get_result(self, resource):
if self._convert_response:
self._update_response_body(resource)
result = self.request.response
else:
result = dict(context=resource)
return result | Converts the given resource to a result to be returned from the view.
Unless a custom renderer is employed, this will involve creating
a representer and using it to convert the resource to a string.
:param resource: Resource to convert.
:type resource: Object implementing
:cla... |
def _update_response_body(self, resource):
rpr = self._get_response_representer(resource)
# Set content type and body of the response.
self.request.response.content_type = \
rpr.content_type.mime_type_string
rpr_body = rpr.to_bytes(resource)
... | Creates a representer and updates the response body with the byte
representation created for the given resource. |
def _update_response_location_header(self, resource):
location = resource_to_url(resource, request=self.request)
loc_hdr = ('Location', location)
hdr_names = [hdr[0].upper() for hdr in self.request.response.headerlist]
try:
idx = hdr_names.index('LOCATION')
e... | Adds a new or replaces an existing Location header to the response
headers pointing to the URL of the given resource. |
def _get_request_representer(self):
try:
mime_type = \
get_registered_mime_type_for_string(self.request.content_type)
except KeyError:
# The client sent a content type we do not support (415).
raise HTTPUnsupportedMediaType()
return as_r... | Returns a representer for the content type specified in the request.
:raises HTTPUnsupportedMediaType: If the specified content type is
not supported. |
def _extract_request_data(self):
rpr = self._get_request_representer()
return rpr.data_from_bytes(self.request.body) | Extracts the data from the representation submitted in the request
body and returns it.
This default implementation uses a representer for the content type
specified by the request to perform the extraction and returns an
object implementing the
:class:`everest.representers.inte... |
def _handle_conflict(self, name):
err = HTTPConflict('Member "%s" already exists!' % name).exception
return self.request.get_response(err) | Handles requests that triggered a conflict.
Respond with a 409 "Conflict" |
def check(self):
request = get_current_request()
ignore_guid = request.params.get('ignore-message')
coll = request.root['_messages']
vote = False
if ignore_guid:
ignore_mb = coll.get(ignore_guid)
if not ignore_mb is None and ignore_mb.text == self... | Implements user message checking for views.
Checks if the current request has an explicit "ignore-message"
parameter (a GUID) pointing to a message with identical text from a
previous request, in which case further processing is allowed. |
def create_307_response(self):
request = get_current_request()
msg_mb = UserMessageMember(self.message)
coll = request.root['_messages']
coll.add(msg_mb)
# Figure out the new location URL.
qs = self.__get_new_query_string(request.query_string,
... | Creates a 307 "Temporary Redirect" response including a HTTP Warning
header with code 299 that contains the user message received during
processing the request. |
def mkdir(*args):
path = ''
for chunk in args:
path = os.path.join(path, chunk)
if not os.path.isdir(path):
os.mkdir(path)
return path | Create a directory specified by a sequence of subdirectories
>>> mkdir("/tmp", "foo", "bar", "baz")
'/tmp/foo/bar/baz'
>>> os.path.isdir('/tmp/foo/bar/baz')
True |
def shell(cmd, *args, **kwargs):
# type: (Union[str, unicode], *Union[str, unicode], **Any) ->Tuple[int, str]
if kwargs.get('rel_path') and not cmd.startswith("/"):
cmd = os.path.join(kwargs['rel_path'], cmd)
status = 0
try:
output = subprocess.check_output(
(cmd,) + arg... | Execute shell command and return output
Args:
cmd (str): the command itself, i.e. part until the first space
*args: positional arguments, i.e. other space-separated parts
rel_path (bool): execute relative to the path (default: `False`)
raise_on_status(bool): bool, raise exception if... |
def raw_filesize(path):
# type: (str) -> Optional[int]
with open('/dev/null', 'w') as devnull:
status, output = shell("du", "-bs", path, raise_on_status=False,
stderr=devnull)
if status != 0:
return None
# output is: <size>\t<path>\n
return int(out... | Get size of a file/directory in bytes.
Will return None if path does not exist or cannot be accessed. |
def listen_for_events():
import_event_modules()
conn = redis_connection.get_connection()
pubsub = conn.pubsub()
pubsub.subscribe("eventlib")
for message in pubsub.listen():
if message['type'] != 'message':
continue
data = loads(message["data"])
if 'name' in d... | Pubsub event listener
Listen for events in the pubsub bus and calls the process function
when somebody comes to play. |
def sendrequest(self, request):
'''
Recieves a request xml as a string and posts it
to the health service url specified in the
settings.py
'''
url = urlparse.urlparse(self.connection.healthserviceurl)
conn = None
if url.scheme == 'https':
... | Recieves a request xml as a string and posts it
to the health service url specified in the
settings.py |
def commit(self, unit_of_work):
MemoryRepository.commit(self, unit_of_work)
if self.is_initialized:
entity_classes_to_dump = set()
for state in unit_of_work.iterator():
entity_classes_to_dump.add(type(state.entity))
for entity_cls in entity_cl... | Dump all resources that were modified by the given session back into
the repository. |
def _validate_pdf_file(self):
if self['pdf_path'] is None:
self._logger.error('--pdf argument must be set')
sys.exit(1)
if not os.path.exists(self['pdf_path']):
self._logger.error('Cannot find PDF ' + self['pdf_path'])
sys.exit(1) | Validate that the pdf_path configuration is set and the referenced
file exists.
Exits the program with status 1 if validation fails. |
def _get_docushare_url(handle, validate=True):
logger = structlog.get_logger(__name__)
logger.debug('Using Configuration._get_docushare_url')
# Make a short link to the DocuShare version page since
# a) It doesn't immediately trigger a PDF download,
# b) It gives the us... | Get a docushare URL given document's handle.
Parameters
----------
handle : `str`
Handle name, such as ``'LDM-151'``.
validate : `bool`, optional
Set to `True` to request that the link resolves by performing
a HEAD request over the network. `False` di... |
def _init_defaults(self):
defaults = {
'build_dir': None,
'build_datetime': datetime.datetime.now(dateutil.tz.tzutc()),
'pdf_path': None,
'extra_downloads': list(),
'environment': None,
'lsstdoc_tex_path': None,
'title'... | Create a `dict` of default configurations. |
def create_permissions_from_tuples(model, codename_tpls):
if codename_tpls:
model_cls = django_apps.get_model(model)
content_type = ContentType.objects.get_for_model(model_cls)
for codename_tpl in codename_tpls:
app_label, codename, name = get_from_codename_tuple(
... | Creates custom permissions on model "model". |
def remove_historical_group_permissions(group=None, allowed_permissions=None):
allowed_permissions = allowed_permissions or ["view"]
for action in allowed_permissions:
for permission in group.permissions.filter(
codename__contains="historical"
).exclude(codename__startswith=act... | Removes group permissions for historical models
except those whose prefix is in `allowed_historical_permissions`.
Default removes all except `view`. |
def traversal(root):
'''Tree traversal function that generates nodes. For each subtree, the
deepest node is evaluated first. Then, the next-deepest nodes are
evaluated until all the nodes in the subtree are generated.'''
stack = [root]
while len(stack) > 0:
node = stack.pop()
if ha... | Tree traversal function that generates nodes. For each subtree, the
deepest node is evaluated first. Then, the next-deepest nodes are
evaluated until all the nodes in the subtree are generated. |
def formatBodyNode(root,path):
'''Format the root node for use as the body node.'''
body = root
body.name = "body"
body.weight = calcFnWeight(body)
body.path = path
body.pclass = None
return bodf formatBodyNode(root,path):
'''Format the root node for use as the body node.'''
... | Format the root node for use as the body node. |
def formatFunctionNode(node,path,stack):
'''Add some helpful attributes to node.'''
#node.name is already defined by AST module
node.weight = calcFnWeight(node)
node.path = path
node.pclass = getCurrentClass(stack)
return nodf formatFunctionNode(node,path,stack):
'''Add some helpful attrib... | Add some helpful attributes to node. |
def calcFnWeight(node):
'''Calculates the weight of a function definition by recursively counting
its child nodes in the AST. Note that the tree traversal will become
O(n^2) instead of O(n) if this feature is enabled.'''
stack = [node]
count = 0
while len(stack) > 0:
node = stack.pop()... | Calculates the weight of a function definition by recursively counting
its child nodes in the AST. Note that the tree traversal will become
O(n^2) instead of O(n) if this feature is enabled. |
def getSourceFnDef(stack,fdefs,path):
'''VERY VERY SLOW'''
found = False
for x in stack:
if isinstance(x, ast.FunctionDef):
for y in fdefs[path]:
if ast.dump(x)==ast.dump(y): #probably causing the slowness
found = True
return y
... | VERY VERY SLOW |
def delete_database(mongo_uri, database_name):
client = pymongo.MongoClient(mongo_uri)
client.drop_database(database_name) | Delete a mongo database using pymongo. Mongo daemon assumed to be running.
Inputs: - mongo_uri: A MongoDB URI.
- database_name: The mongo database name as a python string. |
def delete_collection(mongo_uri, database_name, collection_name):
client = pymongo.MongoClient(mongo_uri)
db = client[database_name]
db.drop_collection(collection_name) | Delete a mongo document collection using pymongo. Mongo daemon assumed to be running.
Inputs: - mongo_uri: A MongoDB URI.
- database_name: The mongo database name as a python string.
- collection_name: The mongo collection as a python string. |
def parse_xml(self, xml):
'''
:param xml: lxml.etree.Element representing a single VocabularyItem
'''
xmlutils = XmlUtils(xml)
self.code_value = xmlutils.get_string_by_xpath('code-value')
self.display_text = xmlutils.get_string_by_xpath('display-text')
self.ab... | :param xml: lxml.etree.Element representing a single VocabularyItem |
async def main():
async with aiohttp.ClientSession() as session:
zaehler = Volkszaehler(loop, session, UUID, host=HOST)
# Get the data
await zaehler.get_data()
print("Average:", zaehler.average)
print("Max:", zaehler.max)
print("Min:", zaehler.min)
prin... | The main part of the example script. |
def create_staging_collection(resource):
ent_cls = get_entity_class(resource)
coll_cls = get_collection_class(resource)
agg = StagingAggregate(ent_cls)
return coll_cls.create_from_aggregate(agg) | Helper function to create a staging collection for the given registered
resource.
:param resource: registered resource
:type resource: class implementing or instance providing or subclass of
a registered resource interface. |
def parse(self):
try:
return self.parse_top_level()
except PartpyError as ex:
self.error = True
print(ex.pretty_print()) | Run the parser over the entire sourestring and return the results. |
def parse_top_level(self):
contacts = []
while not self.eos:
contact = self.parse_contact() # match a contact expression.
if not contact: # There was no contact so end file.
break # This would be a nice place to put other expressions.
conta... | The top level parser will do a loop where it looks for a single
contact parse and then eats all whitespace until there is no more
input left or another contact is found to be parsed and stores them. |
def parse_contact(self):
self.parse_whitespace()
name = self.parse_name() # parse a name expression and get the string.
if not name: # No name was found so shout it out.
raise PartpyError(self, 'Expecting a name')
self.parse_whitespace()
# allow name and e... | Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned. |
def parse_name(self):
name = []
while True:
# Match the current char until it doesnt match the given pattern:
# first char must be an uppercase alpha and the rest must be lower
# cased alphas.
part = self.match_string_pattern(spat.alphau, spat.alp... | This function uses string patterns to match a title cased name.
This is done in a loop until there are no more names to match so as
to be able to include surnames etc. in the output. |
def parse_email(self):
email = []
# Match from current char until a non lower cased alpha
name = self.match_string_pattern(spat.alphal)
if not name:
raise PartpyError(self, 'Expected a valid name')
email.append(name) # Store the name
self.eat_string... | Email address parsing is done in several stages.
First the name of the email use is determined.
Then it looks for a '@' as a delimiter between the name and the site.
Lastly the email site is matched.
Each part's string is stored, combined and returned. |
def require_valid_type(value, *classes):
if value is not None:
valid = False
for auxiliar_class in classes:
if isinstance(value, auxiliar_class):
valid = True
break
if not valid:
raise TypeError() | Checks that the specified object reference is instance of classes and
throws a :py:class:`TypeError` if it is not.
:param value: The object.
:type value: object
:param classes: The classes.
:type classes: list(class) |
def get_development_container_name(self):
if self.__prefix:
return "{0}:{1}-{2}-dev".format(
self.__repository,
self.__prefix,
self.__branch)
else:
return "{0}:{1}-dev".format(
self.__repository,
... | Returns the development container name |
def get_build_container_tag(self):
if self.__prefix:
return "{0}-{1}-{2}".format(
self.__prefix,
self.__branch,
self.__version)
else:
return "{0}-{1}".format(
self.__branch,
self.__version) | Return the build container tag |
def get_branch_container_tag(self):
if self.__prefix:
return "{0}-{1}".format(
self.__prefix,
self.__branch)
else:
return "{0}".format(self.__branch) | Returns the branch container tag |
def custom_server_error(request, template_name='500.html', admin_template_name='500A.html'):
trace = None
if request.user.is_authenticated() and (request.user.is_staff or request.user.is_superuser):
try:
import traceback, sys
trace = traceback.format_exception(*(sys.exc_info... | 500 error handler. Displays a full trackback for superusers and the first line of the
traceback for staff members.
Templates: `500.html` or `500A.html` (admin)
Context: trace
Holds the traceback information for debugging. |
def parse_n_jobs(s):
n_jobs = None
N = cpu_count()
if isinstance(s, int): n_jobs = s
elif isinstance(s, float): n_jobs = int(s)
elif isinstance(s, str):
m = re.match(r'(\d*(?:\.\d*)?)?(\s*\*?\s*n)?$', s.strip())
if m is None: raise ValueError('Unable to parse n_jobs="{}"'.fo... | This function parses a "math"-like string as a function of CPU count.
It is useful for specifying the number of jobs.
For example, on an 8-core machine::
assert parse_n_jobs('0.5 * n') == 4
assert parse_n_jobs('2n') == 16
assert parse_n_jobs('n') == 8
assert parse_n_jobs('4') =... |
def getbool(self, key, **kwargs):
def _string_to_bool(s):
if isinstance(s, str):
if s.strip().lower() in ('true', 't', '1'): return True
elif s.strip().lower() in ('false', 'f', '0', 'None', 'null', ''): return False
raise ValueError('Unable... | Gets the setting value as a :func:`bool` by cleverly recognizing true values.
:rtype: bool |
def getint(self, key, **kwargs):
return self.get(key, cast_func=int, **kwargs) | Gets the setting value as a :obj:`int`.
:rtype: int |
def getfloat(self, key, **kwargs):
return self.get(key, cast_func=float, **kwargs) | Gets the setting value as a :obj:`float`.
:rtype: float |
def getserialized(self, key, decoder_func=None, **kwargs):
value = self.get(key, cast_func=None, **kwargs)
if isinstance(value, (dict, list, tuple)) or value is None:
return value
if decoder_func: return decoder_func(value)
try:
o = json.loads(value)
... | Gets the setting value as a :obj:`dict` or :obj:`list` trying :meth:`json.loads`, followed by :meth:`yaml.load`.
:rtype: dict, list |
def geturi(self, key, **kwargs):
return self.get(key, cast_func=urlparse, **kwargs) | Gets the setting value as a :class:`urllib.parse.ParseResult`.
:rtype: urllib.parse.ParseResult |
def getlist(self, key, delimiter=',', **kwargs):
value = self.get(key, **kwargs)
if value is None: return value
if isinstance(value, str):
value = value.strip()
if value.startswith('[') and value.endswith(']'):
return self.getserialized(key)
... | Gets the setting value as a :class:`list`; it splits the string using ``delimiter``.
:param str delimiter: split the value using this delimiter
:rtype: list |
def getnjobs(self, key, **kwargs):
return self.get(key, cast_func=parse_n_jobs, **kwargs) | Gets the setting value as an integer relative to the number of CPU.
See :func:`ycsettings.settings.parse_n_jobs` for parsing rules.
:rtype: int |
def _in_list(self, original_list, item):
# pylint: disable=no-self-use
for item_list in original_list:
if item is item_list:
return True
return False | Check that an item as contained in a list.
:param original_list: The list.
:type original_list: list(object)
:param item: The item.
:type item: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: True if the item contained in the list or False if not.
:rtype: bool |
def _sort_results(self, results):
parents = []
groups = []
for result in results:
if not self._in_list(parents, result.parent):
parents.append(result.parent)
groups.append([])
groups[len(groups) - 1].append(result)
... | Order the results.
:param results: The disordened results.
:type results: array.bs4.element.Tag
:return: The ordened results.
:rtype: array.bs4.element.Tag |
def _fix_data_select(self):
elements = self.document.select('*')
for element in elements:
attributes = element.attrs.keys()
data_attributes = list()
for attribute in attributes:
if bool(re.findall('^data-', attribute)):
da... | Replace all hyphens of data attributes for 'aaaaa', to avoid error in
search. |
def join_and(value):
# convert numbers to strings
value = [str(item) for item in value]
if len(value) == 1:
return value[0]
if len(value) == 2:
return "%s and %s" % (value[0], value[1])
# join all but the last element
all_but_last = ", ".join(value[:-1])
return "%s and... | Given a list of strings, format them with commas and spaces, but
with 'and' at the end.
>>> join_and(['apples', 'oranges', 'pears'])
"apples, oranges, and pears"
There is surely a better home for this |
def render_activity(activity, grouped_activity=None, *args, **kwargs):
template_name = 'activity_monitor/includes/models/{0.app_label}_{0.model}.html'.format(activity.content_type)
try:
tmpl = loader.get_template(template_name)
except template.TemplateDoesNotExist:
return None
# we ... | Given an activity, will attempt to render the matching template snippet
for that activity's content object
or will return a simple representation of the activity.
Also takes an optional 'grouped_activity' argument that would match up with
what is produced by utils.group_activity |
def show_activity_count(date=None):
if not date:
today = datetime.datetime.now() - datetime.timedelta(hours = 24)
return Activity.objects.filter(timestamp__gte=today).count()
return Activity.objects.filter(timestamp__gte=date).count() | Simple filter to get activity count for a given day.
Defaults to today. |
def show_new_activity(last_seen=None, cap=1000, template='grouped', include=None, exclude=None):
if not last_seen or last_seen is '':
last_seen = datetime.date.today()
actions = Activity.objects.filter(timestamp__gte=last_seen)
if include:
include_types = include.split(',')
act... | Inclusion tag to show new activity,
either since user was last seen or today (if not last_seen).
Note that passing in last_seen is up to you.
Usage: {% show_new_activity %}
Or, to show since last seen: {% show_new_activity last_seen %}
Can also cap the number of items returned. Default is 1000.
... |
def paginate_activity(visible_date=None):
#if visible_date:
# visible_date = datetime.datetime.strptime(visible_date, "%b %d ")
if not visible_date:
visible_date = datetime.date.today()
previous_day = visible_date - datetime.timedelta(days=1)
if visible_date == datetime.date.today()... | Creates "get previous day" / "get next day" pagination for activities.
Visible date is the date of the activities currently being shown,
represented by a date object.
If not provided, it will default to today.
#Expects date as default "Aug. 25, 2014" format. |
def find_files(self):
modules = self.evernode_app.get_modules()
root_path = sys.path[0] if self.evernode_app.root_path is None \
else self.evernode_app.root_path
dirs = [dict(
dir=os.path.join(root_path, 'resources', 'lang'), module="root")]
for mo... | Gets modules routes.py and converts to module imports |
def __root_path(self):
if self.root_path is not None:
if os.path.isdir(self.root_path):
sys.path.append(self.root_path)
return
raise RuntimeError('EverNode requires a valid root path.'
' Directory: %s does not... | Just checks the root path if set |
def write_metadata(self, output_path):
if self._config.lsstdoc is None:
self._logger.info('No known LSST LaTeX source (--tex argument). '
'Not writing a metadata.jsonld file.')
return
# Build a JSON-LD dataset for the report+source reposito... | Build a JSON-LD dataset for LSST Projectmeta.
Parameters
----------
output_path : `str`
File path where the ``metadata.jsonld`` should be written for the
build. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.