Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
382,100 | def execute(self, transition):
self._transitions.append(transition)
if self._thread is None or not self._thread.isAlive():
self._thread = threading.Thread(target=self._transition_loop)
self._thread.setDaemon(True)
self._thread.start() | Queue a transition for execution.
:param transition: The transition |
382,101 | def _isinstance(self, model, raise_error=True):
rv = isinstance(model, self.__model__)
if not rv and raise_error:
raise ValueError( % (model, self.__model__))
return rv | Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise_error (bool) : Flag to specify whether to raise error on
... |
382,102 | def Search(self,key):
results = []
for alert in self.alerts:
if alert.id.lower().find(key.lower()) != -1: results.append(alert)
elif alert.name.lower().find(key.lower()) != -1: results.append(alert)
return(results) | Search alert list by providing partial name, ID, or other key. |
382,103 | def argval(self):
if self.arg is None or any(x is None for x in self.arg):
return None
for x in self.arg:
if not isinstance(x, int):
raise InvalidArgError(self.arg)
return self.arg | Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered. |
382,104 | def top_n_list(lang, n, wordlist=, ascii_only=False):
results = []
for word in iter_wordlist(lang, wordlist):
if (not ascii_only) or max(word) <= :
results.append(word)
if len(results) >= n:
break
return results | Return a frequency list of length `n` in descending order of frequency.
This list contains words from `wordlist`, of the given language.
If `ascii_only`, then only ascii words are considered. |
382,105 | def upsert_entities(self, entities, sync=False):
if entities:
select_for_update_query = (
).format(
table_name=Entity._meta.db_table
)
select_for_update_query_params = []
if... | Upsert a list of entities to the database
:param entities: The entities to sync
:param sync: Do a sync instead of an upsert |
382,106 | def combine(items, k=None):
length_items = len(items)
lengths = [len(i) for i in items]
length = reduce(lambda x, y: x * y, lengths)
repeats = [reduce(lambda x, y: x * y, lengths[i:])
for i in range(1, length_items)] + [1]
if k is not None:
k = k % length
... | Create a matrix in wich each row is a tuple containing one of solutions or
solution k-esima. |
382,107 | def _validate(data_type, parent_path):
if isinstance(data_type, _CLASS_TYPES):
raise TypeError(
"The data type is expected to be an instance object, but got the "
"type instead." % (_format_type(data_type),))
base = _find_base_type(data_type)
if not base:
raise... | Implementation for the `validate` function. |
382,108 | def _output_from_file(self, entry=):
try:
vfile = os.path.join(os.path.dirname(self.fpath), )
with open(vfile, ) as f:
return json.loads(f.read()).get(entry, None)
except:
return None | Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.* |
382,109 | def pearson_correlation_coefficient(predictions, labels, weights_fn=None):
del weights_fn
_, pearson = tf.contrib.metrics.streaming_pearson_correlation(predictions,
labels)
return pearson, tf.constant(1.0) | Calculate pearson correlation coefficient.
Args:
predictions: The raw predictions.
labels: The actual labels.
weights_fn: Weighting function.
Returns:
The pearson correlation coefficient. |
382,110 | def copydb(self, sourcedb, destslab, destdbname=None, progresscb=None):
destdb = destslab.initdb(destdbname, sourcedb.dupsort)
statdict = destslab.stat(db=destdb)
if statdict[] > 0:
raise s_exc.DataAlreadyExists()
rowcount = 0
for chunk in s_common.chunks(... | Copy an entire database in this slab to a new database in potentially another slab.
Args:
sourcedb (LmdbDatabase): which database in this slab to copy rows from
destslab (LmdbSlab): which slab to copy rows to
destdbname (str): the name of the database to copy rows to in dest... |
382,111 | def get_translated_items(fapi, file_uri, use_cache, cache_dir=None):
items = None
cache_file = os.path.join(cache_dir, sha1(file_uri)) if use_cache else None
if use_cache and os.path.exists(cache_file):
print("Using cache file %s for translated items for: %s" % (cache_file, file_uri))
i... | Returns the last modified from smarterling |
382,112 | def check(cls, dap, network=False, yamls=True, raises=False, logger=logger):
dap._check_raises = raises
dap._problematic = False
dap._logger = logger
problems = list()
problems += cls.check_meta(dap)
problems += cls.check_no_self_dependency(dap)
problems... | Checks if the dap is valid, reports problems
Parameters:
network -- whether to run checks that requires network connection
output -- where to write() problems, might be None
raises -- whether to raise an exception immediately after problem is detected |
382,113 | def key_pair(i, region):
if i == 0:
return ("{}_{}".format(RAY, region),
os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
return ("{}_{}_{}".format(RAY, i, region),
os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region))) | Returns the ith default (aws_key_pair_name, key_pair_path). |
382,114 | def generate_single_return_period(args):
qout_file, return_period_file, rivid_index_list, step, num_years, \
method, mp_lock = args
skewvals = [-3.0, -2.8, -2.6, -2.4, -2.2, -2.0, -1.8, -1.6, -1.4, -1.2,
-1.0, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0,
1.2,... | This function calculates a single return period for a single reach |
382,115 | def startMultiple(self, zones):
path =
payload = {: zones}
return self.rachio.put(path, payload) | Start multiple zones. |
382,116 | def reset(self, params, repetition):
print params["name"], ":", repetition
self.debug = params.get("debug", False)
L2Params = json.loads( + params["l2_params"] + )
L4Params = json.loads( + params["l4_params"] + )
L6aParams = json.loads( + params["l6a_params"] + )
seed = params.get("... | Take the steps necessary to reset the experiment before each repetition:
- Make sure random seed is different for each repetition
- Create the L2-L4-L6a network
- Generate objects used by the experiment
- Learn all objects used by the experiment |
382,117 | def metamodel_from_file(file_name, **kwargs):
with codecs.open(file_name, , ) as f:
lang_desc = f.read()
metamodel = metamodel_from_str(lang_desc=lang_desc,
file_name=file_name,
**kwargs)
return metamodel | Creates new metamodel from the given file.
Args:
file_name(str): The name of the file with textX language description.
other params: See metamodel_from_str. |
382,118 | def set_console(stream=STDOUT, foreground=None, background=None, style=None):
if foreground is None:
foreground = _default_foreground
if background is None:
background = _default_background
if style is None:
style = _default_style
attrs = get_attrs(foreground, background, st... | Set console foreground and background attributes. |
382,119 | def init():
if not os.path.exists(__opts__[]):
log.debug(, __opts__[])
os.makedirs(__opts__[])
if not os.path.exists(__opts__[]):
log.debug(, __opts__[])
sqlite3.enable_callback_tracebacks(True)
conn = sqlite3.connect(__opts__[], isolation_level=None)
try:
con... | Get an sqlite3 connection, and initialize the package database if necessary |
382,120 | def as_bits( region_start, region_length, intervals ):
bits = BitSet( region_length )
for chr, start, stop in intervals:
bits.set_range( start - region_start, stop - start )
return bits | Convert a set of intervals overlapping a region of a chromosome into
a bitset for just that region with the bits covered by the intervals
set. |
382,121 | def _worker_thread_upload(self):
max_set_len = self._general_options.concurrency.transfer_threads << 2
while not self.termination_check:
try:
if len(self._transfer_set) > max_set_len:
time.sleep(0.1)
continue
... | Worker thread upload
:param Uploader self: this |
382,122 | def ping(self, message=None):
return self.write(self.parser.ping(message), encode=False) | Write a ping ``frame``. |
382,123 | def _get_callable_from_trace_tuple(
self, trace_tuple: TraceTuple
) -> Tuple[str, str]:
trace_frame = trace_tuple.trace_frame
if trace_tuple.placeholder:
return trace_frame.caller, trace_frame.caller_port
return trace_frame.callee, trace_frame.callee_port | Returns either (caller, caller_port) or (callee, callee_port). |
382,124 | def add_body(self, body):
body.system = self
self.bodies.append(body)
self.unfrozen = np.concatenate((
self.unfrozen[:-2], np.zeros(7, dtype=bool), self.unfrozen[-2:]
)) | Add a :class:`Body` to the system. This function also sets the
``system`` attribute of the body.
:param body:
The :class:`Body` to add. |
382,125 | def load_graphs():
mestate.graphs = []
gfiles = []
if in os.environ:
for dirname, dirnames, filenames in os.walk(os.path.join(os.environ[], ".mavproxy")):
for filename in filenames:
if filename.lower().endswith():
gfiles.append(o... | load graphs from mavgraphs.xml |
382,126 | def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
args = parser.parse_args()
outdir = pathlib.Path(args.outdir)
if not outdir.exists():
raise FileNotFoundError("Output di... | Execute the main routine. |
382,127 | def get_boundaries_of_elements_in_dict(models_dict, clearance=0.):
right = 0.
bottom = 0.
if in models_dict and models_dict[]:
left = list(models_dict[].items())[0][1].get_meta_data_editor()[][0]
top = list(models_dict[].items())[0][1].get_meta_data_editor()[][1]
elif in mod... | Get boundaries of all handed models
The function checks all model meta data positions to increase boundary starting with a state or scoped variables.
It is finally iterated over all states, data and logical port models and linkage if sufficient for respective
graphical editor. At the end a clearance is add... |
382,128 | def has_same_bins(self, other: "HistogramBase") -> bool:
if self.shape != other.shape:
return False
elif self.ndim == 1:
return np.allclose(self.bins, other.bins)
elif self.ndim > 1:
for i in range(self.ndim):
if not np.allclose(self.b... | Whether two histograms share the same binning. |
382,129 | def handle_pubcomp(self):
self.logger.info("PUBCOMP received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubcomp(mid)
self.push_event(evt)
return NC.ERR_SUCCESS | Handle incoming PUBCOMP packet. |
382,130 | def run_step(context):
logger.debug("started")
deprecated(context)
StreamReplacePairsRewriterStep(__name__, , context).run_step()
logger.debug("done") | Parse input file and replace a search string.
This also does string substitutions from context on the fileReplacePairs.
It does this before it search & replaces the in file.
Be careful of order. If fileReplacePairs is not an ordered collection,
replacements could evaluate in any given order. If this i... |
382,131 | async def close(self) -> None:
LOGGER.debug()
if self.cfg.get(, False):
await self.load_cache(True)
Caches.purge_archives(self.dir_cache, True)
await super().close()
for path_rr_id in Tails.links(self._dir_tails):
rr_id = basename(path_rr_i... | Explicit exit. If so configured, populate cache to prove all creds in
wallet offline if need be, archive cache, and purge prior cache archives.
:return: current object |
382,132 | def to_mask(self, method=, subpixels=5):
use_exact, subpixels = self._translate_mask_mode(method, subpixels)
if hasattr(self, ):
radius = self.r
elif hasattr(self, ):
radius = self.r_out
else:
raise ValueError()
masks = []
... | Return a list of `~photutils.ApertureMask` objects, one for each
aperture position.
Parameters
----------
method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the aperture on
the pixel grid. Not all options are available... |
382,133 | def to_iso8601(dt, tz=None):
if tz is not None:
dt = dt.replace(tzinfo=tz)
iso8601 = dt.isoformat()
return iso8601 | Returns an ISO-8601 representation of a given datetime instance.
>>> to_iso8601(datetime.datetime.now())
'2014-10-01T23:21:33.718508Z'
:param dt: a :class:`~datetime.datetime` instance
:param tz: a :class:`~datetime.tzinfo` to use; if None - use a default one |
382,134 | def list(self, filter_title=None, filter_ids=None, page=None):
filters = [
.format(filter_title) if filter_title else None,
.format(.join([str(dash_id) for dash_id in filter_ids])) if filter_ids else None,
.format(page) if page else None
]
return self... | :type filter_title: str
:param filter_title: Filter by dashboard title
:type filter_ids: list of ints
:param filter_ids: Filter by dashboard ids
:type page: int
:param page: Pagination index
:rtype: dict
:return: The JSON response of the API, with an additional... |
382,135 | def _apply_orthogonal_view(self):
left, right, bottom, top = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) | Orthogonal view with respect to current aspect ratio |
382,136 | def calculate_retry_delay(attempt, max_delay=300):
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
delay = int(random.uniform(max_delay - 20, max_delay + 20))
return delay | Calculates an exponential backoff for retry attempts with a small
amount of jitter. |
382,137 | def to_dict(self):
data = {"model": {}}
data["model"]["description"] = self.description
data["model"]["entity_name"] = self.entity_name
data["model"]["package"] = self.package
data["model"]["resource_name"] = self.resource_name
data["model"]["rest_name"] = self... | Transform the current specification to a dictionary |
382,138 | def declare_example(self, source):
with patch_modules():
code = compile(source, "<docs>", "exec")
exec(code, self.namespace) | Execute the given code, adding it to the runner's namespace. |
382,139 | def recalculate_satistics(self):
pars
gframe = wx.BusyInfo(
"Re-calculating statistics for all specimens\n Please wait..", self)
for specimen in list(self.Data.keys()):
if not in list(self.Data[specimen].keys()):
continue
if not in list(self... | update self.Data[specimen]['pars'] for all specimens. |
382,140 | def init_heartbeat(self):
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port))
self.hb_port = self.heartbeat.port
self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port)
self.heartbeat.start()
... | start the heart beating |
382,141 | def _bind_method(self, name, unconditionally=False):
exists = self.run_func(, name)[] in [2, 3, 5]
if not unconditionally and not exists:
raise AttributeError(" object has no attribute " % name)
method_instance = MatlabFunction(weakref.ref(self), name)
... | Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __... |
382,142 | def _get_arrays(self, wavelengths, **kwargs):
x = self._validate_wavelengths(wavelengths)
y = self(x, **kwargs)
if isinstance(wavelengths, u.Quantity):
w = x.to(wavelengths.unit, u.spectral())
else:
w = x
return w, y | Get sampled spectrum or bandpass in user units. |
382,143 | def delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_api_key(apiKey=apiKey)
return {: True}
except ClientError as e:
return {: False, : __utils__[](e)} | Deletes a given apiKey
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.delete_api_key apikeystring |
382,144 | def create(self, name):
return Bucket(name, context=self._context).create(self._project_id) | Creates a new bucket.
Args:
name: a unique name for the new bucket.
Returns:
The newly created bucket.
Raises:
Exception if there was an error creating the bucket. |
382,145 | def _prime_user_perm_caches(self):
perm_cache, group_perm_cache = self._get_user_cached_perms()
self.user._authority_perm_cache = perm_cache
self.user._authority_group_perm_cache = group_perm_cache
self.user._authority_perm_cache_filled = True | Prime both the user and group caches and put them on the ``self.user``.
In addition add a cache filled flag on ``self.user``. |
382,146 | def set_continue(self, name, action, seqno, value=None, default=False,
disable=False):
commands = [ % (name, action, seqno)]
if default:
commands.append()
elif disable:
commands.append()
else:
if not str(value).isdigit() o... | Configures the routemap continue value
Args:
name (string): The full name of the routemap.
action (string): The action to take for this routemap clause.
seqno (integer): The sequence number for the routemap clause.
value (integer): The value to configure for the ... |
382,147 | def get_vouchers(self, vid_encoded=None,
uid_from=None, uid_to=None, gid=None,
valid_after=None, valid_before=None,
last=None, first=None):
resource = self.kvpath(
,
(, vid_encoded),
**{
:... | FETCHES a filtered list of vouchers.
:type vid_encoded: ``alphanumeric(64)``
:param vid_encoded:
Voucher ID, as a string with CRC.
:type uid_from: ``bigint``
:param uid_from:
Filter by source account UID.
:type uid_to: ``bigint``
:param ui... |
382,148 | def make_stream_tls_features(self, stream, features):
if self.stream and stream is not self.stream:
raise ValueError("Single StreamTLSHandler instance can handle"
" only one stream")
self.stream = stream
if self.set... | Update the <features/> element with StartTLS feature.
[receving entity only]
:Parameters:
- `features`: the <features/> element of the stream.
:Types:
- `features`: :etree:`ElementTree.Element`
:returns: update <features/> element.
:returntype: :etree:`... |
382,149 | def missing_pids(self):
missing = []
for p in self.pids:
try:
PersistentIdentifier.get(p.pid_type, p.pid_value)
except PIDDoesNotExistError:
missing.append(p)
return missing | Filter persistent identifiers. |
382,150 | def filter_step(G, covY, pred, yt):
data_pred_mean = np.matmul(pred.mean, G.T)
data_pred_cov = dotdot(G, pred.cov, G.T) + covY
if covY.shape[0] == 1:
logpyt = dists.Normal(loc=data_pred_mean,
scale=np.sqrt(data_pred_cov)).logpdf(yt)
else:
logpyt = ... | Filtering step of Kalman filter.
Parameters
----------
G: (dy, dx) numpy array
mean of Y_t | X_t is G * X_t
covX: (dx, dx) numpy array
covariance of Y_t | X_t
pred: MeanAndCov object
predictive distribution at time t
Returns
-------
pred: MeanAndCov object
... |
382,151 | def replace_namespaced_custom_object_scale(self, group, version, namespace, plural, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_namespaced_custom_object_scale_with_http_info(group, version, namespace, plural, name, body, **kwargs)
else:
... | replace_namespaced_custom_object_scale # noqa: E501
replace scale of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_... |
382,152 | def ReadHuntCounters(self, hunt_id):
num_clients = self.CountHuntFlows(hunt_id)
num_successful_clients = self.CountHuntFlows(
hunt_id, filter_condition=db.HuntFlowsCondition.SUCCEEDED_FLOWS_ONLY)
num_failed_clients = self.CountHuntFlows(
hunt_id, filter_condition=db.HuntFlowsCondition.F... | Reads hunt counters. |
382,153 | def get_item_hrefs(result_collection):
assert result_collection is not None
result = []
links = result_collection.get()
if links is not None:
items = links.get()
if items is not None:
for item in items:
result.append(item.get())
return result | Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be empty if no items were found. |
382,154 | def get_url(self, url, dest, makedirs=False, saltenv=,
no_cache=False, cachedir=None, source_hash=None):
url_data = urlparse(url)
url_scheme = url_data.scheme
url_path = os.path.join(
url_data.netloc, url_data.path).rstrip(os.sep)
if des... | Get a single file from a URL. |
382,155 | def _calc_delta(self,ensemble,scaling_matrix=None):
mean = np.array(ensemble.mean(axis=0))
delta = ensemble.as_pyemu_matrix()
for i in range(ensemble.shape[0]):
delta.x[i,:] -= mean
if scaling_matrix is not None:
delta = scaling_matrix * delta.T
d... | calc the scaled ensemble differences from the mean |
382,156 | def SubmitJob(self, *params, **kw):
fp = self.__expandparamstodict(params, kw)
return self._get_subfolder(, GPJob, fp)._jobstatus | Asynchronously execute the specified GP task. This will return a
Geoprocessing Job object. Parameters are passed in either in order
or as keywords. |
382,157 | def extract(self, start, end):
from copy import deepcopy
eaf_out = deepcopy(self)
for t in eaf_out.get_tier_names():
for ab, ae, value in eaf_out.get_annotation_data_for_tier(t):
if ab > end or ae < start:
eaf_out.remove_annotation(t, (sta... | Extracts the selected time frame as a new object.
:param int start: Start time.
:param int end: End time.
:returns: class:`pympi.Elan.Eaf` object containing the extracted frame. |
382,158 | def index(in_bam, config, check_timestamp=True):
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.path.splitext(in_bam)[0]
if check_timestamp:
bai_exists = utils.file_uptodate(index_file, in_bam) or utils.file_uptodate(alt_... | Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches. |
382,159 | def _create_update_from_file(mode=, uuid=None, path=None):
ret = {}
if not os.path.isfile(path) or path is None:
ret[] = .format(path)
return ret
cmd = .format(
mode=mode,
brand=get(uuid)[] if uuid is not None else ,
path=path
)
res = __salt__[](cmd)... | Create vm from file |
382,160 | def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remov... | Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarr... |
382,161 | def lightcurve_moments(ftimes, fmags, ferrs):
ndet = len(fmags)
if ndet > 9:
series_median = npmedian(fmags)
series_wmean = (
npsum(fmags*(1.0/(ferrs*ferrs)))/npsum(1.0/(ferrs*ferrs))
)
series_mad = npmedian(npabs(fmags - series_median))
serie... | This calculates the weighted mean, stdev, median, MAD, percentiles, skew,
kurtosis, fraction of LC beyond 1-stdev, and IQR.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-finite elements removed.
Returns
-------
dict
A dict... |
382,162 | def _all_get_table_col(self, key, column, fullname):
val = column[0]
try:
if type(val) is int:
return pt.IntCol()
if isinstance(val, (str, bytes)):
itemsize = int(self._prm_get_longest_stringsize(column))
re... | Creates a pytables column instance.
The type of column depends on the type of `column[0]`.
Note that data in `column` must be homogeneous! |
382,163 | def _send(self, key, value, metric_type):
try:
payload = self._build_payload(key, value, metric_type)
LOGGER.debug(, payload)
self._socket.sendto(payload.encode(), self._address)
except socket.error:
LOGGER.exception() | Send the specified value to the statsd daemon via UDP without a
direct socket connection.
:param str key: The key name to send
:param int or float value: The value for the key |
382,164 | def mdaArray(arry, dtype=numpy.float, mask=None):
a = numpy.array(arry, dtype)
res = MaskedDistArray(a.shape, a.dtype)
res[:] = a
res.mask = mask
return res | Array constructor for masked distributed array
@param arry numpy-like array
@param mask mask array (or None if all data elements are valid) |
382,165 | def main():
arguments = docopt.docopt(__doc__, version=)
if arguments[]:
diag.show()
if arguments[]:
diag.reporting()
diag.show()
if arguments[]:
try:
if couchdb.ping():
print
else:
print
except:
... | Main part of command line utility |
382,166 | def export_users(self, body):
return self.client.post(self._url(), data=body) | Export all users to a file using a long running job.
Check job status with get(). URL pointing to the export file will be
included in the status once the job is complete.
Args:
body (dict): Please see: https://auth0.com/docs/api/management/v2#!/Jobs/post_users_exports |
382,167 | def expireat(self, key, when):
expire_time = datetime.fromtimestamp(when)
key = self._encode(key)
if key in self.redis:
self.timeouts[key] = expire_time
return True
return False | Emulate expireat |
382,168 | def get_pdos(dos, lm_orbitals=None, atoms=None, elements=None):
if not elements:
symbols = dos.structure.symbol_set
elements = dict(zip(symbols, [None] * len(symbols)))
pdos = {}
for el in elements:
if atoms and el not in atoms:
continue
... | Extract the projected density of states from a CompleteDos object.
Args:
dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The
density of states.
elements (:obj:`dict`, optional): The elements and orbitals to extract
from the projected density of states. Should be... |
382,169 | def default_antenna1(self, context):
ant1, ant2 = default_base_ant_pairs(self, context)
(tl, tu), (bl, bu) = context.dim_extents(, )
ant1_result = np.empty(context.shape, context.dtype)
ant1_result[:,:] = ant1[np.newaxis,bl:bu]
return ant1_result | Default antenna1 values |
382,170 | def compile(self, pretty=True):
self._object_names = {}
self._shader_deps = {}
for shader_name, shader in self.shaders.items():
this_shader_deps = []
self._shader_deps[shader_name] = this_shader_deps
dep... | Compile all code and return a dict {name: code} where the keys
are determined by the keyword arguments passed to __init__().
Parameters
----------
pretty : bool
If True, use a slower method to mangle object names. This produces
GLSL that is more readable.
... |
382,171 | def mtabstr2doestr(st1):
seperator =
alist = st1.split(seperator)
for num in range(0, len(alist)):
alist[num] = alist[num].lstrip()
st2 =
for num in range(0, len(alist)):
alist = tabstr2list(alist[num])
st2 = st2 + list2doe(alist)
lss = st2.split()
... | mtabstr2doestr |
382,172 | def get_pmids(self):
pmids = []
for ea in self._edge_attributes.values():
edge_pmids = ea.get()
if edge_pmids:
pmids += edge_pmids
return list(set(pmids)) | Get list of all PMIDs associated with edges in the network. |
382,173 | def valid_conkey(self, conkey):
for prefix in _COND_PREFIXES:
trailing = conkey.lstrip(prefix)
if trailing == and conkey:
return True
try:
int(trailing)
return True
except ValueError:
pas... | Check that the conkey is a valid one. Return True if valid. A
condition key is valid if it is one in the _COND_PREFIXES
list. With the prefix removed, the remaining string must be
either a number or the empty string. |
382,174 | def getBagTags(bagInfoPath):
try:
bagInfoString = open(bagInfoPath, "r").read().decode()
except UnicodeDecodeError:
bagInfoString = open(bagInfoPath, "r").read().decode()
bagTags = anvl.readANVLString(bagInfoString)
return bagTags | get bag tags |
382,175 | def retention_period(self, value):
policy = self._properties.setdefault("retentionPolicy", {})
if value is not None:
policy["retentionPeriod"] = str(value)
else:
policy = None
self._patch_property("retentionPolicy", policy) | Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked. |
382,176 | def matchingAnalyseIndexes(self, tokenJson):
s analysis of a single word token;
'
matchingResults = self.matchingAnalyses(tokenJson)
if matchingResults:
indexes = [ tokenJson[ANALYSIS].index(analysis) for analysis in matchingResults ]
return indexes
... | Determines whether given token (tokenJson) satisfies all the rules listed
in the WordTemplate and returns a list of analyse indexes that correspond
to tokenJson[ANALYSIS] elements that are matching all the rules.
An empty list is returned if none of the analyses match (all the rul... |
382,177 | def form(value):
if isinstance(value, FLOAT + INT):
if value <= 0:
return str(value)
elif value < .001:
return % value
elif value < 10 and isinstance(value, FLOAT):
return % value
elif value > 1000:
return .format(int(round(value... | Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2' |
382,178 | def _visible(self, element):
if element.name in self._disallowed_names:
return False
elif re.match(u, six.text_type(element.extract())):
return False
return True | Used to filter text elements that have invisible text on the page. |
382,179 | def putResult(self, result):
self._lock_prev_output.acquire()
for tube in self._tubes_result_output:
tube.put((result, 0))
self._lock_next_output.release() | Register the *result* by putting it on all the output tubes. |
382,180 | def _random_subprocessors(self):
if self._processors is not None:
return (p for p in self._processors)
elif 2**len(self._evil) <= 8 * self._proc_limit:
deletions = self._compute_all_deletions()
if len(deletions) > self._proc_limit:
deletions =... | Produces an iterator of subprocessors. If there are fewer than
self._proc_limit subprocessors to consider (by knocking out a
minimal subset of working qubits incident to broken couplers),
we work exhaustively. Otherwise, we generate a random set of
``self._proc_limit`` subprocessors.
... |
382,181 | def add_child(self, child):
if not isinstance(child, DependencyNode):
raise TypeError()
self._children.append(child) | Add a child node |
382,182 | def register_up(self):
with self.regcond:
self.runningcount += 1
tid = thread.get_ident()
self.tids.append(tid)
self.logger.debug("register_up: (%d) count is %d" %
(tid, self.runningcount))
if self.runningcount ==... | Called by WorkerThread objects to register themselves.
Acquire the condition variable for the WorkerThread objects.
Increment the running-thread count. If we are the last thread to
start, set status to 'up'. This allows startall() to complete
if it was called with wait=True. |
382,183 | def add_obograph_digraph(self, og, node_type=None, predicates=None, xref_graph=None, logical_definitions=None,
property_chain_axioms=None,
parse_meta=True,
**args):
digraph = self.digraph
logging.info("NODES:... | Converts a single obograph to Digraph edges and adds to an existing networkx DiGraph |
382,184 | def _send(self, event):
_LOGGER.debug(, event)
try:
with async_timeout.timeout(10, loop=self._loop):
response = yield from self._websession.post(
self.ALARMDOTCOM_URL + .format(
self._login_info[]),
dat... | Generic function for sending commands to Alarm.com
:param event: Event command to send to alarm.com |
382,185 | def elem_to_container(elem, container=dict, **options):
dic = container()
if elem is None:
return dic
elem.tag = _tweak_ns(elem.tag, **options)
subdic = dic[elem.tag] = container()
options["container"] = container
if elem.text:
_process_elem_text(elem, dic, subdic, **opt... | Convert XML ElementTree Element to a collection of container objects.
Elements are transformed to a node under special tagged nodes, attrs, text
and children, to store the type of these elements basically, however, in
some special cases like the followings, these nodes are attached to the
parent node d... |
382,186 | def headers(self):
action = self.method.soap.action
stock = { : , : action }
result = dict(stock, **self.options.headers)
log.debug(, result)
return result | Get http headers or the http/https request.
@return: A dictionary of header/values.
@rtype: dict |
382,187 | def _init_metadata(self):
QuestionFilesFormRecord._init_metadata(self)
FirstAngleProjectionFormRecord._init_metadata(self)
super(MultiChoiceOrthoQuestionFormRecord, self)._init_metadata() | stub |
382,188 | def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
value = namespace[key]
assert isinstance(value, property)
fget = value.fget
fset = value.fset
fdel = value.fdel
for func in [value.fget, value.fset, value.fdel... | Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them. |
382,189 | def register(cls, range_mixin):
def decorator(range_set_mixin):
cls.add(range_mixin, range_set_mixin)
return range_set_mixin
return decorator | Decorator for registering range set mixins for global use. This works
the same as :meth:`~spans.settypes.MetaRangeSet.add`
:param range_mixin: A :class:`~spans.types.Range` mixin class to
to register a decorated range set mixin class for
:return: A decorator to use o... |
382,190 | def get_parent(self):
if not self.parent:
parent = self._safe_get_element()
if parent:
self.parent = self.api.lookup(ItemId=parent)
return self.parent | Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product. |
382,191 | def load(self):
if not op.exists(self.path):
logger.debug("The GUI state file `%s` doesn't exist.", self.path)
return
assert op.exists(self.path)
logger.debug("Load the GUI state from `%s`.", self.path)
self.update(_bunchify(_load_json(self.p... | Load the state from the JSON file in the config dir. |
382,192 | def line_iterator_to_intermediary(line_iterator):
current_table = None
tables = []
relations = []
errors = []
for line_nb, line, raw_line in filter_lines_from_comments(line_iterator):
try:
new_obj = parse_line(line)
current_table, tables, relations = update_model... | Parse an iterator of str (one string per line) to the intermediary syntax |
382,193 | def remove_class(self, ioclass):
current_ioclasses = self.ioclasses
new_ioclasses = filter(lambda x: x.name != ioclass.name,
current_ioclasses)
self.modify(new_ioclasses=new_ioclasses) | Remove VNXIOClass instance from policy. |
382,194 | def surface_to_image(surface):
from IPython.display import Image
buf = BytesIO()
surface.write_to_png(buf)
data = buf.getvalue()
buf.close()
return Image(data=data) | Renders current buffer surface to IPython image |
382,195 | def tagmask(self, tags):
mask = numpy.zeros(len(tags), bool)
for t, tag in enumerate(tags):
tagname, tagvalue = tag.split()
mask[t] = self.tagvalue(tagname) == tagvalue
return mask | :returns: a boolean array with True where the assets has tags |
382,196 | def get(self, endpoint, params=None):
response = self._session.get(
url=self._url + endpoint,
params=params,
timeout=self._timeout
)
return self._handle_response(response) | Send an HTTP GET request to QuadrigaCX.
:param endpoint: API endpoint.
:type endpoint: str | unicode
:param params: URL parameters.
:type params: dict
:return: Response body from QuadrigaCX.
:rtype: dict
:raise quadriga.exceptions.RequestError: If HTTP OK was not... |
382,197 | def clearness_index(ghi, solar_zenith, extra_radiation, min_cos_zenith=0.065,
max_clearness_index=2.0):
cos_zenith = tools.cosd(solar_zenith)
I0h = extra_radiation * np.maximum(cos_zenith, min_cos_zenith)
kt = ghi / I0h
kt = np.maximum(kt, 0)
kt = np.mini... | Calculate the clearness index.
The clearness index is the ratio of global to extraterrestrial
irradiance on a horizontal plane.
Parameters
----------
ghi : numeric
Global horizontal irradiance in W/m^2.
solar_zenith : numeric
True (not refraction-corrected) solar zenith angle ... |
382,198 | def calculate_manual_reading(basic_data: BasicMeterData) -> Reading:
t_start = basic_data.previous_register_read_datetime
t_end = basic_data.current_register_read_datetime
read_start = basic_data.previous_register_read
read_end = basic_data.current_register_read
value = basic_data.quantity
... | Calculate the interval between two manual readings |
382,199 | def one(iterable, cmp=None):
the_one = False
for i in iterable:
if cmp(i) if cmp else i:
if the_one:
return False
the_one = i
return the_one | Return the object in the given iterable that evaluates to True.
If the given iterable has more than one object that evaluates to True,
or if there is no object that fulfills such condition, return False.
If a callable ``cmp`` is given, it's used to evaluate each element.
>>> one((True, False, Fa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.