Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,400
def _set_weight(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=weight.weight, is_container=, presence=False, yang_name="weight", rest_name="weight", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi...
Setter method for weight, mapped from YANG variable /routing_system/route_map/content/set/weight (container) If this variable is read-only (config: false) in the source YANG file, then _set_weight is considered as a private method. Backends looking to populate this variable should do so via calling this...
363,401
def replace(self, key, value, expire=0, noreply=None): if noreply is None: noreply = self.default_noreply return self._store_cmd(b, {key: value}, expire, noreply)[key]
The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional...
363,402
def list_locked(**kwargs): **** return [.format(pkgname, version(pkgname, **kwargs)) for pkgname in _lockcmd(, name=None, **kwargs)]
Query the package database those packages which are locked against reinstallation, modification or deletion. Returns returns a list of package names with version strings CLI Example: .. code-block:: bash salt '*' pkg.list_locked jail List locked packages within the specified jai...
363,403
def _options_protobuf(self, retry_id): if retry_id is not None: if self._read_only: raise ValueError(_CANT_RETRY_READ_ONLY) return types.TransactionOptions( read_write=types.TransactionOptions.ReadWrite( retry_transaction=retr...
Convert the current object to protobuf. The ``retry_id`` value is used when retrying a transaction that failed (e.g. due to contention). It is intended to be the "first" transaction that failed (i.e. if multiple retries are needed). Args: retry_id (Union[bytes, NoneType]): ...
363,404
def git_push(): new_version = version.__version__ values = list(map(lambda x: int(x), new_version.split())) local() local() local(.format(values[0], values[1], values[2])) local() local()
Push new version and corresponding tag to origin :return:
363,405
def _save_stdin(self, stdin): self.temp_dir = TemporaryDirectory() file_path = os.path.join(self.temp_dir.name, ) try: with open(file_path, ) as f: for line in stdin: f.write(line) except TypeError: self.temp_dir.cleanup() raise ValueError() return file_path
Creates a temporary dir (self.temp_dir) and saves the given input stream to a file within that dir. Returns the path to the file. The dir is removed in the __del__ method.
363,406
def pipool(name, ivals): name = stypes.stringToCharP(name) n = ctypes.c_int(len(ivals)) ivals = stypes.toIntVector(ivals) libspice.pipool_c(name, n, ivals)
This entry point provides toolkit programmers a method for programmatically inserting integer data into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pipool_c.html :param name: The kernel pool name to associate with values. :type name: str :param ivals: An array of integ...
363,407
def _partial_extraction_fixed(self, idx, extra_idx=0): myarray = np.array([]) with open(self.abspath) as fobj: contents = fobj.readlines()[idx+extra_idx:] for line in contents: try: vals = re.findall(r, line) ...
Private method for a single extraction on a fixed-type tab file
363,408
def get_over_current(self, channel): try: bit = self._ch_map[channel][][] except KeyError: raise ValueError( % channel) return not self._get_power_gpio_value(bit)
Reading over current status of power channel
363,409
def prepare_destruction(self): self._tool = None self._painter = None self.relieve_model(self._selection) self._selection = None self._Observer__PROP_TO_METHS.clear() self._Observer__METH_TO_PROPS.clear() self._Observer__PAT_TO_METHS.clear() ...
Get rid of circular references
363,410
def bundle(self, name: str) -> models.Bundle: return self.Bundle.filter_by(name=name).first()
Fetch a bundle from the store.
363,411
def descendants(self, node, relations=None, reflexive=False): if reflexive: decs = self.descendants(node, relations, reflexive=False) decs.append(node) return decs g = None if relations is None: g = self.get_graph() else: ...
Returns all descendants of specified node. The default implementation is to use networkx, but some implementations of the Ontology class may use a database or service backed implementation, for large graphs. Arguments --------- node : str identifier for nod...
363,412
def fetchmany(self, size=None): self._check_closed() if not self._executed: raise ProgrammingError("Require execute() first") if size is None: size = self.arraysize result = [] cnt = 0 while cnt != size: try: r...
Fetch many rows from select result set. :param size: Number of rows to return. :returns: list of row records (tuples)
363,413
def log_listener(log:logging.Logger=None, level=logging.INFO): if log is None: log = logging.getLogger("ProgressMonitor") def listen(monitor): name = "{}: ".format(monitor.name) if monitor.name is not None else "" perc = int(monitor.progress * 100) msg = "[{name}{perc:3d}%] ...
Progress Monitor listener that logs all updates to the given logger
363,414
def _set_ldp_out(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ldp_out.ldp_out, is_container=, presence=False, yang_name="ldp-out", rest_name="ldp-out", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, ex...
Setter method for ldp_out, mapped from YANG variable /mpls_state/ldp/ldp_out (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_out is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_out() ...
363,415
def fillScreen(self, color=None): md.fill_rect(self.set, 0, 0, self.width, self.height, color)
Fill the matrix with the given RGB color
363,416
def edit(self, id): c.prefix = Prefix.get(int(id)) if request.method == : c.prefix.prefix = request.params[] c.prefix.description = request.params[] if request.params[].strip() == : c.prefix.node = None else: ...
Edit a prefix.
363,417
def down_ec2(connection, instance_id, region, log=False): instance = connection.stop_instances(instance_ids=instance_id)[0] while instance.state != "stopped": if log: log_yellow("Instance state: %s" % instance.state) sleep(10) instance.update() if log: l...
shutdown of an existing EC2 instance
363,418
def route(rule=None, **kwargs): _restricted_keys = ["extends", "route", "decorators"] def decorator(f): if inspect.isclass(f): extends = kwargs.pop("extends", None) if extends and hasattr(extends, self.view_key): for k, v in getattr(extends, self.view_key).i...
This decorator defines custom route for both class and methods in the view. It behaves the same way as Flask's @app.route on class: It takes the following args - rule: the root route of the endpoint - decorators: a list of decorators to run on each method on methods: ...
363,419
def register(func_path, factory=mock.MagicMock): global _factory_map _factory_map[func_path] = factory def decorator(decorated_factory): _factory_map[func_path] = decorated_factory return decorated_factory return decorator
Kwargs: func_path: import path to mock (as you would give to `mock.patch`) factory: function that returns a mock for the patched func Returns: (decorator) Usage: automock.register('path.to.func.to.mock') # default MagicMock automock.register('path.to.func.to.mock', Cu...
363,420
def acquire_account_for(self, host, owner=None): for match, pool in self.pools: if match(host) is True: return pool.acquire_account(owner=owner) return self.default_pool.acquire_account(owner=owner)
Acquires an account for the given host and returns it. The host is passed to each of the match functions that were passed in when adding the pool. The first pool for which the match function returns True is chosen to assign an account. :type host: :class:`Host` :param host: The...
363,421
def get_webassets_env_from_settings(settings, prefix=): kwargs = {} cut_prefix = len(prefix) + 1 for k in settings: if k.startswith(prefix): val = settings[k] if isinstance(val, six.string_types): if val.lower() in auto_booly: ...
This function will take all webassets.* parameters, and call the ``Environment()`` constructor with kwargs passed in. The only two parameters that are not passed as keywords are: * base_dir * base_url which are passed in positionally. Read the ``WebAssets`` docs for ``Environment`` for more ...
363,422
def _glimpse_network(self, x_t, l_p): sensor_output = self._refined_glimpse_sensor(x_t, l_p) sensor_output = T.flatten(sensor_output) h_g = self._relu(T.dot(sensor_output, self.W_g0)) h_l = self._relu(T.dot(l_p, self.W_g1)) g = self._relu(T.dot(h_g, self.W_g2_hg) + T.dot...
Parameters: x_t - 28x28 image l_p - 2x1 focus vector Returns: 4x12 matrix
363,423
def make_name(super_name, default_super_name, sub_name): name = super_name if super_name is not None else default_super_name if sub_name is not None: name += + sub_name return name
Helper which makes a `str` name; useful for tf.compat.v1.name_scope.
363,424
def _request_internal(self, command, **kwargs): args = dict(kwargs) if self.ssid: args[] = self.ssid method = getattr(self.api, command) response = method(**args) if response and in response: if response[] == : raise SubregError( ...
Make request parse response
363,425
def within_ipv4_network(self, field, values): v = [ % net for net in values] self.update_filter(.format(field, .join(v)))
This filter adds specified networks to a filter to check for inclusion. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: network definitions, in cidr format, i.e: 1.1.1.0/24.
363,426
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None): if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk))...
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
363,427
def factory(feature): if feature == : return hog elif feature == : return deep elif feature == : return gray elif feature == : return lab elif feature == : return luv elif feature == : return hsv elif feature == : return hls el...
Factory to choose feature extractor :param feature: name of the feature :return: Feature extractor function
363,428
def clean(self): if self.cleaners: yield from asyncio.wait([x() for x in self.cleaners], loop=self.loop)
Run all of the cleaners added by the user.
363,429
def _pad_block(self, handle): extra = handle.tell() % 512 if extra: handle.write(b * (512 - extra))
Pad the file with 0s to the end of the next block boundary.
363,430
def _load_properties(self): self.__loaded = True method = data = _doget(method, photo_id=self.id) photo = data.rsp.photo self.__secret = photo.secret self.__server = photo.server self.__isfavorite = photo.isfavorite self.__lice...
Loads the properties from Flickr.
363,431
def _get_default_jp2_boxes(self): boxes = [JPEG2000SignatureBox(), FileTypeBox(), JP2HeaderBox(), ContiguousCodestreamBox()] height = self.codestream.segment[1].ysiz width = self.codestream.segment[1].xsiz num_component...
Create a default set of JP2 boxes.
363,432
def fake2db_initiator(self, number_of_rows, **connection_kwargs): rows = number_of_rows cursor, conn = self.database_caller_creator(number_of_rows, **connection_kwargs) self.data_filler_simple_registration(rows, cursor, conn) self.data_filler_detailed_registration(rows, cursor,...
Main handler for the operation
363,433
def delete_attributes(self, attrs): assert(isinstance(attrs, list)), "Argument must be a list of names of keys to delete." self._manager.domain.delete_attributes(self.id, attrs) self.reload() return self
Delete just these attributes, not the whole object. :param attrs: Attributes to save, as a list of string names :type attrs: list :return: self :rtype: :class:`boto.sdb.db.model.Model`
363,434
def save_results(self, output_dir=, prefix=, prefix_sep=, image_list=None): if prefix == : prefix_sep = if not exists(output_dir): makedirs(output_dir) logger.debug("Saving results...") if image_list is None: image_lis...
Write out any images generated by the meta-analysis. Args: output_dir (str): folder to write images to prefix (str): all image files will be prepended with this string prefix_sep (str): glue between the prefix and rest of filename image_list (list): optional list ...
363,435
def login(self, account=None, app_account=None, flush=True): with self._get_account(account) as account: if app_account is None: app_account = account self.authenticate(account, flush=False) if self.get_driver().supports_auto_authorize(): ...
Log into the connected host using the best method available. If an account is not given, default to the account that was used during the last call to login(). If a previous call was not made, use the account that was passed to the constructor. If that also fails, raise a TypeError. ...
363,436
def _require_homogeneous_roots(self, accept_predicate, reject_predicate): if len(self.context.target_roots) == 0: raise self.NoActivationsError() def resolve(targets): for t in targets: if type(t) == Target: for r in resolve(t.dependencies): yield r ...
Ensures that there is no ambiguity in the context according to the given predicates. If any targets in the context satisfy the accept_predicate, and no targets satisfy the reject_predicate, returns the accepted targets. If no targets satisfy the accept_predicate, returns None. Otherwise throws TaskEr...
363,437
def create_table(instance, table_id, initial_split_keys=None, column_families=None): if column_families is None: column_families = {} if initial_split_keys is None: initial_split_keys = [] table = Tab...
Creates the specified Cloud Bigtable table. Raises ``google.api_core.exceptions.AlreadyExists`` if the table exists. :type instance: Instance :param instance: The Cloud Bigtable instance that owns the table. :type table_id: str :param table_id: The ID of the table to create in C...
363,438
def fetch(self, endpoint=None, page=1, **kwargs): if not endpoint: raise ValueError() self._endpoint = endpoint params = {"per_page": self.per_page, "page": page, "key": self._api_key } ...
Returns the results of an API call. This is the main work horse of the class. It builds the API query string and sends the request to MetaSmoke. If there are multiple pages of results, and we've configured `max_pages` to be greater than 1, it will automatically paginate ...
363,439
def install(self, opener): _opener = opener if isinstance(opener, Opener) else opener() assert isinstance(_opener, Opener), "Opener instance required" assert _opener.protocols, "must list one or more protocols" for protocol in _opener.protocols: self._protoc...
Install an opener. Arguments: opener (`Opener`): an `Opener` instance, or a callable that returns an opener instance. Note: May be used as a class decorator. For example:: registry = Registry() @registry.install cl...
363,440
def end_anonymous_session_view(request): request.session[] = False messages.add_message(request, messages.INFO, MESSAGES[]) return HttpResponseRedirect(reverse())
End the anonymous session if the user is a superuser.
363,441
def get(self, *args, **kwargs): if not mqueue.qsize(): return None message_data, content_type, content_encoding = mqueue.get() return self.Message(backend=self, body=message_data, content_type=content_type, content_encoding=conte...
Get the next waiting message from the queue. :returns: A :class:`Message` instance, or ``None`` if there is no messages waiting.
363,442
def mark_all_as_active(self, recipient=None): assert_soft_delete() qset = self.deleted() if recipient: qset = qset.filter(recipient=recipient) return qset.update(deleted=False)
Mark current queryset as active(un-deleted). Optionally, filter by recipient first.
363,443
def adj_nodes_aws(aws_nodes): for node in aws_nodes: node.cloud = "aws" node.cloud_disp = "AWS" node.private_ips = ip_to_str(node.private_ips) node.public_ips = ip_to_str(node.public_ips) node.zone = node.extra[] node.size = node.extra[] node.type = node....
Adjust details specific to AWS.
363,444
def get(key, default=-1): if isinstance(key, int): return TransType(key) if key not in TransType._member_map_: extend_enum(TransType, key, default) return TransType[key]
Backport support for original codes.
363,445
def main(request, query, hproPk=None, returnMenuOnly=False): if settings.PIAPI_STANDALONE: global plugIt, baseURI if settings.PIAPI_ORGAMODE and settings.PIAPI_REALUSERS: return gen404(request, baseURI, "Configuration error. PIAPI_ORGAMODE and PIA...
Main method called for main page
363,446
def getObjectsAspecting(self, point, aspList): res = [] for obj in self: if obj.isPlanet() and aspects.isAspecting(obj, point, aspList): res.append(obj) return ObjectList(res)
Returns a list of objects aspecting a point considering a list of possible aspects.
363,447
def citedby_url(self): cite_link = self.coredata.find(, ns) try: return cite_link.get() except AttributeError: return None
URL to Scopus page listing citing papers.
363,448
def default_triple(cls, inner_as_primary=True, inner_as_overcontact=False, starA=, starB=, starC=, inner=, outer=, contact_envelope=): if not conf.devel: raise NotImplementedError(" not officially supported for this releas...
Load a bundle with a default triple system. Set inner_as_primary based on what hierarchical configuration you want. inner_as_primary = True: starA - starB -- starC inner_as_primary = False: starC -- starA - starB This is a constructor, so should be called as: ...
363,449
def cast(current: Any, new: str) -> Any: typ = type(current) orig_new = new if typ == bool: try: return bool(int(new)) except (ValueError, TypeError): pass try: new = new.lower() if (new == ) or (new[0] in (, )): r...
Tries to force a new value into the same type as the current when trying to set the value for a parameter. :param current: current value for the parameter, type varies :param new: new value :return: new value with same type as current, or the current value if there was an error casting
363,450
def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): assert sum([updated, following, folder]) == 1 if folder: assert filter_folder if updated: filter_type = dict(updated=1) e...
Get filtered feed Only one filter type (updated, following, folder) is possible. :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type ...
363,451
def parse_numbering(document, xmlcontent): numbering = etree.fromstring(xmlcontent) document.abstruct_numbering = {} document.numbering = {} for abstruct_num in numbering.xpath(, namespaces=NAMESPACES): numb = {} for lvl in abstruct_num.xpath(, namespaces=NAMESPACES): ...
Parse numbering document. Numbering is defined in file 'numbering.xml'.
363,452
def cancelOrder(self, orderId): self.ibConn.cancelOrder(orderId) self.requestOrderIds() return orderId
cancel order on IB TWS
363,453
def operation_file(uploader, cmd, filename=): if cmd == : operation_list(uploader) if cmd == : for path in filename: uploader.file_do(path) elif cmd == : uploader.file_format() elif cmd == : for path in filename: uploader.file_remove(path) ...
File operations
363,454
def add_into(self, other): if self.sample_rate != other.sample_rate: raise ValueError() if ((other.start_time > self.end_time) or (self.start_time > other.end_time)): return self.copy() other = other.copy() dt = float((other...
Return the sum of the two time series accounting for the time stamp. The other vector will be resized and time shifted wiht sub-sample precision before adding. This assumes that one can assume zeros outside of the original vector range.
363,455
def map_resnum_a_to_resnum_b(resnums, a_aln, b_aln): resnums = ssbio.utils.force_list(resnums) aln_df = get_alignment_df(a_aln, b_aln) maps = aln_df[aln_df.id_a_pos.isin(resnums)] able_to_map_to_b = maps[pd.notnull(maps.id_b_pos)] successful_map_from_a = able_to_map_to_b.id_a_pos.values.toli...
Map a residue number in a sequence to the corresponding residue number in an aligned sequence. Examples: >>> map_resnum_a_to_resnum_b([1,2,3], '--ABCDEF', 'XXABCDEF') {1: 3, 2: 4, 3: 5} >>> map_resnum_a_to_resnum_b(5, '--ABCDEF', 'XXABCDEF') {5: 7} >>> map_resnum_a_to_resnum_b(5, 'ABCDEF', 'ABC...
363,456
def gaussian_pdf(std=10.0, mean=0.0): norm_const = 1.0 def pdf(x): return norm_const*np.exp(-0.5 * ((x-mean)/std)**2) * \ np.sin(np.pi/180.0 * x) norm_dev = quad(pdf, 0.0, 180.0)[0] norm_const /= norm_dev return pdf
Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean in degrees of the Gaussian PDF. This should be a number in the interval [0, 180) Returns: pdf(x), a function that returns the value of the spherical Jacobi...
363,457
def plot_flat(r, c, figsize): "Shortcut for `enumerate(subplots.flatten())`" return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
Shortcut for `enumerate(subplots.flatten())`
363,458
def bellman_ford(graph, weight, source=0): n = len(graph) dist = [float()] * n prec = [None] * n dist[source] = 0 for nb_iterations in range(n): changed = False for node in range(n): for neighbor in graph[node]: alt = dist[node] + weight[node][neighbo...
Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is ...
363,459
def unhide_dataset(dataset_id,**kwargs): user_id = kwargs.get() dataset_i = _get_dataset(dataset_id) if dataset_i.created_by != int(user_id): raise HydraError( %(user_id, dataset_i.name)) dataset_i.hidden = db.DBSession.flush()
Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users c...
363,460
def handle_remove_readonly(func, path, exc): from .compat import ResourceWarning, FileNotFoundError, PermissionError PERM_ERRORS = (errno.EACCES, errno.EPERM, errno.ENOENT) default_warning_message = "Unable to remove file due to permissions restriction: {!r}" exc_type, exc_exception, exc...
Error handler for shutil.rmtree. Windows source repo folders are read-only by default, so this error handler attempts to set them as writeable and then proceed with deletion. :param function func: The caller function :param str path: The target path for removal :param Exception exc: The raised exc...
363,461
def TemplateValidator(value): try: Template(value) except Exception as e: raise ValidationError( _("Cannot compile template (%(exception)s)"), params={"exception": e} )
Try to compile a string into a Django template
363,462
def _set_default(path, dest, name): subvol_id = __salt__[](path)[name][] return __salt__[](subvol_id, dest)
Set the subvolume as the current default.
363,463
def execute(self, command): if isinstance(command, str): self.method(command.split()) elif isinstance(command, list): self.method(command) else: raise TypeError("command should be either a string or list type") if self.error: rais...
Primary method to execute ipmitool commands :param command: ipmi command to execute, str or list e.g. > ipmi = ipmitool('consolename.prod', 'secretpass') > ipmi.execute('chassis status') >
363,464
def get_sql_for_new_models(apps=None, using=DEFAULT_DB_ALIAS): connection = connections[using] tables = connection.introspection.table_names() seen_models = connection.introspection.installed_models(tables) created_models = set() pending_references = {} if apps: apps ...
Unashamedly copied and tweaked from django.core.management.commands.syncdb
363,465
def read_validate_params(self, request): self.refresh_token = request.post_param("refresh_token") if self.refresh_token is None: raise OAuthInvalidError( error="invalid_request", explanation="Missing refresh_token in request body") self.clie...
Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError`
363,466
def apply_object(self, config_obj, apply_on=None): self._init_flat_pointers() try: config_obj_keys = vars(config_obj).keys() except TypeError: config_obj_keys = filter(lambda k: k[0] != , dir(config_obj)) for config_key in config_obj_keys: ...
Apply additional configuration from any Python object This will look for object attributes that exist in the base_config and apply their values on the current configuration object
363,467
def list_as_sub(access_token, subscription_id): endpoint = .join([get_rm_endpoint(), , subscription_id, , , COMP_API]) return do_get_next(endpoint, access_token)
List availability sets in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of the list of availability set properties.
363,468
def __verify_arguments(self): if self.__kmax > len(self.__data): raise ValueError("K max value is bigger than amount of objects in input data.") if self.__kmin <= 1: raise ValueError("K min value should be greater than 1 (impossible to provide " ...
! @brief Checks algorithm's arguments and if some of them is incorrect then exception is thrown.
363,469
def find_root_thrifts(basedirs, sources, log=None): root_sources = set(sources) for source in sources: root_sources.difference_update(find_includes(basedirs, source, log=log)) return root_sources
Finds the root thrift files in the graph formed by sources and their recursive includes. :basedirs: A set of thrift source file base directories to look for includes in. :sources: Seed thrift files to examine. :log: An optional logger.
363,470
def parse_player_info(self, player): if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player.fakeplayer, }
Parse a PlayerInfo struct. This arrives before a FileInfo message
363,471
def DiffPrimitiveArrays(self, oldObj, newObj): if len(oldObj) != len(newObj): __Log__.debug( % (len(oldObj), len(newObj))) return False match = True if self._ignoreArrayOrder: oldSet = oldObj and frozenset(oldObj) or frozenset() newSet = newObj an...
Diff two primitive arrays
363,472
def reset( self ): dataSet = self.dataSet() if ( not dataSet ): dataSet = XScheme() dataSet.reset()
Resets the colors to the default settings.
363,473
def _get_version(): version_string = __salt__[]( [_check_pkgin(), ], output_loglevel=) if version_string is None: return False version_match = VERSION_MATCH.search(version_string) if not version_match: return False return version_match.group(1).split()
Get the pkgin version
363,474
def vgdisplay(vgname=, quiet=False): ** ret = {} cmd = [, ] if vgname: cmd.append(vgname) cmd_ret = __salt__[](cmd, python_shell=False, ignore_retcode=quiet) if cmd_ret[] != 0: return {} out = cmd_ret[].splitlines() for line in out:...
Return information about the volume group(s) vgname volume group name quiet if the volume group is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.vgdisplay salt '*' lvm.vgdisplay nova-volumes
363,475
def _process_iq_response(self, stanza): stanza_id = stanza.stanza_id from_jid = stanza.from_jid if from_jid: ufrom = from_jid.as_unicode() else: ufrom = None res_handler = err_handler = None try: res_handler, err_handler = self...
Process IQ stanza of type 'response' or 'error'. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-n...
363,476
def KIC(N, rho, k): r from numpy import log, array res = log(rho) + 3. * (k+1.) /float(N) return res
r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave.
363,477
def create(cls, fields=None, **fields_kwargs): instance = cls(fields, **fields_kwargs) instance.save() return instance
create an instance of cls with the passed in fields and set it into the db fields -- dict -- field_name keys, with their respective values **fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
363,478
def _ConvertDictToObject(cls, json_dict): class_type = json_dict.get(, None) if not class_type: return json_dict if class_type == : return binascii.a2b_qp(json_dict[]) if class_type == : return tuple(cls._ConvertListToObject(json_dict[])) if class_type == : ...
Converts a JSON dict into an object. The dictionary of the JSON serialized objects consists of: { '__type__': 'AttributeContainer' '__container_type__': ... ... } Here '__type__' indicates the object base type. In this case 'AttributeContainer'. '__container_type__' in...
363,479
def get_diversity(self,X): feature_correlations = np.zeros(X.shape[0]-1) for i in np.arange(1,X.shape[0]-1): feature_correlations[i] = max(0.0,r2_score(X[0],X[i])) self.diversity.append(1-np.mean(feature_correlations))
compute mean diversity of individual outputs
363,480
def get_cds_ranges_for_transcript(self, transcript_id): headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=cds".format(transcript_id) r = self.ensembl_request(ext, headers) cds_ranges = [] for ...
obtain the sequence for a transcript from ensembl
363,481
def com_google_fonts_check_metadata_canonical_weight_value(font_metadata): first_digit = font_metadata.weight / 100 if (font_metadata.weight % 100) != 0 or \ (first_digit < 1 or first_digit > 9): yield FAIL, ("METADATA.pb: The weight is declared" " as {} which is not a" " ...
METADATA.pb: Check that font weight has a canonical value.
363,482
def align(args): valid_modes = ("bwasw", "aln", "mem") p = OptionParser(align.__doc__) p.add_option("--mode", default="mem", choices=valid_modes, help="BWA mode") set_align_options(p) p.set_sam_options() opts, args = p.parse_args(args) mode = opts.mode nargs = len(args) if nar...
%prog align database.fasta read1.fq [read2.fq] Wrapper for three modes of BWA - mem (default), aln, bwasw (long reads).
363,483
def tag(self, repository_tag, tags=[]): if not isinstance(repository_tag, six.string_types): raise TypeError() if not isinstance(tags, list): raise TypeError() if in repository_tag: repository, tag = repository_tag.split() tags.append(t...
Tags image with one or more tags. Raises exception on failure.
363,484
def show_std_icons(): app = qapplication() dialog = ShowStdIcons(None) dialog.show() sys.exit(app.exec_())
Show all standard Icons
363,485
def debug(request, message, extra_tags=, fail_silently=False, async=False): if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
Adds a message with the ``DEBUG`` level.
363,486
def _postrun(cls, span, obj, **kwargs): span.set_tag("response.status_code", obj.status_code) span.set_tag( "response.content_lenght", len(getattr(obj, , "")) )
Trigger to execute just before closing the span :param opentracing.span.Span span: the SpanContext instance :param Any obj: Object to use as context :param dict kwargs: additional data
363,487
def reports(self): if self._metrics is None: self.__init() self._reports = [] for r in self._metrics: url = self._url + "/%s" % six.moves.urllib.parse.quote_plus(r[]) self._reports.append(UsageReport(url=url, ...
returns a list of reports on the server
363,488
def get_manifest_selfLink(self, repo_name, digest=None): url = "%s/%s/manifests" % (self.base, repo_name) if digest is None: digest = return "%s/%s" % (url, digest)
get a selfLink for the manifest, for use by the client get_manifest function, along with the parents pull Parameters ========== repo_name: reference to the <username>/<repository>:<tag> to obtain digest: a tag or shasum version
363,489
def _cond_x(self, word, suffix_len): return word[-suffix_len - 1] in {, } or ( word[-suffix_len - 3 : -suffix_len] == and word[-suffix_len - 1] == )
Return Lovins' condition X. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met
363,490
def rings_full_data(self): for circ_breaker in self.circuit_breakers(): if not circ_breaker.status == : circ_breaker.close() logger.info( ) for ring_nodes in nx.cycle_basis(self._graph, root=self._station)...
Returns a generator for iterating over each ring Yields ------ For each ring, tuple composed by ring ID, list of edges, list of nodes Notes ----- Circuit breakers must be closed to find rings, this is done automatically.
363,491
def wait_for_redfish_firmware_update_to_complete(self, redfish_object): p_state = [] c_state = [] def has_firmware_flash_completed(): curr_state, curr_percent = self.get_firmware_update_progress() p_state[0] = c_state[0] c_state[0] = cur...
Continuously polls for iLO firmware update to complete. :param redfish_object: redfish instance
363,492
def subpoint(self): if self.center != 399: raise ValueError("you can only ask for the geographic subpoint" " of a position measured from Earthij...,j...->i...m deferring the refactoring for now, to get from .toposlib import Topos retur...
Return the latitude and longitude directly beneath this position. Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude`` and ``latitude`` are those of the point on the Earth's surface directly beneath this position, and whose ``elevation`` is the height of this position above t...
363,493
def breakLines(self, width): if self.debug: print (id(self), "breakLines") if not isinstance(width, (tuple, list)): maxWidths = [width] else: maxWidths = width lines = [] lineno = 0 style = self.style _handl...
Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with - kind = 0 - fontName, fontSize, leading, textColor - lines= A list of lines ...
363,494
def Operate(self, values): for val in values: try: if self.Operation(val, self.right_operand): return True except (TypeError, ValueError): pass return False
Takes a list of values and if at least one matches, returns True.
363,495
def read(self): vlrs = self.read_vlrs() self._warn_if_not_at_expected_pos( self.header.offset_to_point_data, "end of vlrs", "start of points" ) self.stream.seek(self.start_pos + self.header.offset_to_point_data) try: points = self._read_points(vl...
Reads the whole las data (header, vlrs ,points, etc) and returns a LasData object
363,496
def SaveAvatarToFile(self, Filename, AvatarId=1): s = % (self.Handle, AvatarId, path2unicode(Filename)) self._Owner._DoCommand( % s, s)
Saves user avatar to a file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id.
363,497
def optimize(image, fmt=, quality=80): from io import BytesIO if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD): image_buffer = BytesIO() image.save(image_buffer, format=fmt, quality=quality) image_buffer.seek(0) p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, s...
Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input
363,498
async def _on_heartbeat(self, update): name = update[] if name not in self.services: return with self._state_lock: self.services[name].heartbeat()
Receive a new heartbeat for a service.
363,499
def parse_csv(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None, sep=",") -> List[Gene]: logger.info("In parse_csv()") df = pd.read_csv(file_path, se...
Read a csv file on differential expression values as Gene objects. :param str file_path: The path to the differential expression file to be parsed. :param config.Params params: An object that includes paths, cutoffs and other information. :return list: A list of Gene objects.