Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,600
def get_DRAT_tail(max_check, L): if max_check == 0: return float() DRAT_tail = (old_div(max_check, L)) * 100. return DRAT_tail
input: tail_check_max, best fit line length output: DRAT_tail
343,601
def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): data = ApiParams() data[] = name data[] = status data[] = description data[] = link data[] = order data[] = group_id data[] = enabled ...
Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (option...
343,602
def get_alt_length(self, individual=0): if isinstance(individual, str): individual = self.individuals[individual] return [len(self.alt[i-1].replace(,)) for i in self.genotype[individual] if i > 0 and not self.alt[i-1].startswith()]
Returns the number of basepairs of each alternative allele
343,603
def write(self, output, mode="w", keep_rc=False): if isinstance(output, six.string_types): already_exists = os.path.exists(output) try: with open(output, mode) as f: p = self._build_pipes(f) rc = p.wait() ...
Executes the pipeline and writes the results to the supplied output. If output is a filename and the file didn't already exist before trying to write, the file will be removed if an exception is raised. Args: output (str or file like object): will create a new file of this ...
343,604
def split_s3_path(url: str) -> Tuple[str, str]: parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path if s3_path.startswith("/"): s3_path = s3_path[1:] return buck...
Split a full s3 path into the bucket name and path.
343,605
def visitLexerAltList(self, ctx: jsgParser.LexerAltListContext): altlist = ctx.lexerAlt() self.visit(altlist[0]) for alt in altlist[1:]: self._rulePattern += self.visit(alt)
lexerAltList: lexerAlt (LBAR lexerAlt)*
343,606
def walk(self): yield self if self.has_arguments(): for arg in self.args_definition: if not arg["name"] in self.arguments: continue value = self.arguments[arg["name"]] if type(value) == list: if ...
Walk through commands.
343,607
def compile_glob(spec): parsed = "".join(parse_glob(spec)) regex = "^{0}$".format(parsed) return re.compile(regex)
Convert the given glob `spec` to a compiled regex.
343,608
def loadThingData(dataDir="data", n=150, w=11): objects = defaultdict(list) encoder = ScalarEncoder(n=n, w=w, minval=1, maxval=25, forced=True) dataPath = os.path.dirname(os.path.realpath(__file__)) dataPath = os.path.join(dataPath, dataDir) objFiles = glob.glob1(dataPath, "*.log") for filename in ...
Load Thing sensation data. There is one file per object, each row contains one feature, location pairs. The format is as follows: [(-33.6705, 75.5003, 2.4207)/10] => [[list of active bits of location], [list of active bits of feature]] The content before "=>" is the true...
343,609
def __split_file(self): if (self.__filename and os.access(self.__filename, os.R_OK)): fhandle = None try: fhandle = os.open(self.__filename, os.O_RDONLY) except OSError: print(("CouldnSplit by day found' self...
Splits combined SAR output file (in ASCII format) in order to extract info we need for it, in the format we want. :return: ``List``-style of SAR file sections separated by the type of info they contain (SAR file sections) without parsing what is exactly what at this p...
343,610
def query_edges(self, bel: Optional[str] = None, source_function: Optional[str] = None, source: Union[None, str, Node] = None, target_function: Optional[str] = None, target: Union[None, str, Node] = None, ...
Return a query over the edges in the database. Usually this means that you should call ``list()`` or ``.all()`` on this result. :param bel: BEL statement that represents the desired edge. :param source_function: Filter source nodes with the given BEL function :param source: BEL term of...
343,611
def get_dict_key(data, key): if isinstance(data, Mapping): if key in data: yield data[key] for key_data in data.values(): for found in get_dict_key(key_data, key): yield found
will serach a mulitdemensional dictionary for a key name and return a value list of matching results
343,612
def _remove_consecutive_delims(expr, ldelim="(", rdelim=")"): tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim) ddelim = [] for ctuple, ntuple in zip(tpars, tpars[1:]): if ctuple == (ntuple[0] - 1, ntuple[1] + 1): ddelim.extend(ntuple) ddelim.sort() for num,...
Remove consecutive delimiters.
343,613
def pubmed(self, pubmedid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): q = self.session.query(models.PubMed) model_queries_config = ( (pubmedid, models.PubMed.pubmedid), ) q = self.get_model_queries(q, model_queries_config) many_t...
Method to query :class:`.models.PubMed` objects in database :param pubmedid: alias symbol(s) :type pubmedid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC...
343,614
def idd2group(fhandle): try: txt = fhandle.read() return iddtxt2groups(txt) except AttributeError as e: txt = open(fhandle, ).read() return iddtxt2groups(txt)
wrapper for iddtxt2groups
343,615
def whoami(anchore_config): ecode = 0 try: aa = contexts[] if aa and in aa and in aa: info = {: aa[] if aa[] else } anchore_print(info, do_formatting=True) else: anchore_print_err() ecode = 1 except Exception as err: an...
Show user data for current user if available :param anchore_config: :return:
343,616
def encode(tsig, *l): fun = encodefuns() if tsig not in fun: raise "No encoder for type %r." % tsig v = fun[tsig](*l) tsig = (tsig + )[: 4] return tsig + ( * 4) + v
Encode a Python value as an ICC type. `tsig` is the type signature to (the first 4 bytes of the encoded value, see [ICC 2004] section 10.
343,617
def allow_role(role): def processor(action, argument): db.session.add( ActionRoles.allow(action, argument=argument, role_id=role.id) ) return processor
Allow a role identified by an email address.
343,618
def exact_(self, column, *values): df = self._exact(column, *values) if df is None: self.err("Can not select exact data") return self._duplicate_(df)
Returns a Dataswim instance with rows that has the exact string value in a column
343,619
def download(self, path=None, file_obj=None, progressbar=False): if path and file_obj: raise OneCodexException("Please specify only one of: path, file_obj") if path is None and file_obj is None: path = os.path.join(os.getcwd(), self.filename) if path and os.pat...
Downloads files from One Codex. Parameters ---------- path : `string`, optional Full path to save the file to. If omitted, defaults to the original filename in the current working directory. file_obj : file-like object, optional Rather than save the f...
343,620
def _make_symlink(self, link_name: str, link_target: str): path = self._file_writer_session.extra_resource_path() if path: dir_path = os.path.dirname(path) symlink_path = os.path.join(dir_path, link_name) _logger.debug(, symlink_path, link_target) ...
Make a symlink on the system.
343,621
def get_messages(self, limit=25, *, query=None, order_by=None, batch=None, download_attachments=False): if self.root: url = self.build_url(self._endpoints.get()) else: url = self.build_url(self._endpoints.get().format( id=self.folder...
Downloads messages from this folder :param int limit: limits the result set. Over 999 uses batch. :param query: applies a filter to the request such as "displayName eq 'HelloFolder'" :type query: Query or str :param order_by: orders the result set based on this condition ...
343,622
def title(self, gender: Optional[Gender] = None, title_type: Optional[TitleType] = None) -> str: gender_key = self._validate_enum(gender, Gender) title_key = self._validate_enum(title_type, TitleType) titles = self._data[][gender_key][title_key] return self.random...
Generate a random title for name. You can generate random prefix or suffix for name using this method. :param gender: The gender. :param title_type: TitleType enum object. :return: The title. :raises NonEnumerableError: if gender or title_type in incorrect format. ...
343,623
def provide_temporary_scripts_path(self): if len(self.options.temporary_scripts_path) > 0: if os.path.isfile(self.options.temporary_scripts_path): self.logger.error("Error: configured script path seems to be a file!") sys.exit(1) ...
When configured trying to ensure that path does exist.
343,624
def download(self, obj, path=None, show_progress=True, resume=True, auto_retry=True, proapi=False): url = obj.get_download_url(proapi) download(url, path=path, session=self.http.session, show_progress=show_progress, resume=resume, auto_retry=au...
Download a file :param obj: :class:`.File` object :param str path: local path :param bool show_progress: whether to show download progress :param bool resume: whether to resume on unfinished downloads identified by filename :param bool auto_retry: whether to retry au...
343,625
def setup_database_connection( pathToYamlFile): import sys import logging import pymysql as ms try: logging.info( + pathToYamlFile) stream = file(pathToYamlFile, ) connDict = yaml.load(stream) except: logging.critical( + pa...
*Start a database connection using settings in yaml file* Given the location of a YAML dictionary containing database credientials, this function will setup and return the connection* **Key Arguments:** - ``pathToYamlFile`` -- path to the YAML dictionary. **Return:** - ``dbConn`` -- conn...
343,626
def step_context(self): if self._step_context is None: self._step_context = StepContextList( self._version, flow_sid=self._solution[], engagement_sid=self._solution[], step_sid=self._solution[], ) return sel...
Access the step_context :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextList
343,627
def ConfirmarArribo(self, numero_carta_de_porte, numero_ctg, cuit_transportista, peso_neto_carga, consumo_propio, establecimiento=None, cuit_chofer=None, **kwargs): "Confirma arribo CTG" ret = self.client.confirmarArribo(request=d...
Confirma arribo CTG
343,628
def addJavaMessages(tempMessage,messageType,java_messages,java_message_types): global g_current_testname global g_java_general_bad_messages global g_java_general_bad_message_types global g_failure_occurred tempMess = tempMessage.strip() if (tempMess not in g_ok_java_messages["general"]): ...
Insert Java messages into java_messages and java_message_types if they are associated with a unit test or into g_java_general_bad_messages/g_java_general_bad_message_types otherwise. Parameters ---------- tempMessage : str contains the bad java messages messageType : str conta...
343,629
def get_collection_es(self): from nefertari.elasticsearch import ES return ES(self.Model.__name__).get_collection(**self._query_params)
Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly.
343,630
def cprint(text="", color=None, on_color=None, attrs=None, **kwargs): columns, lines = shutil.get_terminal_size() if columns == 0: columns = 80 termcolor.cprint(textwrap.fill(text, columns, drop_whitespace=False), color=color, on_color=on_color, attrs=attrs, **...
Colorizes text (and wraps to terminal's width).
343,631
def getMirrorTextureGL(self, eEye): fn = self.function_table.getMirrorTextureGL pglTextureId = glUInt_t() pglSharedTextureHandle = glSharedTextureHandle_t() result = fn(eEye, byref(pglTextureId), byref(pglSharedTextureHandle)) return result, pglTextureId, pglSharedTextu...
Access to mirror textures from OpenGL.
343,632
def visit_tree(node, previsit, postvisit): if not previsit: previsit = lambda node, pvalue: (None, None) if not postvisit: postvisit = lambda node, pvalue, value: None iter_children = iter_children_func(node) done = set() ret = None stack = [(node, None, _PREVISIT)] while stack: current, p...
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par_value)`` - should return ``(par_value, value)`` ...
343,633
def generate_supplied_diff_subparser(subparsers): parser = subparsers.add_parser( , description=constants.SUPPLIED_DIFF_DESCRIPTION, epilog=constants.SUPPLIED_DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.SUPPLIED_DIFF_HELP) parser.set_defaults(func=supplied_diff) ...
Adds a sub-command parser to `subparsers` to run a diff query using the supplied results sets.
343,634
def cache( requires=None, disabled=False, applied_on_method=False, check_param=True, limit=None ): if not requires: requires = [] elif isinstance(requires, collections.Callable): requires = [requires] if not isinstance(check_param, (bool, str)): raise Type...
Avoid to recompute a function if its parameters and its source code doesnt have changed. Args: requires: list of dependencies (functions or function names) disabled (bool): disable the cache mecanism for this function (useful if you only want to use the ...
343,635
def create_checkout_order(self, checkout_id, **params): response = self._post(, , checkout_id, , data=params) return self._make_api_object(response, Order)
https://developers.coinbase.com/api/v2#create-a-new-order-for-a-checkout
343,636
def encoding(self): if self.redirect is not None: return self.redirect.encoding else: return super(TeeStringIO, self).encoding
Gets the encoding of the `redirect` IO object Doctest: >>> redirect = io.StringIO() >>> assert TeeStringIO(redirect).encoding is None >>> assert TeeStringIO(None).encoding is None >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding >>> ...
343,637
def diff(full, dataset_uri, reference_dataset_uri): def echo_header(desc, ds_name, ref_ds_name, prop): click.secho("Different {}".format(desc), fg="red") click.secho("ID, {} in , {} in ".format( prop, ds_name, prop, ref_ds_name)) def echo_diff(diff): for d in diff: ...
Report the difference between two datasets. 1. Checks that the identifiers are identicial 2. Checks that the sizes are identical 3. Checks that the hashes are identical, if the '--full' option is used If a differences is detected in step 1, steps 2 and 3 will not be carried out. Similarly if a dif...
343,638
def getbyuuid(self, uuid): if uuid not in self._schbyuuid: raise KeyError(.format(uuid)) return self._schbyuuid[uuid]
Get a schema by given uuid. :param str uuid: schema uuid to retrieve. :rtype: Schema :raises: KeyError if uuid is not registered already.
343,639
def _get_child_mock(mock, **kw): attribute = "." + kw["name"] if "name" in kw else "()" mock_name = _extract_mock_name(mock) + attribute raise AttributeError(mock_name)
Intercepts call to generate new mocks and raises instead
343,640
def serve(name: str = "", port: int = 5000) -> None: logging.info(" * Listening on port %s", port) httpd = HTTPServer((name, port), RequestHandler) httpd.serve_forever()
A basic way to serve the methods. Args: name: Server address. port: Server port.
343,641
def iter_train_batches(self, max_yield=999): for ev, sample_batch in self._augment_with_replay( self.sample_tasks.completed_prefetch( blocking_wait=True, max_yield=max_yield)): sample_batch.decompress_if_needed() self.batch_buffer.append(samp...
Iterate over train batches. Arguments: max_yield (int): Max number of batches to iterate over in this cycle. Setting this avoids iter_train_batches returning too much data at once.
343,642
def extract_acl(cls, acl): try: scheme, rest = acl.split(":", 1) credential = ":".join(rest.split(":")[0:-1]) cdrwa = rest.split(":")[-1] except ValueError: raise cls.BadACL("Bad ACL: %s. Format is scheme:id:perms" % (acl)) if scheme not ...
parse an individual ACL (i.e.: world:anyone:cdrwa)
343,643
def get_gallery_profile(self): url = (self._imgur._base_url + "/3/account/{0}/" "gallery_profile".format(self.name)) return self._imgur._send_request(url)
Return the users gallery profile.
343,644
def _tokenize(bytes, mimetype, extra_tokens=True): try: ascii_bytes = b.join(re.compile(b).findall(bytes)) ascii_bytes = ascii_bytes.replace(b, b) except: return [] tokens = [] results = re.compile(b).findall(ascii_bytes) tokens += results res...
This function tokenizes the input bytes based on some common characters. It returns the tokens in ASCII format.
343,645
def __initialize_model(self): LOGGER.debug("> Initializing model.") self.beginResetModel() self.root_node = umbra.ui.nodes.DefaultNode(name="InvisibleRootNode") self.__default_project_node = ProjectNode(name=self.__default_project, ...
Initializes the Model.
343,646
def commit(self): commit_response = self._client._firestore_api.commit( self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata, ) self._write_pbs = [] self.write_results = results = l...
Commit the changes accumulated in this batch. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes were applied to this batch. A w...
343,647
def stream_template(template_name, **context): app.update_template_context(context) template = app.jinja_env.get_template(template_name) stream = template.generate(context) return Response(stream_with_context(stream))
Some templates can be huge, this function returns an streaming response, sending the content in chunks and preventing from timeout. :param template_name: template :param **context: parameters for templates. :yields: HTML strings
343,648
def mset(self, values): for key, value in values.items(): self.set(key, value)
Set the value of several keys at once. Args: values (dict): maps a key to its value.
343,649
def write_core_register(self, reg, data): regIndex = register_name_to_index(reg) if is_single_float_register(regIndex) and type(data) is float: data = conversion.float32_to_u32(data) elif is_double_float_register(regIndex) and type(data) is float: data =...
write a CPU register. Will need to pack floating point register values before writing.
343,650
def clean(bld): try: proj=Environment.Environment(Options.lockfile) except IOError: raise Utils.WafError() bld.load_dirs(proj[SRCDIR],proj[BLDDIR]) bld.load_envs() bld.is_install=0 bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]]) try: bld.clean() finally: bld.save()
removes the build files
343,651
def disable_logging(lines, min_level_value, max_level_value): output = while lines: line = lines[0] ret = RE_LOGGING_START.match(line) if not ret: output += line lines = lines[1:] else: logging_lines, remaining_l...
Disables logging statements in these lines whose logging level falls between the specified minimum and maximum levels.
343,652
def make3d(self, forcefield="mmff94", steps=50): pbmol = pb.Molecule(self._obmol) pbmol.make3D(forcefield=forcefield, steps=steps) self._obmol = pbmol.OBMol
A wrapper to pybel's make3D method generate a 3D structure from a 2D or 0D structure. The 3D structure is made very quickly using a combination of rules (e.g. sp3 atoms should have four bonds arranged in a tetrahedron) and ring templates (e.g. cyclohexane is shaped like a chair). Once 3D...
343,653
async def connect(self, timeout=None): self._is_shutdown = False combo_uri = "ws://{}:{}".format(self.host, self.rest) uri = "ws://{}:{}".format(self.host, self.port) log.debug( "Lavalink WS connecting to %s or %s with headers %s", combo_uri, uri, self.headers ...
Connects to the Lavalink player event websocket. Parameters ---------- timeout : int Time after which to timeout on attempting to connect to the Lavalink websocket, ``None`` is considered never, but the underlying code may stop trying past a certain point. ...
343,654
def remove_vote(self, issue): url = self._get_url( + str(issue) + ) self._session.delete(url)
Remove the current authenticated user's vote from an issue. :param issue: ID or key of the issue to remove vote on
343,655
def scroll_y(self, pixels, relative=True): if relative: self.offset.y += int(pixels) else: self.offset.y = int(pixels) self._update()
Negative values for @pixels scroll up, positive values scroll down; @relative determines whether to set the scroll-y value or change as above.
343,656
def register(model, fields, restrict_to=None, manager=None, properties=None, contexts=None): if not contexts: contexts = {} global _REGISTRY _REGISTRY[model] = { : fields, : contexts, : restrict_to, : manager, : properties, } for field in fields...
Tell vinaigrette which fields on a Django model should be translated. Arguments: model -- The relevant model class fields -- A list or tuple of field names. e.g. ['name', 'nickname'] restrict_to -- Optional. A django.db.models.Q object representing the subset of objects to collect translation s...
343,657
def argrelmax(data, axis=0, order=1, mode=): return argrelextrema(data, np.greater, axis, order, mode)
Calculate the relative maxima of `data`. .. versionadded:: 0.11.0 Parameters ---------- data : ndarray Array in which to find the relative maxima. axis : int, optional Axis over which to select from `data`. Default is 0. order : int, optional How many points on each si...
343,658
def addGrammaticalFeatsAndRoots( sentence, foundChains ): _/püüab kodeeridaV_bV_dapüüdkodeerion tulnudV_vad/bV_nudoletule _indicPresent = [,,,,,] _indicImperfect = [, , , , , ] _imperatPlural = [, , ] _conditPreesens = [, , , , , ] _conditPreteerium = [, , , , , ] for i in ...
Täiendab leitud verbiahelaid, lisades iga ahela kylge selle s6nade lemmad (ROOT v2ljad morf analyysist) ning morfoloogilised tunnused (POSTAG+FORM: eraldajaks '_' ning kui on mitu varianti, siis tuuakse k6ik variandid, eraldajaks '/'); Atribuudid ROOTS ja MORPH sisaldavad tunnuste loetelusi...
343,659
def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx): hdridxval = len(self.hdrs) - 1 worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt) return row_idx + 1
Merge all columns and place text string in widened cell.
343,660
def input_validate_nonce(nonce, name=, pad = False): if type(nonce) is not str: raise pyhsm.exception.YHSM_WrongInputType( \ name, str, type(nonce)) if len(nonce) > pyhsm.defines.YSM_AEAD_NONCE_SIZE: raise pyhsm.exception.YHSM_InputTooLong( name, pyhsm.defines.YSM_AE...
Input validation for nonces.
343,661
def _onShortcutPrint(self): dialog = QPrintDialog(self) if dialog.exec_() == QDialog.Accepted: printer = dialog.printer() self.print_(printer)
Ctrl+P handler. Show dialog, print file
343,662
def user(context, institute_id, user_name, user_mail, admin): adapter = context.obj[] institutes = [] for institute in institute_id: institute_obj = adapter.institute(institute_id=institute) if not institute_obj: LOG.warning("Institute % does not exist", institute) ...
Add a user to the database.
343,663
def publish_results(self, dist_dir, use_basename_prefix, vt, bundle_dir, archivepath, id, archive_ext): name = vt.target.basename if use_basename_prefix else id bundle_copy = os.path.join(dist_dir, .format(name)) absolute_symlink(bundle_dir, bundle_copy) self.context.log.info( .format(os...
Publish a copy of the bundle and archive from the results dir in dist.
343,664
def add_plugin_directories(self, paths, except_blacklisted=True): self.directory_manager.add_directories(paths, except_blacklisted)
Adds `directories` to the set of plugin directories. `directories` may be either a single object or a iterable. `directories` can be relative paths, but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in...
343,665
def get_value(self, item, default=None): try: return self[item].value except (AttributeError, KeyError) as e: return default
Get the value of a child
343,666
def save(self, filepath): if type(filepath) != str: raise ValueError("filepath provided is not a string") if filepath.endswith(".json"): spec = self.get_vega(include_data = True) with open(filepath, ) as fp: _json.dump(spec, fp) ...
A method for saving the Plot object in a vega representation Parameters ---------- filepath: string The destination filepath where the plot object must be saved as. The extension of this filepath determines what format the plot will be saved as. Currently sup...
343,667
def is_shaped(self): for description in (self.description, self.description1): if not description: return None if description[:1] == and in description: return description if description[:6] == : return description ...
Return description containing array shape if exists, else None.
343,668
def _stream(self, doc, source, new_data, rollover=None, setter=None): old = self._saved_copy() for k, v in new_data.items(): if isinstance(self[k], np.ndarray) or isinstance(new_data[k], np.ndarray): data = np.append(self[k], new...
Internal implementation to handle special-casing stream events on ``ColumnDataSource`` columns. Normally any changes to the ``.data`` dict attribute on a ``ColumnDataSource`` triggers a notification, causing all of the data to be synchronized between server and clients. The ``....
343,669
def start(self): subscribe(handler=self.forward_prompt, predicate=self.is_prompt) msg = SystemInitRequest( self.system.process_classes, self.infrastructure_class, self.system.followings, self.pipeline_ids ) ...
Starts all the actors to run a system of process applications.
343,670
def run(self): self.state_execution_status = StateExecutionStatus.ACTIVE logger.debug("Entering library state with name ".format(self.library_name, self.name)) self.state_copy._run_id = self._run_id self.state_copy.input_data = self.input_data self.state_copy.o...
This defines the sequence of actions that are taken when the library state is executed It basically just calls the run method of the container state :return:
343,671
def attributes_layout(self, EdgeAttribute=None, maxwidth=None, minrad=None, \ network=None, NodeAttribute=None,nodeList=None, radmult=None, \ spacingx=None, spacingy=None, verbose=False): network=check_network(self,network,verbose=verbose) PARAMS=set_param(["EdgeAttribute","network","NodeAttribute","nodeList",...
Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column containing numeric values that will be used as weights in the layout algorithm. Only columns containing numeric values are shown :param maxwidth (string, optional): Maximum width of a row, i...
343,672
def _convert_axes_to_absolute(dshape, axes): if axes is None: return None elif isinstance(axes, (tuple, list)): return tuple(np.arange(len(dshape))[list(axes)]) else: raise NotImplementedError("axes %s is of unsupported type %s "%(str(axes), type(axes)))
axes = (-2,-1) does not work in reikna, so we have to convetr that
343,673
def time2netscape(t=None): if t is None: dt = datetime.datetime.utcnow() else: dt = datetime.datetime.utcfromtimestamp(t) return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % ( DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1], dt.year, dt.hour, dt.minute, dt.second)
Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like this: Wed, DD-Mon-YYYY HH:MM:SS GMT
343,674
def drop_empty_tables(self): counts = self.count_rows_all() drops = [] for table, count in counts.items(): if count < 1: self.drop(table) drops.append(table) return drops
Drop all empty tables in a database.
343,675
def _parse_args(args): cmd_parser = argparse.ArgumentParser(description=) cmd_parser.add_argument(, help=) cmd_parser.add_argument(, action=, help=) subparsers = cmd_parser.add_subparsers(help=, dest=) parser_start = subparsers.add_parser(, help=) parser_status = subparsers.add_parser(, h...
Argument parsing
343,676
def on_chanmsg(self, from_, channel, message): if message == : self.privmsg(channel, % from_[0]) print( % from_[0]) elif message == : self.quit()
Event handler for channel messages.
343,677
def geodesic(crs, start, end, steps): r import cartopy.crs as ccrs from pyproj import Geod g = Geod(crs.proj4_init) geodesic = np.concatenate([ np.array(start[::-1])[None], np.array(g.npts(start[1], start[0], end[1], end[0], steps - 2)), np.array(end[::-1])[None] ...
r"""Construct a geodesic path between two points. This function acts as a wrapper for the geodesic construction available in `pyproj`. Parameters ---------- crs: `cartopy.crs` Cartopy Coordinate Reference System to use for the output start: (2, ) array_like A latitude-longitude pai...
343,678
def write(filename, mesh, fmt_version, write_binary=True): try: writer = _writers[fmt_version] except KeyError: try: writer = _writers[fmt_version.split(".")[0]] except KeyError: raise ValueError( "Need mesh format in {} (got {})".format( ...
Writes a Gmsh msh file.
343,679
def align_end_hierarchies(hier1, hier2, thres=0.5): dur_h1 = hier1[0][-1] for hier in hier1: assert hier[-1] == dur_h1, "hier1 is not correctly " \ "formatted {} {}".format(hier[-1], dur_h1) dur_h2 = hier2[0][-1] for hier in hier2: assert hier[-1] == dur_h2, "hier2 ...
Align the end of the hierarchies such that they end at the same exact second as long they have the same duration within a certain threshold. Parameters ---------- hier1: list List containing hierarchical segment boundaries. hier2: list List containing hierarchical segment boundaries...
343,680
def ready(self): if self.__timeout < time.time(): self.cancel() return self.__queue.full() and not self.__queue.empty()
Read-only property indicating status of "value" property.
343,681
def parse_annotations(annots, fmt, annot_tables, trans_table): annotations = {} if fmt is False: for contig, feature in parse_gbk(annots): if contig not in annotations: annotations[contig] = [] annotations[contig].append(feature) else: ...
parse annotations in either gbk or Prodigal fasta format
343,682
def _func(self, volume, params): e0, b0, b1, v0 = tuple(params) eta = (volume / v0) ** (1. / 3.) squiggle = -3.*np.log(eta) return e0 + b0 * v0 * squiggle ** 2 / 6. * (3. + squiggle * (b1 - 2))
Pourier-Tarantola equation from PRB 70, 224107
343,683
def timeSlice(requestContext, seriesList, startSliceAt, endSliceAt=): results = [] start = epoch(parseATTime(startSliceAt)) end = epoch(parseATTime(endSliceAt)) for slicedSeries in seriesList: slicedSeries.name = % (slicedSeries.name, ...
Takes one metric or a wildcard metric, followed by a quoted string with the time to start the line and another quoted string with the time to end the line. The start and end times are inclusive. See ``from / until`` in the render api for examples of time formats. Useful for filtering out a part of ...
343,684
def get_factory_kwargs(self): params = dict() exclude = self.derive_exclude() exclude += self.derive_readonly() if self.fields: fields = list(self.fields) for ex in exclude: if ex in fields: fields.remove(ex) ...
Let's us specify any extra parameters we might want to call for our form factory. These can include: 'form', 'fields', 'exclude' or 'formfield_callback'
343,685
def generate_badge_svg(title, value, color=): (title_length, value_length) = get_text_length(title, value) return .format( title_width=title_length + 11, value_width=value_length + 11, width=title_length + value_length + 22, title_position=title_length / 2 + 6, value...
Generate the SVG. :param title: The badge title. :param value: The badge content. :param color: The badge color. (Default: ``'#007ec6'``) :returns: The SVG badge.
343,686
def _post(self, *args, **kwargs): if not in kwargs: kwargs[] = self.timeout req = self.session.post(*args, **kwargs) return req
Wrapper around Requests for POST requests Returns: Response: A Requests Response object
343,687
def scan(self): t1=cm.timeit() self.files1=cm.list_to_lowercase(sorted(os.listdir(self.folder1))) self.files2=cm.list_to_lowercase(sorted(os.listdir(self.folder2))) self.files1abf=[x for x in self.files1 if x.endswith(".abf")] self.files1abf=cm.list_to_lowercase(cm.abfSo...
scan folder1 and folder2 into files1 and files2. since we are on windows, simplify things by making them all lowercase. this WILL cause problems on 'nix operating systems.If this is the case, just run a script to rename every file to all lowercase.
343,688
def write_additional(self, productversion, channel): self.fileobj.seek(self.additional_offset) extras = extras_header.build(dict( count=1, sections=[dict( channel=six.u(channel), productversion=six.u(productversion), size=l...
Write the additional information to the MAR header. Args: productversion (str): product and version string channel (str): channel string
343,689
def convert(self, names, src=None, to=, enforce_list=False, not_found=, exclude_prefix=[, , ]): names = list(names) if ( isinstance(names, tuple) or isinstance(names, set)) else names names = names if isinstance(names, li...
Convert names from a list to another list. Note ---- A lot of the functionality can also be done directly in Pandas DataFrames. For example: coco = CountryConverter() names = ['USA', 'SWZ', 'PRI'] coco.data[coco.data['ISO3'].isin(names)][['ISO2', 'contine...
343,690
def initialise(self, projectname: str, xmlfile: str) -> None: write = commandtools.print_textandtime write(f) hp = hydpytools.HydPy(projectname) write(f) interface = xmltools.XMLInterface(xmlfile) write() interface.update_options() write() ...
Initialise a *HydPy* project based on the given XML configuration file agreeing with `HydPyConfigMultipleRuns.xsd`. We use the `LahnH` project and its rather complex XML configuration file `multiple_runs.xml` as an example (module |xmltools| provides information on interpreting this fil...
343,691
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): local_buffer = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_buffer, kmip_version=kmip_version ) else: ...
Write the data encoding the GetAttributes response payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumera...
343,692
def options(self, new): options = self._create_options(new) if self.widget.value: self.widget.set_param(options=options, value=list(options.values())[:1]) else: self.widget.options = options self.widget.value = list(options.values())[:1]
Set options from list, or instance of named item Over-writes old options
343,693
def xstep(self): r self.YU[:] = self.Y - self.U YUf = sl.rfftn(self.YU, None, self.cri.axisN) YUf0 = self.block_sep0(YUf) YUf1 = self.block_sep1(YUf) b = self.rho * np.sum(np.conj(self.GDf) * YUf1, axis=-1) if self.cri.Cd > 1: b = np.sum(b, axis=self...
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.
343,694
def download_from_url(url, destination_path, force=False, aspera=False, silent=False): if aspera and url.startswith("http"): logger.warn("Aspera Connect allows only FTP servers - falling back to " "normal download") aspera = False try: fn =...
Download file from remote server. If the file is already downloaded and ``force`` flag is on the file will be removed. Args: url (:obj:`str`): Path to the file on remote server (including file name) destination_path (:obj:`str`): Path to the file on local machine (...
343,695
def build_schema_mapping(schema_dir, resource_listing): def resource_name_to_filepath(name): return os.path.join(schema_dir, .format(name)) return dict( (resource, resource_name_to_filepath(resource)) for resource in find_resource_names(resource_listing) )
Discovers schema file locations and relations. :param schema_dir: the directory schema files live inside :type schema_dir: string :param resource_listing: A swagger resource listing :type resource_listing: dict :returns: a mapping from resource name to file path :rtype: dict
343,696
def help_center_user_comments(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/comments api_path = "/api/v2/help_center/users/{id}/comments.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/comments#list-comments
343,697
def ufunc_class_factory(name, nargin, nargout, docstring): assert 0 <= nargin <= 2 def __init__(self, space): if not isinstance(space, LinearSpace): raise TypeError(.format(space)) if nargin == 1: domain = space0 = space dtypes = [space.dtype]...
Create a Ufunc `Operator` from a given specification.
343,698
def tofile(self, f): chunksize = 1024 * 1024 if not self._offset: a = 0 bytelen = self._datastore.bytelength p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1)) while len(p) == chunksize: f.write...
Write the bitstring to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align.
343,699
def unflatten(d, splitter=, inverse=False): if isinstance(splitter, str): splitter = SPLITTER_DICT[splitter] unflattened_dict = {} for flat_key, value in six.viewitems(d): if inverse: flat_key, value = value, flat_key key_tuple = splitter(flat_key) nested_se...
Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will be used to split. 'tuple': Use each eleme...