Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
377,700
def do_quality(self, quality): if (quality == or quality == ): self.logger.debug("quality: converting to gray") self.image = self.image.convert() elif (quality == ): self.logger.debug("quality: converting to bitonal") self.image = se...
Apply value of quality parameter. For PIL docs see <http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.convert>
377,701
def save_models(self, model_path): for group, condition_model_set in self.condition_models.items(): for model_name, model_obj in condition_model_set.items(): out_filename = model_path + \ "{0}_{1}_condition.pkl".format(group, ...
Save machine learning models to pickle files.
377,702
def find(self, pair, default=None): pair = normalizers.normalizeKerningKey(pair) value = self._find(pair, default) if value != default: value = normalizers.normalizeKerningValue(value) return value
Returns the value for the kerning pair. **pair** is a ``tuple`` of two :ref:`type-string`\s, and the returned values will either be :ref:`type-int-float` or ``None`` if no pair was found. :: >>> font.kerning[("A", "V")] -25
377,703
def get_bucket(self, hash_name, bucket_key): if hash_name in self.buckets: if bucket_key in self.buckets[hash_name]: return self.buckets[hash_name][bucket_key] return []
Returns bucket content as list of tuples (vector, data).
377,704
def convert_mapper(self, tomap): frommap = self.crdmap if frommap == tomap: return if hasattr(self, ): x0, y0 = frommap.offset_pt((self.x, self.y), (self.radius, 0)) pts = frommap.to_data(((self.x, self.y), (x0, y0)...
Converts our object from using one coordinate map to another. NOTE: In some cases this only approximately preserves the equivalent point values when transforming between coordinate spaces.
377,705
def minimize_t0s(means, weights, combs): def make_quality_function(means, weights, combs): def quality_function(t0s): sq_sum = 0 for mean, comb, weight in zip(means, combs, weights): sq_sum += ((mean - (t0s[comb[1]] - t0s[comb[0]])) * weight)**2 retu...
Varies t0s to minimize the deviation of the gaussian means from zero. Parameters ---------- means: numpy array of means of all PMT combinations weights: numpy array of weights for the squared sum combs: pmt combinations to use for minimization Returns ------- opt_t0s: optimal t0 values...
377,706
def reduce_loss_dict(loss_dict): world_size = get_world_size() if world_size < 2: return loss_dict with torch.no_grad(): loss_names = [] all_losses = [] for k in sorted(loss_dict.keys()): loss_names.append(k) all_losses.append(loss_dict[k]) ...
Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction.
377,707
def dispatch_command(function, *args, **kwargs): parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER) set_default_command(parser, function) dispatch(parser, *args, **kwargs)
A wrapper for :func:`dispatch` that creates a one-command parser. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_command(foo) ...is a shortcut for:: parser = ArgumentParser() set_default_command(parser, foo) dispatch(parser) This function can be also used as a decora...
377,708
def updateHeader(self, wcsname=None, reusename=False): self.openFile() verbose_level = 1 if not self.perform_update: verbose_level = 0 if self.perform_update: wcscorr.init_wcscorr(self._im.hdu) extlist = [] wcscorr_extn...
Update header of image with shifts computed by *perform_fit()*.
377,709
def rootChild_resetPassword(self, req, webViewer): from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator return URL.fromString( IWebTranslator(self.store).linkTo( IPreferenceAggregator(self.store).storeID))
Redirect authenticated users to their settings page (hopefully they have one) when they try to reset their password. This is the wrong way for this functionality to be implemented. See #2524.
377,710
def _get_table_info(self): self.rowid = None self.fields = [] self.field_info = {} self.cursor.execute( %self.name) for row in self.cursor.fetchall(): field,typ,null,key,default,extra = row self.fields.append(field) self.field...
Database-specific method to get field names
377,711
def get_cameras_schedule(self): resource = "schedule" schedule_event = self.publish_and_get_event(resource) if schedule_event: return schedule_event.get() return None
Return the schedule set for cameras.
377,712
def add(self, *nodes): for node in nodes: node.set_parent(self) self.add_sibling(node)
Adds nodes as siblings :param nodes: GraphNode(s)
377,713
def check_webhook_secret(app_configs=None, **kwargs): from . import settings as djstripe_settings messages = [] secret = djstripe_settings.WEBHOOK_SECRET if secret and not secret.startswith("whsec_"): messages.append( checks.Warning( "DJSTRIPE_WEBHOOK_SECRET does not look valid", hint="It should st...
Check that DJSTRIPE_WEBHOOK_SECRET looks correct
377,714
def iter_actions(self): ns = scpd_body = requests.get(self.base_url + self.scpd_url).content tree = XML.fromstring(scpd_body) vartypes = {} srvStateTables = tree.findall(.format(ns)) for srvStateTable in srvStateTabl...
Yield the service's actions with their arguments. Yields: `Action`: the next action. Each action is an Action namedtuple, consisting of action_name (a string), in_args (a list of Argument namedtuples consisting of name and argtype), and out_args (ditto), eg:: A...
377,715
def login(self, access_token=""): if access_token: credentials = argparse.Namespace(token=access_token, refresh_token=None, id_token=None) else: scopes = ["openid", "email", "offline_access"] from google_auth_oauthlib.flow import InstalledAppFlow ...
Configure and save {prog} authentication credentials. This command may open a browser window to ask for your consent to use web service authentication credentials.
377,716
def find_children(self, pattern=r".*", flags=0, candidates=None): if candidates is None: candidates = [] for child in self.__children: if re.search(pattern, child.name, flags): child not in candidates and candidates.append(child) child.find_...
Finds the children matching the given patten. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.find_children("c", re.IGNORECASE) ...
377,717
def coverage(fn): fp = TraceFuncCoverage(fn) def new_fn(*args, **kw): return fp(*args, **kw) new_fn.__doc__ = fn.__doc__ new_fn.__name__ = fn.__name__ new_fn.__dict__ = fn.__dict__ new_fn.__module__ = fn.__module__ return new_fn
Mark `fn` for line coverage analysis. Results will be printed to sys.stdout on program termination. Usage:: def fn(...): ... fn = coverage(fn) If you are using Python 2.4, you should be able to use the decorator syntax:: @coverage def fn(...): ...
377,718
def _split_audio_by_duration(self, audio_abs_path, results_abs_path, duration_seconds): total_seconds = self._get_audio_duration_seconds(audio_abs_path) current_segment = 0 while current_segment <= total_seconds // duration_seconds + 1: if cu...
Calculates the length of each segment and passes it to self._audio_segment_extractor Parameters ---------- audio_abs_path : str results_abs_path : str A place for adding digits needs to be added prior the the format decleration i.e. name%03.wav. Here, we'...
377,719
def broken_faces(mesh, color=None): adjacency = nx.from_edgelist(mesh.face_adjacency) broken = [k for k, v in dict(adjacency.degree()).items() if v != 3] broken = np.array(broken) if color is not None: color = np.array(color) if not (color.shape == (4,) or col...
Return the index of faces in the mesh which break the watertight status of the mesh. Parameters -------------- mesh: Trimesh object color: (4,) uint8, will set broken faces to this color None, will not alter mesh colors Returns --------------- broken: (n, ) int, indexe...
377,720
def write_long_at(self, n, pos, pack_into=Struct().pack_into): if 0 <= n <= 0xFFFFFFFF: pack_into(self._output_buffer, pos, n) else: raise ValueError(, n) return self
Write an unsigned 32bit value at a specific position in the buffer. Used for writing tables and frames.
377,721
def _multicall_callback(self, values, calls): result = KojiMultiCallIterator(values) result.connection = self.connection result.calls = calls return result
Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :param calls: list of calls we sent in this multicall RPC :re...
377,722
def get_social_login(self, *args, **kwargs): social_login = super(SocialConnectMixin, self).get_social_login(*args, **kwargs) social_login.state[] = AuthProcess.CONNECT return social_login
Set the social login process state to connect rather than login Refer to the implementation of get_social_login in base class and to the allauth.socialaccount.helpers module complete_social_login function.
377,723
def auth_required(realm, auth_func): def auth_decorator(func): def inner(self, *args, **kw): if self.get_authenticated_user(auth_func, realm): return func(self, *args, **kw) return inner return auth_decorator
Decorator that protect methods with HTTP authentication.
377,724
def as_new_format(self, format="ATR"): first_data = len(self.header) raw = self.rawdata[first_data:] data = add_atr_header(raw) newraw = SegmentData(data) image = self.__class__(newraw) return image
Create a new disk image in the specified format
377,725
def isInRoom(self, _id): if SockJSRoomHandler._room.has_key(self._gcls() + _id): if self in SockJSRoomHandler._room[self._gcls() + _id]: return True return False
Check a given user is in given room
377,726
def create_snapshot(self, systemId, snapshotSpecificationObject): self.conn.connection._check_login() response = self.conn.connection._do_post("{}/{}{}/{}".format(self.conn.connection._api_url, "instances/System::", systemId, ), json=snapshotSpecificationObject.__to_dict__()) ...
Create snapshot for list of volumes :param systemID: Cluster ID :param snapshotSpecificationObject: Of class SnapshotSpecification :rtype: SnapshotGroupId
377,727
def update(self, read, write, manage): data = values.of({: read, : write, : manage, }) payload = self._version.update( , self._uri, data=data, ) return SyncMapPermissionInstance( self._version, payload, se...
Update the SyncMapPermissionInstance :param bool read: Read access. :param bool write: Write access. :param bool manage: Manage access. :returns: Updated SyncMapPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance
377,728
def listTheExtras(self, deleteAlso): extras = configobj.get_extra_values(self) expanded = [ (x+ \ ( bool(len(x[0])<1 and hasattr(self[x[1]], )), ) \ ) for x in extras] ret...
Use ConfigObj's get_extra_values() call to find any extra/unknown parameters we may have loaded. Return a string similar to findTheLost. If deleteAlso is True, this will also delete any extra/unknown items.
377,729
def get_is_group_member(self, grp_name, user): self.project_service.set_auth(self._token_project) return self.project_service.get_is_group_member(grp_name, user)
Check if the given user is a member of the named group. Note that a group maintainer is not considered a member unless the user is also explicitly added as a member. Args: name (string): Name of group. user_name (string): User of interest. Returns: ...
377,730
def RemoveClass(self, class_name): if class_name not in self._class_mapping: raise problems.NonexistentMapping(class_name) del self._class_mapping[class_name]
Removes an entry from the list of known classes. Args: class_name: A string with the class name that is to be removed. Raises: NonexistentMapping if there is no class with the specified class_name.
377,731
def MeetsConditions(knowledge_base, source): source_conditions_met = True os_conditions = ConvertSupportedOSToConditions(source) if os_conditions: source.conditions.append(os_conditions) for condition in source.conditions: source_conditions_met &= artifact_utils.CheckCondition( condition, kno...
Check conditions on the source.
377,732
def safe_listget(list_, index, default=): if index >= len(list_): return default ret = list_[index] if ret is None: return default return ret
depricate
377,733
def multi_to_dict(multi): return dict( (key, value[0] if len(value) == 1 else value) for key, value in multi.to_dict(False).items() )
Transform a Werkzeug multidictionnary into a flat dictionnary
377,734
def make_pipeline(context): primary_share = IsPrimaryShare() not_wi = ~IEXCompany.symbol.latest.endswith() not_lp_name = ~IEXCompany.companyName.latest.matches() have_market_cap = IEXKeyStats.marketcap.latest >= 1 price = USEquityPricing.close.latest ...
Create our pipeline.
377,735
def send_request(user_session, method, request): if user_session.session: session = user_session.session try: method = method.upper() if method else if method == GET: if request.filename: return file_download(user_sess...
Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
377,736
def jensen_shannon(logu, self_normalized=False, name=None): with tf.compat.v1.name_scope(name, "jensen_shannon", [logu]): logu = tf.convert_to_tensor(value=logu, name="logu") npdt = logu.dtype.as_numpy_dtype y = tf.nn.softplus(logu) if self_normalized: y -= np.log(2).astype(npdt) return ...
The Jensen-Shannon Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True`, the Jensen-Shannon Csiszar-function is: ```none f(u) = u log(u) - (1 + u) log(1 + u) + (u + 1) log(2) ``` When `self_normalized = False` t...
377,737
def _prefix_from_uri(self, uriname): uripart, tag = uriname.split(, maxsplit=1) uri = uripart.replace(, ) return self.REVERSE_NS[uri] + + tag
Given a fully qualified XML name, find a prefix e.g. {http://ns.adobe.com/pdf/1.3/}Producer -> pdf:Producer
377,738
def status( message: str = None, progress: float = None, section_message: str = None, section_progress: float = None, ): environ.abort_thread() step = _cd.project.get_internal_project().current_step if message is not None: step.progress_message = message if ...
Updates the status display, which is only visible while a step is running. This is useful for providing feedback and information during long-running steps. A section progress is also available for cases where long running tasks consist of multiple tasks and you want to display sub-progress messages ...
377,739
def replace_find_selection(self, focus_replace_text=False): if self.editor is not None: replace_text = to_text_string(self.replace_text.currentText()) search_text = to_text_string(self.search_text.currentText()) case = self.case_button.isChecked() w...
Replace and find in the current selection
377,740
def get_permissions(self, token, resource_scopes_tuples=None, submit_request=False, ticket=None): headers = { "Authorization": "Bearer %s" % token, : , } data = [ (, ), (, self._client_id), (, True), ...
Request permissions for user from keycloak server. https://www.keycloak.org/docs/latest/authorization_services/index .html#_service_protection_permission_api_papi :param str token: client access token :param Iterable[Tuple[str, str]] resource_scopes_tuples: list of tuples (...
377,741
def add_child(self, child): if child: if child.tag in self.contained_children: self.children.append(child) else: raise ETD_MS_StructureException( % (child.tag, self.tag) ...
Add a child object to the current one. Checks the contained_children list to make sure that the object is allowable, and throws an exception if not.
377,742
def select_previous(self): self.footer.clear_message() if self.selected == 0: self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN) return old_index = self.selected new_index = self.selected - 1 self.selected = new_index ...
Move to the previous status in the timeline.
377,743
def get_orgas(self): r = self._request() if not r: return None retour = [] for data in r.json()[]: o = Orga() o.__dict__.update(data) o.pk = o.id retour.append(o) return retour
Return the list of pk for all orgas
377,744
def enable(self): nwin = self.nwin.value() for label, xs, ys, nx, ny in \ zip(self.label[:nwin], self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): label.config(state=) xs.enable() ys.enable() nx.e...
Enables all settings
377,745
def _create_session(self): self.driver = requests.Session(**self.driver_args) self.update_headers(self.current_headers) self.update_cookies(self.current_cookies) self.set_proxy(self.current_proxy)
Creates a fresh session with the default header (random UA)
377,746
def yiq_to_rgb(y, i=None, q=None): if type(y) in [list,tuple]: y, i, q = y r = y + (i * 0.9562) + (q * 0.6210) g = y - (i * 0.2717) - (q * 0.6485) b = y - (i * 1.1053) + (q * 1.7020) return (r, g, b)
Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '({}, {}, {})'.f...
377,747
def write_and_return( command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT): clear_buffer(serial_connection) with serial_with_temp_timeout( serial_connection, timeout) as device_connection: response = _write_to_device_and_return(command, ack, device_connection) ret...
Write a command and return the response
377,748
def _parse_args(self, args): enc = DEFAULT_ENCODING uargs = [py3compat.cast_unicode(a, enc) for a in args] self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
self.parser->self.parsed_data
377,749
def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec): ast_type = ast.__class__.__name__ trigger_functions = rule.get("trigger_function", []) trigger_types = rule.get("trigger_type", []) rule_subject = rule.get("subject") rule_relation = rule.get("relation") ...
Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AST rule (Mapping[str, Any]: computed edge rule
377,750
def get_polygon_pattern_rules(declarations, dirs): property_map = {: , : , : , : , : , : } property_names = property_map.keys() rules = [] for (filter, values) in filtered_property_declarations(declarations, property_names): ...
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
377,751
def _lines_only(shape): lines = _explode_lines(shape) if len(lines) == 1: return lines[0] else: return MultiLineString(lines)
Extract the lines (LineString, MultiLineString) from any geometry. We expect the input to be mostly lines, such as the result of an intersection between a line and a polygon. The main idea is to remove points, and any other geometry which might throw a wrench in the works.
377,752
def activate(self): self.open() a = lvm_lv_activate(self.handle) self.close() if a != 0: raise CommitError("Failed to activate LV.")
Activates the logical volume. *Raises:* * HandleError
377,753
def get_emerg(): key = "emerg:{}".format(datetime.datetime.now().date()) cached = cache.get(key) cached = None if cached: logger.debug("Returning emergency info from cache") return cached else: result = get_emerg_result() cache.set(key, result, timeout=settings...
Get the cached FCPS emergency page, or check it again. Timeout defined in settings.CACHE_AGE["emerg"]
377,754
def delete(self, membershipId): check_type(membershipId, basestring, may_be_none=False) self._session.delete(API_ENDPOINT + + membershipId)
Delete a team membership, by ID. Args: membershipId(basestring): The team membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
377,755
def fetch(self): tlen = self.end - self.start dfs = [] lrange = [x for x in (self.start + timedelta(n) for n in range(tlen.days))] mrange = [] for dt in lrange: if datetime(dt.year, dt.month, 1) not in mrange: ...
Unfortunately, IEX's API can only retrieve data one day or one month at a time. Rather than specifying a date range, we will have to run the read function for each date provided. :return: DataFrame
377,756
def set_physical_page_for_file(self, pageId, ocrd_file, order=None, orderlabel=None): for el_fptr in self._tree.getroot().findall( % ocrd_file.ID, namespaces=NS): el_fptr.getparent().remove(el_fptr) el_structmap = self._tr...
Create a new physical page
377,757
def play(self): if self.state == PygAnimation.PLAYING: pass elif self.state == PygAnimation.STOPPED: self.index = 0 self.elapsed = 0 self.playingStartTime = time.time() self.elapsedStopTime = self.endTimesList[-1] ...
Starts an animation playing.
377,758
def get_dataset(self, dsid, info): dsid_name = dsid.name if dsid_name in self.cache: logger.debug(, dsid_name) return self.cache[dsid_name] if dsid_name in [, ] and dsid_name not in self.nc: dsid_name = dsid_name + logger.debug(, dsid_name)...
Load a dataset.
377,759
def _get_indices(num_results, sequence_indices, dtype, name=None): with tf.compat.v1.name_scope(name, , [num_results, sequence_indices]): if sequence_indices is None: num_results = tf.cast(num_results, dtype=dtype) sequence_indices = tf.range(num_results, dtype=dtype)...
Generates starting points for the Halton sequence procedure. The k'th element of the sequence is generated starting from a positive integer which must be distinct for each `k`. It is conventional to choose the starting point as `k` itself (or `k+1` if k is zero based). This function generates the starting inte...
377,760
def add_variable(self, variable, card=0): if variable not in self.variables: self.variables.append(variable) else: warn(.format(var=variable)) self.cardinalities[variable] = card self.transition_models[variable] = {}
Add a variable to the model. Parameters: ----------- variable: any hashable python object card: int Representing the cardinality of the variable to be added. Examples: --------- >>> from pgmpy.models import MarkovChain as MC >>> model = MC()...
377,761
def isdir(self): if self.type == RAR_BLOCK_FILE: return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY return False
Returns True if entry is a directory.
377,762
def _split_classes_by_kind(self, class_name_to_definition): for class_name in class_name_to_definition: inheritance_set = self._inheritance_sets[class_name] is_vertex = ORIENTDB_BASE_VERTEX_CLASS_NAME in inheritance_set is_edge = ORIENTDB_BASE_EDGE_CLASS_NAME in inh...
Assign each class to the vertex, edge or non-graph type sets based on its kind.
377,763
def rebuildDay( self ): scene = self.scene() if ( not scene ): return start_date = self.dateStart() end_date = self.dateEnd() min_date = scene.minimumDate() max_date = scene.maximumDate() if...
Rebuilds the current item in day mode.
377,764
def get_connection(self, command_name, *keys, **options): self._checkpid() try: connection = self._available_connections[self._pattern_idx].pop() except IndexError: connection = self.make_connection() self._in_use_connections[self._pattern_idx].add(connec...
Get a connection from the pool
377,765
def enrich_backend(url, clean, backend_name, backend_params, cfg_section_name, ocean_index=None, ocean_index_enrich=None, db_projects_map=None, json_projects_map=None, db_sortinghat=None, no_incremental=False, only_identities...
Enrich Ocean index
377,766
def get_sources(self, skydir=None, distance=None, cuts=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, coordsys=, names=None): if skydir is None: skydir = self.skydir if exclude is None: e...
Retrieve list of source objects satisfying the following selections: * Angular separation from ``skydir`` or ROI center (if ``skydir`` is None) less than ``distance``. * Cuts on source properties defined in ``cuts`` list. * TS and Npred in range specified by ``...
377,767
def initialize(self, params, qubits): if isinstance(qubits, QuantumRegister): qubits = qubits[:] else: qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0] return self.append(Initialize(params), qubits)
Apply initialize to circuit.
377,768
def remove_root_bin(self, bin_id): if self._catalog_session is not None: return self._catalog_session.remove_root_catalog(catalog_id=bin_id) return self._hierarchy_session.remove_root(id_=bin_id)
Removes a root bin. arg: bin_id (osid.id.Id): the ``Id`` of a bin raise: NotFound - ``bin_id`` not a root raise: NullArgument - ``bin_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: ...
377,769
def _get_overlaps_tensor(self, L): n, m = L.shape LY = np.array([np.where(L == y, 1, 0) for y in range(self.k_0, self.k + 1)]) O = np.einsum("abc,dbe,fbg->cegadf", LY, LY, LY) / n return torch.from_numpy(O).float()
Transforms the input label matrix to a three-way overlaps tensor. Args: L: (np.array) An n x m array of LF output labels, in {0,...,k} if self.abstains, else in {1,...,k}, generated by m conditionally independent LFs on n data points Outputs: O: ...
377,770
def _members(self): return { key: value for key, value in self.__dict__.items() if not key.startswith("_") and not isinstance(value, Model) }
Return a dict of non-private members.
377,771
def execute_command(self, command): self.info_log("executing command: %s" % command) try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) k = paramiko.RSAKey.from_private_key_file( self.browser_config.ge...
Execute a command on the node Args: command (str)
377,772
def spliced_offset(self, position): assert type(position) == int, \ "Position argument must be an integer, got %s : %s" % ( position, type(position)) if position < self.start or position > self.end: raise ValueError( "In...
Convert from an absolute chromosomal position to the offset into this transcript"s spliced mRNA. Position must be inside some exon (otherwise raise exception).
377,773
def _parse_ical_string(ical_string): start_time = ical_string.splitlines()[0].replace(DTSTART, ) if "RRULE" in ical_string: days = ical_string.splitlines()[1].replace(REPEAT, ) if days == "RRULE:FREQ=DAILY": days = [] else: days = days.split() el...
SU,MO,TU,WE,TH,FR,SA DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=WEEKLY;BYDAY=SA DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=DAILY DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR,SA DTSTART;TZID=America/New_York:20180718T174500
377,774
def admm_linearized(x, f, g, L, tau, sigma, niter, **kwargs): r if not isinstance(L, Operator): raise TypeError( .format(L)) if x not in L.domain: raise OpDomainError( .format(x, L.domain)) tau, tau_in = float(tau), tau if tau <= ...
r"""Generic linearized ADMM method for convex problems. ADMM stands for "Alternating Direction Method of Multipliers" and is a popular convex optimization method. This variant solves problems of the form :: min_x [ f(x) + g(Lx) ] with convex ``f`` and ``g``, and a linear operator ``L``. See S...
377,775
def com_google_fonts_check_production_glyphs_similarity(ttFont, api_gfonts_ttFont): def glyphs_surface_area(ttFont): from fontTools.pens.areaPen import AreaPen glyphs = {} glyph_set = ttFont.getGlyphSet() area_pen = AreaPen(glyph_set) for glyph in glyph_set.keys(): glyph_set[glyph]...
Glyphs are similiar to Google Fonts version?
377,776
def backpropagate_3d_tilted(uSin, angles, res, nm, lD=0, tilted_axis=[0, 1, 0], coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval=None, intp_order=2, dtype=None, ...
r"""3D backpropagation with a tilted axis of rotation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagati...
377,777
def damping_kraus_map(p=0.10): damping_op = np.sqrt(p) * np.array([[0, 1], [0, 0]]) residual_kraus = np.diag([1, np.sqrt(1 - p)]) return [residual_kraus, damping_op]
Generate the Kraus operators corresponding to an amplitude damping noise channel. :param float p: The one-step damping probability. :return: A list [k1, k2] of the Kraus operators that parametrize the map. :rtype: list
377,778
def trimSegments(self, minPermanence=None, minNumSyns=None): if minPermanence is None: minPermanence = self.connectedPerm if minNumSyns is None: minNumSyns = self.activationThreshold totalSegsRemoved, totalSynsRemoved = 0, 0 for c, i in itertools.product(xrange(self.numberOfC...
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. :param minPermanence: (float) Any syn whose permanence is 0 or < ``minPermanence`` will be deleted. If None is passed in, then ``...
377,779
def to_holvi_dict(self): self._jsondata["items"] = [] for item in self.items: self._jsondata["items"].append(item.to_holvi_dict()) self._jsondata["issue_date"] = self.issue_date.isoformat() self._jsondata["due_date"] = self.due_date.isoformat() self._jsondata...
Convert our Python object to JSON acceptable to Holvi API
377,780
def build_ast(expression, debug = False): G = DiGraph() stack = [] for n in expression: if isinstance(n,OperatorNode): if n.ttype == "operator-infix": arg2 = stack.pop() arg1 = stack.pop() if(n...
build an AST from an Excel formula expression in reverse polish notation
377,781
def fromhdf5sorted(source, where=None, name=None, sortby=None, checkCSI=False, start=None, stop=None, step=None): assert sortby is not None, return HDF5SortedView(source, where=where, name=name, sortby=sortby, checkCSI=checkCSI, start...
Provides access to an HDF5 table, sorted by an indexed column, e.g.:: >>> import petl as etl >>> import tables >>> # set up a new hdf5 table to demonstrate with ... h5file = tables.open_file('example.h5', mode='w', title='Test file') >>> h5file.create_group('/', 'testgroup', 'Te...
377,782
def argparser(self): core_parser = self.core_parser core_parser.add_argument(, , type=str, help="The range to search for use") return core_parser
Argparser option with search functionality specific for ranges.
377,783
def update_service(name, service_map): if name in service_map: service = service_map[name] data = service.update() if not data: logger.warning(, name) else: data[] = service.service_name CACHE[name] = dict(data=data, updated=datetime.now()) ...
Get an update from the specified service. Arguments: name (:py:class:`str`): The name of the service. service_map (:py:class:`dict`): A mapping of service names to :py:class:`flash.service.core.Service` instances. Returns: :py:class:`dict`: The updated data.
377,784
def _set_general_compilers(self): for c, c_info in self.compilers.items(): compiler_cls = c_info["cls"](template=c_info["template"]) c_info["channels"] = [] for p in self.processes: if not any([isinstance(p, x) for x in self.skip_class...
Adds compiler channels to the :attr:`processes` attribute. This method will iterate over the pipeline's processes and check if any process is feeding channels to a compiler process. If so, that compiler process is added to the pipeline and those channels are linked to the compiler via s...
377,785
def github_repos(organization, github_url, github_token): headers = {"Authorization": "token {}".format(github_token)} next_cursor = None while next_cursor is not False: params = {: query, : { : organization, : next_cursor}} response = requests.post(github_url, headers...
Return all github repositories in an organization.
377,786
def cublasZgbmv(handle, trans, m, n, kl, ku, alpha, A, lda, x, incx, beta, y, incy): status = _libcublas.cublasZgbmv_v2(handle, trans, m, n, kl, ku, ctypes.byref(cuda.cuDoubleComplex(alpha.real, ...
Matrix-vector product for complex general banded matrix.
377,787
def caesar(shift, data, shift_ranges=(, )): alphabet = dict( (chr(c), chr((c - s + shift) % (e - s + 1) + s)) for s, e in map(lambda r: (ord(r[0]), ord(r[-1])), shift_ranges) for c in range(s, e + 1) ) return .join(alphabet.get(c, c) for c in data)
Apply a caesar cipher to a string. The caesar cipher is a substition cipher where each letter in the given alphabet is replaced by a letter some fixed number down the alphabet. If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, etc... You can define the alphabets that will be shift by s...
377,788
def check_file_list_cache(opts, form, list_cache, w_lock): refresh_cache = False save_cache = True serial = salt.payload.Serial(opts) wait_lock(w_lock, list_cache, 5 * 60) if not os.path.isfile(list_cache) and _lock_cache(w_lock): refresh_cache = True else: attempt = 0 ...
Checks the cache file to see if there is a new enough file list cache, and returns the match (if found, along with booleans used by the fileserver backend to determine if the cache needs to be refreshed/written).
377,789
def get_random(self, size=10): bin_centers_ravel = np.array(np.meshgrid(*self.bin_centers(), indexing=)).reshape(self.dimensions, -1).T hist_ravel = self.histogram.ravel() hist_ravel = hist_ravel.astype(np.float) / np.nansum(hist...
Returns (size, n_dim) array of random variates from the histogram. Inside the bins, a uniform distribution is assumed Note this assumes the histogram is an 'events per bin', not a pdf. TODO: test more.
377,790
def put_attribute(self, id, key, value, **kwargs): kwargs[] = True if kwargs.get(): return self.put_attribute_with_http_info(id, key, value, **kwargs) else: (data) = self.put_attribute_with_http_info(id, key, value, **kwargs) return data
Add attribute to the BuildRecord. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) ...
377,791
def UNIFAC(T, xs, chemgroups, cached=None, subgroup_data=None, interaction_data=None, modified=False): rs temperature, liquid mole fractions, and optionally the subgroup data and interaction parameter data of your choice. The default is to use the original UNIFAC model, with the latest pa...
r'''Calculates activity coefficients using the UNIFAC model (optionally modified), given a mixture's temperature, liquid mole fractions, and optionally the subgroup data and interaction parameter data of your choice. The default is to use the original UNIFAC model, with the latest parameters publish...
377,792
def idmap_get_new(connection, old, tbl): cursor = connection.cursor() cursor.execute("SELECT new FROM _idmap_ WHERE old == ?", (old,)) new = cursor.fetchone() if new is not None: return ilwd.ilwdchar(new[0]) new = tbl.get_next_id() cursor.execute("INSERT INTO _idmap_ VALUES (?, ?)", (old, new)) return...
From the old ID string, obtain a replacement ID string by either grabbing it from the _idmap_ table if one has already been assigned to the old ID, or by using the current value of the Table instance's next_id class attribute. In the latter case, the new ID is recorded in the _idmap_ table, and the class attribute...
377,793
def _wait_for_ip(name, session): start_time = datetime.now() status = None while status is None: status = get_vm_ip(name, session) if status is not None: if status.startswith(): status = None check_time = datetime.now() delta = ch...
Wait for IP to be available during create()
377,794
def get_value(self, key, default={}, nested=True, decrypt=True): key = key.lstrip() if key.endswith("."): key = key[:-1] if nested: path = key.split(".") curr = self.settings for p in path[:-1]: curr = curr.get(p, {}) ...
Retrieve a value from the configuration based on its key. The key may be nested. :param str key: A path to the value, with nested levels joined by '.' :param default: Value to return if the key does not exist (defaults to :code:`dict()`) :param bool decrypt: If :code:`True`, decrypt an ...
377,795
def redirect_stdout(new_stdout): old_stdout, sys.stdout = sys.stdout, new_stdout try: yield None finally: sys.stdout = old_stdout
Redirect the stdout Args: new_stdout (io.StringIO): New stdout to use instead
377,796
def get_datafeeds(self, datafeed_id=None, params=None): return self.transport.perform_request( "GET", _make_path("_ml", "datafeeds", datafeed_id), params=params )
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-datafeed.html>`_ :arg datafeed_id: The ID of the datafeeds to fetch :arg allow_no_datafeeds: Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds...
377,797
def tobinary(self): entrylen = struct.calcsize(self.ENTRYSTRUCT) rslt = [] for (dpos, dlen, ulen, flag, typcd, nm) in self.data: nmlen = len(nm) + 1 toclen = nmlen + entrylen if t...
Return self as a binary string.
377,798
def rm_env(user, name): * lst = list_tab(user) ret = rm_ = None for ind in range(len(lst[])): if name == lst[][ind][]: rm_ = ind if rm_ is not None: lst[].pop(rm_) ret = comdat = _write_cron_lines(user, _render_tab(lst)) if comdat[]: ...
Remove cron environment variable for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_env root MAILTO
377,799
def add_key(self, key): if key not in self.value: self.value[key] = ReducedMetric(self.reducer)
Adds a new key to this metric