code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def authority(self, column=None, value=None, **kwargs):
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) | Provides codes and associated authorizing statutes. |
def txn_storeAssociation(self, server_url, association):
a = association
self.db_set_assoc(
server_url,
a.handle,
self.blobEncode(a.secret),
a.issued,
a.lifetime,
a.assoc_type) | Set the association for the server URL.
Association -> NoneType |
def gram_schmidt(matrix, return_opt='orthonormal'):
r
if return_opt not in ('orthonormal', 'orthogonal', 'both'):
raise ValueError('Invalid return_opt, options are: "orthonormal", '
'"orthogonal" or "both"')
u = []
e = []
for vector in matrix:
if len(u) == 0:... | r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
Returns
-------
Lists of orthogonal vectors, u,... |
def numeric_part(s):
m = re_numeric_part.match(s)
if m:
return int(m.group(1))
return None | Returns the leading numeric part of a string.
>>> numeric_part("20-alpha")
20
>>> numeric_part("foo")
>>> numeric_part("16b")
16 |
def _validatePullParams(MaxObjectCount, context):
if (not isinstance(MaxObjectCount, six.integer_types) or
MaxObjectCount < 0):
raise ValueError(
_format("MaxObjectCount parameter must be integer >= 0 but is "
"{0!A}", MaxObjectCount))
if context is None or le... | Validate the input paramaters for the PullInstances,
PullInstancesWithPath, and PullInstancePaths requests.
MaxObjectCount: Must be integer type and ge 0
context: Must be not None and length ge 2 |
def is_vert_aligned_left(c):
return all(
[
_to_span(c[i]).sentence.is_visual()
and bbox_vert_aligned_left(
bbox_from_span(_to_span(c[i])), bbox_from_span(_to_span(c[0]))
)
for i in range(len(c))
]
) | Return true if all components are vertically aligned on their left border.
Vertical alignment means that the bounding boxes of each Mention of c
shares a similar x-axis value in the visual rendering of the document. In
this function the similarity of the x-axis value is based on the left
border of thei... |
def from_status(status, message=None, extra=None):
if status in HTTP_STATUS_CODES:
return HTTP_STATUS_CODES[status](message=message, extra=extra)
else:
return Error(
code=status, message=message if message else "Unknown Error",
extra=extra
) | Try to create an error from status code
:param int status: HTTP status
:param str message: Body content
:param dict extra: Additional info
:return: An error
:rtype: cdumay_rest_client.errors.Error |
def _get_acronyms(acronyms):
acronyms_str = {}
if acronyms:
for acronym, expansions in iteritems(acronyms):
expansions_str = ", ".join(["%s (%d)" % expansion
for expansion in expansions])
acronyms_str[acronym] = expansions_str
return [{... | Return a formatted list of acronyms. |
def add(self, data, id='*', maxlen=None, approximate=True):
return self.database.xadd(self.key, data, id, maxlen, approximate) | Add data to a stream.
:param dict data: data to add to stream
:param id: identifier for message ('*' to automatically append)
:param maxlen: maximum length for stream
:param approximate: allow stream max length to be approximate
:returns: the added message id. |
def find_peaks(signal):
derivative = np.gradient(signal, 2)
peaks = np.where(np.diff(np.sign(derivative)))[0]
return(peaks) | Locate peaks based on derivative.
Parameters
----------
signal : list or array
Signal.
Returns
----------
peaks : array
An array containing the peak indices.
Example
----------
>>> signal = np.sin(np.arange(0, np.pi*10, 0.05))
>>> peaks = nk.find_peaks(signal)
... |
def azimuth(lons1, lats1, lons2, lats2):
lons1, lats1, lons2, lats2 = _prepare_coords(lons1, lats1, lons2, lats2)
cos_lat2 = numpy.cos(lats2)
true_course = numpy.degrees(numpy.arctan2(
numpy.sin(lons1 - lons2) * cos_lat2,
numpy.cos(lats1) * numpy.sin(lats2)
- numpy.sin(lats1) * cos_l... | Calculate the azimuth between two points or two collections of points.
Parameters are the same as for :func:`geodetic_distance`.
Implements an "alternative formula" from
http://williams.best.vwh.net/avform.htm#Crs
:returns:
Azimuth as an angle between direction to north from first point and
... |
def cpp_prog_builder(build_context, target):
yprint(build_context.conf, 'Build CppProg', target)
workspace_dir = build_context.get_workspace('CppProg', target.name)
build_cpp(build_context, target, target.compiler_config, workspace_dir) | Build a C++ binary executable |
def regulatory_program(self, column=None, value=None, **kwargs):
return self._resolve_call('RAD_REGULATORY_PROG', column,
value, **kwargs) | Identifies the regulatory authority governing a facility, and, by
virtue of that identification, also identifies the regulatory program
of interest and the type of facility.
>>> RADInfo().regulatory_program('sec_cit_ref_flag', 'N') |
def is_coord_subset(subset, superset, atol=1e-8):
c1 = np.array(subset)
c2 = np.array(superset)
is_close = np.all(np.abs(c1[:, None, :] - c2[None, :, :]) < atol, axis=-1)
any_close = np.any(is_close, axis=-1)
return np.all(any_close) | Tests if all coords in subset are contained in superset.
Doesn't use periodic boundary conditions
Args:
subset, superset: List of coords
Returns:
True if all of subset is in superset. |
def get_api_endpoints(self, apiname):
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API endpoints") | Returns the API endpoints |
def double_click(self, on_element=None):
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.double_click()
for _ in range(4):
self.w3c_actions.key_action.pause()
else:
self._actions.... | Double-clicks an element.
:Args:
- on_element: The element to double-click.
If None, clicks on current mouse position. |
def arg_props(self):
d = dict(zip([str(e).lower() for e in self.section.property_names], self.args))
d[self.term_value_name.lower()] = self.value
return d | Return the value and scalar properties as a dictionary. Returns only argumnet properties,
properties declared on the same row as a term. It will return an entry for all of the args declared by the
term's section. Use props to get values of all children and
arg props combined |
def add_to_group(self, group_path):
if self.get_group_path() != group_path:
post_data = ADD_GROUP_TEMPLATE.format(connectware_id=self.get_connectware_id(),
group_path=group_path)
self._conn.put('/ws/DeviceCore', post_data)
sel... | Add a device to a group, if the group doesn't exist it is created
:param group_path: Path or "name" of the group |
def once(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not hasattr(wrapper, 'saved_result'):
wrapper.saved_result = func(*args, **kwargs)
return wrapper.saved_result
wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')
return wrapper | Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To reset the stored valu... |
def getFasta(opened_file, sequence_name):
lines = opened_file.readlines()
seq=str("")
for i in range(0, len(lines)):
line = lines[i]
if line[0] == ">":
fChr=line.split(" ")[0].split("\n")[0]
fChr=fChr[1:]
if fChr == sequence_name:
s=i
... | Retrieves a sequence from an opened multifasta file
:param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+')
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2)
returns... |
def strip_caret_codes(text):
text = text.replace('^^', '\x00')
for token, foo in _ANSI_CODES:
text = text.replace(token, '')
return text.replace('\x00', '^') | Strip out any caret codes from a string. |
def set_parent(self, child, parent):
parents = cmds.listConnections("%s.parent" % child, plugs=True, source=True)
if parents:
cmds.disconnectAttr("%s.parent" % child, "%s" % parents[0])
if parent:
cmds.connectAttr("%s.parent" % child, "%s.children" % parent, force=True, n... | Set the parent of the child reftrack node
:param child: the child reftrack node
:type child: str
:param parent: the parent reftrack node
:type parent: str
:returns: None
:rtype: None
:raises: None |
def fromtree(cls, tree):
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets | Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from. |
def execute_contract_creation(
laser_evm, contract_initialization_code, contract_name=None
) -> Account:
open_states = laser_evm.open_states[:]
del laser_evm.open_states[:]
new_account = laser_evm.world_state.create_account(
0, concrete_storage=True, dynamic_loader=None, creator=CREATOR_ADDRESS
... | Executes a contract creation transaction from all open states.
:param laser_evm:
:param contract_initialization_code:
:param contract_name:
:return: |
def opponent_rank(self):
rank = re.findall(r'\d+', self._opponent_name)
if len(rank) > 0:
return int(rank[0])
return None | Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked. |
def transform(self, sequences):
check_iter_of_sequences(sequences)
transforms = []
for X in sequences:
transforms.append(self.partial_transform(X))
return transforms | Apply dimensionality reduction to sequences
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Sequence data to transform, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
... |
def time_from_number(self, value):
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
minutes, second = divmod(delta.seconds, 60)
hour, minute = divmod(minutes, 60)
return datetime.time(hour, minute, second) | Converts a float value to corresponding time instance. |
def frames(skip=1):
from PyQt4 import QtGui
for i in range(0, viewer.traj_controls.max_index, skip):
viewer.traj_controls.goto_frame(i)
yield i
QtGui.qApp.processEvents() | Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame. |
def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str(password,
opslimit,
memlimit) | Hashes a password with a random salt, using the memory-hard
scryptsalsa208sha256 construct and returning an ascii string
that has all the needed info to check against a future password
The default settings for opslimit and memlimit are those deemed
correct for the interactive user login case.
:par... |
def pop(self, strip=False):
r = self.contents()
self.clear()
if r and strip:
r = r.strip()
return r | Current content popped, useful for testing |
def access_token(self):
access_token = self.get_auth_bearer()
if not access_token:
access_token = self.query_kwargs.get('access_token', '')
if not access_token:
access_token = self.body_kwargs.get('access_token', '')
return access_token | return an Oauth 2.0 Bearer access token if it can be found |
def to_json(self, obj, host=None, indent=None):
if indent:
return json.dumps(deep_map(lambda o: self.encode(o, host), obj),
indent=indent)
else:
return json.dumps(deep_map(lambda o: self.encode(o, host), obj)) | Recursively encode `obj` and convert it to a JSON string.
:param obj:
Object to encode.
:param host:
hostname where this object is being encoded.
:type host: str |
def get(key, value=None, conf_file=_DEFAULT_CONF):
current_conf = _parse_conf(conf_file)
stanza = current_conf.get(key, False)
if value:
if stanza:
return stanza.get(value, False)
_LOG.warning("Block '%s' not present or empty.", key)
return stanza | Get the value for a specific configuration line.
:param str key: The command or stanza block to configure.
:param str value: The command value or command of the block specified by the key parameter.
:param str conf_file: The logrotate configuration file.
:return: The value for a specific configuration... |
def update_kwargs(self, request, **kwargs):
if not 'base' in kwargs:
kwargs['base'] = self.base
if request.is_ajax() or request.GET.get('json'):
kwargs['base'] = self.partial_base
return kwargs | Hook for adding data to the context before
rendering a template.
:param kwargs: The current context keyword arguments.
:param request: The current request object. |
def _bin_zfill(num, width=None):
s = bin(num)[2:]
return s if width is None else s.zfill(width) | Convert a base-10 number to a binary string.
Parameters
num: int
width: int, optional
Zero-extend the string to this width.
Examples
--------
>>> _bin_zfill(42)
'101010'
>>> _bin_zfill(42, 8)
'00101010' |
def lookup_online(byte_sig: str, timeout: int, proxies=None) -> List[str]:
if not ethereum_input_decoder:
return []
return list(
ethereum_input_decoder.decoder.FourByteDirectory.lookup_signatures(
byte_sig, timeout=timeout, proxies=proxies
)
) | Lookup function signatures from 4byte.directory.
:param byte_sig: function signature hash as hexstr
:param timeout: optional timeout for online lookup
:param proxies: optional proxy servers for online lookup
:return: a list of matching function signatures for this hash |
def _short_chrom(self, chrom):
default_allowed = set(["X"])
allowed_chroms = set(getattr(config, "goleft_indexcov_config", {}).get("chromosomes", []))
chrom_clean = chrom.replace("chr", "")
try:
chrom_clean = int(chrom_clean)
except ValueError:
if chrom_cl... | Plot standard chromosomes + X, sorted numerically.
Allows specification from a list of chromosomes via config
for non-standard genomes. |
def addChildFn(self, fn, *args, **kwargs):
if PromisedRequirement.convertPromises(kwargs):
return self.addChild(PromisedRequirementFunctionWrappingJob.create(fn, *args, **kwargs))
else:
return self.addChild(FunctionWrappingJob(fn, *args, **kwargs)) | Adds a function as a child job.
:param fn: Function to be run as a child job with ``*args`` and ``**kwargs`` as \
arguments to this function. See toil.job.FunctionWrappingJob for reserved \
keyword arguments used to specify resource requirements.
:return: The new child job that wraps fn... |
def __set_authoring_nodes(self, source, target):
editor = self.__script_editor.get_editor(source)
editor.set_file(target)
self.__script_editor.model.update_authoring_nodes(editor) | Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode |
def find_orphans(model):
exchange = frozenset(model.exchanges)
return [
met for met in model.metabolites
if (len(met.reactions) > 0) and all(
(not rxn.reversibility) and (rxn not in exchange) and
(rxn.metabolites[met] < 0) for rxn in met.reactions
)
] | Return metabolites that are only consumed in reactions.
Metabolites that are involved in an exchange reaction are never
considered to be orphaned.
Parameters
----------
model : cobra.Model
The metabolic model under investigation. |
def _GetUtf8Contents(self, file_name):
contents = self._FileContents(file_name)
if not contents:
return
if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,
codecs.BOM_UTF16_LE):
self._problems.FileFormat("appears to be encoded in utf-16", (file_name, ))
contents = code... | Check for errors in file_name and return a string for csv reader. |
def read_cBpack(filename):
with gzip.open(filename, 'rb') as infile:
data = msgpack.load(infile, raw=False)
header = data[0]
if (
not isinstance(header, dict) or header.get('format') != 'cB'
or header.get('version') != 1
):
raise ValueError("Unexpected header: %r" % heade... | Read a file from an idiosyncratic format that we use for storing
approximate word frequencies, called "cBpack".
The cBpack format is as follows:
- The file on disk is a gzipped file in msgpack format, which decodes to a
list whose first element is a header, and whose remaining elements are
lis... |
def archive(cwd, output, rev='tip', fmt=None, prefix=None, user=None):
cmd = [
'hg',
'archive',
'{0}'.format(output),
'--rev',
'{0}'.format(rev),
]
if fmt:
cmd.append('--type')
cmd.append('{0}'.format(fmt))
if prefix:
... | Export a tarball from the repository
cwd
The path to the Mercurial repository
output
The path to the archive tarball
rev: tip
The revision to create an archive from
fmt: None
Format of the resulting archive. Mercurial supports: tar,
tbz2, tgz, zip, uzip, and f... |
def no_retry_on_failure(handler):
seen_request_ids = set()
@wraps(handler)
def wrapper(event, context):
if context.aws_request_id in seen_request_ids:
logger.critical('Retry attempt on request id %s detected.',
context.aws_request_id)
return {'stat... | AWS Lambda retries scheduled lambdas that don't execute succesfully.
This detects this by storing requests IDs in memory and exiting early on
duplicates. Since this is in memory, don't use it on very frequently
scheduled lambdas. It logs a critical message then exits with a statusCode
of 200 to avoid f... |
def merge_dicts(target_dict: dict, merge_dict: dict) -> dict:
log.debug("merging dict %s into %s", merge_dict, target_dict)
for key, value in merge_dict.items():
if key not in target_dict:
target_dict[key] = value
return target_dict | Merges ``merge_dict`` into ``target_dict`` if the latter does not already contain a value for each of the key
names in ``merge_dict``. Used to cleanly merge default and environ data into notification payload.
:param target_dict: The target dict to merge into and return, the user provided data for example
:... |
def intr_read(self, dev_handle, ep, intf, size, timeout):
r
_not_implemented(self.intr_read) | r"""Perform an interrut read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
... |
def _load_configuration():
config = configparser.RawConfigParser()
module_dir = os.path.dirname(sys.modules[__name__].__file__)
if 'APPDATA' in os.environ:
os_config_path = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ:
os_config_path = os.environ['XDG_CONFIG_HOME']
elif... | Attempt to load settings from various praw.ini files. |
def set_pair(self, term1, term2, value, **kwargs):
key = self.key(term1, term2)
self.keys.update([term1, term2])
self.pairs[key] = value | Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed) |
def scramble_codelist(self, codelist):
path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)
elem = self.metadata.find(path)
codes = []
for c in elem.iter(E_ODM.CODELIST_ITEM.value):
codes.append(c.get(A_ODM.CODED_VALUE.value))
for c in e... | Return random element from code list |
def _correctArtefacts(self, image, threshold):
image = np.nan_to_num(image)
medianThreshold(image, threshold, copy=False)
return image | Apply a thresholded median replacing high gradients
and values beyond the boundaries |
def _infer_sequence_helper(node, context=None):
values = []
for elt in node.elts:
if isinstance(elt, nodes.Starred):
starred = helpers.safe_infer(elt.value, context)
if not starred:
raise exceptions.InferenceError(node=node, context=context)
if not has... | Infer all values based on _BaseContainer.elts |
def do_denyrep(self, line):
self._split_args(line, 0, 0)
self._command_processor.get_session().get_replication_policy().set_replication_allowed(
False
)
self._print_info_if_verbose("Set replication policy to deny replication") | denyrep Prevent new objects from being replicated. |
def tx(self, *args, **kwargs):
if 0 == len(args): return TX(self)
ops = []
for op in args:
if isinstance(op, list): ops += op
elif isinstance(op, (str,unicode)): ops.append(op)
if 'debug' in kwargs: pp(ops)
tx_proc ="[ %s ]" % "".join(ops)
x = self.rest('POST', self.uri_d... | Executes a raw tx string, or get a new TX object to work with.
Passing a raw string or list of strings will immedately transact
and return the API response as a dict.
>>> resp = tx('{:db/id #db/id[:db.part/user] :person/name "Bob"}')
{db-before: db-after: tempids: }
This gets a fresh `TX()` to pr... |
def parse(self, buf):
self._tokenizer = tokenize_asdl(buf)
self._advance()
return self._parse_module() | Parse the ASDL in the buffer and return an AST with a Module root. |
def f_ac_power(inverter, v_mp, p_mp):
return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter).flatten() | Calculate AC power
:param inverter:
:param v_mp:
:param p_mp:
:return: AC power [W] |
def _set_advertising_data(self, packet_type, data):
payload = struct.pack("<BB%ss" % (len(data)), packet_type, len(data), bytes(data))
response = self._send_command(6, 9, payload)
result, = unpack("<H", response.payload)
if result != 0:
return False, {'reason': 'Error code fr... | Set the advertising data for advertisements sent out by this bled112
Args:
packet_type (int): 0 for advertisement, 1 for scan response
data (bytearray): the data to set |
def add_checkpoint(html_note, counter):
if html_note.text:
html_note.text = (html_note.text + CHECKPOINT_PREFIX +
str(counter) + CHECKPOINT_SUFFIX)
else:
html_note.text = (CHECKPOINT_PREFIX + str(counter) +
CHECKPOINT_SUFFIX)
counter += 1
... | Recursively adds checkpoints to html tree. |
async def _run_socket(self):
try:
while True:
message = await ZMQUtils.recv(self._socket)
msg_class = message.__msgtype__
if msg_class in self._handlers_registered:
self._loop.create_task(self._handlers_registered[msg_class](message... | Task that runs this client. |
def read_csv(filepath):
symbols = []
with open(filepath, 'rb') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
for row in spamreader:
symbols.append(row)
return symbols | Read a CSV into a list of dictionarys. The first line of the CSV determines
the keys of the dictionary.
Parameters
----------
filepath : string
Returns
-------
list of dictionaries |
def vim_enter(self, filename):
success = self.setup(True, False)
if success:
self.editor.message("start_message") | Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible. |
def route(cls, path):
if not path.startswith('/'):
raise ValueError('Routes must start with "/"')
def wrap(fn):
setattr(fn, cls.ROUTE_ATTRIBUTE, path)
return fn
return wrap | A decorator to indicate that a method should be a routable HTTP endpoint.
.. code-block:: python
from compactor.process import Process
class WebProcess(Process):
@Process.route('/hello/world')
def hello_world(self, handler):
return handler.write('<html><title>hello... |
def ts_stream_keys(self, table, timeout=None):
if not riak.disable_list_exceptions:
raise ListError()
t = table
if isinstance(t, six.string_types):
t = Table(self, table)
_validate_timeout(timeout)
resource = self._acquire()
transport = resource.ob... | Lists all keys in a time series table via a stream. This is a
generator method which should be iterated over.
The caller should explicitly close the returned iterator,
either using :func:`contextlib.closing` or calling ``close()``
explicitly. Consuming the entire iterator will also clos... |
def inputfiles(self, inputtemplate=None):
if isinstance(inputtemplate, InputTemplate):
inputtemplate = inputtemplate.id
for inputfile in self.input:
if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate:
yield inputfile | Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate. |
def get_methods(extension_name):
extension = get_extension(extension_name)
methods = {}
for name, i in inspect.getmembers(extension):
if hasattr(i, 'nago_access'):
api_name = i.nago_name
methods[api_name] = i
return methods | Return all methods in extension that have nago_access set |
def process_polychord_run(file_root, base_dir, process_stats_file=True,
**kwargs):
samples = np.loadtxt(os.path.join(base_dir, file_root) + '_dead-birth.txt')
ns_run = process_samples_array(samples, **kwargs)
ns_run['output'] = {'base_dir': base_dir, 'file_root': file_root}
if ... | Loads data from a PolyChord run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requies PolyChord version v1.13 or later and the setting
write_de... |
def get_many_to_many_lines(self, force=False):
lines = []
for field, rel_items in self.many_to_many_waiting_list.items():
for rel_item in list(rel_items):
try:
pk_name = rel_item._meta.pk.name
key = '%s_%s' % (rel_item.__class__.__name_... | Generate lines that define many to many relations for this instance. |
def _notify(self, task, message):
if self.notify_func:
message = common.to_utf8(message.strip())
title = common.to_utf8(u'Focus ({0})'.format(task.name))
self.notify_func(title, message) | Shows system notification message according to system requirements.
`message`
Status message. |
def get_path_directories():
pth = os.environ['PATH']
if sys.platform == 'win32' and os.environ.get("BASH"):
if pth[1] == ';':
pth = pth.replace(';', ':', 1)
return [p.strip() for p in pth.split(os.pathsep) if p.strip()] | Return a list of all the directories on the path. |
def __get_service_from_factory(self, bundle, reference):
try:
factory, svc_reg = self.__svc_factories[reference]
imports = self.__bundle_imports.setdefault(bundle, {})
if reference not in imports:
usage_counter = _UsageCounter()
usage_counter.i... | Returns a service instance from a service factory or a prototype
service factory
:param bundle: The bundle requiring the service
:param reference: A reference pointing to a factory
:return: The requested service
:raise BundleException: The service could not be found |
def transpose(self, name=None):
if name is None:
name = self.module_name + "_transpose"
if self._data_format == DATA_FORMAT_NWC:
stride = self._stride[1:-1]
else:
stride = self._stride[2:]
return Conv1D(output_channels=lambda: self.input_channels,
kernel_shape=self.ke... | Returns matching `Conv1D` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.name`.
Returns:
`Conv1D` module. |
def workflows(self):
if self._workflows is None:
self._workflows = WorkflowList(self._version, workspace_sid=self._solution['sid'], )
return self._workflows | Access the workflows
:returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList |
def get_resultsets(self, routine, *args):
(query, replacements) = self.__build_raw_query(routine, args)
connection = mm.db.ENGINE.raw_connection()
sets = []
try:
cursor = connection.cursor()
cursor.execute(query, replacements)
while 1:
... | Return a list of lists of dictionaries, for when a query returns
more than one resultset. |
def get_last_commit_to_master(repo_path="."):
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
last_... | returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient. |
def remove_showcase(self, showcase):
dataset_showcase = self._get_dataset_showcase_dict(showcase)
showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration)
showcase._write_to_hdx('disassociate', dataset_showcase, 'package_id') | Remove dataset from showcase
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary
Returns:
None |
def _update(self, data):
self.orderby = data['orderby']
self.revision = data['revisionid']
self.title = data['title']
self.lines = [Line(self.guideid, self.stepid, line['lineid'], data=line)
for line in data['lines']]
if data['media']['type'] == 'image':
self.m... | Update the step using the blob of json-parsed data directly from the
API. |
def get_hosted_zones_by_domain(Name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
zones = [z for z in _collect_results(conn.list_hosted_zones, 'HostedZones', {})
if z['Name'] == aws_encode(Name)]
ret = []
for z in zo... | Find any zones with the given domain name and return detailed info about them.
Note that this can return multiple Route53 zones, since a domain name can be used in
both public and private zones.
Name
The domain name associated with the Hosted Zone(s).
region
Region to connect to.
... |
def _ssh_build_mic(self, session_id, username, service, auth_method):
mic = self._make_uint32(len(session_id))
mic += session_id
mic += struct.pack("B", MSG_USERAUTH_REQUEST)
mic += self._make_uint32(len(username))
mic += username.encode()
mic += self._make_uint32(len(ser... | Create the SSH2 MIC filed for gssapi-with-mic.
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:param str service: The requested SSH service
:param str auth_method: The requested SSH authentication mechanism
:return: The ... |
def remove(obj, kind):
if not obj.get_badge(kind):
api.abort(404, 'Badge does not exists')
obj.remove_badge(kind)
return '', 204 | Handle badge removal API
- Returns 404 if the badge for this kind is absent
- Returns 204 on success |
def __getDataFromURL(url):
code = 0
while code != 200:
req = Request(url)
try:
response = urlopen(req)
code = response.code
sleep(0.01)
except HTTPError as error:
code = error.code
if code... | Read HTML data from an user GitHub profile.
:param url: URL of the webpage to download.
:type url: str.
:return: webpage donwloaded.
:rtype: str. |
def new(cls, variable, **kwargs):
return cls.array2mask(numpy.full(variable.shape, True)) | Return a new |DefaultMask| object associated with the
given |Variable| object. |
def search_product(self, limit=100, offset=0, with_price=0, with_supported_software=0,
with_description=0):
response = self.request(E.searchProductSslCertRequest(
E.limit(limit),
E.offset(offset),
E.withPrice(int(with_price)),
E.withSupporte... | Search the list of available products. |
def _api_scrape(json_inp, ndx):
try:
headers = json_inp['resultSets'][ndx]['headers']
values = json_inp['resultSets'][ndx]['rowSet']
except KeyError:
try:
headers = json_inp['resultSet'][ndx]['headers']
values = json_inp['resultSet'][ndx]['rowSet']
except ... | Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): data set from ndx within the
API'... |
def from_string(self, repo, name, string):
try:
log.debug('Creating new item: %s' % name)
blob = Blob.from_string(string)
item = Item(parent=repo, sha=blob.sha, path=name)
item.blob = blob
return item
except AssertionError, e:
raise... | Create a new Item from a data stream.
:param repo: Repo object.
:param name: Name of item.
:param data: Data stream.
:return: New Item class instance. |
def sql(self, query):
limited_query = 'SELECT * FROM ({}) t0 LIMIT 0'.format(query)
schema = self._get_schema_using_query(limited_query)
return ops.SQLQueryResult(query, schema, self).to_expr() | Convert a SQL query to an Ibis table expression
Parameters
----------
Returns
-------
table : TableExpr |
def _audio_response_for_run(self, tensor_events, run, tag, sample):
response = []
index = 0
filtered_events = self._filter_by_sample(tensor_events, sample)
content_type = self._get_mime_type(run, tag)
for (index, tensor_event) in enumerate(filtered_events):
data = tensor_util.make_ndarray(tens... | Builds a JSON-serializable object with information about audio.
Args:
tensor_events: A list of image event_accumulator.TensorEvent objects.
run: The name of the run.
tag: The name of the tag the audio entries all belong to.
sample: The zero-indexed sample of the audio sample for which to
... |
def jd_to_struct_time(jd):
year, month, day = jdutil.jd_to_date(jd)
day_fraction = day - int(day)
hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction)
day = int(day)
year, month, day, hour, minute, second = _roll_negative_time_fields(
year, month, day, hour, minute, second)
retur... | Return a `struct_time` converted from a Julian Date float number.
WARNING: Conversion to then from Julian Date value to `struct_time` can be
inaccurate and lose or gain time, especially for BC (negative) years.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are set to default
values, not real... |
def fix_symbol(self, symbol, reverse=False):
if not self.symbol_mapping:
return symbol
for old, new in self.symbol_mapping:
if reverse:
if symbol == new:
return old
else:
if symbol == old:
return ... | In comes a moneywagon format symbol, and returned in the symbol converted
to one the service can understand. |
def fpopen(*args, **kwargs):
uid = kwargs.pop('uid', -1)
gid = kwargs.pop('gid', -1)
mode = kwargs.pop('mode', None)
with fopen(*args, **kwargs) as f_handle:
path = args[0]
d_stat = os.stat(path)
if hasattr(os, 'chown'):
if (d_stat.st_uid != uid or d_stat.st_gid != gi... | Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes... |
def is_subdirectory(path_a, path_b):
path_a = os.path.realpath(path_a)
path_b = os.path.realpath(path_b)
relative = os.path.relpath(path_a, path_b)
return (not relative.startswith(os.pardir + os.sep)) | Returns True if `path_a` is a subdirectory of `path_b`. |
def list_installed():
cmd = 'Get-WindowsFeature ' \
'-ErrorAction SilentlyContinue ' \
'-WarningAction SilentlyContinue ' \
'| Select DisplayName,Name,Installed'
features = _pshell_json(cmd)
ret = {}
for entry in features:
if entry['Installed']:
ret[entr... | List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed |
def gather_registries() -> Tuple[Dict, Mapping, Mapping]:
id2devices = copy.copy(_id2devices)
registry = copy.copy(_registry)
selection = copy.copy(_selection)
dict_ = globals()
dict_['_id2devices'] = {}
dict_['_registry'] = {Node: {}, Element: {}}
dict_['_selection'] = {Node: {}, Element: {... | Get and clear the current |Node| and |Element| registries.
Function |gather_registries| is thought to be used by class |Tester| only. |
def export_image_to_uri(self, image_id, uri, ibm_api_key=None):
if 'cos://' in uri:
return self.vgbdtg.copyToIcos({
'uri': uri,
'ibmApiKey': ibm_api_key
}, id=image_id)
else:
return self.vgbdtg.copyToExternalSource({'uri': uri}, id=imag... | Export image into the given object storage
:param int image_id: The ID of the image
:param string uri: The URI for object storage of the format
swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>
or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud
... |
def libvlc_media_player_get_state(p_mi):
f = _Cfunctions.get('libvlc_media_player_get_state', None) or \
_Cfunction('libvlc_media_player_get_state', ((1,),), None,
State, MediaPlayer)
return f(p_mi) | Get current movie state.
@param p_mi: the Media Player.
@return: the current state of the media player (playing, paused, ...) See libvlc_state_t. |
async def _get_usage_data(self):
raw_res = await self._session.get(USAGE_URL)
content = await raw_res.text()
soup = BeautifulSoup(content, 'html.parser')
span_list = soup.find_all("span", {"class": "switchDisplay"})
if span_list is None:
raise PyEboxError("Can not get... | Get data usage. |
def command(*args, **kwargs):
def decorator(f):
if 'description' not in kwargs:
kwargs['description'] = f.__doc__
if 'parents' in kwargs:
if not hasattr(f, '_argnames'):
f._argnames = []
for p in kwargs['parents']:
f._argnames += p.... | Decorator to define a command.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
object constructor. |
def get_cache_key(bucket, name, args, kwargs):
u = ''.join(map(str, (bucket, name, args, kwargs)))
return 'native_tags.%s' % sha_constructor(u).hexdigest() | Gets a unique SHA1 cache key for any call to a native tag.
Use args and kwargs in hash so that the same arguments use the same key |
def update_metadata(self, resource, keys_vals):
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.update(resource, keys_vals) | Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
... |
def _get_flaky_attributes(cls, test_item):
return {
attr: cls._get_flaky_attribute(
test_item,
attr,
) for attr in FlakyNames()
} | Get all the flaky related attributes from the test.
:param test_item:
The test callable from which to get the flaky related attributes.
:type test_item:
`callable` or :class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`dict` of `unicode` to... |
def verify_day(self, now):
return self.day == "*" or str(now.day) in self.day.split(" ") | Verify the day |
def GetLastKey(self, voice=1):
voice_obj = self.GetChild(voice)
if voice_obj is not None:
key = BackwardSearch(KeyNode, voice_obj, 1)
if key is not None:
return key
else:
if hasattr(self, "key"):
return self.key
... | key as in musical key, not index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.