_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265400 | dmap | validation | def dmap(fn, record):
"""map for a directory"""
values = (fn(v) for k, v in record.items())
| python | {
"resource": ""
} |
q265401 | apply_types | validation | def apply_types(use_types, guess_type, line):
"""Apply the types on the elements of the line"""
new_line = {}
for k, v in line.items():
| python | {
"resource": ""
} |
q265402 | format_to_csv | validation | def format_to_csv(filename, skiprows=0, delimiter=""):
"""Convert a file to a .csv file"""
if not delimiter:
delimiter = "\t"
input_file = open(filename, "r")
if skiprows:
[input_file.readline() for _ in range(skiprows)]
new_filename = os.path.splitext(filename)[0] + ".csv"
output_file = open(new_filename, "w")
header = input_file.readline().split()
reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter)
writer = csv.DictWriter(output_file, fieldnames=header, delimiter=",")
| python | {
"resource": ""
} |
q265403 | admin_obj_link | validation | def admin_obj_link(obj, display=''):
"""Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
:returns:
Text containing HTML for a link
"""
| python | {
"resource": ""
} |
q265404 | _obj_display | validation | def _obj_display(obj, display=''):
"""Returns string representation of an object, either the default or based
on the display template passed in.
"""
result = ''
if not display:
result = str(obj)
else: | python | {
"resource": ""
} |
q265405 | FancyModelAdmin.add_link | validation | def add_link(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute that appears as a link to the
django admin change page for the type of object being shown. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)`` . This parameter supports django
templating, the context for which contains a dictionary key named
"obj" with the value being the object for the row.
Example usage: | python | {
"resource": ""
} |
q265406 | FancyModelAdmin.add_object | validation | def add_object(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute showing an object. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)``. This parameter supports django templating,
the context for which contains a dictionary key named "obj" with
the value being the object for the row.
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
| python | {
"resource": ""
} |
q265407 | FancyModelAdmin.add_formatted_field | validation | def add_formatted_field(cls, field, format_string, title=''):
"""Adds a ``list_display`` attribute showing a field in the object
using a python %formatted string.
:param field:
Name of the field in the object.
:param format_string:
A old-style (to remain python 2.x compatible) % string formatter
with a single variable reference. The named ``field`` attribute
will be passed to the formatter using the "%" operator.
:param title:
| python | {
"resource": ""
} |
q265408 | post_required | validation | def post_required(method_or_options=[]):
"""View decorator that enforces that the method was called using POST.
This decorator can be called with or without parameters. As it is
expected to wrap a view, the first argument of the method being wrapped is
expected to be a ``request`` object.
.. code-block:: python
@post_required
def some_view(request):
pass
@post_required(['firstname', 'lastname'])
def some_view(request):
pass
The optional parameter contains a single list which specifies the names of
the expected fields in the POST dictionary. The list is not exclusive,
you can pass in fields that are not checked by the decorator.
:param options:
List of the names of expected POST keys.
"""
def decorator(method):
# handle wrapping or wrapping with arguments; if no arguments (and no
# calling parenthesis) then method_or_options will be a list,
# otherwise it will be the wrapped function
expected_fields = []
if not callable(method_or_options):
# not callable means wrapping with arguments
expected_fields = method_or_options
@wraps(method)
def wrapper(*args, **kwargs):
request = args[0]
| python | {
"resource": ""
} |
q265409 | json_post_required | validation | def json_post_required(*decorator_args):
"""View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('data', 'json_data')
def some_view(request):
username = request.json_data['username']
:param field:
The name of the POST field that contains a JSON dictionary
:param request_name:
[optional] Name of the parameter on the request to put the
deserialized JSON data. If not given the field name is used
"""
def decorator(method):
@wraps(method)
def wrapper(*args, **kwargs):
field = decorator_args[0]
if len(decorator_args) == 2:
request_name = decorator_args[1]
else:
request_name = field
request = args[0]
| python | {
"resource": ""
} |
q265410 | Match.sigma_prime | validation | def sigma_prime(self):
"""
Divergence of matched beam
"""
| python | {
"resource": ""
} |
q265411 | MatchPlasma.n_p | validation | def n_p(self):
"""
The plasma density in SI units.
| python | {
"resource": ""
} |
q265412 | main | validation | def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags | python | {
"resource": ""
} |
q265413 | check_environment | validation | def check_environment(target, label):
"""
Performs some environment checks prior to the program's execution
"""
if not git.exists():
click.secho('You must have git installed to use yld.', fg='red')
sys.exit(1)
if not os.path.isdir('.git'):
click.secho('You must cd into a git repository to use yld.', fg='red')
sys.exit(1)
if not git.is_committed(): | python | {
"resource": ""
} |
q265414 | print_information | validation | def print_information(handler, label):
"""
Prints latest tag's information
"""
click.echo('=> Latest stable: {tag}'.format(
tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if
handler.latest_stable else 'magenta')
))
if label is not None:
latest_revision = handler.latest_revision(label)
| python | {
"resource": ""
} |
q265415 | confirm | validation | def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to push the tag {tag} into the upstream?'.format( | python | {
"resource": ""
} |
q265416 | get | validation | def get(f, key, default=None):
"""
Gets an array from datasets.
.. versionadded:: 1.4
"""
if key in f.keys():
val = f[key].value
if default is None:
| python | {
"resource": ""
} |
q265417 | FolderDiff.get_state | validation | def get_state(self):
"""Get the current directory state"""
return [os.path.join(dp, f)
| python | {
"resource": ""
} |
q265418 | ProgressBar.tick | validation | def tick(self):
"""Add one tick to progress bar"""
self.current += 1
if self.current == self.factor:
| python | {
"resource": ""
} |
q265419 | DLL.push | validation | def push(self, k):
"""Push k to the top of the list
>>> l = DLL()
>>> l.push(1)
>>> l
[1]
>>> l.push(2)
>>> l
[2, 1]
>>> l.push(3)
>>> l
[3, 2, 1]
"""
if not self._first:
# first item
self._first = self._last = node = DLL.Node(k)
elif self._first.value == k:
# it's already at the top
return
| python | {
"resource": ""
} |
q265420 | Counter.increment | validation | def increment(cls, name):
"""Call this method to increment the named counter. This is atomic on
the database.
:param name:
Name for a previously created ``Counter`` object
"""
with transaction.atomic():
| python | {
"resource": ""
} |
q265421 | Component.print_loading | validation | def print_loading(self, wait, message):
"""
print loading message on screen
.. note::
loading message only write to `sys.stdout`
:param int wait: seconds to wait
:param str message: message to print
:return: None
"""
tags = ['\\', '|', '/', '-']
for i in range(wait):
time.sleep(0.25)
sys.stdout.write("%(message)s... %(tag)s\r" % {
| python | {
"resource": ""
} |
q265422 | Component.warn_message | validation | def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."):
"""
print warn type message,
if file handle is `sys.stdout`, print color message
:param str message: message to print
:param file fh: file handle,default is `sys.stdout`
:param str prefix: message prefix,default is `[warn]`
:param str suffix: message suffix ,default is `...`
| python | {
"resource": ""
} |
q265423 | Component.error_message | validation | def error_message(self, message, fh=None, prefix="[error]:",
suffix="..."):
"""
print error type message
if file handle is `sys.stderr`, print color message
:param str message: message to print
:param file fh: file handle, default is `sys.stdout`
:param str prefix: message prefix,default is `[error]`
:param str suffix: message suffix ,default is | python | {
"resource": ""
} |
q265424 | Component.system | validation | def system(self, cmd, fake_code=False):
"""
a built-in wrapper make dry-run easier.
you should use this instead use `os.system`
.. note::
to use it,you need add '--dry-run' option in
your argparser options
:param str cmd: command to execute
:param bool fake_code: only display command
| python | {
"resource": ""
} |
q265425 | Firebase_sync.url_correct | validation | def url_correct(self, point, auth=None, export=None):
'''
Returns a Corrected URL to be used for a Request
as per the REST API.
'''
newUrl = self.__url + point + '.json' | python | {
"resource": ""
} |
q265426 | main | validation | def main():
"""
Main method.
This method holds what you want to execute when
the script is run on command line.
"""
args = get_arguments()
setup_logging(args)
version_path = os.path.abspath(os.path.join(
os.path.dirname(__file__),
'..',
'..',
'.VERSION'
))
try:
version_text = open(version_path).read().strip()
except Exception:
print('Could not open or read the .VERSION file')
sys.exit(1)
try:
semver.parse(version_text)
except ValueError:
print(('The .VERSION file contains an invalid '
| python | {
"resource": ""
} |
q265427 | pickle | validation | def pickle(obj, filepath):
"""Pickle and compress."""
arr = pkl.dumps(obj, -1)
with open(filepath, 'wb') as f:
s = 0
while s < len(arr):
e = min(s + blosc.MAX_BUFFERSIZE, len(arr))
| python | {
"resource": ""
} |
q265428 | unpickle | validation | def unpickle(filepath):
"""Decompress and unpickle."""
arr = []
with open(filepath, 'rb') as f:
carr = f.read(blosc.MAX_BUFFERSIZE)
while len(carr) > 0:
| python | {
"resource": ""
} |
q265429 | contact | validation | def contact(request):
"""Displays the contact form and sends the email"""
form = ContactForm(request.POST or None)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = settings.CONTACTFORM_RECIPIENTS
if cc_myself:
| python | {
"resource": ""
} |
q265430 | InitComponent.load_gitconfig | validation | def load_gitconfig(self):
"""
try use gitconfig info.
author,email etc.
"""
gitconfig_path = os.path.expanduser('~/.gitconfig')
if os.path.exists(gitconfig_path):
| python | {
"resource": ""
} |
q265431 | InitComponent.add_arguments | validation | def add_arguments(cls):
"""
Init project.
"""
return [
(('--yes',), dict(action='store_true', help='clean .git repo')),
(('--variable', '-s'),
dict(nargs='+', help='set extra variable,format is name:value')),
| python | {
"resource": ""
} |
q265432 | SlotComponent.run | validation | def run(self, options):
"""
In general, you don't need to overwrite this method.
:param options:
:return:
"""
self.set_signal()
self.check_exclusive_mode()
slot = self.Handle(self)
# start thread
i = 0
while i < options.threads:
t = threading.Thread(target=self.worker, args=[slot])
| python | {
"resource": ""
} |
q265433 | combine_filenames | validation | def combine_filenames(filenames, max_length=40):
"""Return a new filename to use as the combined file name for a
bunch of files, based on the SHA of their contents.
A precondition is that they all have the same file extension
Given that the list of files can have different paths, we aim to use the
most common path.
Example:
/somewhere/else/foo.js
/somewhere/bar.js
/somewhere/different/too/foobar.js
The result will be
/somewhere/148713695b4a4b9083e506086f061f9c.js
Another thing to note, if the filenames have timestamps in them, combine
them all and use the highest timestamp.
"""
# Get the SHA for each file, then sha all the shas.
path = None
names = []
extension = None
timestamps = []
shas = []
filenames.sort()
concat_names = "_".join(filenames)
if concat_names in COMBINED_FILENAMES_GENERATED:
return COMBINED_FILENAMES_GENERATED[concat_names]
for filename in filenames:
name = os.path.basename(filename)
if not extension:
extension = os.path.splitext(name)[1]
elif os.path.splitext(name)[1] != extension:
raise ValueError("Can't combine multiple file extensions")
for base in MEDIA_ROOTS:
try: | python | {
"resource": ""
} |
q265434 | apply_orientation | validation | def apply_orientation(im):
"""
Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,
and if there is an orientation tag that would rotate the image, apply that rotation to
the Image instance given to do an in-place rotation.
:param Image im: Image instance to inspect
:return: A possibly transposed image instance
"""
try:
kOrientationEXIFTag = 0x0112
if hasattr(im, '_getexif'): # only present in JPEGs
e = im._getexif() # returns None if no EXIF data
| python | {
"resource": ""
} |
q265435 | write | validation | def write():
"""Start a new piece"""
click.echo("Fantastic. Let's get started. ")
title = click.prompt("What's the title?")
# Make sure that title doesn't exist.
url = slugify(title)
url = click.prompt("What's | python | {
"resource": ""
} |
q265436 | scaffold | validation | def scaffold():
"""Start a new site."""
click.echo("A whole new site? Awesome.")
title = click.prompt("What's the | python | {
"resource": ""
} |
q265437 | publish | validation | def publish():
"""Publish the site"""
try:
build_site(dev_mode=False, clean=True)
click.echo('Deploying the site...')
# call("firebase deploy", shell=True)
call("rsync -avz -e ssh --progress %s/ %s" % (BUILD_DIR, CONFIG["scp_target"],), shell=True)
| python | {
"resource": ""
} |
q265438 | Git.get_branches | validation | def get_branches(self):
"""Returns a list of the branches"""
return [self._sanitize(branch)
| python | {
"resource": ""
} |
q265439 | Git.get_current_branch | validation | def get_current_branch(self):
"""Returns the currently active branch"""
return next((self._sanitize(branch)
| python | {
"resource": ""
} |
q265440 | Git.create_patch | validation | def create_patch(self, from_tag, to_tag):
"""Create a patch between tags"""
| python | {
"resource": ""
} |
q265441 | one | validation | def one(func, n=0):
"""
Create a callable that applies ``func`` to a value in a sequence.
If the value is not a sequence or is an empty sequence then ``None`` is
returned.
:type func: `callable`
:param func: Callable to be applied to each result.
:type n: `int`
:param n: Index of the value to apply ``func`` to. | python | {
"resource": ""
} |
q265442 | many | validation | def many(func):
"""
Create a callable that applies ``func`` to every value in a sequence.
If the value is not a sequence then an empty list is returned.
:type func: `callable`
:param func: Callable to be applied to the first result.
"""
def _many(result):
| python | {
"resource": ""
} |
q265443 | Text | validation | def Text(value, encoding=None):
"""
Parse a value as text.
:type value: `unicode` or `bytes`
:param value: Text value to parse
:type encoding: `bytes`
:param encoding: Encoding to treat ``bytes`` values as, defaults to
``utf-8``.
:rtype: `unicode`
:return: Parsed text or ``None`` if ``value`` is neither `bytes` nor
| python | {
"resource": ""
} |
q265444 | Integer | validation | def Integer(value, base=10, encoding=None):
"""
Parse a value as an integer.
:type value: `unicode` or `bytes`
:param value: Text value to parse
:type base: `unicode` or `bytes`
:param base: Base to assume ``value`` is specified in.
:type encoding: `bytes`
:param encoding: Encoding to treat ``bytes`` values as, defaults to
``utf-8``.
| python | {
"resource": ""
} |
q265445 | Boolean | validation | def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),
encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for ``True`` values.
:type false: `tuple` of `unicode`
| python | {
"resource": ""
} |
q265446 | Delimited | validation | def Delimited(value, parser=Text, delimiter=u',', encoding=None):
"""
Parse a value as a delimited list.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type parser: `callable` taking a `unicode` parameter
:param parser: Callable to map over the delimited text values.
:type delimiter: `unicode`
:param delimiter: Delimiter text.
:type encoding: `bytes`
:param | python | {
"resource": ""
} |
q265447 | Timestamp | validation | def Timestamp(value, _divisor=1., tz=UTC, encoding=None):
"""
Parse a value as a POSIX timestamp in seconds.
:type value: `unicode` or `bytes`
:param value: Text value to parse, which should be the number of seconds
since the epoch.
:type _divisor: `float`
:param _divisor: Number to divide the value by.
:type tz: `tzinfo`
:param tz: Timezone, defaults to UTC.
:type encoding: `bytes`
:param | python | {
"resource": ""
} |
q265448 | parse | validation | def parse(expected, query):
"""
Parse query parameters.
:type expected: `dict` mapping `bytes` to `callable`
:param expected: Mapping of query argument names to argument parsing
callables.
:type query: `dict` mapping `bytes` to `list` of `bytes`
:param query: Mapping of query argument names to lists of argument values,
this is the form that Twisted Web's `IRequest.args
<twisted:twisted.web.iweb.IRequest.args>` | python | {
"resource": ""
} |
q265449 | CloudWatch.put | validation | def put(self, metrics):
"""
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
"""
if type(metrics) == list:
for metric in | python | {
"resource": ""
} |
q265450 | _renderResource | validation | def _renderResource(resource, request):
"""
Render a given resource.
See `IResource.render <twisted:twisted.web.resource.IResource.render>`.
"""
meth = getattr(resource, 'render_' + nativeString(request.method), None)
if meth is None:
try:
allowedMethods = resource.allowedMethods
| python | {
"resource": ""
} |
q265451 | SpinneretResource._adaptToResource | validation | def _adaptToResource(self, result):
"""
Adapt a result to `IResource`.
Several adaptions are tried they are, in order: ``None``,
`IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource
<twisted:twisted.web.resource.IResource>`, and `URLPath
<twisted:twisted.python.urlpath.URLPath>`. Anything else is returned as
is.
A `URLPath <twisted:twisted.python.urlpath.URLPath>` is treated as
a redirect.
"""
if result is None:
return NotFound()
spinneretResource = ISpinneretResource(result, None)
if spinneretResource is not | python | {
"resource": ""
} |
q265452 | SpinneretResource._handleRenderResult | validation | def _handleRenderResult(self, request, result):
"""
Handle the result from `IResource.render`.
If the result is a `Deferred` then return `NOT_DONE_YET` and add
a callback to write the result to the request when it arrives.
"""
def _requestFinished(result, cancel):
cancel()
return result
if not isinstance(result, Deferred):
result = succeed(result)
def _whenDone(result):
render = getattr(result, 'render', lambda request: result)
renderResult = render(request)
| python | {
"resource": ""
} |
q265453 | ContentTypeNegotiator._negotiateHandler | validation | def _negotiateHandler(self, request):
"""
Negotiate a handler based on the content types acceptable to the
client.
:rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`
:return: Pair of a resource and the content type.
"""
accept = _parseAccept(request.requestHeaders.getRawHeaders('Accept'))
for contentType in accept.keys():
handler = self._acceptHandlers.get(contentType.lower())
| python | {
"resource": ""
} |
q265454 | _parseAccept | validation | def _parseAccept(headers):
"""
Parse and sort an ``Accept`` header.
The header is sorted according to the ``q`` parameter for each header value.
@rtype: `OrderedDict` mapping `bytes` to `dict`
@return: Mapping of media types to header parameters.
| python | {
"resource": ""
} |
q265455 | _splitHeaders | validation | def _splitHeaders(headers):
"""
Split an HTTP header whose components are separated with commas.
Each component is then split on semicolons and the component arguments
converted into a `dict`.
@return: `list` of 2-`tuple` of `bytes`, `dict`
@return: List of header arguments and mapping of component argument names
to | python | {
"resource": ""
} |
q265456 | contentEncoding | validation | def contentEncoding(requestHeaders, encoding=None):
"""
Extract an encoding from a ``Content-Type`` header.
@type requestHeaders: `twisted.web.http_headers.Headers`
@param requestHeaders: Request headers.
@type encoding: `bytes`
@param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one. Defaults to ``UTF-8``.
@rtype: `bytes`
@return: Content encoding. | python | {
"resource": ""
} |
q265457 | maybe | validation | def maybe(f, default=None):
"""
Create a nil-safe callable decorator.
If the wrapped callable receives ``None`` as its argument, it will return
``None`` immediately.
"""
| python | {
"resource": ""
} |
q265458 | settings | validation | def settings(path=None, with_path=None):
"""
Get or set `Settings._wrapped`
:param str path: a python module file,
if user set it,write config to `Settings._wrapped`
:param str with_path: search path
:return: | python | {
"resource": ""
} |
q265459 | Settings.bind | validation | def bind(mod_path, with_path=None):
"""
bind user variable to `_wrapped`
.. note::
you don't need call this method by yourself.
program will call it in `cliez.parser.parse`
.. expection::
if path is not correct,will cause an `ImportError`
:param str mod_path: module path, *use dot style,'mod.mod1'*
:param str with_path: add path to `sys.path`,
if path is file,use its parent.
| python | {
"resource": ""
} |
q265460 | get_version | validation | def get_version():
"""
Get the version from version module without importing more than
necessary.
"""
version_module_path = os.path.join(
os.path.dirname(__file__), "txspinneret", "_version.py")
# The version module contains a variable called __version__
| python | {
"resource": ""
} |
q265461 | TX.send | validation | def send(self, use_open_peers=True, queue=True, **kw):
"""
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method
"""
if not use_open_peers:
ip = kw.get('ip')
port = kw.get('port')
peer = 'http://{}:{}'.format(ip, port)
res = arky.rest.POST.peer.transactions(peer=peer, transactions=[self.tx.tx])
else:
res = arky.core.sendPayload(self.tx.tx)
| python | {
"resource": ""
} |
q265462 | TX.check_confirmations_or_resend | validation | def check_confirmations_or_resend(self, use_open_peers=False, **kw):
"""
check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers | python | {
"resource": ""
} |
q265463 | command_list | validation | def command_list():
"""
Get sub-command list
.. note::
Don't use logger handle this function errors.
Because the error should be a code error,not runtime error.
:return: `list` matched sub-parser
"""
from cliez.conf import COMPONENT_ROOT
root = COMPONENT_ROOT
if root is None:
| python | {
"resource": ""
} |
q265464 | append_arguments | validation | def append_arguments(klass, sub_parsers, default_epilog, general_arguments):
"""
Add class options to argparser options.
:param cliez.component.Component klass: subclass of Component
:param Namespace sub_parsers:
:param str default_epilog: default_epilog
:param list general_arguments: global options, defined by user
:return: Namespace subparser
"""
entry_name = hump_to_underscore(klass.__name__).replace(
'_component',
'')
# set sub command document
epilog = default_epilog if default_epilog \
else 'This tool generate by `cliez` ' \
'https://www.github.com/wangwenpei/cliez'
sub_parser = sub_parsers.add_parser(entry_name, help=klass.__doc__,
| python | {
"resource": ""
} |
q265465 | parse | validation | def parse(parser, argv=None, settings_key='settings', no_args_func=None):
"""
parser cliez app
:param argparse.ArgumentParser parser: an instance
of argparse.ArgumentParser
:param argv: argument list,default is `sys.argv`
:type argv: list or tuple
:param str settings: settings option name,
default is settings.
:param object no_args_func: a callable object.if no sub-parser matched,
parser will call it.
:return: an instance of `cliez.component.Component` or its subclass
"""
argv = argv or sys.argv
commands = command_list()
if type(argv) not in [list, tuple]:
raise TypeError("argv only can be list or tuple")
# match sub-parser
if len(argv) >= 2 and argv[1] in commands:
sub_parsers = parser.add_subparsers()
class_name = argv[1].capitalize() + 'Component'
from cliez.conf import (COMPONENT_ROOT,
LOGGING_CONFIG,
EPILOG,
GENERAL_ARGUMENTS)
sys.path.insert(0, os.path.dirname(COMPONENT_ROOT))
mod = importlib.import_module(
'{}.components.{}'.format(os.path.basename(COMPONENT_ROOT),
argv[1]))
# dynamic load component
klass = getattr(mod, class_name)
sub_parser = append_arguments(klass, sub_parsers, EPILOG,
GENERAL_ARGUMENTS)
options = parser.parse_args(argv[1:])
settings = Settings.bind(
getattr(options, settings_key)
) if settings_key and hasattr(options, settings_key) else None
obj = klass(parser, sub_parser, options, settings)
# init logger
logger_level = logging.CRITICAL
if hasattr(options, 'verbose'):
if options.verbose == 1:
logger_level = logging.ERROR
elif options.verbose == 2:
logger_level = logging.WARNING
elif options.verbose == 3:
logger_level = logging.INFO
obj.logger.setLevel(logging.INFO)
pass
if hasattr(options, 'debug') | python | {
"resource": ""
} |
q265466 | hump_to_underscore | validation | def hump_to_underscore(name):
"""
Convert Hump style to underscore
:param name: Hump Character
:return: str
"""
new_name = ''
pos = 0
for c in name:
if pos == 0:
new_name = c.lower()
| python | {
"resource": ""
} |
q265467 | FuelCheckClient.get_fuel_prices | validation | def get_fuel_prices(self) -> GetFuelPricesResponse:
"""Fetches fuel prices for all stations."""
response = requests.get(
'{}/prices'.format(API_URL_BASE),
headers=self._get_headers(),
timeout=self._timeout,
)
| python | {
"resource": ""
} |
q265468 | FuelCheckClient.get_fuel_prices_for_station | validation | def get_fuel_prices_for_station(
self,
station: int
) -> List[Price]:
"""Gets the fuel prices for a specific fuel station."""
response = requests.get(
'{}/prices/station/{}'.format(API_URL_BASE, station),
headers=self._get_headers(),
timeout=self._timeout,
) | python | {
"resource": ""
} |
q265469 | FuelCheckClient.get_fuel_prices_within_radius | validation | def get_fuel_prices_within_radius(
self, latitude: float, longitude: float, radius: int,
fuel_type: str, brands: Optional[List[str]] = None
) -> List[StationPrice]:
"""Gets all the fuel prices within the specified radius."""
if brands is None:
brands = []
response = requests.post(
'{}/prices/nearby'.format(API_URL_BASE),
json={
'fueltype': fuel_type,
'latitude': latitude,
'longitude': longitude,
'radius': radius,
'brand': brands,
},
headers=self._get_headers(),
timeout=self._timeout,
)
if not response.ok:
raise FuelCheckError.create(response)
data = response.json()
stations = {
| python | {
"resource": ""
} |
q265470 | FuelCheckClient.get_fuel_price_trends | validation | def get_fuel_price_trends(self, latitude: float, longitude: float,
fuel_types: List[str]) -> PriceTrends:
"""Gets the fuel price trends for the given location and fuel types."""
response = requests.post(
'{}/prices/trends/'.format(API_URL_BASE),
json={
'location': {
'latitude': latitude,
'longitude': longitude,
| python | {
"resource": ""
} |
q265471 | FuelCheckClient.get_reference_data | validation | def get_reference_data(
self,
modified_since: Optional[datetime.datetime] = None
) -> GetReferenceDataResponse:
"""
Fetches API reference data.
:param modified_since: The response will be empty if no
changes have been made to the reference data since this
timestamp, otherwise all reference data will be returned.
"""
if modified_since is None:
modified_since = datetime.datetime(year=2010, month=1, day=1)
response = requests.get(
'{}/lovs'.format(API_URL_BASE),
| python | {
"resource": ""
} |
q265472 | PyTemplate.pre | validation | def pre(self, command, output_dir, vars):
"""
Called before template is applied.
"""
# import pdb;pdb.set_trace() | python | {
"resource": ""
} |
q265473 | Text | validation | def Text(name, encoding=None):
"""
Match a route parameter.
`Any` is a synonym for `Text`.
:type name: `bytes`
:param name: Route parameter name.
:type encoding: `bytes`
:param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one.
:return: ``callable`` suitable for use with `route` or `subroute`.
| python | {
"resource": ""
} |
q265474 | Integer | validation | def Integer(name, base=10, encoding=None):
"""
Match an integer route parameter.
:type name: `bytes`
:param name: Route parameter name.
:type base: `int`
:param base: Base to interpret the value in.
:type encoding: `bytes`
:param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one.
:return: ``callable`` suitable for use with | python | {
"resource": ""
} |
q265475 | _matchRoute | validation | def _matchRoute(components, request, segments, partialMatching):
"""
Match a request path against our path components.
The path components are always matched relative to their parent is in the
resource hierarchy, in other words it is only possible to match URIs nested
more deeply than the parent resource.
:type components: ``iterable`` of `bytes` or `callable`
:param components: Iterable of path components, to match against the
request, either static strings or dynamic parameters. As a convenience,
a single `bytes` component containing ``/`` may be given instead of
manually separating the components. If no components are given the null
route is matched, this is the case where ``segments`` is empty.
:type segments: ``sequence`` of `bytes`
:param segments: Sequence of path segments, from the request, to match
against.
:type partialMatching: `bool`
:param partialMatching: Allow partial matching against the request path?
:rtype: 2-`tuple` of `dict` keyed on `bytes` and `list` of `bytes`
:return: Pair of parameter results, mapping parameter names to processed
values, and a list of the remaining request path segments. If there is
no route match the result will be ``None`` and the original request path
segments.
"""
if len(components) == 1 and isinstance(components[0], bytes):
components = components[0]
if components[:1] == '/':
components = components[1:]
components = | python | {
"resource": ""
} |
q265476 | routedResource | validation | def routedResource(f, routerAttribute='router'):
"""
Decorate a router-producing callable to instead produce a resource.
This simply produces a new callable that invokes the original callable, and
calls ``resource`` on the ``routerAttribute``.
If the router producer has multiple routers the attribute can be altered to
choose the appropriate one, for example:
.. code-block:: python
class _ComplexRouter(object):
router = Router()
privateRouter = Router()
@router.route('/')
def publicRoot(self, request, params):
return SomethingPublic(...)
@privateRouter.route('/')
def privateRoot(self, request, params):
| python | {
"resource": ""
} |
q265477 | Router._forObject | validation | def _forObject(self, obj):
"""
Create a new `Router` instance, with it's own set of routes, for
``obj``.
"""
router = type(self)()
| python | {
"resource": ""
} |
q265478 | Router._addRoute | validation | def _addRoute(self, f, matcher):
"""
Add a route handler and matcher | python | {
"resource": ""
} |
q265479 | Router.route | validation | def route(self, *components):
"""
See `txspinneret.route.route`.
This decorator can be stacked with itself to specify | python | {
"resource": ""
} |
q265480 | Router.subroute | validation | def subroute(self, *components):
"""
See `txspinneret.route.subroute`.
This decorator can be stacked with itself to specify | python | {
"resource": ""
} |
q265481 | _tempfile | validation | def _tempfile(filename):
"""
Create a NamedTemporaryFile instance to be passed to atomic_writer
"""
return tempfile.NamedTemporaryFile(mode='w',
| python | {
"resource": ""
} |
q265482 | atomic_write | validation | def atomic_write(filename):
"""
Open a NamedTemoraryFile handle in a context manager
"""
f = _tempfile(os.fsencode(filename))
try:
yield f
finally:
f.close()
| python | {
"resource": ""
} |
q265483 | get_item | validation | def get_item(filename, uuid):
"""
Read entry from JSON file
"""
with open(os.fsencode(str(filename)), "r") as f:
data = json.load(f)
| python | {
"resource": ""
} |
q265484 | set_item | validation | def set_item(filename, item):
"""
Save entry to JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_file)
| python | {
"resource": ""
} |
q265485 | update_item | validation | def update_item(filename, item, uuid):
"""
Update entry by UUID in the JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_file)
# apply modifications to the JSON data wrt UUID
# TODO: handle this in a neat way
if 'products' in products_data[-1]:
# handle orders object
[products_data[i]["products"][0].update(item) for (
| python | {
"resource": ""
} |
q265486 | Command.command_handle | validation | def command_handle(self):
"""Get the number of the shell command."""
self.__results = self.execute(self.args.command)
self.close()
self.logger.debug("results: {}".format(self.__results))
if not self.__results:
self.unknown("{} return nothing.".format(self.args.command))
if len(self.__results) != 1:
self.unknown(
"{} return more than one number.".format(
self.args.command))
self.__result = int(self.__results[0])
self.logger.debug("result: {}".format(self.__result))
if not isinstance(self.__result, (int, long)):
self.unknown(
"{} didn't return single number.".format(
self.args.command))
status = self.ok
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output | python | {
"resource": ""
} |
q265487 | Ssh.execute | validation | def execute(self, command, timeout=None):
"""Execute a shell command."""
try:
self.channel = self.ssh.get_transport().open_session()
except paramiko.SSHException as e:
self.unknown("Create channel error: %s" % e)
try:
self.channel.settimeout(self.args.timeout if not timeout else timeout)
except socket.timeout as e:
self.unknown("Settimeout for channel error: %s" % e)
try:
self.logger.debug("command: {}".format(command))
self.channel.exec_command(command)
except paramiko.SSHException as e:
self.unknown("Execute command error: %s" % e)
try:
self.stdin = self.channel.makefile('wb', -1)
self.stderr = map(string.strip, self.channel.makefile_stderr('rb', -1).readlines())
| python | {
"resource": ""
} |
q265488 | slinky | validation | def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret):
"""Simple program that creates an temp S3 link."""
if not os.environ.get('AWS_ACCESS_KEY_ID') and | python | {
"resource": ""
} |
q265489 | Process.check_readable | validation | def check_readable(self, timeout):
"""
Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean
| python | {
"resource": ""
} |
q265490 | get_indices_list | validation | def get_indices_list(s: Any) -> List[str]:
""" Retrieve a list of characters and escape codes where each escape
code uses only one index. The indexes will not match up with the
| python | {
"resource": ""
} |
q265491 | strip_codes | validation | def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
| python | {
"resource": ""
} |
q265492 | AbstractBundle.init_build | validation | def init_build(self, asset, builder):
"""
Called when builder group collect files
Resolves absolute url if relative passed
:type asset: static_bundle.builders.Asset
:type builder: static_bundle.builders.StandardBuilder
"""
if not self.abs_path:
rel_path = utils.prepare_path(self.rel_bundle_path) | python | {
"resource": ""
} |
q265493 | AbstractBundle.add_file | validation | def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
| python | {
"resource": ""
} |
q265494 | AbstractBundle.add_directory | validation | def add_directory(self, *args, **kwargs):
"""
Add directory or directories list to bundle
:param exclusions: List of excluded paths
:type path: str|unicode
:type exclusions: list
"""
| python | {
"resource": ""
} |
q265495 | AbstractBundle.add_path_object | validation | def add_path_object(self, *args):
"""
Add custom path objects
:type: path_object: static_bundle.paths.AbstractPath
"""
| python | {
"resource": ""
} |
q265496 | AbstractBundle.add_prepare_handler | validation | def add_prepare_handler(self, prepare_handlers):
"""
Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler
"""
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers]
| python | {
"resource": ""
} |
q265497 | AbstractBundle.prepare | validation | def prepare(self):
"""
Called when builder run collect files in builder group
:rtype: list[static_bundle.files.StaticFileResult]
"""
result_files = self.collect_files()
| python | {
"resource": ""
} |
q265498 | FileNumber.filenumber_handle | validation | def filenumber_handle(self):
"""Get the number of files in the folder."""
self.__results = []
self.__dirs = []
self.__files = []
self.__ftp = self.connect()
self.__ftp.dir(self.args.path, self.__results.append)
self.logger.debug("dir results: {}".format(self.__results))
self.quit()
status = self.ok
for data in self.__results:
if "<DIR>" in data:
self.__dirs.append(str(data.split()[3]))
else:
self.__files.append(str(data.split()[2]))
self.__result = len(self.__files)
self.logger.debug("result: {}".format(self.__result))
# Compare the vlaue.
if self.__result > self.args.warning:
status = self.warning
if self.__result > self.args.critical:
status = self.critical
# Output
self.shortoutput = "Found {0} files in {1}.".format(self.__result,
| python | {
"resource": ""
} |
q265499 | DataStore.register_json | validation | def register_json(self, data):
"""
Register the contents as JSON
"""
j = json.loads(data)
self.last_data_timestamp = \
datetime.datetime.utcnow().replace(microsecond=0).isoformat()
try:
for v in j:
# prepare the sensor entry container
self.data[v[self.id_key]] = {}
# add the mandatory entries
self.data[v[self.id_key]][self.id_key] = \
v[self.id_key]
self.data[v[self.id_key]][self.value_key] = \
v[self.value_key]
# add the optional well known entries if provided
if self.unit_key in v:
self.data[v[self.id_key]][self.unit_key] = \
v[self.unit_key]
if self.threshold_key in v:
self.data[v[self.id_key]][self.threshold_key] = \
v[self.threshold_key]
# add any further entries found
for k in self.other_keys:
if k in v:
self.data[v[self.id_key]][k] = v[k]
# add the custom sensor time
if self.sensor_time_key in v:
self.data[v[self.sensor_time_key]][self.sensor_time_key] = | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.