code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
async def open_async(self):
if not self.loop:
self.loop = asyncio.get_event_loop()
await self.partition_manager.start_async() | Starts the host. |
def match_patterns(pathname, patterns):
for pattern in patterns:
if fnmatch(pathname, pattern):
return True
return False | Returns ``True`` if the pathname matches any of the given patterns. |
def box_filter(array, n_iqr=1.5, return_index=False):
if not isinstance(array, np.ndarray):
array = np.array(array)
Q3 = np.percentile(array, 75)
Q1 = np.percentile(array, 25)
IQR = Q3 - Q1
lower, upper = Q1 - n_iqr * IQR, Q3 + n_iqr * IQR
good_index = np.where(np.logical_and(array >= lo... | Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index. |
def cycle_class(self):
if isinstance(self, RelaxTask):
return abiinspect.Relaxation
elif isinstance(self, GsTask):
return abiinspect.GroundStateScfCycle
elif self.is_dfpt_task:
return abiinspect.D2DEScfCycle
return None | Return the subclass of ScfCycle associated to the task or
None if no SCF algorithm if associated to the task. |
def verify_arguments(self, args=None, kwargs=None):
args = self.args if args is None else args
kwargs = self.kwargs if kwargs is None else kwargs
try:
verify_arguments(self._target, self._method_name, args, kwargs)
except VerifyingBuiltinDoubleArgumentError:
if do... | Ensures that the arguments specified match the signature of the real method.
:raise: ``VerifyingDoubleError`` if the arguments do not match. |
def add_port(self, port):
self.ports.append(port)
if port.io_type not in self.port_seqs:
self.port_seqs[port.io_type] = 0
self.port_seqs[port.io_type] += 1
port.sequence = self.port_seqs[port.io_type]
return self | Add a port object to the definition
:param port: port definition
:type port: PortDef |
def parse(self, charset=None, headers=None):
if headers:
self.headers = headers
else:
if self.head:
responses = self.head.rsplit(b'\nHTTP/', 1)
_, response = responses[-1].split(b'\n', 1)
response = response.decode('utf-8', 'ignore'... | Parse headers.
This method is called after Grab instance performs network request. |
def flaky(max_runs=None, min_passes=None, rerun_filter=None):
wrapped = None
if hasattr(max_runs, '__call__'):
wrapped, max_runs = max_runs, None
attrib = default_flaky_attributes(max_runs, min_passes, rerun_filter)
def wrapper(wrapped_object):
for name, value in attrib.items():
... | Decorator used to mark a test as "flaky". When used in conjuction with
the flaky nosetests plugin, will cause the decorated test to be retried
until min_passes successes are achieved out of up to max_runs test runs.
:param max_runs:
The maximum number of times the decorated test will be run.
:t... |
def download_remote_video(self, remote_node, session_id, video_name):
try:
video_url = self._get_remote_video_url(remote_node, session_id)
except requests.exceptions.ConnectionError:
self.logger.warning("Remote server seems not to have video capabilities")
return
... | Download the video recorded in the remote node during the specified test session and save it in videos folder
:param remote_node: remote node name
:param session_id: test session id
:param video_name: video name |
def component_mul(vec1, vec2):
new_vec = Vector2()
new_vec.X = vec1.X * vec2.X
new_vec.Y = vec1.Y * vec2.Y
return new_vec | Multiply the components of the vectors and return the result. |
def create(klass, account, name):
audience = klass(account)
getattr(audience, '__create_audience__')(name)
try:
return audience.reload()
except BadRequest as e:
audience.delete()
raise e | Creates a new tailored audience. |
def unmount(self, path):
del self._mountpoints[self._join_chunks(self._normalize_path(path))] | Remove a mountpoint from the filesystem. |
def fulfill(self):
is_fulfilled, result = self._check_fulfilled()
if is_fulfilled:
return result
else:
raise BrokenPromise(self) | Evaluate the promise and return the result.
Returns:
The result of the `Promise` (second return value from the `check_func`)
Raises:
BrokenPromise: the `Promise` was not satisfied within the time or attempt limits. |
def passive_mode(self) -> Tuple[str, int]:
yield from self._control_stream.write_command(Command('PASV'))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Passive mode', ReplyCodes.entering_passive_mode, reply)
try:
return wpull.proto... | Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine. |
def add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) | Expired in seconds |
def flip(f):
def wrapped(*args, **kwargs):
return f(*flip_first_two(args), **kwargs)
f_spec = make_func_curry_spec(f)
return curry_by_spec(f_spec, wrapped) | Calls the function f by flipping the first two positional
arguments |
def unique(self, key=None):
if isinstance(key, basestring):
key = lambda r, attr=key: getattr(r, attr, None)
ret = self.copy_template()
seen = set()
for ob in self:
if key is None:
try:
ob_dict = vars(ob)
except ... | Create a new table of objects,containing no duplicate values.
@param key: (default=None) optional callable for computing a representative unique key for each
object in the table. If None, then a key will be composed as a tuple of all the values in the object.
@type key: callable, takes the reco... |
def _set_expressions(self, expressions):
Symbolic_core._set_expressions(self, expressions)
Symbolic_core._set_variables(self, self.cacheable)
for x, z in zip(self.variables['X'], self.variables['Z']):
expressions['kdiag'] = expressions['kdiag'].subs(z, x)
Symbolic_core._set_e... | This method is overwritten because we need to modify kdiag by substituting z for x. We do this by calling the parent expression method to extract variables from expressions, then subsitute the z variables that are present with x. |
def get(self, indexes, as_list=False):
if isinstance(indexes, (list, blist)):
return self.get_rows(indexes, as_list)
else:
return self.get_cell(indexes) | Given indexes will return a sub-set of the Series. This method will direct to the specific methods
based on what types are passed in for the indexes. The type of the return is determined by the
types of the parameters.
:param indexes: index value, list of index values, or a list of booleans.
... |
def ecoclass_to_coderef(self, cls):
code = ''
ref = None
for (code,ref,this_cls) in self.mappings():
if cls == this_cls:
return code, ref
return None, None | Map an ECO class to a GAF code
This is the reciprocal to :ref:`coderef_to_ecoclass`
Arguments
---------
cls : str
GAF evidence code, e.g. ISS, IDA
reference: str
ECO class CURIE/ID
Return
------
(str, str)
code, refer... |
def build(matrix):
max_x = max(matrix, key=lambda t: t[0])[0]
min_x = min(matrix, key=lambda t: t[0])[0]
max_y = max(matrix, key=lambda t: t[1])[1]
min_y = min(matrix, key=lambda t: t[1])[1]
yield from (
''.join(matrix[i, j] for i in range(min_x, max_x+1))
for j in range(min_y, max_y... | Yield lines generated from given matrix |
def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':
return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes) | This is an alias for 'dataframe2sasdata'. Why type all that?
:param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigne... |
def to_array(self):
array = super(ShippingAddress, self).to_array()
array['country_code'] = u(self.country_code)
array['state'] = u(self.state)
array['city'] = u(self.city)
array['street_line1'] = u(self.street_line1)
array['street_line2'] = u(self.street_line2)
a... | Serializes this ShippingAddress to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def audits(self, ticket=None, include=None, **kwargs):
if ticket is not None:
return self._query_zendesk(self.endpoint.audits, 'ticket_audit', id=ticket, include=include)
else:
return self._query_zendesk(self.endpoint.audits.cursor, 'ticket_audit', include=include, **kwargs) | Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit.
If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator
works is a different to the other Zenpy generators as it is cursor based, allowing you to change the
directi... |
def _get_mu_tensor(self):
root = self._get_cubic_root()
dr = self._h_max / self._h_min
mu = tf.maximum(
root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)
return mu | Get the min mu which minimize the surrogate.
Returns:
The mu_t. |
def timestamp_from_datetime(dt):
try:
utc_dt = dt.astimezone(pytz.utc)
except ValueError:
utc_dt = dt.replace(tzinfo=pytz.utc)
return timegm(utc_dt.timetuple()) | Compute timestamp from a datetime object that could be timezone aware
or unaware. |
def save_pip(self, out_dir):
try:
import pkg_resources
installed_packages = [d for d in iter(pkg_resources.working_set)]
installed_packages_list = sorted(
["%s==%s" % (i.key, i.version) for i in installed_packages]
)
with open(os.path.j... | Saves the current working set of pip packages to requirements.txt |
async def _senddms(self):
data = self.bot.config.get("meta", {})
tosend = data.get('send_dms', True)
data['send_dms'] = not tosend
await self.bot.config.put('meta', data)
await self.bot.responses.toggle(message="Forwarding of DMs to owner has been {status}.", success=data['send_d... | Toggles sending DMs to owner. |
def take(self, n):
if n <= 0:
return self._transform(transformations.take_t(0))
else:
return self._transform(transformations.take_t(n)) | Take the first n elements of the sequence.
>>> seq([1, 2, 3, 4]).take(2)
[1, 2]
:param n: number of elements to take
:return: first n elements of sequence |
def generate_brome_config():
config = {}
for key in iter(default_config):
for inner_key, value in iter(default_config[key].items()):
if key not in config:
config[key] = {}
config[key][inner_key] = value['default']
return config | Generate a brome config with default value
Returns:
config (dict) |
def hasBeenRotated(self):
try:
return os.stat(self._path).st_ino != self._inode
except OSError:
return True | Returns a boolean indicating whether the file has been removed and recreated during the time it has been open. |
def static_dag_launchpoint(job, job_vars):
input_args, ids = job_vars
if input_args['config_fastq']:
cores = input_args['cpu_count']
a = job.wrapJobFn(mapsplice, job_vars, cores=cores, disk='130G').encapsulate()
else:
a = job.wrapJobFn(merge_fastqs, job_vars, disk='70 G').encapsulate... | Statically define jobs in the pipeline
job_vars: tuple Tuple of dictionaries: input_args and ids |
def cursor_save_attrs (self):
self.cur_saved_r = self.cur_r
self.cur_saved_c = self.cur_c | Save current cursor position. |
async def command(dev, service, method, parameters):
params = None
if parameters is not None:
params = ast.literal_eval(parameters)
click.echo("Calling %s.%s with params %s" % (service, method, params))
res = await dev.raw_command(service, method, params)
click.echo(res) | Run a raw command. |
def set_forbidden_types(self, types):
if self._forbidden_types == types:
return
self._forbidden_types = types
self.invalidateFilter() | Set all forbidden type values
:param typees: a list with forbidden type values
:type typees: list
:returns: None
:rtype: None
:raises: None |
def write_file(self, filename="paths.dat"):
with zopen(filename, "wt") as f:
f.write(str(self) + "\n") | Write paths.dat. |
def section_path_lengths(neurites, neurite_type=NeuriteType.all):
dist = {}
neurite_filter = is_type(neurite_type)
for s in iter_sections(neurites, neurite_filter=neurite_filter):
dist[s] = s.length
def pl2(node):
return sum(dist[n] for n in node.iupstream())
return map_sections(pl2,... | Path lengths of a collection of neurites |
def get_rule(self, template_name):
for regex, render_func in self.rules:
if re.match(regex, template_name):
return render_func
raise ValueError("no matching rule") | Find a matching compilation rule for a function.
Raises a :exc:`ValueError` if no matching rule can be found.
:param template_name: the name of the template |
def format_progress(i, n):
if n == 0:
fraction = 0
else:
fraction = float(i)/n
LEN_BAR = 25
num_plus = int(round(fraction*LEN_BAR))
s_plus = '+'*num_plus
s_point = '.'*(LEN_BAR-num_plus)
return '[{0!s}{1!s}] {2:d}/{3:d} - {4:.1f}%'.format(s_plus, s_point, i, n, fract... | Returns string containing a progress bar, a percentage, etc. |
def normalize_placeholders(arg, inject_quotes=False):
number_placeholders = re.findall(r'{{\s*\d+\s*}}', arg)
for number_placeholder in number_placeholders:
number = re.search(r'\d+', number_placeholder).group()
arg = arg.replace(number_placeholder, '{{_' + number + '}}')
return arg.replace(... | Normalize placeholders' names so that the template can be ingested into Jinja template engine.
- Jinja does not accept numbers as placeholder names, so add a "_"
before the numbers to make them valid placeholder names.
- Surround placeholders expressions with "" so we can preserve spaces inside the posi... |
def transform(self, Y):
try:
return self.data_pca.transform(Y)
except AttributeError:
try:
if Y.shape[1] != self.data.shape[1]:
raise ValueError
return Y
except IndexError:
raise ValueError
ex... | Transform input data `Y` to reduced data space defined by `self.data`
Takes data in the same ambient space as `self.data` and transforms it
to be in the same reduced space as `self.data_nu`.
Parameters
----------
Y : array-like, shape=[n_samples_y, n_features]
n_fea... |
def get_session_identifiers(cls, folder=None, inputfile=None):
sessions = []
if inputfile and folder:
raise MQ2Exception(
'You should specify either a folder or a file')
if folder:
if not os.path.isdir(folder):
return sessions
f... | Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inpu... |
def from_dsn(cls, dsn, **kwargs):
r
init_args = _parse_dsn(dsn)
host, port = init_args.pop('hosts')[0]
init_args['host'] = host
init_args['port'] = port
init_args.update(kwargs)
return cls(**init_args) | r"""Generate an instance of InfluxDBClient from given data source name.
Return an instance of :class:`~.InfluxDBClient` from the provided
data source name. Supported schemes are "influxdb", "https+influxdb"
and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient`
constructor may... |
def fft(xi, yi, axis=0) -> tuple:
if xi.ndim != 1:
raise wt_exceptions.DimensionalityError(1, xi.ndim)
spacing = np.diff(xi)
if not np.allclose(spacing, spacing.mean()):
raise RuntimeError("WrightTools.kit.fft: argument xi must be evenly spaced")
yi = np.fft.fft(yi, axis=axis)
d = (x... | Take the 1D FFT of an N-dimensional array and return "sensible" properly shifted arrays.
Parameters
----------
xi : numpy.ndarray
1D array over which the points to be FFT'ed are defined
yi : numpy.ndarray
ND array with values to FFT
axis : int
axis of yi to perform FFT over
... |
def to_sky(self, wcs, mode='all'):
sky_params = self._to_sky_params(wcs, mode=mode)
return SkyEllipticalAnnulus(**sky_params) | Convert the aperture to a `SkyEllipticalAnnulus` object defined
in celestial coordinates.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transforma... |
def load_datafile(self, name, search_path=None, **kwargs):
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(name, search_path, **kwargs) | find datafile and load them from codec |
def set_meta_rdf(self, rdf, fmt='n3'):
evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt)
self._client._wait_and_except_if_failed(evt) | Set the metadata for this Point in rdf fmt |
def add_reward_function(self):
reward_function = self.model['reward_function']
for condition in reward_function:
condprob = etree.SubElement(self.reward_function, 'Func')
self.add_conditions(condition, condprob)
return self.__str__(self.reward_function)[:-1] | add reward function tag to pomdpx model
Return
---------------
string containing the xml for reward function tag |
def encode (self):
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() | Encodes this SeqCmd to binary and returns a bytearray. |
def qstat(jobid, context='grid'):
scmd = ['qstat', '-j', '%d' % jobid, '-f']
logger.debug("Qstat command '%s'", ' '.join(scmd))
from .setshell import sexec
data = str_(sexec(context, scmd, error_on_nonzero=False))
retval = {}
for line in data.split('\n'):
s = line.strip()
if s.lower().find('do not e... | Queries status of a given job.
Keyword parameters:
jobid
The job identifier as returned by qsub()
context
The setshell context in which we should try a 'qsub'. Normally you don't
need to change the default. This variable can also be set to a context
dictionary in which case we just setup using ... |
def spa_length_in_time(**kwds):
m1 = kwds['mass1']
m2 = kwds['mass2']
flow = kwds['f_lower']
porder = int(kwds['phase_order'])
return findchirp_chirptime(m1, m2, flow, porder) | Returns the length in time of the template,
based on the masses, PN order, and low-frequency
cut-off. |
def delete_api_key(self, api_key_id):
api = self._get_api(iam.DeveloperApi)
api.delete_api_key(api_key_id)
return | Delete an API key registered in the organisation.
:param str api_key_id: The ID of the API key (Required)
:returns: void |
def remove(self, item):
check_not_none(item, "Value can't be None")
item_data = self._to_data(item)
return self._encode_invoke(list_remove_codec, value=item_data) | Removes the specified element's first occurrence from the list if it exists in this list.
:param item: (object), the specified element.
:return: (bool), ``true`` if the specified element is present in this list. |
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max):
if range_min == range_max:
return tensor
float_tensor = tf.to_float(tensor)
scaled_tensor = tf.divide((tf.subtract(float_tensor, range_min) *
tf.constant(float(scale_max - scale_min))),
... | Scale a tensor to scale_min to scale_max.
Args:
tensor: input tensor. Should be a numerical tensor.
range_min: min expected value for this feature/tensor.
range_max: max expected Value.
scale_min: new expected min value.
scale_max: new expected max value.
Returns:
scaled tensor. |
def function(self, function_name, word):
word = self._parse_filter_word(word)
self._add_filter(
*self._prepare_function(function_name, self._attribute, word,
self._negation))
return self | Apply a function on given word
:param str function_name: function to apply
:param str word: word to apply function on
:rtype: Query |
def run(self, once=False):
self._once = once
self.start()
while self.running:
try:
time.sleep(1.0)
except KeyboardInterrupt:
self.stop()
self.join() | Runs the reactor in the main thread. |
def getStats(self):
stats = protocol.ReadStats()
stats.aligned_read_count = self.getNumAlignedReads()
stats.unaligned_read_count = self.getNumUnalignedReads()
return stats | Returns the GA4GH protocol representation of this read group's
ReadStats. |
def send(self, auth_header=None, callback=None, **data):
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | Serializes the message and passes the payload onto ``send_encoded``. |
def make_global_and_nonlocal_decls(code_instrs):
globals_ = sorted(set(
i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOBAL)
))
nonlocals = sorted(set(
i.arg for i in code_instrs
if isinstance(i, instrs.STORE_DEREF) and i.vartype == 'free'
))
out = []
if globa... | Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations. |
def info(args):
session = c.Session(args)
if "all" in args["names"]:
feeds = session.list_feeds()
else:
feeds = args["names"]
for feed in feeds:
aux.pretty_print(session, feed) | Provide information of a number of feeds |
def load_migration_file(self, filename):
path = os.path.join(self.directory, filename)
module = imp.load_source("migration", path)
return module | Load migration file as module. |
def render(self, container, rerender=False):
if rerender:
container.clear()
if not self._rerendering:
self._state = copy(self._fresh_page_state)
self._rerendering = True
try:
self.done = False
self.flowables.flow(container, ... | Flow the flowables into the containers that have been added to this
chain. |
def get_first_webview_context(self):
for context in self.driver_wrapper.driver.contexts:
if context.startswith('WEBVIEW'):
return context
raise Exception('No WEBVIEW context has been found') | Return the first WEBVIEW context or raise an exception if it is not found
:returns: first WEBVIEW context |
def normal_meanvar(data):
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
cumm_sq = np.cumsum([val**2 for val in data])
def cost(s, t):
ts_i = 1.0 / (t-s)
mu = (cumm[t] - cumm[s]) * ts_i
sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2
sig_i = 1.0 / sig
... | Creates a segment cost function for a time series with a
Normal distribution with changing mean and variance
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting ... |
def on_redis_error(self, fname, exc_type, exc_value):
if self.shared_client:
Storage.storage = None
else:
self.storage = None
if self.context.config.REDIS_STORAGE_IGNORE_ERRORS is True:
logger.error("[REDIS_STORAGE] %s" % exc_value)
if fname == '_e... | Callback executed when there is a redis error.
:param string fname: Function name that was being called.
:param type exc_type: Exception type
:param Exception exc_value: The current exception
:returns: Default value or raise the current exception |
def has_next(self):
try:
next_item = self.paginator.object_list[self.paginator.per_page]
except IndexError:
return False
return True | Checks for one more item than last on this page. |
def add_isosurface_grid_data(self, data, origin, extent, resolution,
isolevel=0.3, scale=10,
style="wireframe", color=0xffffff):
spacing = np.array(extent/resolution)/scale
if isolevel >= 0:
triangles = marching_cubes(data, is... | Add an isosurface to current scence using pre-computed data on a grid |
def generate(env):
global PDFTeXAction
if PDFTeXAction is None:
PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR')
global PDFLaTeXAction
if PDFLaTeXAction is None:
PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDFLATEXCOMSTR")
global PDFTeXLaTeXAction
if P... | Add Builders and construction variables for pdftex to an Environment. |
def _plugin_get(self, plugin_name):
if not plugin_name:
return None, u"Plugin name not set"
for plugin in self.controller.plugins:
if not isinstance(plugin, SettablePlugin):
continue
if plugin.name == plugin_name:
return plugin, ""
... | Find plugins in controller
:param plugin_name: Name of the plugin to find
:type plugin_name: str | None
:return: Plugin or None and error message
:rtype: (settable_plugin.SettablePlugin | None, str) |
def _item_to_bucket(iterator, item):
name = item.get("name")
bucket = Bucket(iterator.client, name)
bucket._set_properties(item)
return bucket | Convert a JSON bucket to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type item: dict
:param item: An item to be converted to a bucket.
:rtype: :class:`.Bucket`
:returns: The next bucket in the ... |
def set_config_variables(repo, variables):
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split('.')
writer.set_value(section, option, value)
writer.release() | Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com' |
def _addsub_offset_array(self, other, op):
assert op in [operator.add, operator.sub]
if len(other) == 1:
return op(self, other[0])
warnings.warn("Adding/subtracting array of DateOffsets to "
"{cls} not vectorized"
.format(cls=type(self).__n... | Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self |
def list_dataset_uris(cls, base_uri, config_path):
parsed_uri = generous_parse_uri(base_uri)
uri_list = []
path = parsed_uri.path
if IS_WINDOWS:
path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc)
for d in os.listdir(path):
dir_path = os.path.j... | Return list containing URIs in location given by base_uri. |
def cache_key_name(cls, *args):
if cls.KEY_FIELDS != ():
if len(args) != len(cls.KEY_FIELDS):
raise TypeError(
"cache_key_name() takes exactly {} arguments ({} given)".format(len(cls.KEY_FIELDS), len(args))
)
return 'configuration/{}/cu... | Return the name of the key to use to cache the current configuration |
def read_ncbi_gene2go(fin_gene2go, taxids=None, **kws):
obj = Gene2GoReader(fin_gene2go, taxids=taxids)
if 'taxid2asscs' not in kws:
if len(obj.taxid2asscs) == 1:
taxid = next(iter(obj.taxid2asscs))
kws_ncbi = {k:v for k, v in kws.items() if k in AnnoOptions.keys_exp}
... | Read NCBI's gene2go. Return gene2go data for user-specified taxids. |
def get_location(self, obj):
if not obj.city and not obj.country:
return None
elif obj.city and obj.country:
return '%s, %s' % (obj.city, obj.country)
elif obj.city or obj.country:
return obj.city or obj.country | return user's location |
def discover_setup_packages():
logger = logging.getLogger(__name__)
import eups
eups_client = eups.Eups()
products = eups_client.getSetupProducts()
packages = {}
for package in products:
name = package.name
info = {
'dir': package.dir,
'version': package.v... | Summarize packages currently set up by EUPS, listing their
set up directories and EUPS version names.
Returns
-------
packages : `dict`
Dictionary with keys that are EUPS package names. Values are
dictionaries with fields:
- ``'dir'``: absolute directory path of the set up package... |
def agent_checks(consul_url=None, token=None):
ret = {}
if not consul_url:
consul_url = _get_config()
if not consul_url:
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
function = 'agent/c... | Returns the checks the local agent is managing
:param consul_url: The Consul server URL.
:return: Returns the checks the local agent is managing
CLI Example:
.. code-block:: bash
salt '*' consul.agent_checks |
def rich_presence(self):
kvs = self.get_ps('rich_presence')
data = {}
if kvs:
for kv in kvs:
data[kv.key] = kv.value
return data | Contains Rich Presence key-values
:rtype: dict |
def immediateAssignment(ChannelDescription_presence=0,
PacketChannelDescription_presence=0,
StartingTime_presence=0):
a = L2PseudoLength()
b = TpPd(pd=0x6)
c = MessageType(mesType=0x3F)
d = PageModeAndDedicatedModeOrTBF()
packet = a / b / c / d
if ... | IMMEDIATE ASSIGNMENT Section 9.1.18 |
def register (self, cmd):
if cmd.name is None:
raise ValueError ('no name set for Command object %r' % cmd)
if cmd.name in self.commands:
raise ValueError ('a command named "%s" has already been '
'registered' % cmd.name)
self.commands[cmd.na... | Register a new command with the tool. 'cmd' is expected to be an instance
of `Command`, although here only the `cmd.name` attribute is
investigated. Multiple commands with the same name are not allowed to
be registered. Returns 'self'. |
def file_loc():
import sys
import inspect
try:
raise Exception
except:
file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:])
line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno
return "{}:{}".format(file_, line_) | Return file and line number |
def url_join(base, *args):
scheme, netloc, path, query, fragment = urlsplit(base)
path = path if len(path) else "/"
path = posixpath.join(path, *[('%s' % x) for x in args])
return urlunsplit([scheme, netloc, path, query, fragment]) | Helper function to join an arbitrary number of url segments together. |
def element_at(self, index):
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
if index < 0:
raise OutOfRangeError("Attempt to use negative index.")
try:
return self._iterable[index]
... | Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
... |
def finished(self):
return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED) | True if the job run and finished. There is no difference if the job
finished successfully or errored. |
def update_widget(self, idx=None):
if idx is None:
for w in self._widgets:
idx = self._get_idx_from_widget(w)
self._write_widget(self._read_property(idx), idx)
pass
else: self._write_widget(self._read_property(idx), idx)
return | Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual conditions. |
def set_target_from_config(self, cp, section):
if cp.has_option(section, "niterations"):
niterations = int(cp.get(section, "niterations"))
else:
niterations = None
if cp.has_option(section, "effective-nsamples"):
nsamples = int(cp.get(section, "effective-nsamp... | Sets the target using the given config file.
This looks for ``niterations`` to set the ``target_niterations``, and
``effective-nsamples`` to set the ``target_eff_nsamples``.
Parameters
----------
cp : ConfigParser
Open config parser to retrieve the argument from.
... |
def get_dataset_date_as_datetime(self):
dataset_date = self.data.get('dataset_date', None)
if dataset_date:
if '-' in dataset_date:
dataset_date = dataset_date.split('-')[0]
return datetime.strptime(dataset_date, '%m/%d/%Y')
else:
return None | Get dataset date as datetime.datetime object. For range returns start date.
Returns:
Optional[datetime.datetime]: Dataset date in datetime object or None if no date is set |
def _op_generic_Ctz(self, args):
wtf_expr = claripy.BVV(self._from_size, self._from_size)
for a in reversed(range(self._from_size)):
bit = claripy.Extract(a, a, args[0])
wtf_expr = claripy.If(bit == 1, claripy.BVV(a, self._from_size), wtf_expr)
return wtf_expr | Count the trailing zeroes |
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
app = inliner.document.settings.env.app
ref = 'https://www.github.com/' + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], [] | Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked wit... |
def set_allow_repeat_items(self, allow_repeat_items):
if self.get_allow_repeat_items_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_boolean(allow_repeat_items):
raise InvalidArgument()
self.my_osid_object_form._my_map['allowRepeatIte... | determines if repeat items will be shown, or if the scaffold iteration will simply stop |
def _concat_nbest_translations(translations: List[Translation], stop_ids: Set[int],
length_penalty: LengthPenalty,
brevity_penalty: Optional[BrevityPenalty] = None) -> Translation:
expanded_translations = (_expand_nbest_translation(translation) for trans... | Combines nbest translations through concatenation.
:param translations: A list of translations (sequence starting with BOS symbol,
attention_matrix), score and length.
:param stop_ids: The EOS symbols.
:param length_penalty: LengthPenalty.
:param brevity_penalty: Optional BrevityPenalty.
:r... |
def step_size(self, t0=None, t1=None):
if t0!=None and t1!=None:
tb0 = self.to_bucket( t0 )
tb1 = self.to_bucket( t1, steps=1 )
if tb0==tb1:
return self._step
return self.from_bucket( tb1 ) - self.from_bucket( tb0 )
return self._step | Return the time in seconds of a step. If a begin and end timestamp,
return the time in seconds between them after adjusting for what buckets
they alias to. If t1 and t0 resolve to the same bucket, |
def from_name(cls, name, all_fallback=True):
name = name.upper()
for vocation in cls:
if vocation.name in name or vocation.name[:-1] in name and vocation != cls.ALL:
return vocation
if all_fallback or name.upper() == "ALL":
return cls.ALL
return No... | Gets a vocation filter from a vocation's name.
Parameters
----------
name: :class:`str`
The name of the vocation.
all_fallback: :class:`bool`
Whether to return :py:attr:`ALL` if no match is found. Otherwise, ``None`` will be returned.
Returns
---... |
def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED):
if args == UNDEFINED:
args = tuple()
if kwargs == UNDEFINED:
kwargs = {}
if isinstance(side_effect, (BaseException, Exception, StandardError)):
raise side_effect
elif hasattr(side_effect, '__call__'... | Executes a side effect if one is defined.
:param side_effect: The side effect to execute
:type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters.
:param tuple args: The arguments passed to the stubbed out method
:param dict kwargs: The kwargs passed ... |
def get_likelihood(self, uni_matrix):
uni_dim = uni_matrix.shape[1]
num_edge = len(self.edges)
values = np.zeros([1, num_edge])
new_uni_matrix = np.empty([uni_dim, uni_dim])
for i in range(num_edge):
edge = self.edges[i]
value, left_u, right_u = edge.get_l... | Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditional univariate matrix |
def parser_help_text(help_text):
if help_text is None:
return None, {}
main_text = ''
params_help = {}
for line in help_text.splitlines():
line = line.strip()
match = re.search(r':\s*param\s*(?P<param>\w+)\s*:(?P<help>.*)$', line)
if match:
params_help[match.g... | Takes the help text supplied as a doc string and extraxts the
description and any param arguments. |
def make_node(lower, upper, lineno):
if not is_static(lower, upper):
syntax_error(lineno, 'Array bounds must be constants')
return None
if isinstance(lower, SymbolVAR):
lower = lower.value
if isinstance(upper, SymbolVAR):
upper = upper.value
... | Creates an array bound |
def return_small_clade(treenode):
"used to produce balanced trees, returns a tip node from the smaller clade"
node = treenode
while 1:
if node.children:
c1, c2 = node.children
node = sorted([c1, c2], key=lambda x: len(x.get_leaves()))[0]
else:
return node | used to produce balanced trees, returns a tip node from the smaller clade |
def _partition(entity, sep):
parts = entity.split(sep, 1)
if len(parts) == 2:
return parts[0], sep, parts[1]
else:
return entity, '', '' | Python2.4 doesn't have a partition method so we provide
our own that mimics str.partition from later releases.
Split the string at the first occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the separator. If the separator is not
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.