Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
351,500
def sample_visible_from_hidden(self, hidden, n_features): visible_activation = tf.add( tf.matmul(hidden, tf.transpose(self.W)), self.bv_ ) if self.visible_unit_type == : vprobs = tf.nn.sigmoid(visible_activation) elif self.visible_unit_type ...
Sample the visible units from the hidden units. This is the Negative phase of the Contrastive Divergence algorithm. :param hidden: activations of the hidden units :param n_features: number of features :return: visible probabilities
351,501
def AddEthernetDevice(self, device_name, iface_name, state): path = + device_name wired_props = {: False, : dbus.String(), : dbus.String(), : dbus.UInt32(0)} self.AddObject(path, , wired_props, ...
Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/...
351,502
def gradient(f, **kwargs): pos_kwarg, positions, axes = _process_gradient_args(f, kwargs) return tuple(first_derivative(f, axis=axis, **{pos_kwarg: positions[ind]}) for ind, axis in enumerate(axes))
Calculate the gradient of a grid of values. Works for both regularly-spaced data, and grids with varying spacing. Either `coordinates` or `deltas` must be specified, or `f` must be given as an `xarray.DataArray` with attached coordinate and projection information. If `f` is an `xarray.DataArray`, and...
351,503
def tweet(ctx, message): if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + message) ctx.exit(2) if not ctx.obj[]: ctx.obj[].update_status(message) else: click.echo("Tweet not sent due to dry-run mode.")
Sends a tweet directly to your timeline
351,504
def _get_tuple_from_route(route): if isinstance(route, tuple): assert len(route) >= 2 pattern, handler_class = route[:2] elif isinstance(route, tornado.web.URLSpec): pattern, handler_class = route.regex.pattern, route.handler_class else: raise TypeError("Unknown route ty...
Return (pattern, handler_class, methods) tuple from ``route`` :type route: tuple|tornado.web.URLSpec :rtype: tuple :raises TypeError: If ``route`` is not a tuple or URLSpec
351,505
def load_states(): states = {} __opts__[] = salt.loader.grains(__opts__) __opts__[] = __pillar__ lazy_utils = salt.loader.utils(__opts__) lazy_funcs = salt.loader.minion_mods(__opts__, utils=lazy_utils) lazy_serializers = salt.loader.serializers(__opts__) lazy_states = salt.loader...
This loads our states into the salt __context__
351,506
def GetServerEstimate(server,alias=None): if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call(,,{: alias, : server}) if int(r[]) == 0: return(r)
Gets the estimated monthly cost for a given server. https://t3n.zendesk.com/entries/22422323-GetServerEstimate :param alias: short code for a particular account. If none will use account's default alias :param server: name of server to query
351,507
def save(self, modelfile, layer=None): if layer: obj = {layer: self.model[layer]} else: obj = self.model with open(modelfile, ) as fp: json.dump(obj, fp, indent=2, sort_keys=True)
Save a model file. :param modelfile: The name of the json file to save. :type modelfile: str :param layer: Optionally save only specified layer. :type layer: str
351,508
def get_logging_stream_handler(logger=None, formatter=LOGGING_DEFAULT_FORMATTER): logger = LOGGER if logger is None else logger logging_stream_handler = logging.StreamHandler(Streamer()) logging_stream_handler.setFormatter(formatter) logger.addHandler(logging_stream_handler) return logging_str...
Adds a logging stream handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :param formatter: Handler formatter. :type formatter: Formatter :return: Added handler. ...
351,509
def run(name, params, delay): args = [p for p in params if not in p] kwargs = dict(p.split() for p in params if in p) if name not in celery.tasks: exit_with_error(, name) job = celery.tasks[name] label = job_label(name, args, kwargs) if delay: log.info(, label) jo...
Run the job <name> Jobs args and kwargs are given as parameters without dashes. Ex: udata job run my-job arg1 arg2 key1=value key2=value udata job run my-job -- arg1 arg2 key1=value key2=value
351,510
def parse_vhdl(text): lex = VhdlLexer name = None kind = None saved_type = None end_param_group = False cur_package = None metacomments = [] parameters = [] param_items = [] generics = [] ports = [] sections = [] port_param_index = 0 last_item = None array_range_start_pos = 0 ob...
Parse a text buffer of VHDL code Args: text(str): Source code to parse Returns: Parsed objects.
351,511
def full(shape, val, dtype=None, **kwargs): if dtype is None: dtype = _numpy.float32 return _internal._full(shape=shape, dtype=dtype, value=float(val), **kwargs)
Returns a new array of given shape and type, filled with the given value `val`. Parameters ---------- shape : int or sequence of ints Shape of the new array. val : scalar Fill value. dtype : str or numpy.dtype, optional The value type of the inner value, default to ``np.flo...
351,512
def set(self, key, value, ex=None, px=None, nx=False, xx=False): command = [b, key, value] if ex: command += [b, ascii(ex).encode()] if px: command += [b, ascii(px).encode()] if nx: command.append(b) if xx: command.append(b...
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful :meth:`~tredis.RedisClient.set` operation. If the value is not one of :class:`str`, :class:`bytes`, or ...
351,513
def create_address(self, account_id, **params): response = self._post(, , account_id, , data=params) return self._make_api_object(response, Address)
https://developers.coinbase.com/api/v2#create-address
351,514
def get_host_vsan_system(service_instance, host_ref, hostname=None): s vsan system service_instance Service instance to the host or vCenter host_ref Refernce to ESXi host hostname Name of ESXi host. Default value is None. configManager.vsanSystemconfig.enabledHost\{0}\ ...
Returns a host's vsan system service_instance Service instance to the host or vCenter host_ref Refernce to ESXi host hostname Name of ESXi host. Default value is None.
351,515
def _raise_response_exceptions(response): if not response.ok and in response.headers: msg = response.headers[] if in msg: raise OAuthInsufficientScope(, response.url) elif in msg: raise OAuthInvalidToken(, response.url) else: raise OAuthExc...
Raise specific errors on some status codes.
351,516
def forwards(self, orm): "Write your forwards methods here." rows = db.execute("select distinct feature_type from content_content") for row in rows: feature_type = row[0] try: ft = orm.FeatureType.objects.get(slug=slugify(feature_type)) except...
Write your forwards methods here.
351,517
def lstm(name, input, state_c, state_h, kernel_i, kernel_j, kernel_f, kernel_o, bias_i, bias_j, bias_f, bias_o, new_state_c, new_state_h): nn = Build(name) inputs = nn.concat(input, state_h) i = nn.sigmoid(nn.mad(x=inputs, kernel=kernel_i, bias=bias_i)) j = nn.tanh(nn.mad(inputs, kernel_...
Full: - it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi) - ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf) - ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc) - Ct = ft . Ct_1 + it . ct - ot = f(Xt*Wo + Ht_1*Ro + Po . Ct + Wbo + Rbo) - Ht = ot . h(Ct)
351,518
def learn_mealy_machine(self): logging.info() self._init_table() logging.info() while True: closed = False while not closed: logging.debug() closed, string = self.observation_table.is_closed() ...
Implements the high level loop of the algorithm for learning a Mealy machine. Args: None Returns: MealyMachine: The learned mealy machine
351,519
def retrieve_file_from_EBI(resource, silent = True): if not silent: colortext.printf("Retrieving %s from EBI" % os.path.split(resource)[1], color = "aqua") attempts = 10 while attempts > 0: try: return get_insecure_resource("ftp.ebi.ac.uk", resource)...
Retrieve a file from the RCSB.
351,520
def getAnalyses(self, **kwargs): if kwargs.get(): kwargs[] = kwargs.get() del kwargs[] if kwargs.get(): kwargs[] = kwargs.get() del kwargs[] for key in kwargs: if key not in [, , , ]: sys.std...
Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- O...
351,521
def ancestry(self, context): log.debug("get ancestry %s", context) if context is None: return ancestors.pop()
Return the ancestry of the context (that is, all of the packages and modules containing the context), in order of descent with the outermost ancestor last. This method is a generator.
351,522
def split(self, X, y): check_ts_data(X, y) Xt, Xc = get_ts_data_parts(X) Ns = len(Xt) Xt_new, y_new = self._ts_slice(Xt, y) if Xc is not None: Xc_new = np.concatenate([Xc] * self.n_splits) X_new = TS_Data(Xt_new, Xc_new) else: ...
Splits time series data and target arrays, and generates splitting indices Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (optionally) contextual data y : array-like shape [n_series, ] target vector Returns ------...
351,523
def transliterate(self, word): encoded_word = self.encoder(word) decoded_word = self.decoder(encoded_word) return decoded_word
Transliterate the word from its source language to the target one. The method works by encoding the word into English then decoding the new Enlgish word to the target language.
351,524
def unpack_reply(cls, header, payload): reply = cls( header.session_id, header.packet_count, segments=tuple(ReplySegment.unpack_from(payload, expected_segments=header.num_segments)), header=header ) trace(reply) return reply
Take already unpacked header and binary payload of received request reply and creates message instance :param header: a namedtuple header object providing header information :param payload: payload (BytesIO instance) of message
351,525
def add_abs_path_directories(opts_dict): assert_has_input_output(opts_dict) opts_dict[] = path.abspath(opts_dict[]) if opts_dict[]: opts_dict[] += get_path_separator() opts_dict[] = path.abspath(opts_dict[]) + \ get_path_separator()
Adds 'abs_input' and 'abs_output' to opts_dict :param opts_dict: dictionary that will be modified
351,526
def coerce(self, value, **kwargs): Location = namedtuple(, [, ]) return Location(float(value.get()), float(value.get()))
Coerces value to Location object
351,527
def info(self, **kwargs): path = self._get_series_id_season_number_episode_number_path() response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the primary information about a TV episode by combination of a season and episode number. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any TV series method. Returns: A dict respr...
351,528
def check_encoding(proof_req: dict, proof: dict) -> bool: LOGGER.debug(, proof_req, proof) cd_id2proof_id = {} p_preds = {} for idx in range(len(proof[])): cd_id = proof[][idx][] cd_id2proof_id[cd_id] = idx p_preds[cd_id] = { ...
Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK, False for encoding mismatch
351,529
def others2db(file_path, file_type, is_copy, step_id, db_conn): logging.info("Processing " % file_path) df = db_conn.db_session.query(db_conn.DataFile).filter_by(path=file_path).one_or_none() if not df: df = db_conn.DataFile( path=file_path, type=file_type, ...
Extract some meta-data from files (actually mostly from their paths) and stores it in a DB. Arguments: :param file_path: File path. :param file_type: File type. :param is_copy: Indicate if this file is a copy. :param step_id: Step ID. :param db_conn: Database connection. :return:
351,530
def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self._drag_origin = None widget = self.widget type(widget).mouseReleaseEvent(widget, event)
Handle the mouse release event for the drag operation.
351,531
def data_as_matrix(self, keys=None, return_basis=False, basis=None, alias=None, start=None, stop=None, step=None, window_length=None, ...
Provide a feature matrix, given a list of data items. I think this will probably fail if there are striplogs in the data dictionary for this well. TODO: Deal with striplogs and other data, if present. Args: keys (list): List of the logs to export from the data ...
351,532
def iter_deployments(self, number=-1, etag=None): url = self._build_url(, base_url=self._api) i = self._iter(int(number), url, Deployment, etag=etag) i.headers.update(Deployment.CUSTOM_HEADERS) return i
Iterate over deployments for this repository. :param int number: (optional), number of deployments to return. Default: -1, returns all available deployments :param str etag: (optional), ETag from a previous request for all deployments :returns: generator of :...
351,533
def image_query_record(self, imagename=None): if imagename: with get_image_conn() as conn: result = conn.execute("SELECT * FROM image WHERE " "imagename=?", (imagename,)) image_list = result.fetchall() if not...
Query the image record from database, if imagename is None, all of the image records will be returned, otherwise only the specified image record will be returned.
351,534
def update_port(self, port, name, admin_state_up=True): port_id = self._find_port_id(port) body = {: name, : admin_state_up} return self.network_conn.update_port(port=port_id, body={: body})
Updates a port
351,535
def endswith(self, value): newq = self.copy() newq.setOp(Query.Op.Endswith) newq.setValue(value) return newq
Sets the operator type to Query.Op.Endswith and sets \ the value to the inputted value. This method will only work on text \ based fields. :param value <str> :return <Query> :usage |>>> from orb import Query as Q ...
351,536
def slab_from_csl(csl, surface, normal, trans_cry, max_search=20, quick_gen=False): trans = trans_cry ctrans = np.linalg.inv(trans.T) t_matrix = csl.copy() ab_vector = [] miller = np.matmul(surface, csl.T) if reduce(gcd, mill...
By linear operation of csl lattice vectors to get the best corresponding slab lattice. That is the area of a,b vectors (within the surface plane) is the smallest, the c vector first, has shortest length perpendicular to surface [h,k,l], second, has shortest length itself. Args: ...
351,537
def client_unenroll(self, client): client = self._client_id(client) response = self._delete(url.clients_id.format(id=client)) self._check_response(response, 204)
Unenroll a client. Uses DELETE to /clients/<client> interface. :Args: * *client*: (str) Client's ID
351,538
def SWdensityFromCTD(SA, t, p, potential=False): import numpy import gsw CT = gsw.CT_from_t(SA, t, p) if potential: p = numpy.zeros(len(SA)) return gsw.rho(SA, CT, p)
Calculate seawater density at CTD depth Args ---- SA: ndarray Absolute salinity, g/kg t: ndarray In-situ temperature (ITS-90), degrees C p: ndarray Sea pressure (absolute pressure minus 10.1325 dbar), dbar Returns ------- rho: ndarray Seawater density, i...
351,539
def _cli_command(commands, method=, **kwargs): if not isinstance(commands, (list, tuple)): commands = [commands] rpc_responses = rpc(commands, method=method, **kwargs) txt_responses = [] for rpc_reponse in rpc...
Execute a list of CLI commands.
351,540
def zip_bundle(tag=True): rev = __version__ print("Cleaning old build files.") clean() local("mkdir -p build") print("Bundling new files.") with lcd("sphinx_bootstrap_theme/bootstrap"): local("zip -r ../../build/bootstrap.zip .") dest = os.path.abspath(os.path.join(DL_D...
Create zip file upload bundles. @param tag Use git tag instead of hash?
351,541
def properties_mutator(cls, name, ioper=False): def wrapper(self, *args, **kwargs): if ( getattr(self, , None) is None or getattr(self, , ) == or self is not getattr(self._instance, self._name) ): return getattr(super(cls, s...
Wraps a mutating container method to add HasProperties notifications If the container is not part of a HasProperties instance, behavior is unchanged. However, if it is part of a HasProperties instance the new method calls set, triggering change notifications.
351,542
def read_pal_version(): verfile = os.path.join("cextern", "pal", "configure.ac") verstring = "-1.-1.-1" for line in open(verfile): if line.startswith("AC_INIT"): match = re.search(r"\[(\d+\.\d+\.\d+)\]", line) if match: verstring = match.grou...
Scans the PAL configure.ac looking for the version number. (vers, maj, min, patchlevel) = read_pal_version() Returns the version as a string and the major, minor and patchlevel version integers
351,543
def store_list(self, cb=None): from StringIO import StringIO import json d = {} for k, v in self.list().items(): if in v: del v[] d[k] = v strio = StringIO(json.dumps(d)) sink = self.put_stream() copy_file_...
List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not possible to traverse the tree
351,544
def checkdiff(a,b,sp=True): if sp: a=splitpreserve(a); b=splitpreserve(b) res=applydiff(a,rediff(a,b)) if sp: res=.join(res) return res
take diff of a to b, apply to a, return the applied diff so external code can check it against b
351,545
def get_enabled(name, app): plugins = app.config[] return dict(_ep_to_kv(e) for e in iter_all(name) if e.name in plugins)
Get (and load) entrypoints registered on name and enabled for the given app.
351,546
def get_latex_braced_group(s, pos, brace_type=, **parse_flags): return LatexWalker(s, **parse_flags).get_latex_braced_group(pos=pos, brace_type=brace_type)
Reads a latex expression enclosed in braces {...}. The first token of `s[pos:]` must be an opening brace. Returns a tuple `(node, pos, len)`. `pos` is the first char of the expression (which has to be an opening brace), and `len` is its length, including the closing brace. .. deprecated:: 1.0 ...
351,547
def groupby_count(i, key=None, force_keys=None): counter = defaultdict(lambda: 0) if not key: key = lambda o: o for k in i: counter[key(k)] += 1 if force_keys: for k in force_keys: counter[k] += 0 return counter.items()
Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)]
351,548
def Tags(self): return { IMAGES: self.images.Keys(), AUDIO: self.audios.Keys(), HISTOGRAMS: self.histograms.Keys(), SCALARS: self.scalars.Keys(), COMPRESSED_HISTOGRAMS: self.compressed_histograms.Keys(), TENSORS: self.tensors.Keys(), GRA...
Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary.
351,549
def _every(times, step_size, index): current = index * step_size step = current // times * times reached = current >= step overshot = current >= step + step_size return current and reached and not overshot
Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether the operation should be called for the current index.
351,550
def create_proxy_cert( loaded_cert, loaded_private_key, loaded_public_key, lifetime_hours ): builder = x509.CertificateBuilder() serial = struct.unpack("<Q", os.urandom(8))[0] builder = builder.serial_number(serial) builder = builder.not_valid_before(datetime.dat...
Given cryptography objects for an issuing certificate, a public_key, a private_key, and an int for lifetime in hours, creates a proxy cert from the issuer and public key signed by the private key.
351,551
def load_data_source(local_path, remote_source_list, open_method, open_method_kwargs=dict(), remote_kwargs=dict(), verbose=True): apeozone_cam3_5_54.nchttp://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/t exist then iterate...
Flexible data retreiver to download and cache the data files locally. Usage example (this makes a local copy of the ozone data file): :Example: .. code-block:: python from climlab.utils.data_source import load_data_source from xarray import open_dataset ozonename ...
351,552
def split_stdout_lines(stdout): seen_dash = False for l in stdout.split("\n"): l = l.strip() if l.startswith("---"): seen_dash = True continue if not seen_dash: continue if not l or l.startswit...
Given the standard output from NetMHC/NetMHCpan/NetMHCcons tools, drop all {comments, lines of hyphens, empty lines} and split the remaining lines by whitespace.
351,553
def _scp(p, main=False): global _current_subproject global _current_project if p is None: mp = project() if main or _current_project is None else \ _current_project _current_subproject = Project(main=mp) elif not main: _current_subproject = p else: _c...
scp version that allows a bit more control over whether the project is a main project or not
351,554
def is_primary_in_view(self, viewNo: int) -> Optional[bool]: if viewNo not in self.primaryNames: return False return self.primaryNames[viewNo] == self.name
Return whether this replica was primary in the given view
351,555
def node_has_edge_with_label(self, node_name, edge_label): G = self.G for edge in G.edges(node_name): to = edge[1] relation_name = G.edges[node_name, to][] if relation_name == edge_label: return to return None
Looks for an edge from node_name to some other node with the specified label. Returns the node to which this edge points if it exists, or None if it doesn't. Parameters ---------- G : The graph object node_name : Node that the edge starts at ...
351,556
def _prepare(cls, context: Dict) -> Dict: if not context and cls.raise_empty_context: raise PolyaxonActionException(.format(cls.name)) return context
This is where you should alter the context to fit the action. Default behaviour will leave the context as it is.
351,557
def set_font_properties(style_less, nbfont=None, tcfont=None, monofont=None, monosize=11, tcfontsize=13, nbfontsize=13, prfontsize=95, ...
Parent function for setting notebook, text/md, and codecell font-properties
351,558
def trimNs(seq, line, newagp): start, end = line.component_beg, line.component_end size = end - start + 1 leftNs, rightNs = 0, 0 lid, lo = line.component_id, line.orientation for s in seq: if s in : leftNs += 1 else: break for s in seq[::-1]: ...
Test if the sequences contain dangling N's on both sides. This component needs to be adjusted to the 'actual' sequence range.
351,559
def disapproveproposal(ctx, proposal, account): pprint(ctx.peerplays.disapproveproposal(proposal, account=account))
Disapprove a proposal
351,560
def deliveries(self): key = make_key( event=self.object.event, owner_name=self.object.owner.username, identifier=self.object.identifier ) return redis.lrange(key, 0, 20)
Get delivery log from Redis
351,561
def main_production(self): for rule in self.productions: if rule.leftside[0] == self._initialsymbol: return rule raise IndexError
Returns main rule
351,562
def pillar_refresh(self, force_refresh=False, notify=False): if self.connected: log.debug(, notify) async_pillar = salt.pillar.get_async_pillar( self.opts, self.opts[], self.opts[], self.opts[], pill...
Refresh the pillar
351,563
def circumcenter(self): if self.isRight: return self.hypotenuse.midpoint if self.A.isOrigin: t = self else: t = Triangle(self.A - self.A, self.B - self.A, self.C - self.A) if not t.A.isOrigin: ...
The intersection of the median perpendicular bisectors, Point. The center of the circumscribed circle, which is the circle that passes through all vertices of the triangle. https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 BUG: only finds the circumcenter in t...
351,564
def user_upsert(self, domain, userid, password=None, roles=None, name=None): if not roles or not isinstance(roles, list): raise E.ArgumentError("Roles must be a non-empty list") if password and domain == AuthDomain.External: raise E.ArgumentError("External domains must ...
Upsert a user in the cluster :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID :param password: The user password :param roles: A list of roles. A role can either be a simple string, or a list of `(role, bucket)` pairs. :par...
351,565
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs): libraries = libraries or [] include_dirs = kwargs.pop(, []) library_dirs = kwargs.pop(, []) if sys.platform == "win32": warnings.warn("Windows not yet supported.") ...
Link python extension module (shared object) for importing Parameters ---------- obj_files: iterable of path strings object files to be linked so_file: path string Name (path) of shared object file to create. If not specified it will have the basname of the last object f...
351,566
def init(path=None): default = get_default() if default is not None and not isinstance(default, VoidLogKeeper): return default tee = LogTee() set_default(tee) FluLogKeeper.init(path) tee.add_keeper(, FluLogKeeper()) return tee
Initialize the logging module. Construct the LogTee as the default keeper. Initialize the flulog and append it to the tee.
351,567
def make_segments(x, y): points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) return segments
Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array
351,568
async def disconnect(self): async with self._disconnect_lock: if self._state == ConnectionState.DISCONNECTED: return self._set_state(ConnectionState.DISCONNECTING) logger.info(, self.fingerprint) if self._reconnect_task: ...
Disconnect coroutine
351,569
def _RunCommand(self, command): arguments = shlex.split(command) process = subprocess.Popen( arguments, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) if not process: raise RuntimeError("Running: {0:s} failed.".format(command)) output, error = proces...
Runs the command.
351,570
def get_chebi_name_from_id(chebi_id, offline=False): chebi_name = chebi_id_to_name.get(chebi_id) if chebi_name is None and not offline: chebi_name = get_chebi_name_from_id_web(chebi_id) return chebi_name
Return a ChEBI name corresponding to the given ChEBI ID. Parameters ---------- chebi_id : str The ChEBI ID whose name is to be returned. offline : Optional[bool] Choose whether to allow an online lookup if the local lookup fails. If True, the online lookup is not attempted. Defa...
351,571
def old_decode_aes(key, iv_plus_encrypted): hexed_ciphertext = iv_plus_encrypted[32:] iv = binascii.unhexlify(hexed_iv) ciphertext = binascii.unhexlify(hexed_ciphertext) cipher = AES.new(ensure_bytes(old_pad(key)), mode=AES.MODE_CBC, IV=iv) plaintext = cipher.decrypt(ciphert...
Utility method to decode a payload consisting of the hexed IV + the hexed ciphertext using the given key. See above for more details. :param key: string, <= 32 bytes long :param iv_plus_encrypted: string, a hexed IV + hexed ciphertext
351,572
def authenticate(self, password): if super(FelicaLiteS, self).authenticate(password): self._authenticated = False self.read_from_ndef_service = self.read_without_mac self.write_to_ndef_service = self.wr...
Mutually authenticate with a FeliCa Lite-S Tag. FeliCa Lite-S supports enhanced security functions, one of them is the mutual authentication performed by this method. The first part of mutual authentication is to authenticate the tag with :meth:`FelicaLite.authenticate`. If succ...
351,573
def _create_buffers(self, view_size, buffer_size): requires_zoom_buffer = not view_size == buffer_size self._zoom_buffer = None if self._clear_color is None: if requires_zoom_buffer: self._zoom_buffer = Surface(view_size) self._buffer = Surface(b...
Create the buffers, taking in account pixel alpha or colorkey :param view_size: pixel size of the view :param buffer_size: pixel size of the buffer
351,574
def ParseLine(self, line): kv = line.split(None, 1) keyword = kv[0].lower() if keyword in self._aliases: keyword = self._aliases[keyword] self.processor(keyword, values)
Extracts keyword/value settings from the sshd config. The keyword is always the first string item. Values are the remainder of the string. In cases where an sshd config allows multiple values, these are split according to whatever separator(s) sshd_config permits for that value. Keywords and value...
351,575
def update(self, message): if isinstance(message, ExpanderMessage): zone = -1 if message.type == ExpanderMessage.ZONE: zone = self.expander_to_zone(message.address, message.channel, self.alarmdecoder_object.mode) if zone != -1: statu...
Update zone statuses based on the current message. :param message: message to use to update the zone tracking :type message: :py:class:`~alarmdecoder.messages.Message` or :py:class:`~alarmdecoder.messages.ExpanderMessage`
351,576
def overrides_a_method(class_node: astroid.node_classes.NodeNG, name: str) -> bool: for ancestor in class_node.ancestors(): if name in ancestor and isinstance(ancestor[name], astroid.FunctionDef): return True return False
return True if <name> is a method overridden from an ancestor
351,577
def volumes(self): if not self._is_parsed: self._Parse() self._is_parsed = True return iter(self._volumes.values())
generator(Volume): volumes generator.
351,578
def page(self, *args): for arg in args: self.__pages__.append(arg) return self
Pages takes *args and adds pages in order
351,579
def _send_float(self,value): if type(value) != float: value = float(value) if value > self.board.float_max or value < self.board.float_min: err = "Value {} exceeds the size of the board's float.".format(value) raise OverflowError(...
Return a float as a IEEE 754 format bytes object.
351,580
def time_calls_with_dims(**dims): def time_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): _timer = timer("%s_calls" % pyformance.registry.get_qualname(fn), **dims) with _timer.time(fn=pyformance.registry.get_qualname(fn)): ...
Decorator to time the execution of the function with dimensions.
351,581
def update_link_rewrite(self, old_rel, old_text, new_text, single_link=False): links = self.metadata.xpath(.format(old_rel, old_text)) if len(links) < 1: log.warning(.format(str(old_rel), str(old_text))) return False for link in links: link.text = new...
Rewrite the text() value of a link based on the link/@rel and link/text() value. This is similar to update_link_rel_based but users link/@rel AND link/text() values to determine which links have their link/@text() values updated. :param old_rel: The link/@rel value used to select link nodes to...
351,582
def shutdown(self): super(UDPTendrilManager, self).shutdown() self._sock = None self._sock_event.clear()
Unconditionally shuts the TendrilManager down, killing all threads and closing all tendrils.
351,583
def transform_bbox(bbox, target_crs): warnings.warn("This function is deprecated, use BBox.transform method instead", DeprecationWarning, stacklevel=2) return bbox.transform(target_crs)
Maps bbox from current crs to target_crs :param bbox: bounding box :type bbox: geometry.BBox :param target_crs: target CRS :type target_crs: constants.CRS :return: bounding box in target CRS :rtype: geometry.BBox
351,584
def load_outputs(self): for output in sorted(logdissect.output.__formats__): self.output_modules[output] = \ __import__( + output, globals(), \ locals(), [logdissect]).OutputModule(args=self.output_args)
Load output module(s)
351,585
def on_preliminary_config_changed(self, config_m, prop_name, info): self.check_for_preliminary_config() method_name = info[] if method_name in [, ]: config_key = info[][0] self._handle_config_update(config_m, config_key) elif config_m is self...
Callback when a preliminary config value has been changed Mainly collects information, delegates handling further to _handle_config_update :param ConfigModel config_m: The config model that has been changed :param str prop_name: Should always be 'preliminary_config' :param dict info: I...
351,586
def setNumberRange(key, keyType, start, end): return And( And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)), And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, % (start, end))), )
check number range
351,587
def get_recipe_object(self, mode_name, pipeline_name=): active_mode = self.modes[mode_name] active_pipeline = self.pipelines[pipeline_name] recipe = active_pipeline.get_recipe_object(active_mode) return recipe
Build a recipe object from a given mode name
351,588
def index_lastnot(ol,value): aaaaa length = ol.__len__() for i in range(length-1,-1,-1): if(value == ol[i]): pass else: return(i) return(None)
from elist.elist import * ol = [1,'a',3,'a',4,'a',5] index_lastnot(ol,'a') ####lastIndexOfnot is the same as index_lastnot lastIndexOfnot(ol,'a')
351,589
def add_frequencyseries(self, spectrum, dB=True, power=False, **kwargs): kwargs.setdefault(, spectrum.name) mag = numpy.absolute(spectrum.value) if dB: mag = to_db(mag) if not power: mag *= 2. phase = numpy.angle...
Plot the magnitude and phase of a complex-valued `FrequencySeries` Parameters ---------- spectrum : `~gwpy.frequencyseries.FrequencySeries` the (complex-valued) `FrequencySeries` to display db : `bool`, optional, default: `True` if `True`, display magnitude in d...
351,590
def gevent_wait_callback(conn, timeout=None): while 1: state = conn.poll() if state == extensions.POLL_OK: break elif state == extensions.POLL_READ: wait_read(conn.fileno(), timeout=timeout) elif state == extensions.POLL_WRITE: wait_write(conn...
A wait callback useful to allow gevent to work with Psycopg.
351,591
def make_views(cls, conn): conn.execute() conn.execute( ) conn.commit() conn.execute() conn.execute( ...
Create day_trips and day_stop_times views. day_trips: day_trips2 x trips = days x trips day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times
351,592
def power_cycle_vm(virtual_machine, action=): s name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine onpower onNot enough permissions. Required privilege: {}offpower offNot enough permissions. Required privi...
Powers on/off a virtual machine specified by it's name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine
351,593
def tostring(self, inject): injected_parts = for part in self.parts: injected = part.tostring(inject) tei_tag = next( (attribute for attribute in part.attributes if attribute.key == "tei-tag"), None) if tei_tag and tei_tag.text == "w" and inj...
Convert an element to a single string and allow the passed inject method to place content before any element.
351,594
def stop_jobs(self, job_ids): self.lock() jobs = self.get_jobs(job_ids) for job in jobs: if job.status in (, , ): qdel(job.id, context=self.context) logger.info("Stopped job in the SGE grid." % job) job.submit() self.session.commit() self.unlock()
Stops the jobs in the grid.
351,595
def registerWalkthrough(self, walkthrough): if not walkthrough in self._walkthroughs: self._walkthroughs.append(walkthrough)
Registers the inputed walkthrough to the system. :param walkthrough | <XWalkthrough>
351,596
def fix_timezone(df, freq, tz=None): index_name = df.index.name if isinstance(df.index[0], str): if ("-" in df.index[0][-6:]) | ("+" in df.index[0][-6:]): df.index = pd.to_datetime(df.index, utc=False) df.index = df.index.tz_localize().tz_convert(tz) ...
set timezone for pandas
351,597
def equinox(date, eop_correction=True, terms=106, kinematic=True): epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms) equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar)) if date.d >= 50506 and kinematic: ttt = date.change_scale().julian_century ...
Equinox equation in degrees
351,598
def items(self): L = [] def aux(node, s): s = s + node.char if node.output is not nil: L.append((s, node.output)) for child in node.children.values(): if child is not node: aux(child, s) aux(self.root, ) return iter(L)
Generator returning all keys and values stored in a trie.
351,599
def _add_region_params(region, out_file, items, gatk_type): params = [] variant_regions = bedutils.population_variant_regions(items) region = subset_variant_regions(variant_regions, region, out_file, items) if region: if gatk_type == "gatk4": params += ["-L", bamprep.region_to_g...
Add parameters for selecting by region to command line.