text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT."""
where = dict(where, **kwargs).items()
sql, args = makeSQL("SELECT", table, cols, where, group, order, limit)
return execute(sql, args) | 0.003571 |
def ToJsonString(self):
"""Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
... | 0.00736 |
def mchirp_sampler_imf(**kwargs):
''' Draw chirp mass samples for power-law model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples for ... | 0.002183 |
def generic_api_view(injector):
"""Create DRF generic class-based API view from injector class."""
handler = create_handler(GenericAPIView, injector)
apply_http_methods(handler, injector)
apply_api_view_methods(handler, injector)
apply_generic_api_view_methods(handler, injector)
return injector... | 0.002865 |
def _diversity_metric(solution, population):
"""Return diversity value for solution compared to given population.
Metric is sum of distance between solution and each solution in population,
normalized to [0.0, 1.0].
"""
# Edge case for empty population
# If there are no other solutions, the giv... | 0.001495 |
def do_not_disturb(self):
"""Get if do not disturb is enabled."""
return bool(strtobool(str(self._settings_json.get(
CONST.SETTINGS_DO_NOT_DISTURB)))) | 0.011236 |
def create_asymmetric_key_pair(self, algorithm, length):
"""
Create an asymmetric key pair.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created keys will be compliant.
length(int): The length of the keys ... | 0.001242 |
def _i2c_read_bytes(self, length=1):
"""Read the specified number of bytes from the I2C bus. Length is the
number of bytes to read (must be 1 or more).
"""
for i in range(length-1):
# Read a byte and send ACK.
self._command.append('\x20\x00\x00\x13\x00\x00')
... | 0.003264 |
def find_credentials():
'''
Cycle through all the possible credentials and return the first one that
works.
'''
# if the username and password were already found don't fo though the
# connection process again
if 'username' in DETAILS and 'password' in DETAILS:
return DETAILS['userna... | 0.002134 |
def freeze(self, no_etag=False):
"""Call this method if you want to make your response object ready for
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`.
"""
if not no_etag:
self.add_etag()
supe... | 0.005634 |
def _close(self, status, do_callbacks=True):
"""
Takes the status on which it should leave the connection
and an optional boolean parameter to dispatch the disconnected
and close callbacks if there are any.
"""
if self.is_closed:
self._status = status
... | 0.001908 |
def plural(self):
''' Tries to scrape the plural version from uitmuntend.nl. '''
element = self._first('NN')
if element:
element = element.split('\r\n')[0]
if ' | ' in element:
# This means there is a plural
singular, plural = element.split(' | ')
return [plural.split(' ')[1]]
else:
# Th... | 0.036939 |
def describe_features(self, traj):
"""
Returns a sliced version of the feature descriptor
Parameters
----------
traj : MDtraj trajectory object
Returns
-------
list of sliced dictionaries describing each feature.
"""
features_list = self.f... | 0.004963 |
def resample_returns(
returns,
func,
seed=0,
num_trials=100
):
"""
Resample the returns and calculate any statistic on every new sample.
https://en.wikipedia.org/wiki/Resampling_(statistics)
:param returns (Series, DataFrame): Returns
:param func: Given the resample... | 0.001847 |
def delete_channel(self, channel_id):
"""Deletes channel
"""
req = requests.delete(self.channel_path(channel_id))
return req | 0.012821 |
def get_unique_backends():
"""Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available.
"""
backends = IBMQ.backends()
unique_hardware_backends = []
unique_names = []
for back in backends:
... | 0.003257 |
def prune_feed_map(meta_graph, feed_map):
"""Function to prune the feedmap of nodes which no longer exist."""
node_names = [x.name + ":0" for x in meta_graph.graph_def.node]
keys_to_delete = []
for k, _ in feed_map.items():
if k not in node_names:
keys_to_delete.append(k)
for k in keys_to_delete:
... | 0.020772 |
def stopping_function(results, args=None, rstate=None, M=None,
return_vals=False):
"""
The default stopping function utilized by :class:`DynamicSampler`.
Zipped parameters are passed to the function via :data:`args`.
Assigns the run a stopping value based on a weighted average of t... | 0.0002 |
def get_files_to_commit(autooptions):
"""
Look through the local directory to pick up files to check
"""
workingdir = autooptions['working-directory']
includes = autooptions['track']['includes']
excludes = autooptions['track']['excludes']
# transform glob patterns to regular expressions
... | 0.006092 |
def total(self, xbin1=1, xbin2=-2):
"""
Return the total yield and its associated statistical and
systematic uncertainties.
"""
integral, stat_error = self.hist.integral(
xbin1=xbin1, xbin2=xbin2, error=True)
# sum systematics in quadrature
ups = [0]
... | 0.00223 |
def group_dict_set(iterator: Iterable[Tuple[A, B]]) -> Mapping[A, Set[B]]:
"""Make a dict that accumulates the values for each key in an iterator of doubles."""
d = defaultdict(set)
for key, value in iterator:
d[key].add(value)
return dict(d) | 0.007519 |
def deserialize_assign(self, workflow, start_node):
"""
Reads the "pre-assign" or "post-assign" tag from the given node.
start_node -- the xml node (xml.dom.minidom.Node)
"""
name = start_node.getAttribute('name')
attrib = start_node.getAttribute('field')
value =... | 0.002457 |
def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
real_locals = tb.tb_frame.f_locals.copy()
ctx = real_locals.get('context')
if ctx:
locals = ctx.... | 0.001293 |
def coda_output(pymc_object, name=None, chain=-1):
"""Generate output files that are compatible with CODA
:Arguments:
pymc_object : Model or Node
A PyMC object containing MCMC output.
"""
print_()
print_("Generating CODA output")
print_('=' * 50)
if name is None:
... | 0.000943 |
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('autho... | 0.001389 |
def register_messages_from_checker(self, checker):
"""Register all messages from a checker.
:param BaseChecker checker:
"""
checker.check_consistency()
for message in checker.messages:
self.register_message(message) | 0.007463 |
def dice_pairwise_und(a1, a2):
'''
Calculates pairwise dice similarity for each vertex between two
matrices. Treats the matrices as binary and undirected.
Paramaters
----------
A1 : NxN np.ndarray
Matrix 1
A2 : NxN np.ndarray
Matrix 2
Returns
-------
D : Nx1 np.... | 0.001227 |
def _postprocess_options(dbg, opts):
''' Handle options (`opts') that feed into the debugger (`dbg')'''
# Set dbg.settings['printset']
print_events = []
if opts.fntrace: print_events = ['c_call', 'c_return', 'call', 'return']
if opts.linetrace: print_events += ['line']
if len(print_events):
... | 0.001506 |
def upgrade(refresh=False, root=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep s... | 0.001331 |
def prepare_video_params(self, title=None, tags='Others', description='',
copyright_type='original', public_type='all',
category=None, watch_password=None,
latitude=None, longitude=None, shoot_time=None
)... | 0.003132 |
def get_gdf(stop=True):
"""Returns a string containing a GDF file. Setting stop to True will cause
the trace to stop.
"""
ret = ['nodedef>name VARCHAR, label VARCHAR, hits INTEGER, ' + \
'calls_frac DOUBLE, total_time_frac DOUBLE, ' + \
'total_time DOUBLE, color VARCHAR, width DO... | 0.005952 |
def walkRelocatables(self, shouldRelocateCommand=_shouldRelocateCommand):
"""
for all relocatable commands
yield (command_index, command_name, filename)
"""
for (idx, (lc, cmd, data)) in enumerate(self.commands):
if shouldRelocateCommand(lc.cmd):
name ... | 0.003597 |
def expand_filename_pattern(self, pattern, base_dir, sourcefile=None):
"""
The function expand_filename_pattern expands a filename pattern to a sorted list
of filenames. The pattern can contain variables and wildcards.
If base_dir is given and pattern is not absolute, base_dir and patter... | 0.004757 |
def attach_run_command(cmd):
"""
Run a command when attaching
Please do not call directly, this will execvp the command.
This is to be used in conjunction with the attach method
of a container.
"""
if isinstance(cmd, tuple):
return _lxc.attach_run_command(cmd)
el... | 0.002165 |
def execute(self, **kwargs):
"""
Execute the interactive guessing procedure.
:param show: Whether or not to show the figure. Useful for testing.
:type show: bool
:param block: Blocking call to matplotlib
:type show: bool
Any additional keyword arguments are pass... | 0.003367 |
def etau_madau(wave, z, **kwargs):
"""Madau 1995 extinction for a galaxy at given redshift.
This is the Lyman-alpha prescription from the photo-z code BPZ.
The Lyman-alpha forest approximately has an effective
"throughput" which is a function of redshift and
rest-frame wavelength.
One would mul... | 0.000396 |
def parse_readme():
"""
Crude parsing of modules/README.md
returns a dict of {<module_name>: <documentation>}
"""
name = None
re_mod = re.compile(r'^\#\#\# <a name="(?P<name>[a-z_0-9]+)"></a>')
readme_file = os.path.join(modules_directory(), "README.md")
modules_dict = {}
with open(r... | 0.001385 |
def progress_iter(progress):
'''
Initialize and return a progress bar iter
'''
widgets = [progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer(), ' Returns: [', progressbar.Counter(), '/{0}]'.format(progress['minion_count'])]
bar = progressbar.ProgressBar(widgets=widgets, maxval=... | 0.007979 |
def get(self, sid):
"""
Constructs a TerminatingSipDomainContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.Te... | 0.010753 |
def _poll_loop(self):
"""At self.poll_period poll for changes"""
next_poll = time.time()
while True:
next_poll += self._poll_period
timeout = next_poll - time.time()
if timeout < 0:
timeout = 0
try:
return self._stop... | 0.00304 |
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up ... | 0.040956 |
def _parse_da(self):
"""Extract font name, size and color from default appearance string (/DA object). Equivalent to 'pdf_parse_default_appearance' function in MuPDF's 'pdf-annot.c'.
"""
if not self._text_da:
return
font = "Helv"
fsize = 0
col = (0, 0, 0)
... | 0.004333 |
def calc_regenerated(self, lastvotetime):
''' Uses math formula to calculate the amount
of steem power that would have been regenerated
given a certain datetime object
'''
delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S')
td = delta.days
... | 0.009732 |
def get_out_degrees(self):
'''
API:
get_degree(self)
Description:
Returns degrees of nodes in dictionary format.
Return:
Returns a dictionary of node degrees. Keys are node names, values
are corresponding degrees.
'''
degree... | 0.00346 |
def _indent(x):
"""Indent a string by 4 characters."""
lines = x.splitlines()
for i, line in enumerate(lines):
lines[i] = ' ' + line
return '\n'.join(lines) | 0.005464 |
def _run_cortex(fastq, indexes, params, out_base, dirs, config):
"""Run cortex_var run_calls.pl, producing a VCF variant file.
"""
print(out_base)
fastaq_index = "{0}.fastaq_index".format(out_base)
se_fastq_index = "{0}.se_fastq".format(out_base)
pe_fastq_index = "{0}.pe_fastq".format(out_base)
... | 0.004286 |
def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
#... | 0.003578 |
def getInstalledThemes(self, store):
"""
Collect themes from all offerings installed on this store, or (if called
multiple times) return the previously collected list.
"""
if not store in self._getInstalledThemesCache:
self._getInstalledThemesCache[store] = (self.
... | 0.013363 |
def base64encode(_input=None):
"""Return base64 encoded representation of a string."""
if PY2: # pragma: no cover
return base64.b64encode(_input)
elif PY3: # pragma: no cover
if isinstance(_input, bytes):
return base64.b64encode(_input).decode('UTF-8')
elif isinstance(_... | 0.004751 |
def docker(klass, container_id, shell, script, interval, deregister=None):
"""
Invoke *script* packaged within a running docker container with
*container_id* at a specified *interval* on the configured
*shell* using the Docker Exec API. Optional *register* after which a
failing ... | 0.003096 |
def concepts(self):
""" Return all existing concepts, i.e. dimensions, measures and
attributes within the model. """
for measure in self.measures:
yield measure
for aggregate in self.aggregates:
yield aggregate
for dimension in self.dimensions:
... | 0.004773 |
def createGroup(self, group, vendorSpecific=None):
"""See Also: createGroupResponse()
Args:
group:
vendorSpecific:
Returns:
"""
response = self.createGroupResponse(group, vendorSpecific)
return self._read_boolean_response(response) | 0.006623 |
def gen_stm(src, dst):
"""Return a STM instruction.
"""
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) | 0.019737 |
def _get_LMv2_response(user_name, password, domain_name, server_challenge, client_challenge):
"""
[MS-NLMP] v28.0 2016-07-14
2.2.2.4 LMv2_RESPONSE
The LMv2_RESPONSE structure defines the NTLM v2 authentication LmChallengeResponse
in the AUTHENTICATE_MESSAGE. This response is use... | 0.008584 |
def _get_logger(self, handler):
''' Initialize a PCAP stream for logging data '''
log_file = self._get_log_file(handler)
if not os.path.isdir(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
handler['log_rot_time'] = time.gmtime()
return pcap.open(... | 0.0059 |
def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
::
element = driver.switch_to.active_element
"""
if self._driver.w3c:
return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value']... | 0.007299 |
def open(self, file, mode='r', perm=0o0644):
"""
Opens a file on the node
:param file: file path to open
:param mode: open mode
:param perm: file permission in octet form
mode:
'r' read only
'w' write only (truncate)
'+' read/write
... | 0.003466 |
def cwd(self):
"""
Return a UNIX FS type string of the current working 'directory'.
"""
l_cwd = self.l_cwd[:]
str_cwd = '/'.join(l_cwd)
if len(str_cwd)>1: str_cwd = str_cwd[1:]
return str_cwd | 0.022013 |
def process_messages_loop_internal(self):
"""
Busy loop that processes incoming WorkRequest messages via functions specified by add_command.
Terminates if a command runs shutdown method
"""
logging.info("Starting work queue loop.")
self.connection.receive_loop_with_callba... | 0.01108 |
def tempogram(y=None, sr=22050, onset_envelope=None, hop_length=512,
win_length=384, center=True, window='hann', norm=np.inf):
'''Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_
.. [1] Grosche, Peter, Meinard Müller, and Frank Kurth.
"Cyclic tempogram - A... | 0.001603 |
def wrap_str(self, s=None, wrapper=None):
""" Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead.
"""
wrapper = wrapper or (self.wrapper or ('', ''))
return str('' if s is None else s).join(wrapper) | 0.00627 |
def fetch_data(self, url):
'''
Fetches data from specific url.
:return: The response.
:rtype: dict
'''
return self.http._post_data(url, None, self.http._headers_with_access_token()) | 0.017316 |
def _reaction_po_to_dict(tokens) -> Reaction:
"""Convert a reaction parse object to a DSL.
:type tokens: ParseResult
"""
return Reaction(
reactants=_reaction_part_po_to_dict(tokens[REACTANTS]),
products=_reaction_part_po_to_dict(tokens[PRODUCTS]),
) | 0.003497 |
def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp"):
# type: (str, int, int, str) -> None
"""Compute effective genome size for genome."""
idx = Fasta(fasta)
genome_length = sum([len(c) for c in idx])
logging.info("Temporary directory: " + tmpdir)
logging.info("File analyzed... | 0.002287 |
def _parse_authors(details):
"""
Parse authors of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors = details.find(
"tr",... | 0.001279 |
def generate_span_requests(self, span_datas):
"""Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
... | 0.002571 |
def append_some(ol,*eles,**kwargs):
'''
from elist.elist import *
ol = [1,2,3,4]
id(ol)
append_some(ol,5,6,7,8,mode="original")
ol
id(ol)
####
ol = [1,2,3,4]
id(ol)
new = append_some(ol,5,6,7,8)
new
id(new)
'''
i... | 0.011236 |
def _connect_model(self, model):
"""
Used internally to connect the property into the model, and
register self as a value observer for that property"""
parts = self._prop_name.split(".")
if len(parts) > 1:
# identifies the model
models = parts[:-1]
... | 0.002967 |
def gen403(request, baseURI, reason, project=None):
"""Return a 403 error"""
orgas = None
public_ask = False
if not settings.PIAPI_STANDALONE:
from organizations.models import Organization
if project and project.plugItLimitOrgaJoinable:
orgas = project.plugItOrgaJoinable.or... | 0.003721 |
def find(self, vid=None, pid=None, serial=None, interface=None, \
path=None, release_number=None, manufacturer=None,
product=None, usage=None, usage_page=None):
"""
Attempts to open a device in this `Enumeration` object. Optional
arguments can be provided to filter the re... | 0.004564 |
def edit_wiki_page(self, subreddit, page, content, reason=''):
"""Create or edit a wiki page with title `page` for `subreddit`.
:returns: The json response from the server.
"""
data = {'content': content,
'page': page,
'r': six.text_type(subreddit),
... | 0.003565 |
def rouge_n(eval_sentences, ref_sentences, n=2):
"""Computes ROUGE-N f1 score of two text collections of sentences.
Source: https://www.microsoft.com/en-us/research/publication/
rouge-a-package-for-automatic-evaluation-of-summaries/
Args:
eval_sentences: Predicted sentences.
ref_sentences: Sentences f... | 0.008321 |
def add_state_machine(widget, event=None):
"""Create a new state-machine when the user clicks on the '+' next to the tabs"""
logger.debug("Creating new state-machine...")
root_state = HierarchyState("new root state")
state_machine = StateMachine(root_state)
rafcon.core.singleton.state_machine_manage... | 0.008475 |
def numConnects(self, layerName):
""" Number of incoming weights, including bias. Assumes fully connected. """
count = 0
if self[layerName].active:
count += 1 # 1 = bias
for connection in self.connections:
if connection.active and connection.fromLayer.act... | 0.013605 |
def report_accounts(self, path, per_region=True,
per_capita=False, pic_size=1000,
format='rst', **kwargs):
""" Generates a report to the given path for all extension
This method calls .report_accounts for all extensions
Notes
-----
... | 0.002059 |
def _search_pn(self, href=None, limit=None,
embed_items=None, embed_tracks=None, embed_metadata=None,
embed_insights=None):
"""Function called to retrieve pages 2-n."""
url_components = urlparse(href)
path = url_components.path
data = parse_qs(url_c... | 0.003175 |
def Close(self):
"""Closes the database file object.
Raises:
IOError: if the close failed.
OSError: if the close failed.
"""
if self._connection:
self._cursor = None
self._connection.close()
self._connection = None
# TODO: move this to a central temp file manager and ... | 0.01165 |
def synthesize_property(property_name,
default = None,
contract = None,
read_only = False,
private_member_name = None):
"""
When applied to a class, this decorator adds a property to it and overrides the constructor ... | 0.018217 |
def c2u(name):
"""Convert camelCase (used in PHP) to Python-standard snake_case.
Src:
https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
Parameters
----------
name: A function or variable name in camelCase
Returns
-------
str: Th... | 0.00211 |
def restricted_brands(self):
"""
| Comment: ids of all brands that this ticket form is restricted to
"""
if self.api and self.restricted_brand_ids:
return self.api._get_restricted_brands(self.restricted_brand_ids) | 0.007752 |
def return_params(islitlet, csu_bar_slit_center, params, parmodel):
"""Return individual model parameters from object of type Parameters.
Parameters
----------
islitlet : int
Number of slitlet.
csu_bar_slit_center : float
CSU bar slit center, in mm.
params : :class:`~lmfit.param... | 0.00411 |
def keyPressEvent(self, ev):
"""Stop editing if enter is pressed"""
if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
self._startOrStopEditing()
elif ev.key() == Qt.Key_Escape:
self._cancelEditing()
else:
Kittens.widgets.ClickableTreeWidget.keyPressEvent(s... | 0.006098 |
def safe_unicode(self, buf):
"""
Safely return an unicode encoded string
"""
tmp = ""
buf = "".join(b for b in buf)
for character in buf:
tmp += character
return tmp | 0.008584 |
def _parse_header(cls, header_proto, resource):
"""Deserializes a resource's base64 encoded Protobuf header.
"""
header = header_proto()
try:
header_bytes = base64.b64decode(resource['header'])
header.ParseFromString(header_bytes)
except (KeyError, TypeErr... | 0.002751 |
def htmlNewDoc(URI, ExternalID):
"""Creates a new HTML document """
ret = libxml2mod.htmlNewDoc(URI, ExternalID)
if ret is None:raise treeError('htmlNewDoc() failed')
return xmlDoc(_obj=ret) | 0.014563 |
def add_task(self, keywords, context, rule):
"""Map a function to a list of keywords
Parameters
----------
keywords : iterable of str
sequence of strings which should trigger the given function
context : Context
A Context object created using desired func... | 0.003257 |
def plot_origin(self): # TODO add attribute option to color vectors
"""
Plot vectors of positional transition of LISA values starting
from the same origin.
"""
import matplotlib.cm as cm
import matplotlib.pyplot as plt
ax = plt.subplot(111)
xlim = [self._... | 0.00314 |
def remove_prefix(self, prefix):
"""Remove network prefix.
"""
self._req('prefix remove %s' % prefix)
time.sleep(1)
self._req('netdataregister') | 0.01087 |
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versionin... | 0.003676 |
def make_tarball(base_name, base_dir, compress='gzip',
verbose=False, dry_run=False):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'compress'
... | 0.002622 |
def f_get_all(self, name, max_depth=None, shortcuts=True):
""" Searches for all occurrences of `name` under `node`.
Links are NOT considered since nodes are searched bottom up in the tree.
:param node:
Start node
:param name:
Name of what to look for, can be ... | 0.005865 |
def visit_arg(self, node, parent):
"""visit an arg node by returning a fresh AssName instance"""
return self.visit_assignname(node, parent, node.arg) | 0.012121 |
def _reduce_input(self, inputs, reducer, final=NotImplemented):
"""
Iterate over input, collect values with the same key, and call the reducer for each unique key.
"""
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.... | 0.009398 |
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specifi... | 0.000622 |
def note_delete(self, note_id):
"""delete a specific note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
"""
return self._get('notes/{0}.json'.format(note_id), method='DELETE',
auth=True) | 0.006757 |
def filter(self, **kwargs):
# @TODO refactor with models as dicts
"""filter results of dataset eg.
Query('Posts').filter(post_type='post')
"""
f_field = kwargs.keys()[0]
f_value = kwargs[f_field]
_newset = []
for m in self._dataset:
if hasattr(m, f_field):
if geta... | 0.011933 |
def vagrant(self, name=''):
"""
Run the following tasks on a vagrant box.
First, you need to import this task in your ``fabfile.py``::
from fabric.api import *
from burlap.vagrant import vagrant
@task
def some_task():
run('echo h... | 0.003333 |
def send_article_message(self, user_id, articles, kf_account=None):
"""
发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
... | 0.001292 |
def add_attachment(self, issue, attachment, filename=None):
"""Attach an attachment to an issue and returns a Resource for it.
The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready
for its use. The user is still responsible for tidying up (e... | 0.004726 |
def diff(self, other):
"""
Diff function for Incar. Compares two Incars and indicates which
parameters are the same and which are not. Useful for checking whether
two runs were done using the same parameters.
Args:
other (Incar): The other Incar object to compare to... | 0.001599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.