text
stringlengths
78
104k
score
float64
0
0.18
def infinity_norm(A): """Infinity norm of a matrix (maximum absolute row sum). Parameters ---------- A : csr_matrix, csc_matrix, sparse, or numpy matrix Sparse or dense matrix Returns ------- n : float Infinity norm of the matrix Notes ----- - This serves as an...
0.000755
def handle_valid(self, form=None, *args, **kwargs): """ Called after the form has validated. """ # Take a chance and try save a subclass of a ModelForm. if hasattr(form, 'save'): form.save() # Also try and call handle_valid method of the form itself. i...
0.005013
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
0.00078
def iter_tokens(cls, blob): """ Iterate over tokens found in blob contents :param blob: Input string with python file contents :return: token iterator """ readline_func = io.StringIO(blob.decode('utf-8')).readline return tokenize.generate_tokens(readline_func)
0.003521
def load_EROS_lc(filename='lm0010n22323.time'): """ Read an EROS light curve and return its data. Parameters ---------- filename : str, optional A light-curve filename. Returns ------- dates : numpy.ndarray An array of dates. magnitudes : numpy.ndarray An ar...
0.00158
def unquote(s): """Unquote the indicated string.""" # Ignore the left- and rightmost chars (which should be quotes). # Use the Python engine to decode the escape sequence i, N = 1, len(s) - 1 ret = [] while i < N: if s[i] == '\\' and i < N - 1: ret.append(UNQUOTE_MAP.get(s[i+1], s[i+1])) i +...
0.030691
def add_lvl_to_ui(self, level, header): """Insert the level and header into the ui. :param level: a newly created level :type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel` :param header: a newly created header :type header: QtCore.QWidget|None :returns: N...
0.005172
def add_scalar(self, name, value, step): """Log a scalar variable.""" self.writer.add_scalar(name, value, step)
0.015748
def get_output(self): ''' Execute a command through system shell. First checks to see if the requested command is executable. Returns (returncode, stdout, 0) ''' if self.is_hostname: # short circuit for hostame with internal method return determine_hostnam...
0.000824
async def set_contents(self, **params): """Writes users content to database Accepts: - public key (required) - content (required) - description - price - address """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Miss...
0.044658
def info(self): """get information about this term Parameters ---------- Returns ------- dict containing information to duplicate this term """ info = super(TensorTerm, self).info info.update({'terms':[term.info for term in self._terms]}) ...
0.009036
def raw_section_content_identifier(self, value): """ Setter for **self. __raw_section_content_identifier** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is...
0.006593
def _retransmit(self, transaction, message, future_time, retransmit_count): """ Thread function to retransmit the message in the future :param transaction: the transaction that owns the message that needs retransmission :param message: the message that needs the retransmission task ...
0.003836
def _make_output(value, output_script, version=None): ''' byte-like, byte-like -> TxOut ''' if 'decred' in riemann.get_current_network_name(): return tx.DecredTxOut( value=value, version=version, output_script=output_script) return tx.TxOut(value=value, ou...
0.00289
def delete_app_info(app_id): """ delete app info from local db """ try: conn = get_conn() c = conn.cursor() c.execute("DELETE FROM container WHERE app_id='{0}'".format(app_id)) c.execute("DELETE FROM app WHERE id='{0}'".format(app_id)) conn.commit() #print...
0.006452
def remove_host(self, host): """ Called when the control connection observes that a node has left the ring. Intended for internal use only. """ if host and self.metadata.remove_host(host): log.info("Cassandra host %s removed", host) self.on_remove(host)
0.006289
def load_job_from_container(self, container_path, config_string=None): """ Load the job from the given :class:`aeneas.container.Container` object. If ``config_string`` is ``None``, the container must contain a configuration file; otherwise use the provided config string ...
0.002641
def write(self, font, feaFile, compiler=None): """Write features and class definitions for this font to a feaLib FeatureFile object. Returns True if feature file was modified, False if no new features were generated. """ self.setContext(font, feaFile, compiler=compiler) ...
0.004008
def add_arguments(cls, parser, sys_arg_list=None): """ Arguments for the TCP health monitor plugin. """ parser.add_argument('--tcp_check_interval', dest='tcp_check_interval', required=False, default=2, type=float, ...
0.002312
def size(cell): """ Return the size (maximum cardinality) of a SPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/size_c.html :param cell: Input cell. :type cell: spiceypy.utils.support_types.SpiceCell :return: The size of the input cell. :rtype: int ...
0.002387
def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
0.008065
def button_input(self, title, message, buttons, default, timeout=None, dimensions=None): ''' Function to accept input in the form of a button click. ''' # Create the dialog box self.response = default self.top = tkinter.Tk() self.top.title(title) # Use d...
0.006159
def ensure_contiguity_in_observation_rows(obs_id_vector): """ Ensures that all rows pertaining to a given choice situation are located next to one another. Raises a helpful ValueError otherwise. This check is needed because the hessian calculation function requires the design matrix to have contigui...
0.000729
def _handle_amqp_frame(self, data_in): """Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame """ if not data_in: return data_in, None, None try: byte_count, channel_id, frame_in = ...
0.002574
def _set_remote(self, stream=False): """ Call :py:meth:`~._args_for_remote`; if the return value is not None, execute 'terraform remote config' with those arguments and ensure it exits 0. :param stream: whether or not to stream TF output in realtime :type stream: bool ...
0.002635
def wrapped(f): """ Decorator to append routed docstrings """ import inspect def extract(func): append = "" args = inspect.getargspec(func) for i, a in enumerate(args.args): if i < (len(args) - len(args.defaults)): append += str(a) + ", " ...
0.003333
def partition_services(self, **args): """Partitions two connected services. Not two sets of services (TODO) Expects usual arguments and srcprobability and dstprobability, that indicates probability of terminating connections from source to dest and vice versa """ rule = args.cop...
0.00603
def schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None): """Schedules a function to be called according to some timed rules. Paramet...
0.002596
def close(self): """Close the poll instance.""" if self._poll is None: return self._poll.close() self._poll = None self._readers = 0 self._writers = 0 self._events = 0 clear_callbacks(self)
0.007547
def set_dialog_position(self): """Positions the tab switcher in the top-center of the editor.""" left = self.editor.geometry().width()/2 - self.width()/2 top = self.editor.tabs.tabBar().geometry().height() self.move(self.editor.mapToGlobal(QPoint(left, top)))
0.006734
def expand_families(stmts_in, **kwargs): """Expand FamPlex Agents to individual genes. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to expand. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ...
0.001195
def get_relationships_by_genus_type(self, relationship_genus_type=None): """Gets a ``RelationshipList`` corresponding to the given relationship genus ``Type`` which does not include relationships of types derived from the specified ``Type``. arg: relationship_genus_type (osid.type.Type):...
0.003687
def get_pos(self, sector): """Get index (into the raw data of the disk image) of start of sector This base class method assumes the sectors are one after another, in order starting from the beginning of the raw data. """ if not self.sector_is_valid(sector): raise Byt...
0.004115
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
0.007299
def read(self, nbytes: int = 0) -> bytes: """ read *at most* ``nbytes`` """ if nbytes == 0 or len(self.output) <= nbytes: data = bytes(self.output) del self.output[:] return data data = bytes(self.output[:nbytes]) del self.output[:nbyte...
0.005848
def import_module_or_none(module_label): """ Imports the module with the given name. Returns None if the module doesn't exist, but it does propagates import errors in deeper modules. """ try: # On Python 3, importlib has much more functionality compared to Python 2. return impor...
0.003318
def real_time_scheduling(self, availability, oauth, event, target_calendars=()): """Generates an real time scheduling link to start the OAuth process with an event to be automatically upserted :param dict availability: - A dict describing the availability details for the event: :pa...
0.005873
def create(self, password, username, realm=None): """ Creates a storage password. A `StoragePassword` can be identified by <username>, or by <realm>:<username> if the optional realm parameter is also provided. :param password: The password for the credentials - this is the only part of...
0.004488
def encode(self, lname, max_length=4, german=False): """Calculate the PSHP Soundex/Viewex Coding of a last name. Parameters ---------- lname : str The last name to encode max_length : int The length of the code returned (defaults to 4) german : bo...
0.000416
def innerHTML(self, html: str) -> None: # type: ignore """Set innerHTML both on this node and related browser node.""" df = self._parse_html(html) if self.connected: self._set_inner_html_web(df.html) self._empty() self._append_child(df)
0.00692
def list(self, product, store_view=None, identifierType=None): """ Retrieve product image list :param product: ID or SKU of product :param store_view: Code or ID of store view :param identifierType: Defines whether the product or SKU value is passe...
0.005814
def connected_sets(C, directed=True): r"""Compute connected components for a directed graph with weights represented by the given count matrix. Parameters ---------- C : scipy.sparse matrix or numpy ndarray square matrix specifying edge weights. directed : bool, optional Whether ...
0.001165
def hz_to_octs(frequencies, A440=440.0): """Convert frequencies (Hz) to (fractional) octave numbers. Examples -------- >>> librosa.hz_to_octs(440.0) 4. >>> librosa.hz_to_octs([32, 64, 128, 256]) array([ 0.219, 1.219, 2.219, 3.219]) Parameters ---------- frequencies : numbe...
0.001433
def points(ys, width=None): '''Usage: import scipy.stats def walk(steps, position=0): for step in steps: position += step yield position positions = list(walk(scipy.stats.norm.rvs(size=1000))) points(positions) ''' if width is None: width = terminal.wi...
0.00092
def gen(name, data): """Generate dataentry *name* from *data*.""" return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join( '%s:%s' % (attr, value) for attr, value in data.items()))
0.00939
def on_kill(self): """ Cancel the submitted athena query """ if self.query_execution_id: self.log.info('⚰️⚰️⚰️ Received a kill Signal. Time to Die') self.log.info( 'Stopping Query with executionId - %s', self.query_execution_id ) ...
0.004695
def create_domain_record(self, domain_id, record_type, data, name=None, priority=None, port=None, weight=None): """ This method creates a new domain name with an A record for the specified [ip_address]. Required parameters domain_id: ...
0.002823
def _parsed_cmd(self): """ We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc ru...
0.003883
def verify_response(response, status_code, content_type=None): """Verifies that a response has the expected status and content type. Args: response: The ResponseTuple to be checked. status_code: An int, the HTTP status code to be compared with response status. content_type: A string w...
0.00464
def guest_config_minidisks(self, userid, disk_info): """Punch the script that used to process additional disks to vm :param str userid: the user id of the vm :param disk_info: a list contains disks info for the guest. It contains dictionaries that describes disk info for each dis...
0.001162
def is_contiguous(self): """Return offset and size of contiguous data, else None. Excludes prediction and fill_order. """ if (self.compression != 1 or self.bitspersample not in (8, 16, 32, 64)): return None if 'TileWidth' in self.tags: if...
0.001714
def to_dict(self): """Returns OrderedDict whose keys are self.attrs""" ret = OrderedDict() for attrname in self.attrs: ret[attrname] = self.__getattribute__(attrname) return ret
0.00885
def make_epub_base(location): """ Creates the base structure for an EPUB file in a specified location. This function creates constant components for the structure of the EPUB in a specified directory location. Parameters ---------- location : str A path string to a local directory ...
0.00571
def brightness(level=100, group=0): """ Assumes level is out of 100 """ if level not in range(0,101): raise Exception("Brightness must be value between 0 and 100") b = int(floor(level / 4.0) + 2) #lights want values 2-27 return (COMMANDS['ON'][group], Command(0x4E, b))
0.013652
def readObject(self): """ Reads an anonymous object from the data stream. @rtype: L{ASObject<pyamf.ASObject>} """ obj = pyamf.ASObject() self.context.addObject(obj) obj.update(self.readObjectAttributes(obj)) return obj
0.007018
def fetchall_textdefs(ont): """ fetch all text defs for an ontology """ logging.info("fetching text defs for: "+ont) namedGraph = get_named_graph(ont) query = """ prefix IAO: <http://purl.obolibrary.org/obo/IAO_> SELECT * WHERE {{ GRAPH <{g}> {{ ?c IAO:0000115 ?d }} FI...
0.002041
def lookup_future_symbol(self, symbol): """Lookup a future contract by symbol. Parameters ---------- symbol : str The symbol of the desired contract. Returns ------- future : Future The future contract referenced by ``symbol``. R...
0.002774
def _logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True): """Stable logsumexp when b >= 0 and b is scalar. b_inv overwrites b unless b_inv is None. """ # check dimensions for result arrays ary = np.asarray(ary) if ary.dtype.kind == "i": ary = ary.astype...
0.001604
def parse_form(self, req, name, field): """Pull a form value from the request.""" try: return core.get_value(req.form, name, field) except AttributeError: pass return core.missing
0.008511
def zipfiles(self, path=None, arcdirname='data'): """Returns a .zip archive of selected rasters.""" if path: fp = open(path, 'w+b') else: prefix = '%s-' % arcdirname fp = tempfile.NamedTemporaryFile(prefix=prefix, suffix='.zip') with zipfile.ZipFile(fp...
0.002561
def configure_filters(app): """ Configure application filters (jinja2) """ for (name, filter) in _filters.iteritems(): app.jinja_env.filters[name] = filter
0.005814
def translate(value): """ Translates given schema from "pythonic" syntax to a validator. Usage:: >>> translate(str) IsA(str) >>> translate('hello') IsA(str, default='hello') """ if isinstance(value, BaseValidator): return value if value is None: ...
0.00062
def base_path(self): """Base absolute path of container.""" return os.path.join(self.container.base_path, self.name)
0.015152
def _keep_alive(self): """ Send keep alive messages continuously to bridge. """ send_next_keep_alive_at = 0 while not self.is_closed: if not self.is_ready: self._reconnect() continue if time.monotonic() > send_next_keep_ali...
0.00145
def get_repositories(self, digests): """ Build the repositories metadata :param digests: dict, image -> digests """ if self.workflow.push_conf.pulp_registries: # If pulp was used, only report pulp images registries = self.workflow.push_conf.pulp_registrie...
0.002086
def _expand_terms(self, terms): """ Expands terms of the dataset to the appropriate fields. It will parse the search phrase and return only the search term components that are applicable to a Dataset query. Args: terms (dict or str): Returns: dict: keys are fie...
0.005202
def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32: """ Returns the block hash for the canonical block at the given number. Raises BlockNotFound if there's no block header with the given number in the canonical chain. """ return self._get_canonical_b...
0.008523
def isobaric_expansion_g(self): r'''Isobaric (constant-pressure) expansion of the gas phase of the chemical at its current temperature and pressure, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Utilizes the temperature-deriva...
0.003866
def ipython_paste(self,e): u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array. If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space""" if sel...
0.021711
def print_table(seqs, id2name, name): """ print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ itable = open('%s.itable' % (name.rsplit('.', 1)[0]), 'w') print('\t'.join(['#sequence', 'gene', 'model', 'inserti...
0.003036
def do_metric_name_list(mc, args): '''List names of metrics.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.tenant_...
0.002472
def scroll(self, rect, dx, dy, attr=None, fill=' '): u'''Scroll a rectangle.''' if attr is None: attr = self.attr x0, y0, x1, y1 = rect source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1) dest = self.fixcoord(x0 + dx, y0 + dy) style = CHAR_INFO() style...
0.007339
def whois_domains(self, domains): """Calls WHOIS domain end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_result} """ api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self._multi_get(a...
0.005698
def urls(order_by: Optional[str] = None): """List all URLs registered with the app.""" url_rules: List[Rule] = current_app.url_map._rules # sort the rules. by default they're sorted by priority, # ie in the order they were registered with the app if order_by == 'view': url_rules = sorted(ur...
0.001914
async def download_artifacts(context, file_urls, parent_dir=None, session=None, download_func=download_file, valid_artifact_task_ids=None): """Download artifacts in parallel after validating their URLs. Valid ``taskId``s for download include the task's dependencies and the ``ta...
0.004085
def frame_apply(obj, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, ignore_failures=False, args=None, kwds=None): """ construct and return a row or column based frame apply object """ axis = obj._get_axis_number(axis) if axis == 0: ...
0.001653
def ensure_dir(dir_path): """ If DIR_PATH does not exist, makes it. Failing that, raises Exception. Returns True if dir already existed; False if it had to be made. """ exists = dir_exists(dir_path) if not exists: try: os.makedirs(dir_path) except(Exception,RuntimeErr...
0.004348
def _from_json_list(cls, response_raw, wrapper=None): """ :type response_raw: client.BunqResponseRaw :type wrapper: str|None :rtype: client.BunqResponse[list[cls]] """ json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) arra...
0.002296
def get_window_size(self, window): """ Get a window's size. """ w_ret = ctypes.c_uint(0) h_ret = ctypes.c_uint(0) _libxdo.xdo_get_window_size(self._xdo, window, ctypes.byref(w_ret), ctypes.byref(h_ret)) return window_size(w_ret....
0.0059
def disable_contact_svc_notifications(self, contact): """Disable service notifications for a contact Format of the line that triggers function call:: DISABLE_CONTACT_SVC_NOTIFICATIONS;<contact_name> :param contact: contact to disable :type contact: alignak.objects.contact.Conta...
0.004792
def __load_countries(self, db): """Load the list of countries""" try: countries = self.__read_countries_file() except IOError as e: raise LoadError(str(e)) try: with db.connect() as session: for country in countries: ...
0.004878
def equivalent_diameter(target, pore_volume='pore.volume', pore_shape='sphere'): r""" Calculates the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- target : OpenPNM Geometry Object The Geometry object which this ...
0.001035
def discharge(self): """Discharge per unit length""" Q = np.zeros(self.aq.naq) Q[self.layers] = self.parameters[:, 0] return Q
0.012658
def register(name: str = None) -> type: """ Register classes that could be initialized from JSON configuration file. If name is not passed, the class name is converted to snake-case. """ def decorate(model_cls: type, reg_name: str = None) -> type: model_name = reg_name or short_name(model_cl...
0.002699
def validateStringInput(input_key,input_data, read=False): """ To check if a string has the required format. This is only used for POST APIs. """ log = clog.error_log func = None if '*' in input_data or '%' in input_data: func = validationFunctionWildcard.get(input_key) if func i...
0.010957
def month_boundaries(dt=None): ''' Return a 2-tuple containing the datetime instances for the first and last dates of the current month or using ``dt`` as a reference. ''' dt = dt or date.today() wkday, ndays = calendar.monthrange(dt.year, dt.month) start = datetime(dt.year, dt.month, 1) ...
0.002732
def update_from_defaultParams(self, defaultParams=None, plotters=True): """Update from the a dictionary like the :attr:`defaultParams` Parameters ---------- defaultParams: dict The :attr:`defaultParams` like dictionary. If None, the ...
0.004431
def create_case(self, name, email, subject, description, businessImpact, priority, phone): """ Send a case creation to SalesForces to create a ticket. @param name of the person creating the case. @param email of the person creating the case. @param subject of the cas...
0.00129
def _merge_ws(self, item, container): # type: (Item, Container) -> bool """ Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged. """ last = container.last_item() if not last...
0.007564
def get_int(self, key, default=UndefinedKey): """Return int representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: int :return: int value :type r...
0.004724
def reinterpret_bits_to_hstruct(sigOrVal, hStructT): """ Reinterpret signal of type Bits to signal of type HStruct """ container = hStructT.fromPy(None) offset = 0 for f in hStructT.fields: t = f.dtype width = t.bit_length() if f.name is not None: s = sigOrVal...
0.002114
def validate(self): """ Validate attributes by running all self._validate_*() methods. :raises TypeError: if an attribute has invalid type :raises ValueError: if an attribute contains invalid value """ method_names = sorted([i for i in dir(self) if i.startswith("_validat...
0.006438
def calculate_dielectric_properties(dielectric, properties, average=True): r"""Calculate optical properties from the dielectric function Supported properties: Absorption ~~~~~~~~~~ The unit of alpha is :math:`\mathrm{cm}^{-1}`. Refractive index :math:`n` h...
0.000195
def _merge_dimensions(dimension, preferred=None, dont_extend=False): """ Take the LayoutDimension from this `Window` class and the received preferred size from the `UIControl` and return a `LayoutDimension` to report to the parent container. """ dimension = dimension or L...
0.001576
def decrypt(data, key): '''decrypt the data with the key''' data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_decrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(resu...
0.002959
def _rolling_window(self, array, size): """ Compute rolling windows of width ``size`` of the given array. Return a numpy 2D stride array, where rows are the windows, each of ``size`` elements. :param array: the data array :type array: numpy 1D array (n) :param ...
0.004732
def headers(self): """ The contig ID must be twenty characters or fewer. The names of the headers created following SPAdes assembly are usually far too long. This renames them as the sample name """ for sample in self.metadata.samples: # Create an attribute to store t...
0.006425
def transition(trname='', field='', check=None, before=None, after=None): """Decorator to declare a function as a transition implementation.""" if is_callable(trname): raise ValueError( "The @transition decorator should be called as " "@transition(['transition_name'], **kwargs)")...
0.004098
def _parse_numbered_syllable(unparsed_syllable): """Return the syllable and tone of a numbered Pinyin syllable.""" tone_number = unparsed_syllable[-1] if not tone_number.isdigit(): syllable, tone = unparsed_syllable, '5' elif tone_number == '0': syllable, tone = unparsed_syllable[:-1], '...
0.001919
def _get_line(self): """Get a line or raise StopIteration""" line = self._f.readline() if len(line) == 0: raise StopIteration return line
0.01105