code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def _learn(connections, rng, learningSegments, activeInput,
potentialOverlaps, initialPermanence, sampleSize,
permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment):
connections.adjustSynapses(learningSegments, activeInput,
permanenceIncre... | Adjust synapse permanences, grow new synapses, and grow new segments.
@param learningActiveSegments (numpy array)
@param learningMatchingSegments (numpy array)
@param segmentsToPunish (numpy array)
@param activeInput (numpy array)
@param potentialOverlaps (numpy array) |
def fractional_base(fractional_part, input_base=10, output_base=10,
max_depth=100):
fractional_part = fractional_part[1:]
fractional_digits = len(fractional_part)
numerator = 0
for i, value in enumerate(fractional_part, 1):
numerator += value * input_base ** (frac... | Convert the fractional part of a number from any base to any base.
Args:
fractional_part(iterable container): The fractional part of a number in
the following form: ( ".", int, int, int, ...)
input_base(int): The base to convert from (defualt 10).
output_base(int): The ... |
def fix_list_arguments(self):
either = [list(c.children) for c in self.either.children]
for case in either:
case = [c for c in case if case.count(c) > 1]
for a in [e for e in case if type(e) == Argument]:
a.value = []
return self | Find arguments that should accumulate values and fix them. |
async def handle_json_response(responses):
json_data = {}
if responses.status != 200:
err_msg = HttpProcessingError(code=responses.status,
message=await responses.json())
logging.error("Wallabag: aiohttp error {err_msg}".format(
... | get the json data response
:param responses: the json response
:return the json data without 'root' node |
def tabulate(data,
header=None,
col_align=None,
):
if not data and not header:
return []
if data:
n_cols = len(data[0])
else:
assert header is not None
n_cols = len(header)
if not all(len(row) == n_cols for row in dat... | Format data as a table without any fancy features.
col_align: l/r/c or a list/string of l/r/c. l = left, r = right, c = center
Return a list of strings (lines of the table). |
def OnLabelSizeIntCtrl(self, event):
self.attrs["labelsize"] = event.GetValue()
post_command_event(self, self.DrawChartMsg) | Label size IntCtrl event handler |
def lsattr(path):
*
if not salt.utils.path.which() or salt.utils.platform.is_aix():
return None
if not os.path.exists(path):
raise SaltInvocationError("File or directory does not exist: " + path)
cmd = [, path]
result = __salt__[](cmd, ignore_retcode=True, python_shell=False)
... | .. versionadded:: 2018.3.0
.. versionchanged:: 2018.3.1
If ``lsattr`` is not installed on the system, ``None`` is returned.
.. versionchanged:: 2018.3.4
If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX``
is not the same thing as the linux version.
Obtain ... |
def calculate_item_depth(self, tree_alias, item_id, depth=0):
item = self.get_item_by_id(tree_alias, item_id)
if hasattr(item, ):
depth = item.depth + depth
else:
if item.parent is not None:
depth = self.calculate_item_depth(tree_alias, item.pare... | Calculates depth of the item in the tree.
:param str|unicode tree_alias:
:param int item_id:
:param int depth:
:rtype: int |
def call(self, url, method=None, args=None):
if not args:
args = {}
if sys.version_info.major == 3:
data = urllib.parse.urlparse(url)
path = data.path.rstrip() +
_args = dict(urllib.parse.parse_qs(data.query,
... | Calls the first function matching the urls pattern and method.
Args:
url (str): Url for which to call a matching function.
method (str, optional): The method used while registering a
function.
Defaults to None
args (dict, optional): Additional... |
def which(program, paths=None):
def is_exe(fpath):
return (os.path.exists(fpath) and
os.access(fpath, os.X_OK) and
os.path.isfile(os.path.realpath(fpath)))
found_path = None
fpath, fname = os.path.split(program)
if fpath:
program = os.pat... | takes a program name or full path, plus an optional collection of search
paths, and returns the full path of the requested executable. if paths is
specified, it is the entire list of search paths, and the PATH env is not
used at all. otherwise, PATH env is used to look for the program |
def corr(x, y=None, method=None):
if not y:
return callMLlibFunc("corr", x.map(_convert_to_vector), method).toArray()
else:
return callMLlibFunc("corr", x.map(float), y.map(float), method) | Compute the correlation (matrix) for the input RDD(s) using the
specified method.
Methods currently supported: I{pearson (default), spearman}.
If a single RDD of Vectors is passed in, a correlation matrix
comparing the columns in the input RDD is returned. Use C{method=}
to spec... |
def open(self, session, resource_name,
access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
raise NotImplementedError | Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:param access_mo... |
def update(self, value):
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | Add a value to the sample. |
def validate_allowed_values(allowed_values, value):
if not allowed_values or isinstance(value, CFNParameter):
return True
return value in allowed_values | Support a variable defining which values it allows.
Args:
allowed_values (Optional[list]): A list of allowed values from the
variable definition
value (obj): The object representing the value provided for the
variable
Returns:
bool: Boolean for whether or not th... |
def send(self, message):
if not self.connected:
raise TransportError()
self.logger.debug(, message)
self._q.put(message) | Send the supplied *message* (xml string) to NETCONF server. |
def add_standard_attention_hparams(hparams):
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("attention_key_channels", 0)
hparams.add_hparam("attention_value_channels", 0)
hparams.add_hparam("attention_dropout", 0.0)
hparams.add_hparam("at... | Adds the hparams used by get_standardized_layers. |
def show_kernel_error(self, error):
eol = sourcecode.get_eol_chars(error)
if eol:
error = error.replace(eol, )
self.is_error_shown = True | Show kernel initialization errors in infowidget. |
def get_session(config=None):
sess = tf.get_default_session()
if sess is None:
sess = make_session(config=config, make_default=True)
return sess | Get default session or create one with a given config |
def upload(self, path, docs, **params):
logger.warning()
return self.post(path, docs=docs) | A deprecated alias for post(path, docs=docs), included only for
backward compatibility. |
def press(self):
@param_to_property(
key=["home", "back", "left", "right", "up", "down", "center",
"menu", "search", "enter", "delete", "del", "recent",
"volume_up", "volume_down", "volume_mute", "camera", "power"]
)
def _press(key, meta=Non... | press key via name or key code. Supported key name includes:
home, back, left, right, up, down, center, menu, search, enter,
delete(or del), recent(recent apps), volume_up, volume_down,
volume_mute, camera, power.
Usage:
d.press.back() # press back key
d.press.menu() # ... |
def zero_year_special_case(from_date, to_date, start, end):
if start == and end == :
if from_date.startswith() and not to_date.startswith():
return True
if not from_date.startswith() and to_date.startswith():
return False
if from_date... | strptime does not resolve a 0000 year, we must handle this. |
def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
if port_db.get() != DEVICE_OWNER_ROUTER_INTF:
return
router = self.l3_plugin.get_router(context, router_id)
gw_i... | Get the VLAN and port for this hosting device
The VLAN used between the APIC and the external router is stored
by the APIC driver. This calls into the APIC driver to first get
the ACI VRF information associated with this port, then uses that
to look up the VLAN to use for this port to ... |
def set_volume_level(self, volume):
if self._volume_level is not None:
if volume > self._volume_level:
num = int(self._max_volume * (volume - self._volume_level))
self._volume_level = volume
self._device.vol_up(num=num)
elif volume... | Set volume level. |
def replace_store_credit_payment_by_id(cls, store_credit_payment_id, store_credit_payment, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._replace_store_credit_payment_by_id_with_http_info(store_credit_payment_id, store_credit_payment, **kwargs)
else:
(da... | Replace StoreCreditPayment
Replace all attributes of StoreCreditPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_store_credit_payment_by_id(store_credit_payment_id, store_credit_payment... |
def runSamplesPermu(self, df, gmt=None):
assert self.min_size <= self.max_size
mkdirs(self.outdir)
self.resultsOnSamples = OrderedDict()
outdir = self.outdir
for name, ser in df.iteritems():
self.outdir = os.path.join(outdir, str(name))
... | Single Sample GSEA workflow with permutation procedure |
def convert(self, vroot, entry_variables):
for converter in self.converters:
vroot = converter.convert(vroot, entry_variables)
return vroot | Convert a given graph.
Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially.
Args:
vroot (:obj:`Variable`): NNabla Variable
entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. |
def elapsed(self):
if self.ready():
return self.wall_time
now = submitted = datetime.now()
for msg_id in self.msg_ids:
if msg_id in self._client.metadata:
stamp = self._client.metadata[msg_id][]
if stamp and stamp < submit... | elapsed time since initial submission |
def im2mat(I):
return I.reshape((I.shape[0] * I.shape[1], I.shape[2])) | Converts and image to matrix (one pixel per line) |
def set_observable(self,tseq,qseq):
tnt = None
qnt = None
if len(tseq) > 0: tnt = tseq[0]
if len(qseq) > 0: qnt = qseq[0]
self._observable.set(len(tseq),len(qseq),tnt,qnt) | Set the observable sequence data
:param tseq: target sequence (from the homopolymer)
:param qseq: query sequence ( from the homopolymer)
:type tseq: string
:type qseq: string |
def _update_events(self):
events = self._skybell.dev_cache(self, CONST.EVENT) or {}
for activity in self._activities:
event = activity.get(CONST.EVENT)
created_at = activity.get(CONST.CREATED_AT)
old_event = events.get(event)
if old_event and c... | Update our cached list of latest activity events. |
def is_sortable_index(self, index_name, catalog):
index = self.get_index(index_name, catalog)
if not index:
return False
return index.meta_type in ["FieldIndex", "DateIndex"] | Returns whether the index is sortable |
def bounce(sequence):
N = len(sequence)
def f(i):
div, mod = divmod(i, N)
if div % 2 == 0:
return sequence[mod]
else:
return sequence[N-mod-1]
return partial(force, sequence=_advance(f)) | Return a driver function that can advance a "bounced" sequence
of values.
.. code-block:: none
seq = [0, 1, 2, 3]
# bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...]
Args:
sequence (seq) : a sequence of values for the driver to bounce |
def text_pb(tag, data, description=None):
try:
tensor = tensor_util.make_tensor_proto(data, dtype=np.object)
except TypeError as e:
raise TypeError(, e)
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
summary = summary_pb2.Summary()
summary.val... | Create a text tf.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A Python bytestring (of type bytes), a Unicode string, or a numpy data
array of those types.
description: Optional long-form description for this summary, as a `str`.
Markdown is supported. Defaults to empty.... |
def init(self, force_deploy=False):
machines = self.provider_conf.machines
networks = self.provider_conf.networks
_networks = []
for network in networks:
ipnet = IPNetwork(network.cidr)
_networks.append({
"netpool": list(ipnet)[10:-10],
... | Reserve and deploys the vagrant boxes.
Args:
force_deploy (bool): True iff new machines should be started |
def visit_project(self, item):
if not item.remote_id:
command = CreateProjectCommand(self.settings, item)
self.task_runner_add(None, item, command)
else:
self.settings.project_id = item.remote_id | Adds create project command to task runner if project doesn't already exist. |
def list_attributes(self):
return [attribute for attribute, value in self.iteritems() if issubclass(value.__class__, Attribute)] | Returns the Node attributes names.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.list_attributes()
['attributeB', 'attributeA']
:return: Attributes names.
:rtype: list |
def _set_data(self, action):
data = self._load_response(action)
self._handle_continuations(data, )
if action == :
members = data.get().get()
if members:
self._add_members(members)
if action == :
rand = data[][][0]
... | Set category member data from API response |
def num_listeners(self, event=None):
if event is not None:
return len(self._listeners[event])
else:
return sum(len(l) for l in self._listeners.values()) | Return the number of listeners for ``event``.
Return the total number of listeners for all events on this object if
``event`` is :class:`None`. |
def prod_sum_var(A, B):
return A.multiply(B).sum(1).A1 if issparse(A) else np.einsum(, A, B) | dot product and sum over axis 1 (var) equivalent to np.sum(A * B, 1) |
def add_text(self, text, label=None):
if label is None:
label = self._label_metadata[][0]
else:
if not self.my_osid_object_form._is_valid_string(
label, self.get_label_metadata()) or in label:
raise InvalidArgument()
if text i... | stub |
def bass(self):
response = self.renderingControl.GetBass([
(, 0),
(, ),
])
bass = response[]
return int(bass) | int: The speaker's bass EQ.
An integer between -10 and 10. |
def _subprocess_method(self, command):
p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.output, self.error = p.communicate()
self.status = p.returncode | Use the subprocess module to execute ipmitool commands
and and set status |
def enrich(self, column1, column2):
if column1 not in self.data.columns or \
column2 not in self.data.columns:
return self.data
self.data["timedifference"] = (self.data[column2] - self.data[column1]) / np.timedelta64(1, )
return self.data | This method calculates the difference in seconds between
the 2 columns (column2 - column1)
The final result may provided negative values depending on the values
from column1 and column2.
:param column1: first column. Values in column1 must be datetime type
:param column2: s... |
def debug(f, *args, **kwargs):
kwargs.update({: logging.DEBUG})
return _stump(f, *args, **kwargs) | Automatically log progress on function entry and exit. Default logging
value: debug.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each '{varname}' will be replaced by the v... |
async def remove_albums(self, *albums):
_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]
await self.user.http.delete_saved_albums(.join(_albums)) | Remove one or more albums from the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs |
def dimension_values(self, dimension, expanded=True, flat=True):
val = self._cached_constants.get(dimension, None)
if val:
return np.array([val])
else:
raise Exception("Dimension %s not found in %s." %
(dimension, self.__class__.__name... | Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
on the type of data:
* Colum... |
def get_num_image_channels(module_or_spec, signature=None, input_name=None):
if input_name is None:
input_name = "images"
input_info_dict = module_or_spec.get_input_info_dict(signature)
try:
shape = input_info_dict[input_name].get_shape()
except KeyError:
raise ValueError("Module is missing input... | Returns expected num_channels dimensions of an image input.
This is for advanced users only who expect to handle modules with
image inputs that might not have the 3 usual RGB channels.
Args:
module_or_spec: a Module or ModuleSpec that accepts image inputs.
signature: a string with the key of the signatu... |
def list_all_refund_operations(cls, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._list_all_refund_operations_with_http_info(**kwargs)
else:
(data) = cls._list_all_refund_operations_with_http_info(**kwargs)
return data | List RefundOperations
Return a list of RefundOperations
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_refund_operations(async=True)
>>> result = thread.get()
:param async b... |
def filter(self, run_counts, criteria):
correctness = criteria[]
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = filtered_counts[key][correctness]
return filtered_counts | Return run counts only for examples that are still correctly classified |
def rebalance(self):
if self.args.num_gens < self.args.max_partition_movements:
self.log.warning(
"num-gens ({num_gens}) is less than max-partition-movements"
" ({max_partition_movements}). max-partition-movements will"
" never be reached.".fo... | The genetic rebalancing algorithm runs for a fixed number of
generations. Each generation has two phases: exploration and pruning.
In exploration, a large set of possible states are found by randomly
applying assignment changes to the existing states. In pruning, each
state is given a sc... |
def stop(self):
if not self.stopped:
self.stopped = True
if self.pendingHeartbeat is not None:
self.pendingHeartbeat.cancel()
self.pendingHeartbeat = None | Permanently stop sending heartbeats. |
def verify_dataset(X, y):
X_shape, y_shape = np.array(X).shape, np.array(y).shape
if len(X_shape) != 2:
raise exceptions.UserError("X must be 2-dimensional array")
if len(y_shape) != 1:
raise exceptions.UserError("y must be 1-dimensional array")
if X_shape[0] != y_shape[0]:
... | Verifies if a dataset is valid for use i.e. scikit-learn format
Used to verify a dataset by returning shape and basic statistics of
returned data. This will also provide quick and dirty check on
capability of host machine to process the data.
Args:
X (array-like): Features array
y (ar... |
def _q_to_dcm(self, q):
assert(len(q) == 4)
arr = super(Quaternion, self)._q_to_dcm(q)
return self._dcm_array_to_matrix3(arr) | Create DCM (Matrix3) from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: Matrix3 |
def get_flow_by_id(self, flow_id):
tmp_flows = self.diagram_graph.edges(data=True)
for flow in tmp_flows:
if flow[2][consts.Consts.id] == flow_id:
return flow | Gets an edge (flow) with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param flow_id: string with edge ID. |
def get_event_from_name(self, event_name):
return next((e for e in self.events if e.name == event_name), None) | Return an event from a name
Args:
event_name (str): name of the event
Returns:
Event |
def write_text(self, text, encoding=None, errors=,
linesep=os.linesep, append=False):
r
if isinstance(text, text_type):
if linesep is not None:
text = U_NEWLINE.sub(linesep, text)
text = text.encode(encoding or sys.getdefaultencoding(), errors)
... | r""" Write the given text to this file.
The default behavior is to overwrite any existing file;
to append instead, use the `append=True` keyword argument.
There are two differences between :meth:`write_text` and
:meth:`write_bytes`: newline handling and Unicode handling.
See be... |
def normalize_address(self, hostname):
if config_get():
return hostname
if hostname != unit_get():
return get_host_ip(hostname, fallback=hostname)
return | Ensure that address returned is an IP address (i.e. not fqdn) |
def allocate_sync_ensembles(self, tolerance = 0.1):
if (self.__ccore_legion_dynamic_pointer is not None):
self.__output = wrapper.legion_dynamic_get_output(self.__ccore_legion_dynamic_pointer);
return allocate_sync_ensembles(self.__output, tolerance); | !
@brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster.
@param[in] tolerance (double): Maximum error for allocation of synchronous ensemble oscillators.
@return (list) Grours of indexes o... |
async def stop(self):
state = await self.state()
res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID)
return res | Stop playback? |
def read(self, visibility_timeout=None, callback=None):
def _read(rs):
if callable(callback):
callback(rs[0] if len(rs) == 1 else None)
self.get_messages(1, visibility_timeout, callback=callback) | Read a single message from the queue.
:type visibility_timeout: int
:param visibility_timeout: The timeout for this message in seconds
:rtype: :class:`boto.sqs.message.Message`
:return: A single message or None if queue is empty |
def upload_file(self, **kwargs):
params = None
if not in kwargs:
raise AttributeError("Parameter must be given")
else:
params = {
"filename": kwargs[]
}
if not in kwargs:
raise AttributeError("Parameter must be... | Upload a file to the Gett service. Takes keyword arguments.
Input:
* ``filename`` the filename to use in the Gett service (required)
* ``data`` the file contents to store in the Gett service (required) - must be a string
* ``sharename`` the name of the share in which to stor... |
def compose (composite_property_s, component_properties_s):
from . import property
component_properties_s = to_seq (component_properties_s)
composite_property = property.create_from_string(composite_property_s)
f = composite_property.feature
if len(component_properties_s) > 0 and isinstance(c... | Sets the components of the given composite property.
All parameters are <feature>value strings |
def webify_file(srcfilename: str, destfilename: str) -> None:
with open(srcfilename) as infile, open(destfilename, ) as ofile:
for line_ in infile:
ofile.write(escape(line_)) | Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process. |
def _replace_with_new_dims(
self: T,
variables: = None,
coord_names: set = None,
attrs: = __default,
indexes: = __default,
inplace: bool = False,
) -> T:
dims = dict(calculate_dimensions(variables))
return self._replace(
varia... | Replace variables with recalculated dimensions. |
def get_url_from_entry(entry):
if in entry.fields:
return entry.fields[]
elif entry.type.lower() == :
return + entry.fields[]
elif in entry.fields:
return entry.fields[]
elif in entry.fields:
return + entry.fields[]
else:
raise NoEntryUrlError() | Get a usable URL from a pybtex entry.
Parameters
----------
entry : `pybtex.database.Entry`
A pybtex bibliography entry.
Returns
-------
url : `str`
Best available URL from the ``entry``.
Raises
------
NoEntryUrlError
Raised when no URL can be made from the... |
def dump(
self, stream, progress=None, lower=None, upper=None,
incremental=False, deltas=False
):
cmd = [SVNADMIN, , ]
if progress is None:
cmd.append()
if lower is not None:
cmd.append()
if upper is None:
cmd.appen... | Dump the repository to a dumpfile stream.
:param stream: A file stream to which the dumpfile is written
:param progress: A file stream to which progress is written
:param lower: Must be a numeric version number
:param upper: Must be a numeric version number
See ``svnadmin help ... |
def getMaturedSwarmGenerations(self):
result = []
modifiedSwarmGens = sorted(self._modifiedSwarmGens)
for key in modifiedSwarmGens:
(swarmId, genIdx) = key
if key in self._maturedSwarmGens:
self._modifiedSwarmGens.remove(key)
continue
... | Return a list of swarm generations that have completed and the
best (minimal) errScore seen for each of them.
Parameters:
---------------------------------------------------------------------
retval: list of tuples. Each tuple is of the form:
(swarmId, genIdx, bestErrScore) |
def _generate_filename(cls, writer_spec, name, job_id, num,
attempt=None, seg_index=None):
naming_format = cls._TMP_FILE_NAMING_FORMAT
if seg_index is None:
naming_format = writer_spec.get(cls.NAMING_FORMAT_PARAM,
cls._DEFAULT_NAMING_FORM... | Generates a filename for a particular output.
Args:
writer_spec: specification dictionary for the output writer.
name: name of the job.
job_id: the ID number assigned to the job.
num: shard number.
attempt: the shard attempt number.
seg_index: index of the seg. None means the fi... |
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME):
if required:
if django.VERSION < (1, 11):
actual_decorator = user_passes_test(
lambda u: u.is_authenticated(),
redirect_field_name=redirect_field_name
)
... | Decorator for views that, if required, checks that the user is logged in and redirect
to the log-in page if necessary. |
def close(self) -> None:
if not self._closed:
self._async_client.close()
self._io_loop.close()
self._closed = True | Closes the HTTPClient, freeing any resources used. |
def _set_item_querytime(self, item, type_check=True):
if isinstance(item, Versionable):
item._querytime = self.querytime
elif isinstance(item, VersionedQuerySet):
item.querytime = self.querytime
else:
if type_check:
raise TypeError(
... | Sets the time for which the query was made on the resulting item
:param item: an item of type Versionable
:param type_check: Check the item to be a Versionable
:return: Returns the item itself with the time set |
def tree_sph(polar, azimuthal, n, standardization, symbolic=False):
cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos
config = {
"acoustic": ("complex spherical", False),
"quantum mechanic": ("complex spherical", True),
"geodetic": ("complex spherical 1", False)... | Evaluate all spherical harmonics of degree at most `n` at angles `polar`,
`azimuthal`. |
def save_keywords(filename, xml):
tmp_dir = os.path.dirname(filename)
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
file_desc = open(filename, "w")
file_desc.write(xml)
file_desc.close() | Save keyword XML to filename. |
def identifier_md5(self):
as_int = (self.identifier * 1e4).astype(np.int64)
hashed = util.md5_object(as_int.tostring(order=))
return hashed | Return an MD5 of the identifier |
def search_service_code(self, service_index):
log.debug("search service code index {0}".format(service_index))
a, e = self.pmm[3] & 7, self.pmm[3] >> 6
timeout = max(302E-6 * (a + 1) * 4**e, 0.002)
data = pack("<H", service_index)
data = self.s... | Search for a service code that corresponds to an index.
The Search Service Code command provides access to the
iterable list of services and areas within the activated
system. The *service_index* argument may be any value from 0
to 0xffff. As long as there is a service or area found for... |
def parse_html(html, cleanup=True):
if cleanup:
html = cleanup_html(html)
return fragment_fromstring(html, create_parent=True) | Parses an HTML fragment, returning an lxml element. Note that the HTML will be
wrapped in a <div> tag that was not in the original document.
If cleanup is true, make sure there's no <head> or <body>, and get
rid of any <ins> and <del> tags. |
def fast_corr(x, y=None, destination=None):
if y is None:
y = x
r = fast_cov.fast_cov(x, y, destination)
std_x = numpy.std(x, axis=0, ddof=1)
std_y = numpy.std(y, axis=0, ddof=1)
numpy.divide(r, std_x[:, numpy.newaxis], out=r)
numpy.divide(r, std_y[numpy.newaxis, :], out=r)
... | calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix
between x and y (with dimensions OxP). If destination is provided, put the results there.
In the language of statistics the columns are the variables and the rows are the observat... |
def get_transformer_encoder(config: transformer.TransformerConfig, prefix: str) -> :
encoder_seq = EncoderSequence([], dtype=config.dtype)
cls, encoder_params = _get_positional_embedding_params(config.positional_embedding_type,
config.model_size,
... | Returns a Transformer encoder, consisting of an embedding layer with
positional encodings and a TransformerEncoder instance.
:param config: Configuration for transformer encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. |
def classifymetagenome(self):
logging.info()
self.classifycall = \
.format(self.clarkpath,
self.filelist,
self.reportlist,
self.cpus)
classify = True
for sample in self.runmetadata.samples:... | Run the classify metagenome of the CLARK package on the samples |
def replace(self, target):
if sys.version_info < (3, 3):
raise NotImplementedError("replace() is only available "
"with Python 3.3 and later")
self._accessor.replace(self, target) | Rename this path to the given path, clobbering the existing
destination if it exists. |
def download_videos(self, path, since=None, camera=, stop=10):
if since is None:
since_epochs = self.last_refresh
else:
parsed_datetime = parse(since, fuzzy=True)
since_epochs = parsed_datetime.timestamp()
formatted_date = get_time(time_to_convert=si... | Download all videos from server since specified time.
:param path: Path to write files. /path/<cameraname>_<recorddate>.mp4
:param since: Date and time to get videos from.
Ex: "2018/07/28 12:33:00" to retrieve videos since
July 28th 2018 at 12:33:00
... |
def _check_and_handle_includes(self, from_file):
logger.debug("Check/handle includes from %s", from_file)
try:
paths = self._parser.get("INCLUDE", "paths")
except (config_parser.NoSectionError,
config_parser.NoOptionError) as exc:
logger.debug("_c... | Look for an optional INCLUDE section in the given file path. If
the parser set `paths`, it is cleared so that they do not keep
showing up when additional files are parsed. |
def get_arcs(analysis):
if not analysis.has_arcs():
return None
branch_lines = analysis.branch_lines()
branches = []
for l1, l2 in analysis.arcs_executed():
if l1 in branch_lines:
branches.extend((l1, 0, abs(l2), 1))
for l1, l2 ... | Hit stats for each branch.
Returns a flat list where every four values represent a branch:
1. line-number
2. block-number (not used)
3. branch-number
4. hits (we only get 1/0 from coverage.py) |
def get_file_checksums(url, ftp=None):
assert isinstance(url, (str, _oldstr))
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
close_connection = False
ftp_server =
ftp_user =
if ftp is None:
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_user)
clos... | Download and parse an Ensembl CHECKSUMS file and obtain checksums.
Parameters
----------
url : str
The URL of the CHECKSUM file.
ftp : `ftplib.FTP` or `None`, optional
An FTP connection.
Returns
-------
`collections.OrderedDict`
An ordered dictionary containing ... |
def grant_jsapi_ticket(self):
self._check_appid_appsecret()
if callable(self.__jsapi_ticket_refreshfunc):
self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self.__jsapi_ticket_refreshfunc()
return
response_json = self.__request.get(
url="https:/... | 获取 jsapi ticket 并更新当前配置
:return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 None) |
def cleanup(self):
remove = []
for handle, assoc in self.assocs.items():
if assoc.expiresIn == 0:
remove.append(handle)
for handle in remove:
del self.assocs[handle]
return len(remove), len(self.assocs) | Remove expired associations.
@return: tuple of (removed associations, remaining associations) |
def cli(ctx, email, first_name, last_name, password, metadata={}):
return ctx.gi.users.update_user(email, first_name, last_name, password, metadata=metadata) | Update an existing user
Output:
a dictionary containing user information |
def get_partial_text(fulltext):
def _get_index(x):
return int(float(x) / 100 * len(fulltext))
partial_text = [
fulltext[_get_index(start):_get_index(end)]
for start, end in current_app.config[
"CLASSIFIER_PARTIAL_TEXT_PERCENTAGES"
]
]
return "\n".join(p... | Return a short version of the fulltext used with partial matching mode.
The version is composed of 20% in the beginning and 20% in the middle of
the text. |
def _file_size(file_path, uncompressed=False):
_, ext = os.path.splitext(file_path)
if uncompressed:
if ext in {".gz", ".gzip"}:
with gzip.GzipFile(file_path, mode="rb") as fp:
try:
fp.seek(0, os.SEEK_END)
return fp.tell()
... | Return size of a single file, compressed or uncompressed |
def push_rule_nodes(self) -> bool:
if self.rule_nodes is None:
self.rule_nodes = collections.ChainMap()
self.tag_cache = collections.ChainMap()
self.id_cache = collections.ChainMap()
else:
self.rule_nodes = self.rule_nodes.new_child()
... | Push context variable to store rule nodes. |
def ParseFileObject(self, parser_mediator, file_object):
if not self.LINE_STRUCTURES:
raise errors.UnableToParseFile()
encoding = self._ENCODING or parser_mediator.codepage
text_reader = EncodedTextReader(
encoding, buffer_size=self.BUFFER_SIZE)
text_reader.Reset()
try:
t... | Parses a text file-like object using a pyparsing definition.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot ... |
def encrypt_password(**kwargs):
new_value = kwargs[]
field = kwargs[]
min_length = field.params[]
if len(new_value) < min_length:
raise ValueError(
.format(
field.name, field.params[]))
if new_value and not crypt.match(new_value):
new_value = str(cry... | Crypt :new_value: if it's not crypted yet. |
def get_orientation_radians(self):
raw = self._get_raw_data(, )
if raw is not None:
raw[] = raw.pop()
raw[] = raw.pop()
raw[] = raw.pop()
self._last_orientation = raw
return deepcopy(self._last_orientation) | Returns a dictionary object to represent the current orientation in
radians using the aircraft principal axes of pitch, roll and yaw |
def apply(self,word,ctx=None):
chars = get_letters(word)
flag = True
reason = None
prev_letter = None
for char in chars:
if prev_letter == char:
flag = False
break
prev_letter = char
if not flag:
... | ignore ctx information right now |
def _set_proto_vrrpv3(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=proto_vrrpv3.proto_vrrpv3, is_container=, presence=False, yang_name="proto-vrrpv3", rest_name="protocol", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, re... | Setter method for proto_vrrpv3, mapped from YANG variable /rbridge_id/ipv6/proto_vrrpv3 (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_proto_vrrpv3 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... |
def _delay_for_ratelimits(cls, start):
stop = datetime.now()
duration_microseconds = (stop - start).microseconds
if duration_microseconds < cls.REQUEST_TIME_MICROSECONDS:
time.sleep((cls.REQUEST_TIME_MICROSECONDS - duration_microseconds)
/ MICROSECONDS... | If request was shorter than max request time, delay |
def _check_type_x_is_y(self, node, left, operator, right):
left_func = utils.safe_infer(left.func)
if not (
isinstance(left_func, astroid.ClassDef) and left_func.qname() == TYPE_QNAME
):
return
if operator in ("is", "is not") and _is_one_arg_pos_call(rig... | Check for expressions like type(x) == Y. |
def add_to_object(self, target: object, override: bool = False) -> int:
nret = 0
for k, v in self:
key = k.upper()
exists = hasattr(target, key)
if not exists or (override and isinstance(getattr(target, k), (Namespace, _RDFNamespace))):
setatt... | Add the bindings to the target object
:param target: target to add to
:param override: override existing bindings if they are of type Namespace
:return: number of items actually added |
def merge_tracks(self, track_indices=None, mode=, program=0,
is_drum=False, name=, remove_merged=False):
if mode not in (, , ):
raise ValueError("`mode` must be one of {, , }.")
merged = self[track_indices].get_merged_pianoroll(mode)
merged_track = Tra... | Merge pianorolls of the tracks specified by `track_indices`. The merged
track will have program number as given by `program` and drum indicator
as given by `is_drum`. The merged track will be appended at the end of
the track list.
Parameters
----------
track_indices : li... |
def get_default_config(self):
config = super(EntropyStatCollector, self).get_default_config()
config.update({
:
})
return config | Returns the default collector settings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.