text
stringlengths
78
104k
score
float64
0
0.18
def set_background_color(self, color): """ Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing. """ # Set a new default color map. self.default_color_map = self.darkbg_color_map.copy() if color.value() >= 127: ...
0.002551
def to_utc_datetime(self, value): """ from value to datetime with tzinfo format (datetime.datetime instance) """ if isinstance(value, (six.integer_types, float, six.string_types)): value = self.to_naive_datetime(value) if isinstance(value, datetime.datetime): ...
0.002911
def get_required_pull_request_reviews(self): """ :calls: `GET /repos/:owner/:repo/branches/:branch/protection/required_pull_request_reviews <https://developer.github.com/v3/repos/branches>`_ :rtype: :class:`github.RequiredPullRequestReviews.RequiredPullRequestReviews` """ headers...
0.007508
def event_types(self): """ Raises ------ IndexError When there is no selected rater """ try: events = self.rater.find('events') except AttributeError: raise IndexError('You need to have at least one rater') return [x.ge...
0.00578
def eval_objfn(self): r"""Compute components of objective function as well as total contribution to objective function. Data fidelity term is :math:`(1/2) \| H \mathbf{x} - \mathbf{s} \|_2^2` and regularisation term is :math:`\| W_{\mathrm{tv}} \sqrt{(G_r \mathbf{x})^2 + (G_c \ma...
0.00304
def ensure_str(text): u"""Convert unicode to str using pyreadline_codepage""" if isinstance(text, unicode): try: return text.encode(pyreadline_codepage, u"replace") except (LookupError, TypeError): return text.encode(u"ascii", u"replace") return text
0.003236
def write_puml(self, filename=''): """ Writes PUML from the system. If filename is given, stores result in the file. Otherwise returns result as a string. """ def get_type(o): type = 'program' if isinstance(o, AbstractSensor): type ...
0.002602
def is_valid_github_uri(uri: URI, expected_path_terms: Tuple[str, ...]) -> bool: """ Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms...
0.003922
def update_attrs(self): """ Add attributes such as count/end_time that can be present """ for key, value in self._response_json.items(): if key != 'results' and type(value) not in (list, dict): setattr(self, key, value)
0.007605
def check_specifier(dist, attr, value): """Verify that value is a valid version specifier""" try: packaging.specifiers.SpecifierSet(value) except packaging.specifiers.InvalidSpecifier as error: tmpl = ( "{attr!r} must be a string " "containing valid version specifiers...
0.002433
def DocInheritMeta(style="parent", abstract_base_class=False): """ A metaclass that merges the respective docstrings of a parent class and of its child, along with their properties, methods (including classmethod, staticmethod, decorated methods). Parameters ---------- style: Union[...
0.006568
def best_response(self, opponents_actions, tie_breaking='smallest', payoff_perturbation=None, tol=None, random_state=None): """ Return the best response action(s) to `opponents_actions`. Parameters ---------- opponents_actions : scalar(int) or array_like ...
0.000948
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
0.005556
def merge(adata, ldata, copy=True): """Merges two annotated data matrices. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix (reference data set). ldata: :class:`~anndata.AnnData` Annotated data matrix (to be merged into adata). Returns ------- ...
0.003899
def split_and_strip_without(string, exclude, separator_regexp=None): """Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, was, here ', ['was']) ['fred', 'here'] """ result = split_and_strip(string, separa...
0.002358
def extrusion(target, throat_perimeter='throat.perimeter', throat_length='throat.length'): r""" Calculate surface area for an arbitrary shaped throat give the perimeter and length. Parameters ---------- target : OpenPNM Object The object which this model is associated with...
0.00128
def _split_constraints(constraints, concrete=True): """ Returns independent constraints, split from this Frontend's `constraints`. """ splitted = [ ] for i in constraints: splitted.extend(i.split(['And'])) l.debug("... splitted of size %d", len(splitted)) ...
0.010817
def server_doc(self_or_cls, obj, doc=None): """ Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance. """ if not isinstance(obj, (Plot, BokehServerWidgets)): ...
0.004237
def _get_mixing_indices(size, seed=None, name=None): """Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generate...
0.001485
def find_charged(self, mol): """Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid.""" data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain') a_set = [] # Iterate through all residue, exclude those in c...
0.005553
def retrieve_paths(self, products, report_path, suffix=None): """Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expe...
0.001783
def traverse(self, traverser, **kwargs): """ Implementation of mandatory interface for traversing the whole rule tree. This method will call the ``traverse`` method of child rule tree and then perform arbitrary conversion of the result before returning it back. The optional ``kwa...
0.009032
def send(r, pools=None): """Sends a given Request object.""" if pools: r._pools = pools r.send() return r.response
0.007092
def as_call(self): """ Return this call as it is called in its source. """ default = self._default() default = ', ' + default if default else '' return "pyconfig.%s(%r%s)" % (self.method, self.get_key(), default)
0.007663
def _store32(ins): """ Stores 2nd operand content into address of 1st operand. store16 a, x => *(&a) = x """ op = ins.quad[1] indirect = op[0] == '*' if indirect: op = op[1:] immediate = op[0] == '#' # Might make no sense here? if immediate: op = op[1:] if is_int...
0.000943
def convert_to_int(x: Any, default: int = None) -> int: """ Transforms its input into an integer, or returns ``default``. """ try: return int(x) except (TypeError, ValueError): return default
0.004405
def _end_flusher_loop(self): """ Let flusher_loop coroutine quit - useful when disconnecting. """ if not self.is_connected or self.is_connecting or self.io.closed(): if self._flush_queue is not None and self._flush_queue.empty(): self._flush_pending(check_conn...
0.00542
def observe(self): """ Check if the request is an observing request. :return: 0, if the request is an observing request """ for option in self.options: if option.number == defines.OptionRegistry.OBSERVE.number: # if option.value is None: ...
0.004329
def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start...
0.00439
def decode_to_unicode(text, default_encoding='utf-8'): """Decode input text into Unicode representation. Decode input text into Unicode representation by first using the default encoding utf-8. If the operation fails, it detects the type of encoding used in the given text. For optimal result, i...
0.0018
def render_app_description(context, app, fallback="", template="/admin_app_description.html"): """ Render the application description using the default template name. If it cannot find a template matching the given path, fallback to the fallback argument. """ try: template = app['app_label']...
0.009217
def OnSelectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectCard(self, card) self.feedbacktext.SetLabel('Selected card: ' + repr(card)) if hasattr(self.selectedcard, 'connection'...
0.00551
def recurse_module( overall_record, index, shared, stop_types=STOP_TYPES, already_seen=None, min_size=0 ): """Creates a has-a recursive-cost hierarchy Mutates objects in-place to produce a hierarchy of memory usage based on reference-holding cost assignment """ for record in recurse( ...
0.020108
def get_resources(connection): """ Do an RTSP-DESCRIBE request, then parse out available resources from the response """ resp = connection.describe(verbose=False).split('\r\n') resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )] return resources
0.016026
def run(cmd, shell=False, debug=False): 'Run a command and return the output.' proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell) (out, _) = proc.communicate() # no need for stderr if debug: print(cmd) print(out) return out
0.003636
def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): """ Truncates a colormap to use. Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib """ new_cmap = LinearSegmentedColormap.from_list( 'trunc({n},{a:...
0.004454
def filter_muons(blob): """Write all muons from McTracks to Muons.""" tracks = blob['McTracks'] muons = tracks[tracks.type == -13] # PDG particle code blob["Muons"] = Table(muons) return blob
0.004673
def interpolate(self, lat, lon, var): """ Interpolate each var on the coordinates requested """ subset, dims = self.crop(lat, lon, var) if np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['lon'] for x in lon]): yn = np.nonzero([y in lat...
0.002224
def summary(self, indicator_data): """Return a summary value for any given indicator type.""" summary = None for v in self._value_fields: if indicator_data.get(v) is not None: summary = indicator_data.get(v) break return indicator_data.get('sum...
0.00597
def _format_assertmsg(obj): """Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects py.io.saferepr() is used first. """ # reprlib appears to have a b...
0.001059
def pspawn_wrapper(self, sh, escape, cmd, args, env): """Wrapper function for handling piped spawns. This looks to the calling interface (in Action.py) like a "normal" spawn, but associates the call with the PSPAWN variable from the construction environment and with the streams to which...
0.004762
def _alpha(self, L): """ Covariance-derived term to construct expectations. See Rasmussen & Williams. Parameters ---------- L : np.ndarray Cholesky triangular Returns ---------- np.ndarray (alpha) """ return la.cho_solve(...
0.015707
def find_additional_properties(instance, schema): """ Return the set of additional properties for the given ``instance``. Weeds out properties that should have been validated by ``properties`` and / or ``patternProperties``. Assumes ``instance`` is dict-like already. """ properties = sch...
0.001706
def on_epoch_end(self, last_metrics, **kwargs): "Set the final result in `last_metrics`." return add_metrics(last_metrics, self.val/self.count)
0.012579
def _cursor_position_changed(self): """ Updates the document formatting based on the new cursor position. """ # Clear out the old formatting. self._text_edit.setExtraSelections([]) # Attempt to match a bracket for the new cursor position. cursor = self._text_edit.textCur...
0.005563
def _GetCachedFileByPath(self, key_path_upper): """Retrieves a cached Windows Registry file for a key path. Args: key_path_upper (str): Windows Registry key path, in upper case with a resolved root key alias. Returns: tuple: consist: str: key path prefix WinRegistryF...
0.004529
def get_cache(self, cache_name, miss_fn): """ Get an L{AsyncLRUCache} object with the given name. If such an object does not exist, it will be created. Since the cache is permanent, this method can be called only once, e.g., in C{startService}, and it value stored indefinitely....
0.002304
def _fstat_sig(self): """p-value of the F-statistic.""" return 1.0 - scs.f.cdf(self._fstat, self._df_reg, self._df_err)
0.014599
def parse_list_cmd(proc, args, listsize=10): """Parses arguments for the "list" command and returns the tuple: (filename, first line number, last line number) or sets these to None if there was some problem.""" text = proc.current_command[len(args[0])+1:].strip() if text in frozenset(('', '.', '+'...
0.00201
def fire_metric(metric_name, metric_value): """ Fires a metric using the MetricsApiClient """ metric_value = float(metric_value) metric = {metric_name: metric_value} metric_client.fire_metrics(**metric) return "Fired metric <{}> with value <{}>".format(metric_name, metric_value)
0.006601
def path_constant(self, name, value): """Declare and set a project global constant, whose value is a path. The path is adjusted to be relative to the invocation directory. The given value path is taken to be either absolute, or relative to this project root.""" assert is_iterable...
0.006944
def _get_operations(self, context): """Returns a list of operations that need to be performed to turn the cached source code into the one in the buffer.""" #Most of the time, the real-time update is going to fire with #incomplete statements that don't result in any changes being made ...
0.009023
def split_emails(msg): """ Given a message (which may consist of an email conversation thread with multiple emails), mark the lines to identify split lines, content lines and empty lines. Correct the split line markers inside header blocks. Header blocks are identified by the regular expression...
0.001309
def _bell(self): u'''ring the bell if requested.''' if self.bell_style == u'none': pass elif self.bell_style == u'visible': raise NotImplementedError(u"Bellstyle visible is not implemented yet.") elif self.bell_style == u'audible': self.console.bell() ...
0.009828
def add(self, *args, **kwargs): """ Add new mapping from args and kwargs >>> om = OperationIdMapping() >>> om.add( ... OperationIdMapping(), ... 'aiohttp_apiset.swagger.operations', # any module ... getPets='mymod.handler', ... getPet='mymod.get_...
0.002604
def deregister(self, key): """ Deregisters an existing key. `key` String key to deregister. Returns boolean. """ res = super(ExtRegistry, self).deregister(key) if key in self._type_info: del self._type_info[key] return re...
0.006231
def build_blast_db_from_fasta_file(fasta_file, is_protein=False, output_dir=None, HALT_EXEC=False): """Build blast db from fasta_path; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_fil...
0.0013
def _wait_until_machine_finish(self): """ Internal method wait until machine finish and kill main process (booted) :return: None """ self.image._wait_for_machine_finish(self.name) # kill main run process self.start_process.kill() # TODO: there are...
0.005803
def convert_via_profile(self, data_np, order, inprof_name, outprof_name): """Convert the given RGB data from the working ICC profile to the output profile in-place. Parameters ---------- data_np : ndarray RGB image data to be displayed. order : str ...
0.002055
def _check_years(self, cell, prior_year): ''' Helper method which defines the rules for checking for existence of a year indicator. If the cell is blank then prior_year is used to determine validity. ''' # Anything outside these values shouldn't auto # categorize to strin...
0.004237
def _transition_stage(self, step, total_steps, brightness=None, color=None): """ Get a transition stage at a specific step. :param step: The current step. :param total_steps: The total number of steps. :param brightness: The brightness to transition to ...
0.003074
def get_keywords(self, entry): """ get list of models.Keyword objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Keyword` objects """ keyword_objects = [] for keyword in entry.iterfind("./keyword"): ...
0.004386
def runTask(self, task, timeout=None): """Run a child task to completion. Returns the result of the child task. """ # Initialize the task. task.initialize(self) # Start the task. task.start() # Lets other threads run time.sleep(0) # Wai...
0.004706
def normalizeURL(url): """Normalize a URL, converting normalization failures to DiscoveryFailure""" try: normalized = urinorm.urinorm(url) except ValueError, why: raise DiscoveryFailure('Normalizing identifier: %s' % (why[0],), None) else: return urlparse.urldefrag(normalized...
0.003086
def is_network_source_fw(cls, nwk, nwk_name): """Check if SOURCE is FIREWALL, if yes return TRUE. If source is None or entry not in NWK DB, check from Name. Name should have constant AND length should match. """ if nwk is not None: if nwk.source == fw_const.FW_CONST:...
0.002116
def intersectsExtent(self, extent): "Determine if an extent intersects this instance extent" return \ self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \ self.extent[1] <= extent[3] and self.extent[3] >= extent[1]
0.007491
def _build_likelihood(self): r""" q_alpha, q_lambda are variational parameters, size N x R This method computes the variational lower bound on the likelihood, which is: E_{q(F)} [ \log p(Y|F) ] - KL[ q(F) || p(F)] with q(f) = N(f | K alpha + mean, [K^-1 + ...
0.003408
def get_attached_devices_2(self): """ Return list of connected devices to the router with details. This call is slower and probably heavier on the router load. Returns None if error occurred. """ _LOGGER.info("Get attached devices 2") success, response = self._...
0.001304
def refresh(self, token, timeout): """Modify an existing lock's timeout. token: Valid lock token. timeout: Suggested lifetime in seconds (-1 for infinite). The real expiration time may be shorter than requested! Returns: Lock dictionary. ...
0.001978
def word(self): """Return last changes with word diff""" try: output = ensure_unicode(self.git.diff( '--no-color', '--word-diff=plain', 'HEAD~1:content', 'HEAD:content', ).stdout) except sh.ErrorReturnCode_12...
0.001773
def create_user(server_context, email, container_path=None, send_email=False): """ Create new account :param server_context: A LabKey server context. See utils.create_server_context. :param email: :param container_path: :param send_email: true to send email notification to user :return: ...
0.005474
def parse_idf(file_like): """ Records are created from string. They are not attached to idf yet. in idf: header comment, chapter comments, records in record: head comment, field comments, tail comment """ tables_data = {} head_comment = "" record_data = None make_new_record = Tru...
0.000636
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): """Handle an event received from an adapter.""" if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, eve...
0.004261
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message...
0.003396
def fill(self, paths): """ Initialise the tree. paths is a list of strings where each string is the relative path to some file. """ for path in paths: tree = self.tree parts = tuple(path.split('/')) dir_parts = parts[:-1] b...
0.00534
def calc_grad(self): """The gradient of the cost w.r.t. the parameters.""" if self._fresh_JTJ: return self._graderr else: residuals = self.calc_residuals() return 2*np.dot(self.J, residuals)
0.008
def walk(self, maxresults=100, maxdepth=None): """Walk the object tree, ignoring duplicates and circular refs.""" log.debug("step") self.seen = {} self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals ...
0.002865
def query(self, stringa): """SPARQL query / wrapper for rdflib sparql query method """ qres = self.rdflib_graph.query(stringa) return list(qres)
0.011905
def _get_par_summary(sim, n, probs): """Summarize chains merged and individually Parameters ---------- sim : dict from stanfit object n : int parameter index probs : iterable of int quantiles Returns ------- summary : dict Dictionary containing summaries ...
0.003686
def collectData(reads1, reads2, square, matchAmbiguous): """ Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids w...
0.000778
def hdate(self, date): """Set the dates of the HDate object based on a given Hebrew date.""" # Sanity checks if date is None and isinstance(self.gdate, datetime.date): # Calculate the value since gdate has been set date = self.hdate if not isinstance(date, Hebrew...
0.002774
def subs(self, *args): """Substitute a symbolic expression in ``['x', 'y', 'z']`` This is a wrapper around the substitution mechanism of `sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_. Any symbolic expression in the columns ``['x', 'y', 'z']`` of ``self``...
0.001219
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_ses...
0.005476
def linear_regression(self, target, regression_length, mask=NotSpecified): """ Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inp...
0.000851
def calc_paired_insert_stats(in_bam, nsample=1000000): """Retrieve statistics for paired end read insert distances. """ dists = [] n = 0 with pysam.Samfile(in_bam, "rb") as in_pysam: for read in in_pysam: if read.is_proper_pair and read.is_read1: n += 1 ...
0.002222
def envelope(self, instrument): """ Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float) """ def envelopeFunc(mz): if is...
0.004011
def p_reset(self, program): """ reset : RESET primary """ program[0] = node.Reset([program[2]]) self.verify_reg(program[2], 'qreg')
0.011696
def ip_prefixes_sanity_check(config, bird_configuration): """Sanity check on IP prefixes. Arguments: config (obg): A configparser object which holds our configuration. bird_configuration (dict): A dictionary, which holds Bird configuration per IP protocol version. """ for ip_ve...
0.001135
def _get_indices(self, data): """ Compute indices along temporal dimension corresponding to the sought percentile :param data: Input 3D array holding the reference band :type data: numpy array :return: 2D array holding the temporal index corresponding to percentile "...
0.009709
def quantile(x, q): """ Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature ...
0.004938
def create_cache_cluster(name, wait=600, security_groups=None, region=None, key=None, keyid=None, profile=None, **args): ''' Create a cache cluster. Example: .. code-block:: bash salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \ ...
0.006431
def has_readonly(self, s): """Tests whether store `s` is read-only.""" for t in self.transitions: if list(t.lhs[s]) != list(t.rhs[s]): return False return True
0.009479
def filter_counter(self, counter, min=2, max=100000000): """ Filter the counted records. Returns: List with record numbers. """ records_filterd = {} counter_all_records = 0 for item in counter: counter_all_records += 1 if max > counter[ite...
0.003711
def null_lml(self): """ Log of the marginal likelihood for the null hypothesis. It is implemented as :: 2·log(p(Y)) = -n·p·log(2𝜋s) - log|K| - n·p, for which s and 𝚩 are optimal. Returns ------- lml : float Log of the marginal likelih...
0.004132
def types(self): """A tuple containing the value types for this Slot. The Python equivalent of the CLIPS deftemplate-slot-types function. """ data = clips.data.DataObject(self._env) lib.EnvDeftemplateSlotTypes( self._env, self._tpl, self._name, data.byref) ...
0.005195
def set_copyright(self, copyright=None): """Sets the copyright. :param copyright: the new copyright :type copyright: ``string`` :raise: ``InvalidArgument`` -- ``copyright`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` ...
0.002516
def _initialize_rest(self): """Used to initialize the View object on first use. """ if self._submit_context is None: raise ValueError("View has not been created.") job = self._submit_context._job_access() self._view_object = job.get_views(name=self.name)[0]
0.006472
def calculate(self, token_list_x, token_list_y): ''' Calculate similarity with the Dice coefficient. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns...
0.008576
def create_code_cell(block): """Create a notebook code cell from a block.""" code_cell = nbbase.new_code_cell(source=block['content']) attr = block['attributes'] if not attr.is_empty: code_cell.metadata \ = nbbase.NotebookNode({'attributes': attr.to_dict()}) ...
0.003565
def get_vdW_settings(self): '''Determine the vdW type if using vdW xc functional or correction scheme from the input otherwise''' xc = self.get_xc_functional().scalars[0].value if 'vdw' in xc.lower(): # vdW xc functional return Value(scalars=[Scalar(value=xc)]) else: ...
0.007569