code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def _ensure_channel_connected(self, destination_id):
if destination_id not in self._open_channels:
self._open_channels.append(destination_id)
self.send_message(
destination_id, NS_CONNECTION,
{MESSAGE_TYPE: TYPE_CONNECT,
: {},
... | Ensure we opened a channel to destination_id. |
def _normalize_correlation_data(self, corr_data, norm_unit):
if norm_unit > 1:
num_samples = len(corr_data)
[_, d2, d3] = corr_data.shape
second_dimension = d2 * d3
normalized_corr_data = corr_data.reshape(1,
... | Normalize the correlation data if necessary.
Fisher-transform and then z-score the data for every norm_unit samples
if norm_unit > 1.
Parameters
----------
corr_data: the correlation data
in shape [num_samples, num_processed_voxels, num_voxels]
norm_... |
def youtube_id(self):
m = re.search(r, self.embed)
if m:
return m.group(1)
return | Extract and return Youtube video id |
def obj2str(obj, pk_protocol=pk_protocol):
return base64.b64encode(pickle.dumps(
obj, protocol=pk_protocol)).decode("utf-8") | Convert arbitrary object to utf-8 string, using
base64encode algorithm.
Usage::
>>> from weatherlab.lib.dataIO.pk import obj2str
>>> data = {"a": 1, "b": 2}
>>> obj2str(data, pk_protocol=2)
'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg=='
**中文文档**
将可Pickle化的Python对象转化为utf-8... |
def _parse_next_token(self):
while self._position < self.limit:
token = self._next_pattern()
if token:
return token
return None | Will parse patterns until it gets to the next token or EOF. |
def _proxy(self):
if self._context is None:
self._context = QueueContext(
self._version,
account_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: QueueContext for this QueueInstance
:rtype: twilio.rest.api.v2010.account.queue.QueueContext |
def newidfobject(self, key, aname=, defaultvalues=True, **kwargs):
obj = newrawobject(self.model, self.idd_info,
key, block=self.block, defaultvalues=defaultvalues)
abunch = obj2bunch(self.model, self.idd_info, obj)
if aname:
warnings.warn("The ... | Add a new idfobject to the model. If you don't specify a value for a
field, the default value will be set.
For example ::
newidfobject("CONSTRUCTION")
newidfobject("CONSTRUCTION",
Name='Interior Ceiling_class',
Outside_Layer='LW Concrete',
... |
def get_field_values_as_list(self,field):
fieldproduct_name_exactMauris risus risus lacus. sitdolor auctor Vivamus fringilla. vulputatesemper nisi lacus nulla sedvel amet diam sed posuerevitae neque ultricies, Phasellus acconsectetur nisi orci, eu diamsapien, nisi accumsan accumsan Inligula. odio ipsum sit velt... | :param str field: The name of the field for which to pull in values.
Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example::
>>> r.get_field_values_as_list('product_name_exact')
['Mauris risus risus l... |
def del_module(self, module):
rev = util.get_latest_revision(module)
del self.modules[(module.arg, rev)] | Remove a module from the context |
def verify_firebase_token(id_token, request, audience=None):
return verify_token(
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL) | Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typica... |
def get_lb_pkgs(self):
_filter = {: {:
utils.query_filter()}}
packages = self.prod_pkg.getItems(id=0, filter=_filter)
pkgs = []
for package in packages:
if not package[].startswith():
pkgs.append(package)
return ... | Retrieves the local load balancer packages.
:returns: A dictionary containing the load balancer packages |
def cancel(self):
target_url = self._client.get_url(, , , {: self.id})
r = self._client.request(, target_url)
logger.info("cancel(): %s", r.status_code) | Cancel a pending publish task |
def diff_roessler(value_array, a, c):
b=a
diff_array = np.zeros(3)
diff_array[0] = -value_array[1] - value_array[2]
diff_array[1] = value_array[0] + a * value_array[1]
diff_array[2] = b + value_array[2] * (value_array[0] - c)
return diff_array | The Roessler attractor differential equation
:param value_array: 3d array containing the x,y, and z component values.
:param a: Constant attractor parameter
:param c: Constant attractor parameter
:return: 3d array of the Roessler system evaluated at `value_array` |
def mock_server_receive(sock, length):
msg = b
while length:
chunk = sock.recv(length)
if chunk == b:
raise socket.error(errno.ECONNRESET, )
length -= len(chunk)
msg += chunk
return msg | Receive `length` bytes from a socket object. |
def connect(self):
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name] | Starts the mongodb connection. Must be called before anything else
will work. |
def to_array(self):
array = super(PassportFile, self).to_array()
array[] = u(self.file_id)
array[] = int(self.file_size)
array[] = int(self.file_date)
return array | Serializes this PassportFile to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def _get_next_or_previous_by_order(self, is_next, **kwargs):
lookup = self.with_respect_to()
lookup["_order"] = self._order + (1 if is_next else -1)
concrete_model = base_concrete_model(Orderable, self)
try:
queryset = concrete_model.objects.published
except ... | Retrieves next or previous object by order. We implement our
own version instead of Django's so we can hook into the
published manager, concrete subclasses and our custom
``with_respect_to`` method. |
def list_upgrades(refresh=True, **kwargs):
*
if salt.utils.data.is_true(refresh):
refresh_db()
upgrades = {}
lines = __salt__[](
).splitlines()
for line in lines:
comps = line.split()
if comps[2] == "SAME":
continue
if comps[2] == "not installed"... | List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkgutil.list_upgrades |
def ndimage_to_list(image):
inpixeltype = image.pixeltype
dimension = image.dimension
components = 1
imageShape = image.shape
nSections = imageShape[ dimension - 1 ]
subdimension = dimension - 1
suborigin = iio.get_origin( image )[0:subdimension]
subspacing = iio.get_spacing( image ... | Split a n dimensional ANTsImage into a list
of n-1 dimensional ANTsImages
Arguments
---------
image : ANTsImage
n-dimensional image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'... |
def iiOfAny(instance, classes):
if type(classes) not in [list, tuple]:
classes = [classes]
return any(
type(instance).__name__ == cls.__name__
for cls in classes
) | Returns true, if `instance` is instance of any (iiOfAny) of the `classes`.
This function doesn't use :py:func:`isinstance` check, it just compares the
`class` names.
This can be generaly dangerous, but it is really useful when you are
comparing class serialized in one module and deserialized in anothe... |
def init_environment():
os.environ[] =
pluginpath = os.pathsep.join((os.environ.get(, ), constants.BUILTIN_PLUGIN_PATH))
os.environ[] = pluginpath | Set environment variables that are important for the pipeline.
:returns: None
:rtype: None
:raises: None |
def create_session(self, user_agent, remote_address, client_version):
self.session_counter += 1
self.sessions[self.session_counter] = session = self.session_class()
session.user_agent = user_agent
session.remote_address = remote_address
session.client_version ... | Create a new session.
:param str user_agent: Client user agent
:param str remote_addr: Remote address of client
:param str client_version: Remote client version
:return: The new session id
:rtype: int |
def checksum(self, path, hashtype=):
return self._handler.checksum(hashtype, posix_path(path)) | Returns the checksum of the given path. |
def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False):
if isinstance(values, tensor_pb2.TensorProto):
return values
if dtype:
dtype = dtypes.as_dtype(dtype)
is_quantized = dtype in [
dtypes.qint8,
dtypes.quint8,
dtypes.qint16,
dtypes... | Create a TensorProto.
Args:
values: Values to put in the TensorProto.
dtype: Optional tensor_pb2 DataType value.
shape: List of integers representing the dimensions of tensor.
verify_shape: Boolean that enables verification of a shape of values.
Returns:
A `TensorPr... |
def execute(self,
image = None,
command = None,
app = None,
writable = False,
contain = False,
bind = None,
stream = False,
nv = False,
return_result=False):
from spython.utils import check_install
... | execute: send a command to a container
Parameters
==========
image: full path to singularity image
command: command to send to container
app: if not None, execute a command in context of an app
writable: This option makes the file system accessible as read/write
... |
def pretend_option(fn):
def set_pretend(ctx, param, value):
from peltak.core import context
from peltak.core import shell
context.set(, value or False)
if value:
shell.cprint(, _pretend_msg())
return click.option(
,
is_flag=T... | Decorator to add a --pretend option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'pretend' if the command needs it. To get the current value you can do:
>>> from peltak.comm... |
def check_version(version, range_=None):
if range_ and version not in range_:
raise RezBindError("found version %s is not within range %s"
% (str(version), str(range_))) | Check that the found software version is within supplied range.
Args:
version: Version of the package as a Version object.
range_: Allowable version range as a VersionRange object. |
def put(self, key, value, lease=None):
payload = {
"key": _encode(key),
"value": _encode(value)
}
if lease:
payload[] = lease.id
self.post(self.get_url("/kv/put"), json=payload)
return True | Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean |
def filter(self, *filt, **kwargs):
filtfilt = kwargs.pop(, False)
form, filt = filter_design.parse_filter(
filt, analog=kwargs.pop(, False),
sample_rate=self.sample_rate.to().value,
)
if form == :
try:
... | Filter this `TimeSeries` with an IIR or FIR filter
Parameters
----------
*filt : filter arguments
1, 2, 3, or 4 arguments defining the filter to be applied,
- an ``Nx1`` `~numpy.ndarray` of FIR coefficients
- an ``Nx6`` `~numpy.ndarray` of SOS coeffi... |
def find_node(self, name, create=False):
name = self._validate_name(name)
node = self.nodes.get(name)
if node is None:
if not create:
raise KeyError
node = self.node_factory()
self.nodes[name] = node
return node | Find a node in the zone, possibly creating it.
@param name: the name of the node to find
@type name: dns.name.Name object or string
@param create: should the node be created if it doesn't exist?
@type create: bool
@raises KeyError: the name is not known and create was not specif... |
def apply(expr, func, axis=0, names=None, types=None, reduce=False,
resources=None, keep_nulls=False, args=(), **kwargs):
if not isinstance(expr, CollectionExpr):
return
if isinstance(func, FunctionWrapper):
names = names or func.output_names
types = types or func.output... | Apply a function to a row when axis=1 or column when axis=0.
:param expr:
:param func: function to apply
:param axis: row when axis=1 else column
:param names: output names
:param types: output types
:param reduce: if True will return a sequence else return a collection
:param resources: re... |
def isdir(path):
system = get_instance(path)
return system.isdir(system.ensure_dir_path(path)) | Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists. |
def from_args(self, **kwargs):
for k, v in iitems(kwargs):
if v is not None:
if k in self.MUST_BE_LIST and isinstance(v, string_class):
v = [v]
setattr(self, k, v) | Read config values from `kwargs`. |
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs):
s = requests.Session()
ua = kwargs.get()
if not ua:
ua = UserAgent.get(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs)
s.headers[] = ua
extra_params = os.getenv()
... | Set up and return Session object that is set up with retrying. Requires either global user agent to be set or
appropriate user agent parameter(s) to be completed.
Args:
user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed.
user_agent_config_yaml (Optional[str]): ... |
def save_load(jid, clear_load, minion=None):
cb_ = _get_connection()
try:
jid_doc = cb_.get(six.text_type(jid))
except couchbase.exceptions.NotFoundError:
cb_.add(six.text_type(jid), {}, ttl=_get_ttl())
jid_doc = cb_.get(six.text_type(jid))
jid_doc.value[] = clear_load
... | Save the load to the specified jid |
def _get_cross_pt_dual_simp(self, dual_simp):
matrix_surfs = [self.facets[dual_simp[i]].normal for i in range(3)]
matrix_e = [self.facets[dual_simp[i]].e_surf for i in range(3)]
cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e)
return cross_pt | |normal| = 1, e_surf is plane's distance to (0, 0, 0),
plane function:
normal[0]x + normal[1]y + normal[2]z = e_surf
from self:
normal_e_m to get the plane functions
dual_simp: (i, j, k) simplices from the dual convex hull
i, j, k: plane index(same or... |
def do_videoplaceholder(parser, token):
name, params = parse_placeholder(parser, token)
return VideoPlaceholderNode(name, **params) | Method that parse the imageplaceholder template tag. |
def check(frame) -> None:
if frame.rsv1 or frame.rsv2 or frame.rsv3:
raise WebSocketProtocolError("Reserved bits must be 0")
if frame.opcode in DATA_OPCODES:
return
elif frame.opcode in CTRL_OPCODES:
if len(frame.data) > 125:
... | Check that this frame contains acceptable values.
Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this
frame contains incorrect values. |
def result(self):
if not self._result:
if not self._persistence_engine:
return None
self._result = self._persistence_engine.get_context_result(self)
return self._result | Return the context result object pulled from the persistence_engine
if it has been set. |
def download_historical(tickers_list, output_folder):
__validate_list(tickers_list)
for ticker in tickers_list:
file_name = os.path.join(output_folder, ticker + )
with open(file_name, ) as f:
base_url =
try:
urlopen(base_url + ticker)
... | Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:param tickers_list: List of tickers that will be returned.
... |
def attach_template(self, _template, _key, **unbound_var_values):
if _key in unbound_var_values:
raise ValueError( % _key)
unbound_var_values[_key] = self
return _DeferredLayer(self.bookkeeper,
_template.as_layer().construct,
[],
... | Attaches the template to this with the _key is supplied with this layer.
Note: names were chosen to avoid conflicts.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_var_values: The values for the unbound_vars.
Returns:
A new layer... |
def onecmd(self, statement: Union[Statement, str]) -> bool:
if not isinstance(statement, Statement):
statement = self._complete_statement(statement)
if statement.command in self.macros:
stop = self._run_macro(statement)
else:
func =... | This executes the actual do_* method for a command.
If the command provided doesn't exist, then it executes default() instead.
:param statement: intended to be a Statement instance parsed command from the input stream, alternative
acceptance of a str is present only for backw... |
def major_tick_mark(self):
majorTickMark = self._element.majorTickMark
if majorTickMark is None:
return XL_TICK_MARK.CROSS
return majorTickMark.val | Read/write :ref:`XlTickMark` value specifying the type of major tick
mark to display on this axis. |
def make_application():
settings = {}
application = web.Application([web.url(, SimpleHandler)], **settings)
statsd.install(application, **{: })
return application | Create a application configured to send metrics.
Metrics will be sent to localhost:8125 namespaced with
``webapps``. Run netcat or a similar listener then run this
example. HTTP GETs will result in a metric like::
webapps.SimpleHandler.GET.204:255.24497032165527|ms |
def _parse_binding_config(self, binding_config):
parsed_bindings = set()
for acl in binding_config[]:
for intf in acl[]:
parsed_bindings.add((intf[], acl[],
a_const.INGRESS_DIRECTION))
for intf in acl[]:
... | Parse configured interface -> ACL bindings
Bindings are returned as a set of (intf, name, direction) tuples:
set([(intf1, acl_name, direction),
(intf2, acl_name, direction),
...,
]) |
def WriteAllCrashDetails(client_id,
crash_details,
flow_session_id=None,
hunt_session_id=None,
token=None):
if data_store.AFF4Enabled():
with aff4.FACTORY.Create(
client_id, aff4_grr.VFSGRRClient, tok... | Updates the last crash attribute of the client. |
def search_shows_by_keyword(self, keyword, unite=0, source_site=None,
category=None, release_year=None,
area=None, orderby=,
paid=None, hasvideotype=None,
page=1, count=20):
u... | doc: http://open.youku.com/docs/doc?id=82 |
def accuracy(conf_matrix):
total, correct = 0.0, 0.0
for true_response, guess_dict in conf_matrix.items():
for guess, count in guess_dict.items():
if true_response == guess:
correct += count
total += count
return correct/total | Given a confusion matrix, returns the accuracy.
Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml |
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):
start = time.time()
while True:
found = self.find_devices(service_uuids, name)
if len(found) > 0:
return found[0]
if time.time(... | Return the first device that advertises the specified service UUIDs or
has the specified name. Will wait up to timeout_sec seconds for the device
to be found, and if the timeout is zero then it will not wait at all and
immediately return a result. When no device is found a value of None is
... |
def _reset(self, constraints=None):
if self._proc is None:
self._start_proc()
else:
if self.support_reset:
self._send("(reset)")
for cfg in self._init:
self._send(cfg)
else:
self._stop_proc(... | Auxiliary method to reset the smtlib external solver to initial defaults |
def update_one(self, filter, update, **kwargs):
self._arctic_lib.check_quota()
return self._collection.update_one(filter, update, **kwargs) | See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one |
def load(self):
LOGGER.debug(, self.name, self.query)
if self.waiting:
self.notify(, , target=, ntype=)
else:
self.waiting = True
try:
response = yield self.client.fetch(self.url, auth_username=self.auth_username,
... | Load data from Graphite. |
def write_matrix(outputfile, matrix):
try:
stream = open(outputfile, )
for row in matrix:
if isinstance(row, list) or isinstance(row, tuple):
row = [str(el).strip() for el in row]
stream.write(.join(row) + )
else:
stream.w... | Write down the provided matrix in the specified outputfile.
:arg outputfile, name of the outputfile in which the QTLs found are
written.
:arg matrix, the list of lists of data to write. |
def host_type(host):
if not host:
return HOST_REG_NAME
elif host[0] == :
return HOST_IP_LITERAL
elif __valid_IPv4address(host):
return HOST_IPV4_ADDRESS
else:
return HOST_REG_NAME | Correctly classify correct RFC 3986 compliant hostnames, but do not try
hard to validate compliance anyway...
NOTE: indeed we allow a small deviation from the RFC 3986: IPv4
addresses are allowed to contain bytes represented in hexadecimal or
octal notation when begining respectively with '0x'/'0X' and ... |
def try_next(self):
try:
change = self._cursor._try_next(True)
except ConnectionFailure:
self._resume()
change = self._cursor._try_next(False)
except OperationFailure as exc:
if exc.code in _NON_RESUMABLE_GETMORE_ERRORS:
... | Advance the cursor without blocking indefinitely.
This method returns the next change document without waiting
indefinitely for the next change. For example::
with db.collection.watch() as stream:
while stream.alive:
change = stream.try_next()
... |
def get(self, key, default=None):
try:
value = self.__getitem__(key)
except KeyError:
value = None
if isinstance(value, bytes):
value = value.decode()
return value or default | Return the value at key ``key``, or default value ``default``
which is None by default.
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc.get('l0')
['1', '2', '3', '4']
>>> dc['l0']
['1', '2', '3', '4']
>>> dc.clear()
:param key: key of valu... |
def to_color(self, value, maxvalue, scale, minvalue=0.0):
if scale == :
if minvalue >= maxvalue:
raise Exception()
else:
value = 1.*(value-minvalue) / (maxvalue-minvalue)
elif scale == :
if value < 1 or maxvalue <= 1:
... | convert continuous values into colors using matplotlib colorscales
:param value: value to be converted
:param maxvalue: max value in the colorscale
:param scale: lin, log, sqrt
:param minvalue: minimum of the input values in linear scale (default is 0)
:return: the color correspo... |
def author_structure(user):
return {: user.pk,
: user.get_username(),
: user.__str__(),
: user.email} | An author structure. |
def check_command(self, command):
code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command))
if code != 0:
print("Command is not callable: {0}".format(command))
return False
else:
return True | Check if command can be called. |
def print_summary(self) -> None:
print("Tasks execution time summary:")
for mon_task in self._monitor_tasks:
print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time)) | Prints the tasks' timing summary. |
def compile_protos():
subprocess.check_call(
["python", "makefile.py", "--clean"], cwd=THIS_DIRECTORY) | Builds necessary assets from sources. |
def delete_token(self,
token_name,
project_name,
dataset_name):
url = self.url() + "/nd/resource/dataset/{}".format(dataset_name)\
+ "/project/{}".format(project_name)\
+ "/token/{}/".format(token_name)
req =... | Delete a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
token_name (str): Token name
channel_name (str): Channel name project is based on
Returns:
bool: True if ... |
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
watcher = watch.Watch()
for event in watcher.stream(
resource.get,
namespace=namespace,
name=name,
field_selector=... | Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filte... |
async def _connect_and_read(self):
while not self._stopped:
try:
self._connection_attempts += 1
async with aiohttp.ClientSession(
loop=self._event_loop,
timeout=aiohttp.ClientTimeout(total=self.timeout),
... | Retreives and connects to Slack's RTM API.
Makes an authenticated call to Slack's RTM API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
retrieve a new url and reconnect any time the... |
def adjoint(self):
import scipy.sparse
adjoint_ops = [op.adjoint for op in self.ops.data]
data = np.empty(len(adjoint_ops), dtype=object)
data[:] = adjoint_ops
indices = [self.ops.col, self.ops.row]
shape = (self.ops.shape[1], self.ops.shape[0])
... | Adjoint of this operator.
The adjoint is given by taking the transpose of the matrix
and the adjoint of each component operator.
In weighted product spaces, the adjoint needs to take the
weightings into account. This is currently not supported.
Returns
-------
... |
def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0):
cov = {}
s2bins, bins2s = parse_s2bins(s2bins)
rna_cov = parse_rna(rna, s2bins, min_rna)
s2bins, bins2s = filter_missing_rna(s2bins, bins2s, rna_cov)
for line in mapping:
line = line.strip().split()
... | 1. determine bin coverage
2. determine rRNA gene coverage
3. compare |
def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
try:
N = values_list.count()
except:
N = len(values_list)
if verbosity > 0:
print % N
index, dupes = {}, {}
pbar = None
if verbosity and N > min(1000000, max(0, 1... | Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]})
True |
def experiment(parser, token):
try:
token_contents = token.split_contents()
experiment_name, alternative, weight, user_variable = _parse_token_contents(token_contents)
node_list = parser.parse((, ))
parser.delete_first_token()
except ValueError:
raise template.Templ... | Split Testing experiment tag has the following syntax :
{% experiment <experiment_name> <alternative> %}
experiment content goes here
{% endexperiment %}
If the alternative name is neither 'test' nor 'control' an exception is raised
during rendering. |
def set_mode(self, mode):
if not mode:
raise AbodeException(ERROR.MISSING_ALARM_MODE)
elif mode.lower() not in CONST.ALL_MODES:
raise AbodeException(ERROR.INVALID_ALARM_MODE, CONST.ALL_MODES)
mode = mode.lower()
response = self._abode.send_request(
... | Set Abode alarm mode. |
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE):
s encrypt
{}/{}.key{}/{}.crt{}/{}.csr{certificates_path}/{common_name}-signed.crtopenssl req -new -sha256 -key {private_key_path} -subj "/CN={common_name}" -out {certificate_request_path}'
cmd = cmd.format(
private_key_path=private_key_p... | Sign certificate with acme_tiny for let's encrypt |
def move_active_window(x, y):
window_id = get_window_id()
cmd=[,, window_id, str(x), str(y)]
subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate() | Moves the active window to a given position given the window_id and absolute co ordinates,
--sync option auto passed in, will wait until actually moved before giving control back to us
will do nothing if the window is maximized |
def _eq(self, other):
return (self.type, self.children) == (other.type, other.children) | Compare two nodes for equality. |
def _to_chi(rep, data, input_dim, output_dim):
if rep == :
return data
_check_nqubit_dim(input_dim, output_dim)
if rep == :
return _from_operator(, data, input_dim, output_dim)
if rep != :
data = _to_choi(rep, data, input_dim, output_dim)
return _choi_to_chi(da... | Transform a QuantumChannel to the Chi representation. |
def save_session(zap_helper, file_path):
console.debug(.format(file_path))
zap_helper.zap.core.save_session(file_path, overwrite=) | Save the session. |
def sanitize_url(url: str) -> str:
for part in reversed(url.split()):
filename = re.sub(r, , part)
if len(filename) > 0:
break
else:
raise ValueError(, url)
return filename | Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename |
def start(configfile=None, daemonize=False, environment=None,
fastcgi=False, scgi=False, pidfile=None,
cgi=False, debug=False):
sys.path = [] + sys.path
def new_as_dict(self, raw=True, vars=None):
result = {}
for section in self.sections():
... | Subscribe all engine plugins and start the engine. |
def combine_lists_reducer(
key: str,
merged_list: list,
component: COMPONENT
) -> list:
merged_list.extend(getattr(component, key))
return merged_list | Reducer function to combine the lists for the specified key into a
single, flat list
:param key:
The key on the COMPONENT instances to operate upon
:param merged_list:
The accumulated list of values populated by previous calls to this
reducer function
:param component:
T... |
def chrome_tracing_object_transfer_dump(self, filename=None):
client_id_to_address = {}
for client_info in ray.global_state.client_table():
client_id_to_address[client_info["ClientID"]] = "{}:{}".format(
client_info["NodeManagerAddress"],
client_info[... | Return a list of transfer events that can viewed as a timeline.
To view this information as a timeline, simply dump it as a json file
by passing in "filename" or using using json.dump, and then load go to
chrome://tracing in the Chrome web browser and load the dumped file.
Make sure to ... |
def get(cls, id, api=None):
id = Transform.to_resource(id)
api = api if api else cls._API
if in cls._URL:
extra = {: cls.__name__, : {: id}}
logger.info(.format(cls), extra=extra)
resource = api.get(url=cls._URL[].format(id=id)).json()
re... | Fetches the resource from the server.
:param id: Resource identifier
:param api: sevenbridges Api instance.
:return: Resource object. |
def make_encoder(self,formula_dict,inter_list,param_dict):
X_dict = {}
Xcol_dict = {}
encoder_dict = {}
for key in formula_dict:
encoding,arg = formula_dict[key]
if in encoding:
drop_name = arg
... | make the encoder function |
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None,
drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None,
pad_idx:int=1) -> nn.Module:
"Create a text classifier from `arch` and it... | Create a text classifier from `arch` and its `config`, maybe `pretrained`. |
def sign(self, method, params):
query_str = utils.percent_encode(params.items(), True)
str_to_sign = "{0}&%2F&{1}".format(
method, utils.percent_quote(query_str)
)
sig = hmac.new(
utils.to_bytes(self._secret_key + "&"),
utils.to_bytes(str_to... | Calculate signature with the SIG_METHOD(HMAC-SHA1)
Returns a base64 encoeded string of the hex signature
:param method: the http verb
:param params: the params needs calculate |
def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):
get_bids_data = {}
if bid_ids:
get_bids_data[] = bid_ids
if project_ids:
get_bids_data[] = project_ids
get_bids_data[] = limit
get_bids_data[] = offset
response = make_get_request(session, , params_d... | Get the list of bids |
def acquire_lock(cls, mode, user=None):
if not user:
return
with EteSyncCache.lock:
cls.user = user
cls.etesync = cls._get_etesync_for_user(cls.user)
if cls._should_sync():
cls._mark_sync()
cls.etesync.get_or_cre... | Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty. |
def get_next_invalid_time_from_t(self, timestamp):
timestamp = int(timestamp)
original_t = timestamp
dr_mins = []
for daterange in self.dateranges:
timestamp = original_t
cont = True
while cont:
start = daterange.get_... | Get the next invalid time
:param timestamp: timestamp in seconds (of course)
:type timestamp: int or float
:return: timestamp of next invalid time
:rtype: int or float |
def _subset(self, subset):
pl = Pipeline(bundle=self.bundle)
for group_name, pl_segment in iteritems(self):
if group_name not in subset:
continue
pl[group_name] = pl_segment
return pl | Return a new pipeline with a subset of the sections |
def hide(self, selections):
atomsbonds
if in selections:
self.hidden_state[] = selections[]
self.on_atom_hidden_changed()
if in selections:
self.hidden_state[] = selections[]
self.on_bond_hidden_changed()
if in selections:
... | Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
representation.hide({'atoms': Selection([0], sys... |
def variableMissingValue(ncVar):
attributes = ncVarAttributes(ncVar)
if not attributes:
return None
for key in (, , , , ):
if key in attributes:
missingDataValue = attributes[key]
return missingDataValue
return None | Returns the missingData given a NetCDF variable
Looks for one of the following attributes: _FillValue, missing_value, MissingValue,
missingValue. Returns None if these attributes are not found. |
def process_cancel(self):
self.log_response_message()
if not self.in_cancel:
return
while True:
token_id = self.get_token_id()
self.process_token(token_id)
if not self.in_cancel:
return | Process the incoming token stream until it finds
an end token DONE with the cancel flag set.
At that point the connection should be ready to handle a new query.
In case when no cancel request is pending this function does nothing. |
def deserialize_by_field(value, field):
if isinstance(field, forms.DateTimeField):
value = parse_datetime(value)
elif isinstance(field, forms.DateField):
value = parse_date(value)
elif isinstance(field, forms.TimeField):
value = parse_time(value)
return value | Some types get serialized to JSON, as strings.
If we know what they are supposed to be, we can deserialize them |
def write_data(hyper_params,
mode,
sequence,
num_threads):
if not isinstance(sequence, Sequence) and not (callable(getattr(sequence, "__getitem__", None)) and callable(getattr(sequence, "__len__", None))):
raise ValueError("sequence must be tf.keras.utils.Se... | Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation".
:param sequence: A tf.keras.uti... |
def _api_put(self, url, **kwargs):
kwargs[] = self.url + url
kwargs[] = self.auth
headers = deepcopy(self.headers)
headers.update(kwargs.get(, {}))
kwargs[] = headers
self._put(**kwargs) | A convenience wrapper for _put. Adds headers, auth and base url by
default |
def send_audio_packet(self, data, *, encode=True):
self.checked_add(, 1, 65535)
if encode:
encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)
else:
encoded_data = data
packet = self._get_voice_packet(encoded_data)
try:
... | Sends an audio packet composed of the data.
You must be connected to play audio.
Parameters
----------
data: bytes
The :term:`py:bytes-like object` denoting PCM or Opus voice data.
encode: bool
Indicates if ``data`` should be encoded into Opus.
... |
def get_objects(self):
objects = {}
for key in six.iterkeys(self.form_classes):
objects[key] = None
return objects | Returns dictionary with the instance objects for each form. Keys should match the
corresponding form. |
def process(self, frames, eod):
src_index = 0
remaining = len(frames)
while remaining:
space = self.buffer_size - self.len
copylen = remaining < space and remaining or space
src = frames[src_index:src_index + copylen]
if self.len == 0 and... | Returns an iterator over tuples of the form (buffer, eod)
where buffer is a fixed-sized block of data, and eod indicates whether
this is the last block.
In case padding is deactivated the last block may be smaller than
the buffer size. |
def parameters_to_datetime(self, p):
dt = p[self._param_name]
return datetime(dt.year, dt.month, dt.day) | Given a dictionary of parameters, will extract the ranged task parameter value |
def mget(self, *keys):
keys = list(map(self.get_key, keys))
return list(map(self._loads, self._client.mget(*keys))) | -> #list of values at the specified @keys |
def deleteMetadata(self, remote, address, key):
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
except Exception as err:
LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err)) | Delete metadata of device |
def parse_refresh(text):
match = re.search(r, text, re.IGNORECASE)
if match:
url = match.group(1)
if url.startswith():
url = url.strip()
elif url.startswith("")
return clean_link_soup(url) | Parses text for HTTP Refresh URL.
Returns:
str, None |
def from_dict(self, description):
assert(self.ident == description[])
self.partitions = description[]
self.indices = description[] | Configures the task store to be the task_store described
in description |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.