text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def execute_nb(fname, metadata=None, save=True, show_doc_only=False):
"Execute notebook `fname` with `metadata` for preprocessing."
# Any module used in the notebook that isn't inside must be in the same directory as this script
with open(fname) as f: nb = nbformat.read(f, as_version=4)
ep_class = Execu... | 0.008264 |
def nhapDaiHan(self, cucSo, gioiTinh):
"""Nhap dai han
Args:
cucSo (TYPE): Description
gioiTinh (TYPE): Description
Returns:
TYPE: Description
"""
for cung in self.thapNhiCung:
khoangCach = khoangCachCung(cung.cungSo, self.cungMen... | 0.004988 |
def Poll(generator=None, condition=None, interval=None, timeout=None):
"""Periodically calls generator function until a condition is satisfied."""
if not generator:
raise ValueError("generator has to be a lambda")
if not condition:
raise ValueError("condition has to be a lambda")
if interval is None:... | 0.013699 |
def normalize_api_path(api_path):
"""
Resolve paths with '..' to normalized paths, raising an error if the final
result is outside root.
"""
normalized = posixpath.normpath(api_path.strip('/'))
if normalized == '.':
normalized = ''
elif normalized.startswith('..'):
raise Path... | 0.00274 |
def get_transport(host, username, key):
""" Create a transport object
:param host: the hostname to connect to
:type host: str
:param username: SSH username
:type username: str
:param key: key object used for authentication
:type key: paramiko.RSAKey
:return:... | 0.002669 |
def unfurl(jwt):
"""
Return the body of a signed JWT, without verifying the signature.
:param jwt: A signed JWT
:return: The body of the JWT as a 'UTF-8' string
"""
_rp_jwt = factory(jwt)
return json.loads(_rp_jwt.jwt.part[1].decode('utf8')) | 0.01087 |
def modify(self, **patch):
"""Custom modify method to implement monitor parameter formatting."""
if 'monitor' in patch:
value = self._format_monitor_parameter(patch['monitor'])
patch['monitor'] = value
return super(Pool, self)._modify(**patch) | 0.006873 |
def _handle_get(self, transaction):
"""
Handle GET requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request
"""
path = str("/" +... | 0.002698 |
def zero_order_tikhonov(pst, parbounds=True,par_groups=None,
reset=True):
"""setup preferred-value regularization
Parameters
----------
pst : pyemu.Pst
the control file instance
parbounds : bool
flag to weight the prior information equations according
... | 0.003033 |
def axml(input_, output, file_, resource):
"""
Parse the AndroidManifest.xml.
Parsing is either direct or from a given APK and prints in XML format or
saves to file.
This tool can also be used to process any AXML encoded file, for example
from the layout directory.
Example:
\b
... | 0.001247 |
def get_html_text_editor(
name,
id=None,
content='',
textual_content=None,
width='300px',
height='200px',
enabled=True,
file_upload_url=None,
toolbar_set="Basic",
custom_configurations_path='/js/ckeditor/invenio-ckeditor-config.js',
... | 0.001791 |
def _get_vqa_v2_image_feature_dataset(
directory, feature_url, feature_filename="mscoco_feat.tar.gz"):
"""Extract the VQA V2 feature data set to directory unless it's there."""
feature_file = generator_utils.maybe_download_from_drive(
directory, feature_filename, feature_url)
with tarfile.open(feature_f... | 0.012953 |
def certify_dict(
value, schema=None, allow_extra=False, required=True, key_certifier=None, value_certifier=None,
include_collections=False,
):
"""
Certifies a dictionary, checking it against an optional schema.
The schema should be a dictionary, with keys corresponding to the expected keys in `val... | 0.001627 |
def _import(self, datadict):
"""
Internal method to import instance variables data from a dictionary
:param dict datadict: The dictionary containing variables values.
"""
self.GUID = datadict.get("GUID", uuid.uuid1())
self.FileName = datadict.get("FileName", "")
... | 0.004292 |
def process_calibration(self, save=False):
"""processes the data gathered in a calibration run (does not work if multiple
calibrations), returns resultant dB"""
if not self.save_data:
raise Exception("Runner must be set to save when run, to be able to process")
... | 0.008296 |
def lookup(self, key_name, headers=None, callback=None):
"""
Deprecated: Please use get_key method.
:type key_name: string
:param key_name: The name of the key to retrieve
:rtype: :class:`boto.s3.key.Key`
:returns: A Key object from this bucket.
... | 0.010076 |
async def unicode_type(self, elem):
"""
Unicode type
:param elem:
:return:
"""
if self.writing:
await dump_uvarint(self.iobj, len(elem))
await self.iobj.awrite(bytes(elem, 'utf8'))
else:
ivalue = await load_uvarint(self.iobj)
... | 0.004024 |
def permutations(x):
'''Given a listlike, x, return all permutations of x
Returns the permutations of x in the lexical order of their indices:
e.g.
>>> x = [ 1, 2, 3, 4 ]
>>> for p in permutations(x):
>>> print p
[ 1, 2, 3, 4 ]
[ 1, 2, 4, 3 ]
[ 1, 3, 2, 4 ]
[ 1, 3, 4, 2 ]
... | 0.0031 |
def load_from_file(module_path):
"""
Load a python module from its absolute filesystem path
Borrowed from django-cms
"""
from imp import load_module, PY_SOURCE
imported = None
if module_path:
with open(module_path, 'r') as openfile:
imported = load_module('mod', openfil... | 0.005195 |
def LODS(cpu, dest, src):
"""
Loads string.
Loads a byte, word, or doubleword from the source operand into the AL, AX, or EAX register, respectively. The
source operand is a memory location, the address of which is read from the DS:ESI or the DS:SI registers
(depending on the ad... | 0.006649 |
def _resize_discr(discr, newshp, offset, discr_kwargs):
"""Return a space based on ``discr`` and ``newshp``.
Use the domain of ``discr`` and its partition to create a new
uniformly discretized space with ``newshp`` as shape. In axes where
``offset`` is given, it determines the number of added/removed c... | 0.000289 |
def drop(x, keep=0.5):
"""Randomly set some pixels to zero by a given keeping probability.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] or [row, col].
keep : float
The keeping probability (0, 1), the lower more values will be set to zero.
... | 0.001739 |
def set(self, field, value):
"""
Sets the value of an app field.
:param str field:
The name of the app field. Trying to set immutable fields
``uuid`` or ``key`` will raise a ValueError.
:param value:
The new value of the app field.
:raises: Va... | 0.003378 |
def plotER(self,*args,**kwargs):
"""
NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS)
"""
if... | 0.017058 |
def get_params(self):
"""
Get parameters for web service, noting whether any are "complex"
"""
params = {}
complex = False
for name, opt in self.filter_options.items():
if opt.ignored:
continue
if self.set_param(params, name):
... | 0.005305 |
def sp_sum_values(self):
"""
return sp level values
input:
"values": {
"spa": {
"19": "385",
"18": "0",
"20": "0",
"17": "0",
"16": "0"
},
"spb": {
"19": "... | 0.002528 |
def info_update(self, obj_id, data):
'''Update metadata with of a specified object.
See http://msdn.microsoft.com/en-us/library/live/hh243648.aspx
for the list of RW keys for each object type.'''
return self(obj_id, method='put', data=data, auth_header=True) | 0.022305 |
def wind44(msg):
"""Wind speed and direction.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), direction (degree)
"""
d = hex2bin(data(msg))
status = int(d[4])
if not status:
return None
speed = bin2int(d[5:14]) # k... | 0.002309 |
def is_recording():
"""Get status on recording/not recording.
Returns
-------
Current state of recording.
"""
curr = ctypes.c_bool()
check_call(_LIB.MXAutogradIsRecording(ctypes.byref(curr)))
return curr.value | 0.004132 |
def after(self, dt, inc=False):
""" Returns the first recurrence after the given datetime instance. The
inc keyword defines what happens if dt is an occurrence. With
inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self... | 0.003454 |
def has_child_families(self, family_id):
"""Tests if a family has any children.
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if the ``family_id`` has children,
``false`` otherwise
raise: NotFound - ``family_id`` is not found
... | 0.003476 |
def marginal_loglike(self, x):
"""Marginal log-likelihood.
Returns ``L_marg(x) = \int L(x,y|z') L(y) dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._marg_interp is None:
# This calcu... | 0.008529 |
def get_hex_color(layer_type):
"""
Determines the hex color for a layer.
:parameters:
- layer_type : string
Class name of the layer
:returns:
- color : string containing a hex color for filling block.
"""
COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B'... | 0.001156 |
def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to se... | 0.002791 |
def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit ... | 0.001997 |
def norm(self, estimate=False, **kwargs):
"""Return the operator norm of this operator.
If this operator is non-linear, this should be the Lipschitz constant.
Parameters
----------
estimate : bool
If true, estimate the operator norm. By default, it is estimated
... | 0.001136 |
def transact(
self,
contract_method: ContractFunction,
):
""" A wrapper around to_be_called.transact() that waits until the transaction succeeds. """
txhash = contract_method.transact(self.transaction)
LOG.debug(f'Sending txHash={encode_hex(txhash)}')
(receipt... | 0.008621 |
def load_into_collection_from_file(collection, filename,
content_type=None):
"""
Loads resources from the specified file into the given collection
resource.
If no content type is provided, an attempt is made to look up the
extension of the given filename in the MI... | 0.001284 |
def cmd_string(name, cmd):
# type: (AName, ACmd) -> ADefine
"""Define a string parameter coming from a shell command to be used within
this YAML file. Trailing newlines will be stripped."""
value = subprocess.check_output(cmd, shell=True).rstrip("\n")
return Define(name, value) | 0.003356 |
def parse_config(self):
"""
Parse the xml file with remote servers and discover resources on each found server.
"""
tree = ElementTree.parse(self.file_xml)
root = tree.getroot()
for server in root.findall('server'):
destination = server.text
name =... | 0.007673 |
def array(source_array, ctx=None, dtype=None):
"""Creates an array from any object exposing the array interface.
Parameters
----------
source_array : array_like
An object exposing the array interface, an object whose `__array__`
method returns an array, or any (nested) sequence.
ctx... | 0.002504 |
def _start_refresh_timer(self):
"""Start the Vim timer. """
if not self._timer:
self._timer = self._vim.eval(
"timer_start({}, 'EnTick', {{'repeat': -1}})"
.format(REFRESH_TIMER)
) | 0.007937 |
def action(act, config):
"""
CLI action preprocessor
"""
if not config:
pass
elif act is "list":
do_list()
else:
config_dir = os.path.join(CONFIG_ROOT, config)
globals()["do_" + act](config, config_dir) | 0.003876 |
def list_group_s_users(self, group_id, include=None, search_term=None):
"""
List group's users.
Returns a list of users in the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] =... | 0.003617 |
def configurar_interface_de_rede(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ConfigurarInterfaceDeRede')
... | 0.006928 |
def get_hnd(self, cache_id_obj, section=None, method=None):
"""Gets a handle for the given cache file with exclusive access.
The handle is meant to be used in a resource block.
Parameters
----------
cache_id_obj : object
An object uniquely identifying the cached r... | 0.001026 |
def add_note(self, note):
"""Add a note to the usernotes wiki page.
Arguments:
note: the note to be added (Note)
Returns the update message for the usernotes wiki
Raises:
ValueError when the warning type of the note can not be found in the
store... | 0.001697 |
def extract_data(invoicefile, templates=None, input_module=pdftotext):
"""Extracts structured data from PDF/image invoices.
This function uses the text extracted from a PDF file or image and
pre-defined regex templates to find structured data.
Reads template if no template assigned
Required fields... | 0.001824 |
def uniform_binned(self, name=None):
"""
Return a new histogram with constant width bins along all axes by
using the bin indices as the bin edges of the new histogram.
"""
if self.GetDimension() == 1:
new_hist = Hist(
self.GetNbinsX(), 0, self.GetNbins... | 0.001771 |
def contact_addresses(self):
"""
Provides a reference to contact addresses used by this server.
Obtain a reference to manipulate or iterate existing contact
addresses::
>>> from smc.elements.servers import ManagementServer
>>> mgt_server = Manage... | 0.007335 |
def _set_xml_from_keys(self, root, item, **kwargs):
"""Create SubElements of root with kwargs.
Args:
root: Element to add SubElements to.
item: Tuple key/value pair from self.data_keys to add.
kwargs:
For each item in self.data_keys, if it has a
... | 0.001365 |
def span_to_bytes(thrift_span):
"""
Returns a TBinaryProtocol encoded Thrift span.
:param thrift_span: thrift object to encode.
:returns: thrift object in TBinaryProtocol format bytes.
"""
transport = TMemoryBuffer()
protocol = TBinaryProtocol(transport)
thrift_span.write(protocol)
... | 0.002817 |
def _set_show_mpls_statistics_ldp_tunnel(self, v, load=False):
"""
Setter method for show_mpls_statistics_ldp_tunnel, mapped from YANG variable /brocade_mpls_rpc/show_mpls_statistics_ldp_tunnel (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_statistics_ld... | 0.005817 |
def status(self, status):
"""Sets the status of this StoreCreditPayment.
:param status: The status of this StoreCreditPayment.
:type: str
"""
allowed_values = ["pending", "awaitingRetry", "successful", "failed"]
if status is not None and status not in allowed_values:
... | 0.003914 |
def create_resource(self, uri):
"""Creates a new Resource.
The created ressource type depends on the used URI.
:param uri: the resource URI
:type uri: URI
:return: a new Resource
:rtype: Resource
.. seealso:: URI, Resource, XMIResource
"""
if is... | 0.00295 |
def get_values(self, k, v):
"""Get a list of values from the key value metadata attribute.
Args:
k (str):
Key in :class:`api.results`.metadata
v (str):
Values from each item in the key of :class:`api.results`.metadata
Returns:
A list containing all the ``v`` value... | 0.011609 |
def reduce_annotations(self, annotations, options):
"""Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT)."""
getfnc_qual_ev = options.getfnc_qual_ev()
return [nt for nt in annotations if getfnc_qual_ev(nt.Qualifier, nt.Evidence_Code)] | 0.013652 |
def _authorization_headers_valid(self, token_type, token):
"""Verify authorization headers for a request.
Parameters
token_type (str)
Type of token to access resources.
token (str)
Server Token or OAuth 2.0 Access Token.
Returns
... | 0.002954 |
def decamel_to_snake(string):
"""Convert to lower case, join camel case with underscore.
CamelCase -> camel_case. Camel Case -> camel_case.
"""
strings = [decamel(word) if not word.isupper() else word.lower()
for word in string.split()]
return "_".join([snake(dstring)for dstring in st... | 0.003058 |
def _load_source_model(self):
"""
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.sou... | 0.027174 |
def decode(self, envelope, session, **kwargs):
""" :meth:`.WMessengerOnionCoderLayerProto.decode` method implementation.
:param envelope: original envelope
:param session: original session
:param kwargs: additional arguments
:return: WMessengerBytesEnvelope
"""
return WMessengerBytesEnvelope(b64decode(e... | 0.025424 |
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1):
"""Generate tensor for TensorBoard (casting, clipping)
Args:
name: name for visualization operation
*imgs: multiple tensors as list
scale_func: scale input tensors to fit range [0, 255]
Example:... | 0.004894 |
def send_ignore(self, bytes=None):
"""
Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing
firewalls.
@param bytes: ... | 0.002894 |
def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True,
normed_pdf=False, ax=None, **kwds):
"""
draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple o... | 0.002006 |
def undelete_derived_metric(self, id, **kwargs): # noqa: E501
"""Undelete a specific derived metric definition # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api... | 0.002125 |
def content_allows_robots (self):
"""
Return False if the content of this URL forbids robots to
search for recursive links.
"""
if not self.is_html():
return True
# construct parser object
handler = linkparse.MetaRobotsFinder()
parser = htmlsax... | 0.003831 |
def _get_plugins_by_entry_points(self):
"""
Registers plugin classes, which are in sys.path and have an entry_point called 'groundwork.plugin'.
:return: dict of plugin classes
"""
# Let's find and register every plugin, which is in sys.path and has defined a entry_point 'groundwo... | 0.006149 |
def read_xml(filename):
"""
Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None
"""
parser = et.XMLParser(remove_blank_text=True)
isfile=False
try:
isfile = os.path.exists(filename)
except ... | 0.002421 |
def from_api(cls, **kwargs):
"""Create a new instance from API arguments.
This will switch camelCase keys into snake_case for instantiation.
It will also identify any ``Instance`` or ``List`` properties, and
instantiate the proper objects using the values. The end result being
... | 0.001894 |
def Categories(unicode_dir=_UNICODE_DIR):
"""Returns dict mapping category names to code lists.
Args:
unicode_dir: Unicode data directory
Returns:
dict mapping category names to code lists
"""
categories = {}
def DoLine(codes, fields):
"""Process single UnicodeData.txt line, updating categor... | 0.012658 |
def send_message(self, peer: Peer, text: str, reply: int=None, link_preview: bool=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
"""
Send message to peer.
:param peer: Peer to send message to.
:param text: Text to send.
:param reply:... | 0.017937 |
def __apply_func(self, other, func_name):
""" delegate operations to the *samples* attribute, but in a time
correct manner by considering the *timestamps*
"""
if isinstance(other, Signal):
if len(self) and len(other):
start = max(self.timestamps[0], other.ti... | 0.001337 |
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-sep... | 0.001584 |
def get_data_disk_size(vm_, swap, linode_id):
'''
Return the size of of the data disk in MB
.. versionadded:: 2016.3.0
'''
disk_size = get_linode(kwargs={'linode_id': linode_id})['TOTALHD']
root_disk_size = config.get_cloud_config_value(
'disk_size', vm_, __opts__, default=disk_size - s... | 0.002674 |
def login(self, authc_token):
"""
:type authc_token: authc_abcs.AuthenticationToken
authc_token's password is cleartext that is stored as a bytearray.
The authc_token password is cleared in memory, within the authc_token,
when authentication is successful.
"""
se... | 0.002804 |
def openAPIDoc(**kwargs):
"""
Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object
"""
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The ... | 0.004178 |
def readSettings(self):
"""Recommended call to read all meter settings at once.
Returns:
bool: True if all subsequent serial calls completed with ACK.
"""
success = (self.readHolidayDates() and
self.readMonthTariffs(ReadMonths.kWh) and
s... | 0.003738 |
def extract_subjects(cert_pem):
"""Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A se... | 0.004735 |
def get_upload_pipeline(in_fd, out_fd, rate_limit=None,
gpg_key=None, lzop=True):
""" Create a UNIX pipeline to process a file for uploading.
(Compress, and optionally encrypt) """
commands = []
if rate_limit is not None:
commands.append(PipeViewerRateLimitFilter(rate... | 0.001931 |
def fastqfilter(self):
"""Filter the reads into separate files based on taxonomic assignment"""
printtime('Creating filtered .fastqfiles', self.start)
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
... | 0.004 |
def set_prompt(scope, prompt=None):
"""
Defines the pattern that is recognized at any future time when Exscript
needs to wait for a prompt.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and continues as soon as the
pattern is fou... | 0.001548 |
def is_request_type(request_type):
# type: (str) -> Callable[[HandlerInput], bool]
"""A predicate function returning a boolean, when request type is
the passed-in type.
The function can be applied on a
:py:class:`ask_sdk_core.handler_input.HandlerInput`, to check
if the input request type is th... | 0.001244 |
def check_command(args):
"""Checks that all dependencies in the specified requirements file are
up to date."""
outdated = check_requirements_file(args.requirements_file,
args.skip_packages)
if outdated:
print('Requirements in {} are out of date:'.format(
... | 0.001742 |
def gen_bidi(output, ascii_props=False, append=False, prefix=""):
"""Generate `bidi class` property."""
bidi_class = {}
max_range = MAXASCII if ascii_props else MAXUNICODE
with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'UnicodeData.txt'), 'r', 'utf-8') as uf:
for line in uf:
... | 0.001441 |
def _create_no_protein(self):
"""Create a no-protein result"""
alt_data = AltTranscriptData([],
None,
None,
False,
None,
... | 0.004515 |
def inference(self, kern, X, Z, likelihood, Y, indexD, output_dim, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None):
"""
The first phase of inference:
Compute: log-likelihood, dL_dKmm
Cached intermediate results: Kmm, KmmInv,
"""
input_dim = Z.shape[0]
u... | 0.008753 |
def convert_to_cvxpy(sdp):
"""Convert an SDP relaxation to a CVXPY problem.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`cvxpy.Problem`.
"""
from cvxpy import Minimize, Problem, Variable
row_offsets = [0]
cumulative_sum = 0
for bl... | 0.000546 |
def json_data(self):
"""The json representation of a transmissions."""
return {
"vector_id": self.vector_id,
"origin_id": self.origin_id,
"destination_id": self.destination_id,
"info_id": self.info_id,
"network_id": self.network_id,
... | 0.005 |
def provider_login_url(parser, token):
"""
{% provider_login_url "facebook" next=bla %}
{% provider_login_url "openid" openid="http://me.yahoo.com" next=bla %}
"""
bits = token.split_contents()
provider_id = bits[1]
params = token_kwargs(bits[2:], parser, support_legacy=False)
return Pro... | 0.002793 |
def match(fullname1, fullname2, strictness='default', options=None):
"""
Takes two names and returns true if they describe the same person.
:param string fullname1: first human name
:param string fullname2: second human name
:param string strictness: strictness settings to use
:param dict optio... | 0.001475 |
def setComment(self, msg):
"""Sets the widget text to *msg*
:param msg: overwrites any existing text with *msg*
:type msg: str
"""
self.ui.commentTxtedt.setPlainText(msg)
# move text cursor to end
self.ui.commentTxtedt.moveCursor(QtGui.QTextCursor.End) | 0.006472 |
def p_sysargs(self, p):
'sysargs : sysargs COMMA sysarg'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | 0.015267 |
def get_upsert_sql(
self,
rows,
unique_fields,
update_fields,
auto_field_name=None,
only_insert=False,
return_rows=True
):
"""
Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT)
INSERT INTO table_name (fie... | 0.0037 |
def configure_sources(update=False,
sources_var='install_sources',
keys_var='install_keys'):
"""Configure multiple sources from charm configuration.
The lists are encoded as yaml fragments in the configuration.
The fragment needs to be included as a string. Sourc... | 0.000765 |
def send_message(self, app_mxit_id, target_user_ids, message='', contains_markup=True,
spool=None, spool_timeout=None, links=None, scope='message/send'):
"""
Send a message (from a Mxit app) to a list of Mxit users
"""
data = {
'From': app_mxit_id,
... | 0.006553 |
def main():
""" Main function """
# Read configuration from the config file if present, else fall back to
# command line options
if args.config:
config = config_file_parser.get_configuration(args.config)
access_key_id = config['access-key-id']
secret_access_key = config['secret-a... | 0.000562 |
def is_file(package):
"""Determine if a package name is for a File dependency."""
if hasattr(package, "keys"):
return any(key for key in package.keys() if key in ["file", "path"])
if os.path.exists(str(package)):
return True
for start in SCHEME_LIST:
if str(package).startswith(... | 0.00271 |
def subprocess_manager(self, exec_args):
''' Bro subprocess manager '''
try:
sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)
except OSError:
raise RuntimeError('Could not run bro executable (either not installed or not... | 0.008708 |
def getrmlsthelper(self):
"""
Makes a system call to rest_auth.py, a Python script modified from
https://github.com/kjolley/BIGSdb/tree/develop/scripts/test
And downloads the most up-to-date rMLST profile and alleles
"""
# Set the path/name of the folder to contain the ne... | 0.00262 |
def showImage(layout, imagePath="", imageObj=None, offset=(0, 0),
bgcolor=COLORS.Off, brightness=255):
"""Display an image on the matrix"""
if not isinstance(layout, Matrix):
raise RuntimeError("Must use Matrix with showImage!")
layout.all_off()
return show_image(layout.set, layo... | 0.002404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.