Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
383,700
def main(argv=None): try: colorama.init() if argv is None: argv = sys.argv[1:] _main(argv) except RuntimeError as e: print(colorama.Fore.RED + + str(e) + colorama.Style.RESET_ALL) sys.exit(1) else: sys.exit(0)
Main entry point when the user runs the `trytravis` command.
383,701
def num_rings(self): num = self._libinput.libinput_device_tablet_pad_get_num_rings( self._handle) if num < 0: raise AttributeError() return num
The number of rings a device with the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability provides. Returns: int: The number of rings or 0 if the device has no rings. Raises: AttributeError
383,702
def open_interpreter(self, fnames): for path in sorted(fnames): self.sig_open_interpreter.emit(path)
Open interpreter
383,703
def write_early_data(self, data: bytes) -> int: if self._is_handshake_completed: raise IOError() self._ssl.write_early_data(data) final_length = self._flush_ssl_engine() return final_length
Returns the number of (encrypted) bytes sent.
383,704
def getsize(store, path=None): path = normalize_storage_path(path) if hasattr(store, ): return store.getsize(path) elif isinstance(store, dict): if path in store: v = store[path] size = buffer_size(v) else: members = listdir(...
Compute size of stored items for a given path. If `store` provides a `getsize` method, this will be called, otherwise will return -1.
383,705
def param(f): s abc attribute being set to the value of type(imm).abc(x). Params may not accept variable, variadic keyword, or default argumentsParameter transformation functions must take exactly one argumentis_paramname'] = f.__name__ f = staticmethod(f) return f
The @param decorator, usable in an immutable class (see immutable), specifies that the following function is actually a transformation on an input parameter; the parameter is required, and is set to the value returned by the function decorated by the parameter; i.e., if you decorate the function abc with @...
383,706
def submit_sample(self, filepath, filename, tags=[]): apiurl = params = {: base64.b64encode(filename.encode()), : self.reanalyze} if tags: params[] = .join(tags) if os.path.isfile(filepath): res = self.session.post(url=self.url + apiur...
Uploads a new sample to VMRay api. Filename gets sent base64 encoded. :param filepath: path to sample :type filepath: str :param filename: filename of the original file :type filename: str :param tags: List of tags to apply to the sample :type tags: list(str) :re...
383,707
def contains_key(self, key): check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_contains_key_codec, key_data, key=key_data, thread_id=thread_id())
Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ...
383,708
def chop(self, bits=1): s = len(self) if s % bits != 0: raise ValueError("expression length (%d) should be a multiple of (%d)" % (len(self), bits)) elif s == bits: return [ self ] else: return list(reversed([ self[(n+1)*bits - 1:n*bits] for n...
Chops a BV into consecutive sub-slices. Obviously, the length of this BV must be a multiple of bits. :returns: A list of smaller bitvectors, each ``bits`` in length. The first one will be the left-most (i.e. most significant) bits.
383,709
def hook_point(self, hook_name): self.my_daemon.hook_point(hook_name=hook_name, handle=self)
Generic function to call modules methods if such method is avalaible :param hook_name: function name to call :type hook_name: str :return:None
383,710
def to_date(value, default=None): if isinstance(value, DateTime): return value if not value: if default is None: return None return to_date(default) try: if isinstance(value, str) and in value: return DateTime(value, datefmt=) ...
Tries to convert the passed in value to Zope's DateTime :param value: The value to be converted to a valid DateTime :type value: str, DateTime or datetime :return: The DateTime representation of the value passed in or default
383,711
def _raw_sql(self, values): if isinstance(self.model._meta.pk, CharField): when_clauses = " ".join( [self._when("".format(x), y) for (x, y) in values] ) else: when_clauses = " ".join([self._when(x, y) for (x, y) in values]) table_name ...
Prepare SQL statement consisting of a sequence of WHEN .. THEN statements.
383,712
def build_from_info(cls, info): info = deepcopy(info) if in info: cls_ = TERMS[info.pop()] if issubclass(cls_, MetaTermMixin): return cls_.build_from_info(info) else: cls_ = cls return cls_(**info)
build a Term instance from a dict Parameters ---------- cls : class info : dict contains all information needed to build the term Return ------ Term instance
383,713
def _compute_soil_linear_factor(cls, pga_rock, imt): if imt.period >= 1: return np.ones_like(pga_rock) else: sl = np.zeros_like(pga_rock) pga_between_100_500 = (pga_rock > 100) & (pga_rock < 500) pga_greater_equal_500 = pga_rock >= 500 ...
Compute soil linear factor as explained in paragraph 'Functional Form', page 1706.
383,714
def find_root( self, rows ): maxes = sorted( rows.values(), key = lambda x: x.cumulative ) if not maxes: raise RuntimeError( ) root = maxes[-1] roots = [root] for key,value in rows.items(): if not value.parents: log.debug( , value...
Attempt to find/create a reasonable root node from list/set of rows rows -- key: PStatRow mapping TODO: still need more robustness here, particularly in the case of threaded programs. Should be tracing back each row to root, breaking cycles by sorting on cumulative time, and then coll...
383,715
def genestats(args): p = OptionParser(genestats.__doc__) p.add_option("--groupby", default="conf_class", help="Print separate stats groupby") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gff_file, = args gb = ...
%prog genestats gffile Print summary stats, including: - Number of genes - Number of single-exon genes - Number of multi-exon genes - Number of distinct exons - Number of genes with alternative transcript variants - Number of predicted transcripts - Mean number of distinct exons per gen...
383,716
def check_perplexities(self, perplexities): usable_perplexities = [] for perplexity in sorted(perplexities): if 3 * perplexity > self.n_samples - 1: new_perplexity = (self.n_samples - 1) / 3 if new_perplexity in usable_perplexities: ...
Check and correct/truncate perplexities. If a perplexity is too large, it is corrected to the largest allowed value. It is then inserted into the list of perplexities only if that value doesn't already exist in the list.
383,717
def train(self, x = None, y = None, training_frame = None, fold_column = None, weights_column = None, validation_frame = None, leaderboard_frame = None, blending_frame = None): ncols = training_frame.ncols names = training_frame.names if self.project_name is Non...
Begins an AutoML task, a background task that automatically builds a number of models with various algorithms and tracks their performance in a leaderboard. At any point in the process you may use H2O's performance or prediction functions on the resulting models. :param x: A list of c...
383,718
def start_new_log(self): filename = self.new_log_filepath() self.block_cnt = 0 self.logfile = open(filename, ) print("DFLogger: logging started (%s)" % (filename)) self.prev_cnt = 0 self.download = 0 self.prev_download = 0 self.last_idle_status_p...
open a new dataflash log, reset state
383,719
def readline(self): line = self.file.readline() if self.grammar and line: try: return self.grammar.parseString(line).asDict() except ParseException: return self.readline() else: return line
Reads (and optionally parses) a single line.
383,720
def to_netflux(flux): r if issparse(flux): return sparse.tpt.to_netflux(flux) elif isdense(flux): return dense.tpt.to_netflux(flux) else: raise _type_not_supported
r"""Compute the netflux from the gross flux. Parameters ---------- flux : (M, M) ndarray Matrix of flux values between pairs of states. Returns ------- netflux : (M, M) ndarray Matrix of netflux values between pairs of states. Notes ----- The netflux or effective c...
383,721
def pick(self): v = random.uniform(0, self.ub) d = self.dist c = self.vc - 1 s = self.vc while True: s = s / 2 if s == 0: break if v <= d[c][1]: c -= s else: c += s ...
picks a value accoriding to the given density
383,722
def find_signature_input_colocation_error(signature_name, inputs): for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected_colocation_groups: return ( "A tensor x used as input in a si...
Returns error message for colocation of signature inputs, or None if ok.
383,723
def correct_dmdt(d, dmind, dtind, blrange): data = numpyview(data_mem, , datashape(d)) data_resamp = numpyview(data_resamp_mem, , datashape(d)) bl0,bl1 = blrange data_resamp[:, bl0:bl1] = data[:, bl0:bl1] rtlib.dedisperse_resample(data_resamp, d[], d[], d[][dmind], d[][dtind], blrange, verbose...
Dedisperses and resamples data *in place*. Drops edges, since it assumes that data is read with overlapping chunks in time.
383,724
def process_edge_dijkstra(self, current, neighbor, pred, q, component): Dijkstras algorithm. User does not need to call this method directly. Input: current: Name of the current node. neighbor: Name of the neighbor node. pred: Predecessor tree. q: ...
API: process_edge_dijkstra(self, current, neighbor, pred, q, component) Description: Used by search() method if the algo argument is 'Dijkstra'. Processes edges along Dijkstra's algorithm. User does not need to call this method directly. Input: current: Name of the cu...
383,725
def generateExecutable(self, outpath=, signed=False): if not (self.runtime() or self.specfile()): return True if not self.distributionPath(): return True if os.path.exists(self.distributionPath()): shutil.rmtree(self.distributionPath()) if ...
Generates the executable for this builder in the output path. :param outpath | <str>
383,726
def set_background_corpus(self, background): if issubclass(type(background), TermDocMatrixWithoutCategories): self._background_corpus = pd.DataFrame(background .get_term_freq_df() .sum(axis...
Parameters ---------- background
383,727
def get_generator(tweet): if is_original_format(tweet): if sys.version_info[0] == 3 and sys.version_info[1] >= 4: parser = GeneratorHTMLParser(convert_charrefs=True) else: parser = GeneratorHTMLParser() parser.feed(tweet["source"]) return {"link": parser....
Get information about the application that generated the Tweet Args: tweet (Tweet): A Tweet object (or a dictionary) Returns: dict: keys are 'link' and 'name', the web link and the name of the application Example: >>> from tweet_parser.getter_methods.tweet_generator import...
383,728
def _leapfrog_integrator_one_step( target_log_prob_fn, independent_chain_ndims, step_sizes, current_momentum_parts, current_state_parts, current_target_log_prob, current_target_log_prob_grad_parts, state_gradients_are_stopped=False, name=None): ...
Applies `num_leapfrog_steps` of the leapfrog integrator. Assumes a simple quadratic kinetic energy function: `0.5 ||momentum||**2`. #### Examples: ##### Simple quadratic potential. ```python import matplotlib.pyplot as plt %matplotlib inline import numpy as np import tensorflow as tf from tensorfl...
383,729
def find_mutant_amino_acid_interval( cdna_sequence, cdna_first_codon_offset, cdna_variant_start_offset, cdna_variant_end_offset, n_ref, n_amino_acids): cdna_alt_nucleotides = cdna_sequence[ cdna_variant_start_offset:cdna_variant_end_offset] n_alt = l...
Parameters ---------- cdna_sequence : skbio.DNA or str cDNA sequence found in RNAseq data cdna_first_codon_offset : int Offset into cDNA sequence to first complete codon, lets us skip past UTR region and incomplete codons. cdna_variant_start_offset : int Interbase start...
383,730
def on_message(self, websocket, msg): if msg: lines = [] for li in msg.split(): li = li.strip() if li: lines.append(li) msg = .join(lines) if msg: return self.pubsub.publish(self.channel,...
When a new message arrives, it publishes to all listening clients.
383,731
def random_string(length, charset): n = len(charset) return .join(charset[random.randrange(n)] for _ in range(length))
Return a random string of the given length from the given character set. :param int length: The length of string to return :param str charset: A string of characters to choose from :returns: A random string :rtype: str
383,732
def set_post_data(self): self.form.data = self.post_data_dict for field_key, field in self.form.fields.items(): if has_digit(field_key): base_key = make_key(field_key, exclude_last_string=True) ...
Need to set form data so that validation on all post data occurs and places newly entered form data on the form object.
383,733
def create(**kwargs): secType = kwargs.get(, ) cls = { : Contract, : Stock, : Option, : Future, : ContFuture, : Forex, : Index, : CFD, : Bond, : Commodity, : Futur...
Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given.
383,734
def Flush(self): if self.locked and self.CheckLease() == 0: self._RaiseLockError("Flush") self._WriteAttributes() self._SyncAttributes() if self.parent: self.parent.Flush()
Syncs this object with the data store, maintaining object validity.
383,735
def onDragSelection(self, event): if self.grid.GetSelectionBlockTopLeft(): bottom_right = eval(repr(self.grid.GetSelectionBlockBottomRight()).replace("GridCellCoordsArray: ", "").replace("GridCellCoords", "")) top_left = eval(repr(self.grid...
Set self.df_slice based on user's selection
383,736
def salt_master(project, target, module, args=None, kwargs=None): client = project.cluster.head.ssh_client cmd = [] cmd.extend(generate_salt_cmd(target, module, args, kwargs)) cmd.append() cmd.append() cmd = .join(cmd) output = client.exec_command(cmd, sudo=True) if output[] == 0:...
Execute a `salt` command in the head node
383,737
def create_as_library(cls, url): site = { "crawler": "Download", "url": url } cfg_file_path = os.path.dirname(__file__) + os.path.sep + + os.path.sep + return cls(cfg_file_path, site, 0, False, False, True)
Creates a single crawler as in library mode. Crawling will start immediately. :param url: :return:
383,738
def delete_page_property(self, page_id, page_property): url = .format(page_id=page_id, page_property=str(page_property)) return self.delete(path=url)
Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return:
383,739
def calculate_perf_100nsec_timer(previous, current, property_name): n0 = previous[property_name] n1 = current[property_name] d0 = previous["Timestamp_Sys100NS"] d1 = current["Timestamp_Sys100NS"] if n0 is None or n1 is None: return return (n1 - n0) / (d1 - d0) * 100
PERF_100NSEC_TIMER https://technet.microsoft.com/en-us/library/cc728274(v=ws.10).aspx
383,740
def unmarshal(self, v): try: return self.choices[v] except KeyError: self.log.warning("No such choice {0} for field {1}.".format(v, self)) return v
Convert the value from Strava API format to useful python representation. If the value does not appear in the choices attribute we log an error rather than raising an exception as this may be caused by a change to the API upstream so we want to fail gracefully.
383,741
def unique_identifier(self): for t in IDENTIFIER_PRIORITY: found = self._tree.getroot().find( % t, NS) if found is not None: return found.text
Get the unique identifier by looking through ``mods:identifier`` See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
383,742
def create_container_definition(container_name, image, port=80, cpu=1.0, memgb=1.5, environment=None): nameenvnamevalueenvvalue container = {: container_name} container_properties = {: image} container_properties[] = [{: port}] container_properties[] = { : {: ...
Makes a python dictionary of container properties. Args: container_name: The name of the container. image (str): Container image string. E.g. nginx. port (int): TCP port number. E.g. 8080. cpu (float): Amount of CPU to allocate to container. E.g. 1.0. memgb (float): Memory i...
383,743
def main(): col1,col2=0,1 sym,size = ,20 xlab,ylab=, lines=0 if in sys.argv: print(main.__doc__) sys.exit() if in sys.argv: ind=sys.argv.index() file=sys.argv[ind+1] else: print(main.__doc__) sys.exit() if in sys.argv: ...
NAME plotxy_magic.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT Any MagIC formatted file SYNTAX plotxy_magic.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command rec -c col1 col2 specify columns ...
383,744
def store(self): if msgpack is None: log.error() else: try: with salt.utils.files.fopen(self._path, ) as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": s...
Write content of the entire cache to disk
383,745
def copy(self): tokens = ([t for t in self.tokens] if isinstance(self.tokens, list) else self.tokens) return Identifier(tokens, 0)
Return copy of self Returns: Identifier object
383,746
def add_group_members(self, members): if not isinstance(members, list): members = [members] if not getattr(self, , None): self.group_members = members else: self.group_members.extend(members)
Add a new group member to the groups list :param members: member name :type members: str :return: None
383,747
def _bubbleP(cls, T): c = cls._blend["bubble"] Tj = cls._blend["Tj"] Pj = cls._blend["Pj"] Tita = 1-T/Tj suma = 0 for i, n in zip(c["i"], c["n"]): suma += n*Tita**(i/2.) P = Pj*exp(Tj/T*suma) return P
Using ancillary equation return the pressure of bubble point
383,748
def run(self, agent_host): total_reward = 0 self.prev_s = None self.prev_a = None is_first_action = True world_state = agent_host.getWorldState() while world_state.is_mission_running: current_r = 0 ...
run the agent on the world
383,749
def mk_function(metamodel, s_sync): action = s_sync.Action_Semantics_internal label = s_sync.Name return lambda **kwargs: interpret.run_function(metamodel, label, action, kwargs)
Create a python function from a BridgePoint function.
383,750
def pad_to_size(text, x, y): input_lines = text.rstrip().split("\n") longest_input_line = max(map(len, input_lines)) number_of_input_lines = len(input_lines) x = max(x, longest_input_line) y = max(y, number_of_input_lines) output = "" padding_top = int((y - number_of_input_lines) / 2) ...
Adds whitespace to text to center it within a frame of the given dimensions.
383,751
def get_breadcrumbs(self): if not self.breadcrumbs: return None else: allowed_breadcrumbs = [] for breadcrumb in self.breadcrumbs: if breadcrumb[1] is not None and not view_from_url( breadcrumb[1] ...
Breadcrumb format: (('name', 'url'), ...) or None if not used.
383,752
def update(self): if not self._queue: return dim, widget_type, attr, old, new = self._queue[-1] self._queue = [] dim_label = dim.pprint_label label, widget = self.widgets[dim_label] if widget_type == : if isinstance(label, AutocompleteIn...
Handle update events on bokeh server.
383,753
def is_list_like(obj, allow_sets=True): return (isinstance(obj, abc.Iterable) and not isinstance(obj, (str, bytes)) and not (isinstance(obj, np.ndarray) and obj.ndim == 0) and not (allow_sets is False and isinstance(obj, abc.Set)))
Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- obj : The object to check allow_sets : boolean, d...
383,754
def _calculate_Hfr(self, T): if self.isCoal: return self._calculate_Hfr_coal(T) Hfr = 0.0 for compound in self.material.compounds: index = self.material.get_compound_index(compound) dHfr = thermo.H(compound, T, self._compound_mfrs[index]) ...
Calculate the enthalpy flow rate of the stream at the specified temperature. :param T: Temperature. [°C] :returns: Enthalpy flow rate. [kWh/h]
383,755
def channels(self): if not self._channels: self._channels = self._call_api()[] return self._channels
List of channels of this slack team
383,756
def _handle_get(self, request_data): der = base64.b64decode(request_data) ocsp_request = self._parse_ocsp_request(der) return self._build_http_response(ocsp_request)
An OCSP GET request contains the DER-in-base64 encoded OCSP request in the HTTP request URL.
383,757
def setLength(self, personID, length): self._connection._sendDoubleCmd( tc.CMD_SET_PERSON_VARIABLE, tc.VAR_LENGTH, personID, length)
setLength(string, double) -> None Sets the length in m for the given person.
383,758
def aggregate(input, **params): PARAM_CFG_EXTRACT = PARAM_CFG_SUBSTITUTE = PARAM_CFG_AGGREGATE = AGGR_FIELD = AGGR_FUNC = extract_params = params.get(PARAM_CFG_EXTRACT) extract_params.update({AccessParams.KEY_TYPE: AccessParams.TYPE_MULTI}) dataset = __extract(input, extract_p...
Returns aggregate :param input: :param params: :return:
383,759
def metapolicy(self, permitted): if permitted not in VALID_SITE_CONTROL: raise TypeError(SITE_CONTROL_ERROR.format(permitted)) if permitted == SITE_CONTROL_NONE: self.domains = {} self.header_domains = {} self.identities = [] ...
Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defined in this module. By default, Flash assumes a value of ``m...
383,760
async def connect(self) -> None: def protocol_factory() -> Protocol: return Protocol(client=self) _, protocol = await self.loop.create_connection( protocol_factory, host=self.host, port=self.port, ssl=self.ssl ) if s...
Open a connection to the defined server.
383,761
def bisect(func, a, b, xtol=1e-6, errorcontrol=True, testkwargs=dict(), outside=, ascending=None, disp=False): search = True if ascending is None: if errorcontrol: testkwargs.update(dict(type_=, force=True)) fa = func.test0(a, **testkwar...
Find root by bysection search. If the function evaluation is noisy then use `errorcontrol=True` for adaptive sampling of the function during the bisection search. Parameters ---------- func: callable Function of which the root should be found. If `errorcontrol=True` then the functi...
383,762
def getAllSavedQueries(self, projectarea_id=None, projectarea_name=None, creator=None, saved_query_name=None): pa_id = (self.rtc_obj ._pre_get_resource(projectarea_id=projectarea_id, projectarea_name=projectarea_na...
Get all saved queries created by somebody (optional) in a certain project area (optional, either `projectarea_id` or `projectarea_name` is needed if specified) If `saved_query_name` is specified, only the saved queries match the name will be fetched. Note: only if `creator` is ...
383,763
def pre_parse_and_validate_signavio(self, bpmn, filename): self._check_for_disconnected_boundary_events_signavio(bpmn, filename) self._fix_call_activities_signavio(bpmn, filename) return bpmn
This is the Signavio specific editor hook for pre-parsing and validation. A subclass can override this method to provide additional parseing or validation. It should call the parent method first. :param bpmn: an lxml tree of the bpmn content :param filename: the source file na...
383,764
def previous_row(self): row = self.currentIndex().row() rows = self.source_model.rowCount() if row == 0: row = rows self.selectRow(row - 1)
Move to previous row from currently selected row.
383,765
def refresh_modules(self, module_string=None, exact=True): if not module_string: if time.time() > (self.last_refresh_ts + 0.1): self.last_refresh_ts = time.time() else: return update_i3status = False for name, modu...
Update modules. if module_string is None all modules are refreshed if module_string then modules with the exact name or those starting with the given string depending on exact parameter will be refreshed. If a module is an i3status one then we refresh i3status. To prevent abuse, ...
383,766
def get_register_func(base_class, nickname): if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def register(klass, name=None): assert issubclass(klass, base_class), \ "Can only register subclass of %s"%base_class.__name__ ...
Get registrator function. Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a registrator function
383,767
def get_default_config(self): config = super(NetworkCollector, self).get_default_config() config.update({ : , : [, , , , , , , ], : [, ], : , }) return config
Returns the default collector settings
383,768
def add_exception_handler(self, exception_handler): if exception_handler is None: raise RuntimeConfigException( "Valid Exception Handler instance to be provided") if not isinstance(exception_handler, AbstractExceptionHandler): raise RuntimeConfi...
Register input to the exception handlers list. :param exception_handler: Exception Handler instance to be registered. :type exception_handler: AbstractExceptionHandler :return: None
383,769
def _get_asset_urls(self, asset_id): dom = get_page(self._session, OPENCOURSE_ASSETS_URL, json=True, id=asset_id) logging.debug(, asset_id) urls = [] for element in dom[]: typeName = element[] definition = element[] ...
Get list of asset urls and file names. This method may internally use AssetRetriever to extract `asset` element types. @param asset_id: Asset ID. @type asset_id: str @return List of dictionaries with asset file names and urls. @rtype [{ 'name': '<filename.ext>' ...
383,770
async def create_local_did(self, seed: str = None, loc_did: str = None, metadata: dict = None) -> DIDInfo: LOGGER.debug(, loc_did, metadata) cfg = {} if seed: cfg[] = seed if loc_did: cfg[] = loc_did if not self.handle: LOGGER.debug...
Create and store a new local DID for use in pairwise DID relations. :param seed: seed from which to create (default random) :param loc_did: local DID value (default None to let indy-sdk generate) :param metadata: metadata to associate with the local DID (operation always sets 'since...
383,771
def service_group(self, service_name): for group in EFConfig.SERVICE_GROUPS: if self.services(group).has_key(service_name): return group return None
Args: service_name: the name of the service in the service registry Returns: the name of the group the service is in, or None of the service was not found
383,772
def summarize(self): data = [ [, self.seqrecord.id], [, .join(self.gdomain_regions) if self.gdomain_regions else None], [, self.evalue_bh_rabs], [, self.evalue_bh_non_rabs], [, .join(map(str, self.rabf_motifs)) if self.rabf_motifs else None], ...
G protein annotation summary in a text format :return: A string summary of the annotation :rtype: str
383,773
def decode(self, encoded): if self.enforce_reversible: self.enforce_reversible = False if self.encode(self.decode(encoded)) != encoded: raise ValueError( % encoded) self.enforce_reversible = True return encoded
Decodes an object. Args: object_ (object): Encoded object. Returns: object: Object decoded.
383,774
def fetch_pillar(self): log.debug(, self.ext) fresh_pillar = Pillar(self.opts, self.grains, self.minion_id, self.saltenv, ext=self.ext, functions...
In the event of a cache miss, we need to incur the overhead of caching a new pillar.
383,775
def stop_change(self): self.logger.info("Dimmer %s stop_change", self.device_id) self.hub.direct_command(self.device_id, , ) success = self.hub.check_success(self.device_id, , ) if success: self.logger.info("Dimmer %s stop_change: Light stopped changing successfully...
Stop changing light level manually
383,776
def load(stream, Loader=None): if Loader is None: load_warning() Loader = FullLoader loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
Parse the first YAML document in a stream and produce the corresponding Python object.
383,777
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir): try: with tarfile.open(archive) as tfile: tfile.extractall(path=outdir) except Exception as err: msg = "error extracting %s: %s" % (archive, err) raise util.PatoolError(msg) return None
Extract a TAR archive with the tarfile Python module.
383,778
def migrate_file(src_id, location_name, post_fixity_check=False): location = Location.get_by_name(location_name) f_src = FileInstance.get(src_id) f_dst = FileInstance.create() db.session.commit() try: f_dst.copy_contents( f_src, progress_callback=...
Task to migrate a file instance to a new location. .. note:: If something goes wrong during the content copy, the destination file instance is removed. :param src_id: The :class:`invenio_files_rest.models.FileInstance` ID. :param location_name: Where to migrate the file. :param post_fixity_che...
383,779
def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable): exit_code = 0 if ftdi_enable: exit_code = Drivers().ftdi_enable() elif ftdi_disable: exit_code = Drivers().ftdi_disable() elif serial_enable: exit_code = Drivers().serial_enable() elif ser...
Manage FPGA boards drivers.
383,780
def _got_srv(self, addrs): with self.lock: if not addrs: self._dst_service = None if self._dst_port: self._dst_nameports = [(self._dst_name, self._dst_port)] else: self._dst_nameports = [] ...
Handle SRV lookup result. :Parameters: - `addrs`: properly sorted list of (hostname, port) tuples
383,781
def min_ems(self, value: float) -> : raise_not_number(value) self.minimum = .format(value) return self
Set the minimum size in ems.
383,782
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame: series = table[self.name] self._check_series_name(series) col = self.name data = series.copy() for recoder in self.recoders.values(): try: data = recoder(data) ...
Pass the provided series obj through each recoder function sequentially and return the final result. Args: table (pd.DataFrame): A dataframe on which to apply recoding logic. validate (bool): If ``True``, recoded table must pass validation tests.
383,783
def _compose_mro(cls, types): bases = set(cls.__mro__) def is_related(_type): return ( _type not in bases and hasattr(_type, ) and issubclass(cls, _type) ) types = [n for n in types if is_related(n)] def is_strict_base(_typ...
Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm.
383,784
def burn(self): if not self.data: raise ValueError("No data available") if hasattr(self, ): self.calculations() self.start_svg() self.calculate_graph_dimensions() self.foreground = etree.Element("g") self.draw_graph() self.draw_titles() self.draw_legend() self.draw_data() self.graph.appen...
Process the template with the data and config which has been set and return the resulting SVG. Raises ValueError when no data set has been added to the graph object.
383,785
def VerifyStructure(self, parser_mediator, line): try: structure = self._DPKG_LOG_LINE.parseString(line) except pyparsing.ParseException as exception: logger.debug( .format( exception)) return False return in structure and in structure
Verifies if a line from a text file is in the expected format. Args: parser_mediator (ParserMediator): parser mediator. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if not.
383,786
def get_relationships_by_query(self, relationship_query): and_list = list() or_list = list() for term in relationship_query._query_terms: if in relationship_query._query_terms[term] and in relationship_query._query_terms[term]: and_list.ap...
Gets a list of ``Relationships`` matching the given relationship query. arg: relationship_query (osid.relationship.RelationshipQuery): the relationship query return: (osid.relationship.RelationshipList) - the returned ``RelationshipList`` raise...
383,787
def fit(self, matrix, epochs=5, no_threads=2, verbose=False): shape = matrix.shape if (len(shape) != 2 or shape[0] != shape[1]): raise Exception() if not sp.isspmatrix_coo(matrix): raise Exception() random_state = check_random_state(self.r...
Estimate the word embeddings. Parameters: - scipy.sparse.coo_matrix matrix: coocurrence matrix - int epochs: number of training epochs - int no_threads: number of training threads - bool verbose: print progress messages if True
383,788
def get_messages(session, query, limit=10, offset=0): query[] = limit query[] = offset response = make_get_request(session, , params_data=query) json_data = response.json() if response.status_code == 200: return json_data[] else: raise MessagesNotFoundException( ...
Get one or more messages
383,789
def __reset_crosshair(self): self.lhor.set_ydata(self.y_coord) self.lver.set_xdata(self.x_coord)
redraw the cross-hair on the horizontal slice plot Parameters ---------- x: int the x image coordinate y: int the y image coordinate Returns -------
383,790
def remove(self, value): ret = libxml2mod.xmlACatalogRemove(self._o, value) return ret
Remove an entry from the catalog
383,791
def get_dimension_type(self, dim): dim = self.get_dimension(dim) if dim is None: return None elif dim.type is not None: return dim.type elif dim in self.vdims: return np.float64 return self.interface.dimension_type(self, dim)
Get the type of the requested dimension. Type is determined by Dimension.type attribute or common type of the dimension values, otherwise None. Args: dimension: Dimension to look up by name or by index Returns: Declared type of values along the dimension
383,792
def _validate_param(param): detail = None if param.oper not in goldman.config.QUERY_FILTERS: detail = \ \ .format(param.oper, param) elif param.oper in goldman.config.GEO_FILTERS: try: if not isinstance(param.val, list) or len(param.v...
Ensure the filter cast properly according to the operator
383,793
def get_power_status() -> SystemPowerStatus: get_system_power_status = ctypes.windll.kernel32.GetSystemPowerStatus get_system_power_status.argtypes = [ctypes.POINTER(SystemPowerStatus)] get_system_power_status.restype = wintypes.BOOL status = SystemPowerStatus() if not get_system_power_status(...
Retrieves the power status of the system. The status indicates whether the system is running on AC or DC power, whether the battery is currently charging, how much battery life remains, and if battery saver is on or off. :raises OSError: if the call to GetSystemPowerStatus fails :return: the power...
383,794
def poll(self): if not self.pod_reflector.first_load_future.done(): yield self.pod_reflector.first_load_future data = self.pod_reflector.pods.get(self.pod_name, None) if data is not None: if data.status.phase == : return None ...
Check if the pod is still running. Uses the same interface as subprocess.Popen.poll(): if the pod is still running, returns None. If the pod has exited, return the exit code if we can determine it, or 1 if it has exited but we don't know how. These are the return values JupyterHub exp...
383,795
def _finish_progress(self): if self._show_progressbar: if self._progressbar is None: self._initialize_progressbar() if self._progressbar is not None: self._progressbar.finish() if self._progress_callback is not None: self._pr...
Mark the progressbar as finished. :return: None
383,796
def validate(self): required = [, ] valid_data = { : ([, ], , ), : ([, , , ], , ), : ([], , ), : ([, , ], , ), : ([, , ], , ), : ([, , ], , ...
Checks that at least required params exist
383,797
def encrypt(s, base64 = False): e = _cipher().encrypt(s) return base64 and b64encode(e) or e
对称加密函数
383,798
def get_parser(parser=None): from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter if parser is None: parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) subparsers = parser.add_subparsers() pkg_init_parser...
Get parser for mpu.
383,799
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False): self.searchString = searchString self.category = category self.math = math self.game = game self.searchFiles = searchFiles self.extension = extension
Call this function with all the settings to use for future operations on a repository, must be called FIRST