code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def getCaCerts(self):
retn = []
path = s_common.genpath(self.certdir, 'cas')
for name in os.listdir(path):
if not name.endswith('.crt'):
continue
full = s_common.genpath(self.certdir, 'cas', name)
retn.append(self._loadCertPath(full))
r... | Return a list of CA certs from the CertDir.
Returns:
[OpenSSL.crypto.X509]: List of CA certificates. |
def _get_compressor_options(
self,
side: str,
agreed_parameters: Dict[str, Any],
compression_options: Dict[str, Any] = None,
) -> Dict[str, Any]:
options = dict(
persistent=(side + "_no_context_takeover") not in agreed_parameters
)
wbits_header = a... | Converts a websocket agreed_parameters set to keyword arguments
for our compressor objects. |
def object2code(key, code):
if key in ["xscale", "yscale"]:
if code == "log":
code = True
else:
code = False
else:
code = unicode(code)
return code | Returns code for widget from dict object |
def do_set_hub_connection(self, args):
params = args.split()
username = None
password = None
host = None
port = None
try:
username = params[0]
password = params[1]
host = params[2]
port = params[3]
except IndexError:... | Set Hub connection parameters.
Usage:
set_hub_connection username password host [port]
Arguments:
username: Hub username
password: Hub password
host: host name or IP address
port: IP port [default 25105] |
def conv2bin(data):
if data.min() < 0 or data.max() > 1:
data = normalize(data)
out_data = data.copy()
for i, sample in enumerate(out_data):
for j, val in enumerate(sample):
if np.random.random() <= val:
out_data[i][j] = 1
else:
out_dat... | Convert a matrix of probabilities into binary values.
If the matrix has values <= 0 or >= 1, the values are
normalized to be in [0, 1].
:type data: numpy array
:param data: input matrix
:return: converted binary matrix |
def cd(dest):
origin = os.getcwd()
try:
os.chdir(dest)
yield dest
finally:
os.chdir(origin) | Temporarily cd into a directory |
def num_taps(sample_rate, transitionwidth, gpass, gstop):
gpass = 10 ** (-gpass / 10.)
gstop = 10 ** (-gstop / 10.)
return int(2/3. * log10(1 / (10 * gpass * gstop)) *
sample_rate / transitionwidth) | Returns the number of taps for an FIR filter with the given shape
Parameters
----------
sample_rate : `float`
sampling rate of target data
transitionwidth : `float`
the width (in the same units as `sample_rate` of the transition
from stop-band to pass-band
gpass : `float`
... |
def main(fast=False):
print('Running benchmarks...\n')
results = bench_run(fast=fast)
bench_report(results) | Run all benchmarks and print report to the console. |
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,
profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if key_id.startswith('alias/'):
key_id = _get_key_id(key_id)
r = {}
try:
conn.revoke_grant(key_id, grant_id)
... | Revoke a grant from a key.
CLI example::
salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j... |
def get(interface, method, version=1,
apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'],
caller=None, session=None, params=None):
url = u"%s://%s/%s/%s/v%s/" % (
'https' if https else 'http', apihost, interface, method, version)
return webapi_request(url, 'GET', caller=cal... | Send GET request to an API endpoint
.. versionadded:: 0.8.3
:param interface: interface name
:type interface: str
:param method: method name
:type method: str
:param version: method version
:type version: int
:param apihost: API hostname
:type apihost: str
:param https: whether... |
def message_to_event(zclient, msg):
if not isinstance(msg, zebra.ZebraMessage):
return None
body_cls = msg.get_body_class(msg.version, msg.command)
ev_cls = getattr(MOD, _event_name(body_cls), None)
if ev_cls is None:
return None
return ev_cls(zclient, msg) | Converts Zebra protocol message instance to Zebra protocol service
event instance.
If corresponding event class is not defined, returns None.
:param zclient: Zebra client instance.
:param msg: Zebra protocol message.
:return: Zebra protocol service event. |
def decode_arr(data):
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | Extract a numpy array from a base64 buffer |
def retrieve_password_from_keyring(credential_id, username):
try:
import keyring
return keyring.get_password(credential_id, username)
except ImportError:
log.error('USE_KEYRING configured as a password, but no keyring module is installed')
return False | Retrieve particular user's password for a specified credential set from system keyring. |
def remove_move(name):
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | Remove item from six.moves. |
def next_task(self, item, raise_exceptions=None, **kwargs):
filename = os.path.basename(item)
batch = self.get_batch(filename)
tx_deserializer = self.tx_deserializer_cls(
allow_self=self.allow_self, override_role=self.override_role
)
try:
tx_deserializer.d... | Deserializes all transactions for this batch and
archives the file. |
def put(self, id=None):
toa = self.request.headers.get("Caesium-TOA")
if not toa:
self.raise_error(400, "Caesium-TOA header is required, none found")
self.finish(self.request.headers.get("Caesium-TOA"))
meta = self._get_meta_data()
meta["bulk_id"] = uuid.uuid4().g... | Update many objects with a single PUT.
Example Request::
{
"ids": ["52b0ede98ac752b358b1bd69", "52b0ede98ac752b358b1bd70"],
"patch": {
"foo": "bar"
}
} |
def get(self):
if self.num is None:
if self.num_inst == 0:
return (self.name, float('nan'))
else:
return (self.name, self.sum_metric / self.num_inst)
else:
names = ['%s'%(self.name[i]) for i in range(self.num)]
values = [x /... | Get the current evaluation result.
Override the default behavior
Returns
-------
name : str
Name of the metric.
value : float
Value of the evaluation. |
def compile_mako_files(self, app_config):
for subdir_name in self.SEARCH_DIRS:
subdir = subdir_name.format(
app_path=app_config.path,
app_name=app_config.name,
)
def recurse_path(path):
self.message('searching for Mako templates... | Compiles the Mako templates within the apps of this system |
def _write_summary(self, session, frame):
summary = session.run(self.summary_op, feed_dict={
self.frame_placeholder: frame
})
path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)
write_file(summary, path) | Writes the frame to disk as a tensor summary. |
def parse_trips(self, xml, requested_time):
obj = xmltodict.parse(xml)
trips = []
if 'error' in obj:
print('Error in trips: ' + obj['error']['message'])
return None
try:
for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:
newtrip ... | Parse the NS API xml result into Trip objects |
def get_bars(self, lookback=None, as_dict=False):
bars = self._get_symbol_dataframe(self.parent.bars, self)
bars = self.parent._add_signal_history(df=bars, symbol=self)
lookback = self.bar_window if lookback is None else lookback
bars = bars[-lookback:]
if not bars.empty > 0 and ... | Get bars for this instrument
:Parameters:
lookback : int
Max number of bars to get (None = all available bars)
as_dict : bool
Return a dict or a pd.DataFrame object
:Retruns:
bars : pd.DataFrame / dict
The bars for thi... |
async def get_authenticated_user(
self, redirect_uri: str, code: str
) -> Dict[str, Any]:
handler = cast(RequestHandler, self)
http = self.get_auth_http_client()
body = urllib.parse.urlencode(
{
"redirect_uri": redirect_uri,
"code": code,
... | Handles the login for the Google user, returning an access token.
The result is a dictionary containing an ``access_token`` field
([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).
Unlike other ``get_authenticated_user`` methods in this packa... |
def get_coin_snapshot(fsym, tsym):
url = build_url('coinsnapshot', fsym=fsym, tsym=tsym)
data = load_data(url)['Data']
return data | Get blockchain information, aggregated data as well as data for the
individual exchanges available for the specified currency pair.
Args:
fsym: FROM symbol.
tsym: TO symbol.
Returns:
The function returns a dictionairy containing blockain as well as
trading information from the different exchanges were t... |
def _normalize_files(item, fc_dir=None):
files = item.get("files")
if files:
if isinstance(files, six.string_types):
files = [files]
fastq_dir = flowcell.get_fastq_dir(fc_dir) if fc_dir else os.getcwd()
files = [_file_to_abs(x, [os.getcwd(), fc_dir, fastq_dir]) for x in files... | Ensure the files argument is a list of absolute file names.
Handles BAM, single and paired end fastq, as well as split inputs. |
def on_storage_device_change(self, medium_attachment, remove, silent):
if not isinstance(medium_attachment, IMediumAttachment):
raise TypeError("medium_attachment can only be an instance of type IMediumAttachment")
if not isinstance(remove, bool):
raise TypeError("remove can only... | Triggered when attached storage devices of the
associated virtual machine have changed.
in medium_attachment of type :class:`IMediumAttachment`
The medium attachment which changed.
in remove of type bool
TRUE if the device is removed, FALSE if it was added.
in ... |
def complete(self):
comp = []
for k, v in self.key.items():
if v['type'] == 'value':
if 'complete' in v:
comp += v['complete'](self.inp_cmd[-1])
else:
comp.append(k)
return comp | Return list of valid completions
Returns a list of valid completions on the current level in the
tree. If an element of type 'value' is found, its complete callback
function is called (if set). |
def filter(self, field_name, operand, value):
if operand not in self._FILTER_OPERANDS:
raise ValueError('Operand must be one of {}'.format(', '.join(self._FILTER_OPERANDS)))
record_stub = record_factory(self._app)
field = record_stub.get_field(field_name)
self._raw['filters']... | Adds a filter to report
Notes:
All filters are currently AND'ed together
Args:
field_name (str): Target field name to filter on
operand (str): Operand used in comparison. See `swimlane.core.search` for options
value: Target value used in comparision |
def gen_procfile(ctx, wsgi, dev):
if wsgi is None:
if os.path.exists("wsgi.py"):
wsgi = "wsgi.py"
elif os.path.exists("app.py"):
wsgi = "app.py"
else:
wsgi = "app.py"
ctx.invoke(gen_apppy)
def write_procfile(filename, server_process, debug)... | Generates Procfiles which can be used with honcho or foreman. |
def _availableResultsFraction( self ):
tr = self.notebook().numberOfResults() + self.notebook().numberOfPendingResults()
if tr == 0:
return 0
else:
return (self.notebook().numberOfResults() + 0.0) / tr | Private method to return the fraction of results available, as a real number
between 0 and 1. This does not update the results fetched from the cluster.
:returns: the fraction of available results |
def find_all(self, string, callback):
for index, output in self.iter(string):
callback(index, output) | Wrapper on iter method, callback gets an iterator result |
def gauge(self, stat, value, rate=1, delta=False):
if value < 0 and not delta:
if rate < 1:
if random.random() > rate:
return
with self.pipeline() as pipe:
pipe._send_stat(stat, '0|g', 1)
pipe._send_stat(stat, '%s|g' % v... | Set a gauge value. |
def from_jd(jd, method=None):
method = method or 'equinox'
if method == 'equinox':
return _from_jd_equinox(jd)
else:
return _from_jd_schematic(jd, method) | Calculate date in the French Revolutionary
calendar from Julian day. The five or six
"sansculottides" are considered a thirteenth
month in the results of this function. |
def initialize_memory(basic_block):
global MEMORY
MEMORY = basic_block.mem
get_labels(MEMORY, basic_block)
basic_block.mem = MEMORY | Initializes global memory array with the given one |
def data_vectors(self):
return {field: self.record[field] for field in self.record.dtype.names
if field != 'sample'} | The per-sample data in a vector.
Returns:
dict: A dict where the keys are the fields in the record and the
values are the corresponding arrays.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,
... |
def from_string(values, separator, remove_duplicates = False):
result = AnyValueArray()
if values == None or len(values) == 0:
return result
items = str(values).split(separator)
for item in items:
if (item != None and len(item) > 0) or remove_duplicates == False:
... | Splits specified string into elements using a separator and assigns
the elements to a newly created AnyValueArray.
:param values: a string value to be split and assigned to AnyValueArray
:param separator: a separator to split the string
:param remove_duplicates: (optional) true to rem... |
def loads(self, value):
raw = False if self.encoding == "utf-8" else True
if value is None:
return None
return msgpack.loads(value, raw=raw, use_list=self.use_list) | Deserialize value using ``msgpack.loads``.
:param value: bytes
:returns: obj |
def list_depth(list_, func=max, _depth=0):
depth_list = [list_depth(item, func=func, _depth=_depth + 1)
for item in list_ if util_type.is_listlike(item)]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[... |
def list_clients():
p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser())
for path in glob.glob(p):
try:
yield PosixClient(path)
except socket.error:
pass | List all the servers that are running. |
def create_request_setting(self,
service_id,
version_number,
name,
default_host=None,
force_miss=None,
force_ssl=None,
action=None,
bypass_busy_wait=None,
max_stale_age=None,
hash_keys=None,
xff=None,
timer_support=None,
geo_headers=None,
request_condition=None):
body = self._formdata({
... | Creates a new Request Settings object. |
def _handle_no_candidates(self):
if self.dom is not None and len(self.dom):
dom = prep_article(self.dom)
dom = build_base_document(dom, self._return_fragment)
return self._remove_orphans(
dom.get_element_by_id("readabilityBody"))
else:
logg... | If we fail to find a good candidate we need to find something else. |
def get_context(self, name):
contexts = self.data['contexts']
for context in contexts:
if context['name'] == name:
return context
raise KubeConfError("context name not found.") | Get context from kubeconfig. |
def timeslice_generator(self):
slice_id = 0
while slice_id < self.n_timeslices:
blob = self.get_blob(slice_id)
yield blob
slice_id += 1 | Uses slice ID as iterator |
def ceilpow2(n):
signif,exponent = frexp(n)
if (signif < 0):
return 1;
if (signif == 0.5):
exponent -= 1;
return (1) << exponent; | convenience function to determine a power-of-2 upper frequency limit |
def last_datetime(self):
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | Return the time of the last operation on the bundle as a datetime object |
def switch_to_next_app(self):
log.debug("switching to next app...")
cmd, url = DEVICE_URLS["switch_to_next_app"]
self.result = self._exec(cmd, url) | switches to the next app |
def collect_filters_to_first_location_occurrence(compound_match_query):
new_match_queries = []
for match_query in compound_match_query.match_queries:
location_to_filters = _construct_location_to_filter_list(match_query)
already_filtered_locations = set()
new_match_traversals = []
... | Collect all filters for a particular location to the first instance of the location.
Adding edge field non-exsistence filters in `_prune_traverse_using_omitted_locations` may
result in filters being applied to locations after their first occurence.
OrientDB does not resolve this behavior correctly. Therefo... |
def elements(self):
return (self.country_code, self.check_digits, self.bank_identifier,
self.bank_account_number) | Return the IBAN's Country Code, check digits, Bank Identifier and
Bank Account Number as tuple. |
def asyncPipeStrconcat(context=None, _INPUT=None, conf=None, **kwargs):
splits = yield asyncGetSplits(_INPUT, conf['part'], **cdicts(opts, kwargs))
_OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), splits)
returnValue(iter(_OUTPUT)) | A string module that asynchronously builds a string. Loopable. No direct
input.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'part': [
{'value': <'<img src="'>},
{'subkey': <'i... |
def tmdb_find(
api_key, external_source, external_id, language="en-US", cache=True
):
sources = ["imdb_id", "freebase_mid", "freebase_id", "tvdb_id", "tvrage_id"]
if external_source not in sources:
raise MapiProviderException("external_source must be in %s" % sources)
if external_source == "imdb... | Search for The Movie Database objects using another DB's foreign key
Note: language codes aren't checked on this end or by TMDb, so if you
enter an invalid language code your search itself will succeed, but
certain fields like synopsis will just be empty
Online docs: developers.themoviedb.org/... |
def fib(number: int) -> int:
if number < 2:
return number
return fib(number - 1) + fib(number - 2) | Simple Fibonacci function.
>>> fib(10)
55 |
def read_stream(self, stream_id, size=None):
rv = []
try:
with (yield from self._get_stream(stream_id).rlock):
if size is None:
rv.append((
yield from self._get_stream(stream_id).read_frame()))
self._flow_control... | Read data from the given stream.
By default (`size=None`), this returns all data left in current HTTP/2
frame. In other words, default behavior is to receive frame by frame.
If size is given a number above zero, method will try to return as much
bytes as possible up to the given size, ... |
def cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth,
verticalPadding, horizontalPadding, verticalStride, horizontalStride):
status = _libcudnn.cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight,
window... | Initialize a 2D pooling descriptor.
This function initializes a previously created pooling descriptor object.
Parameters
----------
poolingDesc : cudnnPoolingDescriptor
Handle to a previously created pooling descriptor.
mode : cudnnPoolingMode
Enumerant to specify the pooling mode.... |
def _build_logger(self, level=logging.INFO):
self._debug_stream = StringIO()
logger = logging.getLogger('sprinter')
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setLevel(level)
logger.addHandler(out_hdlr)
debug_hdlr = logging.StreamHandler(self._debug_stream)
... | return a logger. if logger is none, generate a logger from stdout |
def merge_dimensions(dimensions_list):
dvalues = defaultdict(list)
dimensions = []
for dims in dimensions_list:
for d in dims:
dvalues[d.name].append(d.values)
if d not in dimensions:
dimensions.append(d)
dvalues = {k: list(unique_iterator(itertools.chain(... | Merges lists of fully or partially overlapping dimensions by
merging their values.
>>> from holoviews import Dimension
>>> dim_list = [[Dimension('A', values=[1, 2, 3]), Dimension('B')],
... [Dimension('A', values=[2, 3, 4])]]
>>> dimensions = merge_dimensions(dim_list)
>>> dimensio... |
def extract_terms(self, nb):
emt = ExtractMetatabTerms()
emt.preprocess(nb, {})
return emt.terms | Extract some term values, usually set with tags or metadata |
def random_regions(base, n, size):
spread = size // 2
base_info = collections.defaultdict(list)
for space, start, end in base:
base_info[space].append(start + spread)
base_info[space].append(end - spread)
regions = []
for _ in range(n):
space = random.choice(base_info.keys())... | Generate n random regions of 'size' in the provided base spread. |
def serialize(self, now=None):
created = self.created if self.created is not None else now
el = etree.Element(utils.lxmlns("mets") + self.subsection, ID=self.id_string)
if created:
el.set("CREATED", created)
status = self.get_status()
if status:
el.set("ST... | Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children |
def inverable_unique_two_lists(item1_list, item2_list):
import utool as ut
unique_list1, inverse1 = np.unique(item1_list, return_inverse=True)
unique_list2, inverse2 = np.unique(item2_list, return_inverse=True)
flat_stacked, cumsum = ut.invertible_flatten2((unique_list1, unique_list2))
flat_unique, ... | item1_list = aid1_list
item2_list = aid2_list |
def clear(self):
logger.info("Resetting indexes")
state = self.app_state
for _name, idx in state.indexes.items():
writer = AsyncWriter(idx)
writer.commit(merge=True, optimize=True, mergetype=CLEAR)
state.indexes.clear()
state.indexed_classes.clear()
... | Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes. |
def tag_handler(self, cmd):
cmd.from_ = self._find_interesting_from(cmd.from_)
self.keep = cmd.from_ is not None | Process a TagCommand. |
def code(self):
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | the http status code to return to the client, by default, 200 if a body is present otherwise 204 |
def _os_install(self, package_file):
packages = " ".join(json.load(package_file.open()))
if packages:
for packager in self.pkg_install_cmds:
if packager in self.context.externalbasis:
installer = self.pkg_install_cmds[packager]
return f"RUN ... | take in a dict return a string of docker build RUN directives
one RUN per package type
one package type per JSON key |
def author_preview_view(self, context):
children_contents = []
fragment = Fragment()
for child_id in self.children:
child = self.runtime.get_block(child_id)
child_fragment = self._render_child_fragment(child, context, 'preview_view')
fragment.add_frag_resource... | View for previewing contents in studio. |
def find_directories(root, pattern):
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(dirs, pattern)
results.extend(os.path.join(base, d) for d in matched)
return results | Find all directories matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of dir paths relative to root |
def get_event_attendees(self, event_id):
query = urllib.urlencode({'key': self._api_key,
'event_id': event_id})
url = '{0}?{1}'.format(RSVPS_URL, query)
data = self._http_get_json(url)
rsvps = data['results']
return [parse_member_from_rsvp(rsvp) ... | Get the attendees of the identified event.
Parameters
----------
event_id
ID of the event to get attendees for.
Returns
-------
List of ``pythonkc_meetups.types.MeetupMember``.
Exceptions
----------
* PythonKCMeetupsBadJson
*... |
def merge_tree(self, rhs, base=None):
args = ["--aggressive", "-i", "-m"]
if base is not None:
args.append(base)
args.append(rhs)
self.repo.git.read_tree(args)
return self | Merge the given rhs treeish into the current index, possibly taking
a common base treeish into account.
As opposed to the from_tree_ method, this allows you to use an already
existing tree as the left side of the merge
:param rhs:
treeish reference pointing to the 'other' s... |
def sub(x, y, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sub,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | Return ``x`` - ``y``. |
def query_module_funcs(self, module):
funcs = self.session.query(Export).filter_by(
module=module).all()
return funcs | Query the functions in the specified module. |
def sentences(self):
sents = []
spans = self.sentence_tokenizer.span_tokenize(self.text)
for span in spans:
sent = Sentence(
text=self.text[span[0]:span[1]],
start=span[0],
end=span[1],
word_tokenizer=self.word_tokenizer... | Return a list of Sentences that make up this text passage. |
def get_scopes_information(self):
scopes = StandardScopeClaims.get_scopes_info(self.params['scope'])
if settings.get('OIDC_EXTRA_SCOPE_CLAIMS'):
scopes_extra = settings.get(
'OIDC_EXTRA_SCOPE_CLAIMS', import_str=True).get_scopes_info(self.params['scope'])
for inde... | Return a list with the description of all the scopes requested. |
def transform_revision(self, revision):
config = self.manager.get_source('config')
return config.load_resource(revision) | make config revision look like describe output. |
def match_path(pathname,
included_patterns=None,
excluded_patterns=None,
case_sensitive=True):
included = ["*"] if included_patterns is None else included_patterns
excluded = [] if excluded_patterns is None else excluded_patterns
return _match_path(pathname, incl... | Matches a pathname against a set of acceptable and ignored patterns.
:param pathname:
A pathname which will be matched against a pattern.
:param included_patterns:
Allow filenames matching wildcard patterns specified in this list.
If no pattern is specified, the function treats the path... |
def getpath(self, encoding='utf-8', errors='strict'):
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors) | Return the normalized decoded URI path. |
def AddTransaction(self, tx):
if BC.Default() is None:
return False
if tx.Hash.ToBytes() in self.MemPool.keys():
return False
if BC.Default().ContainsTransaction(tx.Hash):
return False
if not tx.Verify(self.MemPool.values()):
logger.error("... | Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise. |
def replace_urls(status):
text = status.text
if not has_url(status):
return text
urls = [(e['indices'], e['expanded_url']) for e in status.entities['urls']]
urls.sort(key=lambda x: x[0][0], reverse=True)
for (start, end), url in urls:
text = text[:start] + url + text[end:]
return... | Replace shorturls in a status with expanded urls.
Args:
status (tweepy.status): A tweepy status object
Returns:
str |
def get_portfolios3():
g1 = [0]
g2 = [1]
g7 = [2]
g13 = [3]
g14 = [4]
g15 = [5]
g16 = [6]
g18 = [7]
g21 = [8]
g22 = [9]
g23 = [10, 11]
portfolios = [g1 + g15 + g18,
g2 + g16 + g21,
g13 + g22,
g7 + g23]
passive = g1... | Returns portfolios with U12 and U20 generators removed and generators
of the same type at the same bus aggregated. |
def save(self):
self.projects.save()
self.experiments.save()
safe_dump(self.global_config, self._globals_file,
default_flow_style=False) | Save the entire configuration files |
def list(self, limit=50, offset=0):
logger.info("list(limit=%s, offset=%s) [lid=%s,pid=%s]", limit, offset, self.__lid, self.__pid)
evt = self._client._request_point_value_list(self.__lid, self.__pid, self._type, limit=limit, offset=offset)
self._client._wait_and_except_if_failed(evt)
re... | List `all` the values on this Point.
Returns QAPI list function payload
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLin... |
def get_root_path():
root_path = __file__
return os.path.dirname(os.path.realpath(root_path)) | Get the root path for the application. |
def get_flow_by_idx(self, idx, bus):
P, Q = [], []
if type(idx) is not list:
idx = [idx]
if type(bus) is not list:
bus = [bus]
for line_idx, bus_idx in zip(idx, bus):
line_int = self.uid[line_idx]
if bus_idx == self.bus1[line_int]:
... | Return seriesflow based on the external idx on the `bus` side |
def response(self, msgtype, msgid, error, result):
self._proxy.response(msgid, error, result) | Handle an incoming response. |
def adaptive_universal_transformer_multilayer_hard():
hparams = adaptive_universal_transformer_multilayer_tpu()
hparams.batch_size = 256
hparams.hard_attention_k = 8
hparams.add_step_timing_signal = True
hparams.self_attention_type = "dot_product_relative_v2"
hparams.max_relative_position = 256
return hpa... | Multi-layer config for adaptive Transformer with hard attention. |
def create_entity_class(self):
entity = Entity()
entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-', ''))
entity.RowKey = 'rk{}'.format(str(uuid.uuid4()).replace('-', ''))
entity.age = 39
entity.large = 933311100
entity.sex = 'male'
entity.married =... | Creates a class-based entity with fixed values, using all of the supported data types. |
def audio_visual_key(name=None):
if name is None:
name = 'AVI Field'
society_code = basic.numeric(3)
society_code = society_code.setName('Society Code') \
.setResultsName('society_code')
av_number = basic.alphanum(15, extended=True, isLast=True)
field_empty = pp.Regex('[ ]{15}')
... | Creates the grammar for an Audio Visual Key code.
This is a variation on the ISAN (International Standard Audiovisual Number)
:param name: name for the field
:return: grammar for an ISRC field |
def endpoints(self):
children = [item.endpoints() for item in self.items]
return self.name, self.endpoint, children | Get all the endpoints under this node in a tree like structure.
Returns:
(tuple):
name (str): This node's name.
endpoint (str): Endpoint name relative to root.
children (list): ``child.endpoints for each child |
def intranges_contain(int_, ranges):
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
if pos > 0:
left, right = _decode_range(ranges[pos-1])
if left <= int_ < right:
return True
if pos < len(ranges):
left, _ = _decode_range(ranges[pos])
... | Determine if `int_` falls into one of the ranges in `ranges`. |
def stop(self, message):
self._stop = time.clock()
VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start))) | Manually stops timer with the message.
:param message: The display message. |
def _pipe(obj, func, *args, **kwargs):
if isinstance(func, tuple):
func, target = func
if target in kwargs:
msg = '%s is both the pipe target and a keyword argument' % target
raise ValueError(msg)
kwargs[target] = obj
return func(*args, **kwargs)
else:
... | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of... |
async def post(self):
post = (await self.region._get_messages(
fromid=self._post_id, limit=1))[0]
assert post.id == self._post_id
return post | Get the message lodged.
Returns
-------
an :class:`aionationstates.ApiQuery` of :class:`aionationstates.Post` |
def merge_dicts(*dicts, **kwargs):
result = {}
for d in dicts:
result.update(d)
result.update(kwargs)
return result | Merges dicts and kwargs into one dict |
def create_handler(cls, message_handler, buffer_size, logger):
cls.BUFFER_SIZE = buffer_size
cls.message_handler = message_handler
cls.logger = logger
cls.message_handler.logger = logging.getLogger(message_handler.__class__.__name__)
cls.message_handler.logger.setLevel(logger.lev... | Class variables used here since the framework creates an instance for each connection
:param message_handler: the MessageHandler used to process each message.
:param buffer_size: the TCP buffer size.
:param logger: the global logger.
:return: this class. |
def clip_by_value(x, min, max):
r
from .function_bases import maximum2 as maximum2_base
from .function_bases import minimum2 as minimum2_base
return minimum2_base(maximum2_base(x, min), max) | r"""Clip inputs by values.
.. math::
y = \begin{cases}
max & (x > max) \\
x & (otherwise) \\
min & (x < min)
\end{cases}.
Args:
x (Variable): An input variable.
min (Variable): A min variable by which `x` is clipped. Note tha... |
def _load_income_model(self):
self._add_model(self.income, self.state.income, IncomeModel) | Create income model from core income |
def fw_create(self, data, fw_name=None, cache=False):
LOG.debug("FW create %s", data)
try:
self._fw_create(fw_name, data, cache)
except Exception as exc:
LOG.error("Exception in fw_create %s", str(exc)) | Top level FW create function. |
def _parsePageToken(pageToken, numValues):
tokens = pageToken.split(":")
if len(tokens) != numValues:
msg = "Invalid number of values in page token"
raise exceptions.BadPageTokenException(msg)
try:
values = map(int, tokens)
except ValueError:
msg = "Malformed integers in ... | Parses the specified pageToken and returns a list of the specified
number of values. Page tokens are assumed to consist of a fixed
number of integers seperated by colons. If the page token does
not conform to this specification, raise a InvalidPageToken
exception. |
def combine_expression_columns(df, columns_to_combine, remove_combined=True):
df = df.copy()
for ca, cb in columns_to_combine:
df["%s_(x+y)/2_%s" % (ca, cb)] = (df[ca] + df[cb]) / 2
if remove_combined:
for ca, cb in columns_to_combine:
df.drop([ca, cb], inplace=True, axis=1)
... | Combine expression columns, calculating the mean for 2 columns
:param df: Pandas dataframe
:param columns_to_combine: A list of tuples containing the column names to combine
:return: |
def getTheta(k, nTrials=100000):
theDots = np.zeros(nTrials)
w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k)
for i in range(nTrials):
theDots[i] = w1[i].dot(w1[i])
dotMean = theDots.mean()
print("k=", k, "min/mean/max diag of w dot products",
theDots.min(), dotMean, theDots.max())
theta = ... | Estimate a reasonable value of theta for this k. |
def path(self, path):
self._path = self.manager.get_abs_image_path(path)
log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path)) | Path of the IOU executable.
:param path: path to the IOU image executable |
def from_config(cls, shelf, obj, **kwargs):
def subdict(d, keys):
new = {}
for k in keys:
if k in d:
new[k] = d[k]
return new
core_kwargs = subdict(obj, recipe_schema['schema'].keys())
core_kwargs = normalize_schema(recipe_s... | Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each RecipeExtension can extract and handle data from the
configura... |
def process_fasta(fasta, **kwargs):
logging.info("Nanoget: Starting to collect statistics from a fasta file.")
inputfasta = handle_compressed_input(fasta, file_type="fasta")
return ut.reduce_memory_usage(pd.DataFrame(
data=[len(rec) for rec in SeqIO.parse(inputfasta, "fasta")],
columns=["len... | Combine metrics extracted from a fasta file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.