Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
362,300
def get_subgraph_by_annotations(graph, annotations, or_=None): edge_filter_builder = ( build_annotation_dict_any_filter if (or_ is None or or_) else build_annotation_dict_all_filter ) return get_subgraph_by_edge_filter(graph, edge_filter_builder(annotations))
Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True any annotation should be present, if False all annotations should be pr...
362,301
def _validate_label(self, label): letter_pattern = compile("^[a-z]{1}$") number_pattern = compile("^[0]{1}$|^[1-9]{1,2}$") icon_pattern = compile("^[a-zA-Z ]{1,}$") if not match(letter_pattern, label)\ and not match(number_pattern, label)\ and not m...
Validates label, raising error if invalid.
362,302
def wrap_form_params(func): @functools.wraps(func) def wrapper(request, *args, **kwargs): ctype, pdict = parse_header(request.headers.get(, )) if ctype == "application/x-www-form-urlencoded": params = {} for key, value in parse_qs(request.body.decode("utf-8")).items...
A middleware that parses the url-encoded body and attach the result to the request `form_params` attribute. This middleware also merges the parsed value with the existing `params` attribute in same way as `wrap_query_params` is doing.
362,303
def extract_features_and_generate_model(essays, algorithm=util_functions.AlgorithmTypes.regression): f = feature_extractor.FeatureExtractor() f.initialize_dictionaries(essays) train_feats = f.gen_feats(essays) set_score = numpy.asarray(essays._score, dtype=numpy.int) if len(util_functions.f7(...
Feed in an essay set to get feature vector and classifier essays must be an essay set object additional array is an optional argument that can specify a numpy array of values to add in returns a trained FeatureExtractor object and a trained classifier
362,304
def json_format(out, graph): steps = {} for step, deps in each_step(graph): steps[step.name] = {} steps[step.name]["deps"] = [dep.name for dep in deps] json.dump({"steps": steps}, out, indent=4) out.write("\n")
Outputs the graph in a machine readable JSON format.
362,305
def _get_prep_params(data): realign_param = dd.get_realign(data) realign_param = "gatk" if realign_param is True else realign_param return {"realign": realign_param}
Retrieve configuration parameters with defaults for preparing BAM files.
362,306
def update_permission(obj, data): full_permissions = get_all_perms(obj) def apply_perm(perm_func, perms, entity): if perms == : perms = full_permissions for perm in perms: perm_codename = get_full_perm(perm, obj) if perm_codename not in full_per...
Update object permissions.
362,307
def user_has(ability, get_user=import_user): def wrapper(func): @wraps(func) def inner(*args, **kwargs): from .models import Ability desired_ability = Ability.query.filter_by( name=ability).first() user_abilities = [] current_user ...
Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability
362,308
def request(self, method, path, params=None, headers=None, body=None): if not headers: headers = {} if not params: params = {} headers["Accept"] = "application/json" headers["Accept-Version"] = "^1.15.0" if self.auth_token: headers["A...
Base method for making a Losant API request
362,309
def get_dimensions_from_user(self, no_dim): if no_dim != 3: raise NotImplementedError( _("Currently, only 3D grids are supported.")) dim_dialog = DimensionsEntryDialog(self.main_window) if dim_dialog.ShowModal() != wx.ID_OK: dim_dialo...
Queries grid dimensions in a model dialog and returns n-tuple Parameters ---------- no_dim: Integer \t Number of grid dimensions, currently must be 3
362,310
async def _move(self, target_position: , speed: float = None, home_flagged_axes: bool = True): to_transform = tuple((tp for ax, tp in target_position.items() if ax in Axis.gantry_axes())) ...
Worker function to apply robot motion. Robot motion means the kind of motions that are relevant to the robot, i.e. only one pipette plunger and mount move at the same time, and an XYZ move in the coordinate frame of one of the pipettes. ``target_position`` should be an ordered dict (or...
362,311
def from_cryptography_key(cls, crypto_key): pkey = cls() if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, dsa.DSAPublicKey, dsa.DSAPrivateKey)): raise TypeError("Unsupported key type") pkey._pkey = crypto_key._evp_pk...
Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0
362,312
def find_home_directory(): if WINDOWS: directory = os.environ.get() if not directory: directory = os.path.expanduser(r) else: import pwd entry = pwd.getpwuid(os.getuid()) directory = entry.pw_dir return directory
Look up the home directory of the effective user id. :returns: The pathname of the home directory (a string). .. note:: On Windows this uses the ``%APPDATA%`` environment variable (if available) and otherwise falls back to ``~/Application Data``.
362,313
def get_environ(cls, prefix): return ((key[len(prefix) + 1:], value) for key, value in os.environ.items() if key.startswith( % prefix))
Retrieves environment variables from a namespace. Args: prefix (str): The prefix, without a trailing underscore. Returns: list: A list of environment variable keys and values.
362,314
def parse(line): m = LOG_FORMAT.match(line) if m is None: return access = Access._make(m.groups()) entry = { : access.host, : access.path, : access.query, : access.method, : access.protocol, : int(access.status) } entry[] = datetime.da...
Parse accesslog line to map Python dictionary. Returned dictionary has following keys: - time: access time (datetime; naive) - utcoffset: UTC offset of access time (timedelta) - host: remote IP address. - path: HTTP request path, this will be splitted from query. - query: HTTP requert query st...
362,315
def detect_batch(self, batch): self.mod.forward(batch, is_train=False) detections = self.mod.get_outputs()[0] positive_detections = Detector.filter_positive_detections(detections) return positive_detections
Return detections for batch :param batch: :return:
362,316
def plotEz(self,*args,**kwargs): if kwargs.pop(,False): kwargs[]= else: kwargs[]= return self.plot(*args,**kwargs)
NAME: plotEz PURPOSE: plot Ez(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS)
362,317
def from_image(cls, image, filename): source = Image.open(BytesIO(image)) source = source.convert() width = int(math.ceil(source.size[0] / 8.0)) data = [] for line in _chunked(list(source.getdata()), source.size[0]): row = .join([ if p else for p in line])...
Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.
362,318
def GetHasherNamesFromString(cls, hasher_names_string): hasher_names = [] if not hasher_names_string or hasher_names_string.strip() == : return hasher_names if hasher_names_string.strip() == : return cls.GetHasherNames() for hasher_name in hasher_names_string.split(): hasher_na...
Retrieves a list of a hasher names from a comma separated string. Takes a string of comma separated hasher names transforms it to a list of hasher names. Args: hasher_names_string (str): comma separated names of hashers to enable, the string 'all' to enable all hashers or 'none' to disable...
362,319
def get_dbg_brk_linux32(): debugger = get_debugger() code = b eax = debugger.get_reg("eax") ebx = debugger.get_reg("ebx") eip = debugger.get_reg("eip") efl = debugger.get_reg("efl") debugger.set_reg("eax", 45) debugger.set_reg("ebx", 0) base = debugger.image_b...
Return the current brk value in the debugged process (only x86 Linux)
362,320
def is_frond(u, v, dfs_data): d_u = D(u, dfs_data) d_v = D(v, dfs_data) edge_id = dfs_data[].get_first_edge_id_by_node_ids(u, v) return True if dfs_data[][edge_id] == and d_v < d_u else False
Determines if the edge uv is a frond ("backedge").
362,321
def _from_jd_equinox(jd): jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour)
Calculate the FR day using the equinox as day 1
362,322
def deprecated(conditional=True): def deprecate_decorator(f): import nose def _deprecated_imp(*args, **kwargs): try: f(*args, **kwargs) if not len(l) > 0: raise AssertionError("No warning raised when...
Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, option...
362,323
def fuzzy_match(image, template, normed_tolerance=None, raw_tolerance=None, method=): if method == : if not raw_tolerance: raw_tolerance = 0.95 if not normed_tolerance: normed_tolerance = 0.95 results = np.array(match_via_correlation(image, template, raw_toleranc...
Determines, using one of two methods, whether a match(es) is present and returns the positions of the bottom right corners of the matches. Fuzzy matches returns regions, so the center of each region is returned as the final match location USE THIS FUNCTION IF you need to match, e.g. the same image...
362,324
def formatTimeFromNow(secs=None): return datetime.utcfromtimestamp(time.time() + int(secs or 0)).strftime(timeFormat)
Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str
362,325
def read(self, b=-1): remaining_bytes = b data = io.BytesIO() while True: try: chunk = to_bytes(self.__wrapped__.read(remaining_bytes)) except ValueError: if self.__wrapped__.closed: break raise ...
Keep reading from source stream until either the source stream is done or the requested number of bytes have been obtained. :param int b: number of bytes to read :return: All bytes read from wrapped stream :rtype: bytes
362,326
def update_devices(self, selection=None): if selection is not None: self.nodes = selection.nodes self.elements = selection.elements self._update_deviceorder()
Determines the order, in which the |Node| and |Element| objects currently handled by the |HydPy| objects need to be processed during a simulation time step. Optionally, a |Selection| object for defining new |Node| and |Element| objects can be passed.
362,327
def handle(cls, value, context, **kwargs): try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value) return context.hook_data[hook...
Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key>
362,328
def delete_individual(self, ind_obj): logger.info("Deleting individual {0} from database" .format(ind_obj.ind_id)) self.session.delete(ind_obj) self.save() return ind_obj
Delete a case from the database Args: ind_obj (puzzle.models.Individual): initialized individual model
362,329
def query_record_useful_review(comID, value): query1 = params1 = (comID,) res1 = run_sql(query1, params1) if len(res1) == 0: return 0 nb_votes_yes = int(res1[0][1]) if value >= 1: nb_votes_yes = int(res1[0][1]) + 1 nb_votes_total = int(res1[0][0]) + 1 que...
private funciton Adjust the number of useful votes and number of total votes for a comment. :param comID: comment id :param value: +1 or -1 :return: integer 1 if successful, integer 0 if not
362,330
def to_pinyin(s, accented=True): identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s if accented else accented_to_numbered(s) else: return numbered_to_accented(s) if accented else s elif identity == ZHUYIN: return zhuyin_to_...
Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
362,331
def helical_turbulent_Nu_Mori_Nakayama(Re, Pr, Di, Dc): r D_ratio = Di/Dc if Pr < 1: term1 = Pr/(26.2*(Pr**(2/3.) - 0.074))*Re**0.8*D_ratio**0.1 term2 = 1. + 0.098*(Re*D_ratio*D_ratio)**-0.2 else: term1 = Pr**0.4/41.*Re**(5/6.)*(Di/Dc)**(1/12.) term2 = 1. + 0.061/(Re*(Di/...
r'''Calculates Nusselt number for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Mori and Nakayama [1]_, also shown in [2]_ and [3]_. For :math:`Pr < 1`: .. math:: Nu = \frac{Pr}{26.2(Pr^{2/3}-0.074)}Re^{0.8}\le...
362,332
def disable_contactgroup_svc_notifications(self, contactgroup): for contact_id in contactgroup.get_contacts(): self.disable_contact_svc_notifications(self.daemon.contacts[contact_id])
Disable service notifications for a contactgroup Format of the line that triggers function call:: DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name> :param contactgroup: contactgroup to disable :type contactgroup: alignak.objects.contactgroup.Contactgroup :return: None
362,333
def delete_vm_image(self, vm_image_name, delete_vhd=False): _validate_not_none(, vm_image_name) path = self._get_vm_image_path(vm_image_name) if delete_vhd: path += return self._perform_delete(path, as_async=True)
Deletes the specified VM Image from the image repository that is associated with the specified subscription. vm_image_name: The name of the image. delete_vhd: Deletes the underlying vhd blob in Azure storage.
362,334
def encodeBinaryData(dataArray, bitEncoding, compression): arrayLength = len(dataArray) floattype, __ = interpretBitEncoding(bitEncoding) fmt = .format(endian=, arraylength=arrayLength, floattyp...
Function to encode a ``numpy.array`` into a mzML byte array. This is the inverse function of :func:`decodeBinaryData`. :param dataArray: #TODO: docstring :param bitEncoding: #TODO: docstring :param compression: #TODO: docstring :returns: #TODO: docstring
362,335
def get_default(self, node): if node.inst.properties.get("intr", False): return not node.inst.properties.get("sticky", False) else: return False
Unless specified otherwise, intr fields are implicitly stickybit
362,336
def write_table(self): super(TextTableWriter, self).write_table() if self.is_write_null_line_after_table: self.write_null_line()
|write_table|. .. note:: - |None| values are written as an empty string.
362,337
def start(self): self._setup_ipc() thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),)) thread.start() signal.signal(signal.SIGTERM, self._exit_gracefully) try: zmq.proxy(self.sub, self.pub) except zmq.ZMQ...
Listen to messages and publish them.
362,338
def _qualify_map(key, content): if not isinstance(key, basestring): return key, content min_len = None max_len = None modifier = [] m = RE_MATCH_CSTR(key) if not m: raise KeyError("Unable to parse, invalid key: %r" % key) if m.group(3) is not None: mi...
When a dictionary key is optional/optionalnull/mandatory, its corresponding _value_ is decorated in an Optional/OptionalNull/Mandatory tuple. This function undo the decoration when necessary.
362,339
def getheader (self, name, default=None): value = self.headers.get(name) if value is None: return default return unicode_safe(value, encoding=HEADER_ENCODING)
Get decoded header value. @return: decoded header value or default of not found @rtype: unicode or type of default
362,340
def download_memory_dump(self, sha256, environment_id, dest_dir): dest_path = os.path.join(dest_dir, ) if self.download(sha256, environment_id, VXSTREAM_DOWNLOAD_MEMORY, dest_path) is None: return None with open(dest_path, ) as fp: blob = fp.read(1024) ...
Downloads the given memory dump into the given directory. Returns a tuple of a list of files extracted from what was downloaded, and the path to the combined memory dump.
362,341
async def unsafe_ask_async(self, patch_stdout: bool = False) -> Any: if not utils.ACTIVATED_ASYNC_MODE: await utils.activate_prompt_toolkit_async_mode() if patch_stdout: return await self.application.run_async().to_asyncio_future() else: ...
Ask the question using asyncio and return user response. Does not catch keyboard interrupts.
362,342
def generate_import_code(pipeline, operators, impute=False): def merge_imports(old_dict, new_dict): for key in new_dict.keys(): if key in old_dict.keys(): old_dict[key] = set(old_dict[key]) | set(new_dict[key]) else: old_...
Generate all library import calls for use in TPOT.export(). Parameters ---------- pipeline: List List of operators in the current optimized pipeline operators: List of operator class from operator library impute : bool Whether to impute new values in the feature set. Re...
362,343
def get_config(): config_path = path.join( (os.environ.get() or path.expanduser()), ) if not path.exists(config_path): sys.exit("Canutf-8blackredgreenyellowbluemagentacyanwhitecolors, colorsrepo_directoryt find the tldr repo, check the `repo_directory` " "setting in...
Get the configurations from .tldrrc and return it as a dict.
362,344
def from_envvar(self, variable_name, silent=False): rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError( % ...
Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment var...
362,345
def create_layer(self, lipid_indices=None, flip_orientation=False): layer = mb.Compound() if not lipid_indices: lipid_indices = list(range(self.n_lipids_per_layer)) shuffle(lipid_indices) for n_type, n_of_lipid_type in enumerate(self.number_of_each_lipid_per_lay...
Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, default=False Flip the orientation of the layer with respect to the z-di...
362,346
def to_satoshis(input_quantity, input_type): assert input_type in UNIT_CHOICES, input_type if input_type in (, , ): satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type][]) elif input_type == : satoshis = input_quantity else: raise Exception( % input_type)...
convert to satoshis, no rounding
362,347
def setup(self): if not self.mask_source.start: raise SystemExit("Canmaskmask_sizemask_centerstartbothmask_centerstartmask_centermask_centerstartbothmask_centerendbothmask_centerstartmask_centerendmask_centerboth': event_list = sorted(zip(starts, ends)) mas...
Create mask list. Consists of all tuples between which this filter accepts lines.
362,348
def get_proteins_psms_for_map(self): fields = [, , , ] firstjoin = (, , ) genetable = return self.get_unique_gene_psms(genetable, fields, firstjoin)
Gets gene-PSM combinations from DB and filters out uniques on the fly. Filtering is done since PSM are stored per protein, not per gene, so there may be a lot of *plicates
362,349
def set_timestamp(self,timestamp=None): if timestamp is None: import time timestamp = time.strftime() self.node.set(,timestamp)
Set the timestamp of the linguistic processor, set to None for the current time @type timestamp:string @param timestamp: version of the linguistic processor
362,350
def segment(filenames, format, **options): output = open(format, rollover=True, **options) if isinstance(filenames, str): filenames = [ filenames ] for filename in filenames: with open(filename, ) as stream: for header, packet in stream: output.write(packet...
Segment the given pcap file(s) by one or more thresholds (``nbytes``, ``npackets``, ``nseconds``). New segment filenames are determined based on the ``strftime(3)`` ``format`` string and the timestamp of the first packet in the file. :param filenames: Single filename (string) or list of filenames ...
362,351
def sign(self, M, t=None, h=None, mgf=None, sLen=None): if t is None: M = pkcs_os2ip(M) n = self.modulus if M > n-1: warning("Message to be signed is too long for key modulus") return None s = self._rsasp1(M) ...
Sign message 'M' using 't' signature scheme where 't' can be: - None: the message 'M' is directly applied the RSASP1 signature primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.2.1. Simply put, the message undergo a modular exponentiation using the pri...
362,352
def fit(ts, fs=[], all_params=[], fit_vars=None, alg=, make_bounded=True): if fit_vars is None: fit_vars = [f._peakargs for f in fs] initc = [min(ts.values)] for f, peak_params, to_fit in zip(fs, all_params, fit_vars): if in to_fit: to_fit.remove() if make_...
Use a minimization algorithm to fit a AstonSeries with analytical functions.
362,353
def _sync(self, timeout_ms=30000): response = self.api.sync(self.sync_token, timeout_ms) prev_sync_token = self.sync_token self.sync_token = response["next_batch"] if self._handle_thread is not None: self._handle_thread.get() is_first_sync = (p...
Reimplements MatrixClient._sync, add 'account_data' support to /sync
362,354
def polyline(self, arr): for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
Draw a set of lines
362,355
def add_input(self, **kwargs): self._closed() def _get_item(args): if not args: raise ValueError("No parameter specified.") item = args.popitem() if args: raise ValueError("Too many parameters, not clear what to d...
Add workflow input. Args: kwargs (dict): A dict with a `name: type` item and optionally a `default: value` item, where name is the name (id) of the workflow input (e.g., `dir_in`) and type is the type of the input (e.g., `'Directory'`). ...
362,356
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)): assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) assert isinstance(angle, list) l_angle = len(angle) assert l_angle == l_pt-1 for i in angle: assert isin...
Return given point rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis.
362,357
def get_items(self, url, container, container_object, local_object): headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object ) return self._getter( uri=container_uri, h...
Get an objects from a container. :param url: :param container:
362,358
def update_translations(self, project_id, file_path=None, language_code=None, overwrite=False, fuzzy_trigger=None): return self._upload( project_id=project_id, updating=self.UPDATING_TRANSLATIONS, file_path=file_path, language_...
Updates translations overwrite: set it to True if you want to overwrite definitions fuzzy_trigger: set it to True to mark corresponding translations from the other languages as fuzzy for the updated values
362,359
def wsvg(paths=None, colors=None, filename=os_path.join(getcwd(), ), stroke_widths=None, nodes=None, node_colors=None, node_radii=None, openinbrowser=False, timestamp=False, margin_size=0.1, mindim=600, dimensions=None, viewbox=None, text=None, text_path=None, font_size...
Convenience function; identical to disvg() except that openinbrowser=False by default. See disvg() docstring for more info.
362,360
def explicit_rel_links(self, rels=(, )): for match in self._rel_re.finditer(self.content): found_rels = match.group(1).lower().split() for rel in rels: if rel in found_rels: break else: continue match = ...
Yields all links with the given relations
362,361
def constrain_property(self,prop,**kwargs): if prop not in self.constraints: self.constraints.append(prop) for pop in self.poplist: try: pop.constrain_property(prop,**kwargs) except AttributeError: logging.info( % (pop.model,pr...
Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments passed to that function for each population.
362,362
def get_reply(session, url, post=False, data=None, headers=None, quiet=False): request_headers = {} if headers is None else headers request = requests.Request( if post else , url, data=data, headers=request_heade...
Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whet...
362,363
def _remove(self, client_kwargs): with _handle_azure_exception(): if in client_kwargs: return self.client.delete_file( share_name=client_kwargs[], directory_name=client_kwargs[], file_name=client_kwarg...
Remove an object. args: client_kwargs (dict): Client arguments.
362,364
def request_instance(vm_=None, call=None): if call == : raise SaltCloudSystemExit( ) log.info(, vm_[]) salt.utils.cloud.check_name(vm_[], ) conn = get_conn() kwargs = vm_.copy() try: kwargs[] = get_image(conn, vm_) except Exception...
Put together all of the information necessary to request an instance through Novaclient and then fire off the request the instance. Returns data about the instance
362,365
def center_of_mass(self, scalars_weight=False): comfilter = vtk.vtkCenterOfMass() comfilter.SetInputData(self) comfilter.SetUseScalarsAsWeights(scalars_weight) comfilter.Update() return np.array(comfilter.GetCenter())
Returns the coordinates for the center of mass of the mesh. Parameters ---------- scalars_weight : bool, optional Flag for using the mesh scalars as weights. Defaults to False. Return ------ center : np.ndarray, float Coordinates for the center o...
362,366
def is_mapped_luks_device(dev): _, dirs, _ = next(os.walk( .format(os.path.basename(os.path.realpath(dev)))) ) is_held = len(dirs) > 0 return is_held and is_luks_device(dev)
Determine if dev is a mapped LUKS device :param: dev: A full path to a block device to be checked :returns: boolean: indicates whether a device is mapped
362,367
def get_command_instance(name, parent=None, checkexists=True): cname = "%sCommand" % name.lower().capitalize() gl = globals() condition = ( cname not in gl or (checkexists and gl[cname].extension and gl[cname].extension not in RequireCommand.loaded_extensions) ) if cond...
Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name...
362,368
def _parse_request(self): self.req_method = self.req_params = {} self.req_rpc_version = self.req_id = 0 self.data = self.rfile.read(int(self.headers.get())) data_dict = json.loads(self.data) self.req_method = data_dict[] self.req_params = decode...
Parse the request
362,369
def _prepare_record(record, index, doc_type): if current_app.config[]: data = copy.deepcopy(record.replace_refs()) else: data = record.dumps() data[] = pytz.utc.localize(record.created).isoformat() \ if record.created else None data[] = pytz....
Prepare record data for indexing. :param record: The record to prepare. :param index: The Elasticsearch index. :param doc_type: The Elasticsearch document type. :returns: The record metadata.
362,370
def _get_longest_hit_at_ref_end(self, nucmer_hits, hits_to_exclude=None): if hits_to_exclude is None: hits_to_exclude = set() hits_at_end = [hit for hit in nucmer_hits if self._is_at_ref_end(hit) and hit not in hits_to_exclude] return self._get_longest_hit_by_ref_length(hits...
Input: list of nucmer hits to the same reference. Returns the longest hit to the end of the reference, or None if there is no such hit
362,371
def csv2dict(csv_filename, deli=, encoding=None, key_is_header=False): with open(csv_filename, encoding=encoding) as csv_file: if key_is_header: reader = csv.reader(csv_file, delimiter=deli) fieldnames = next(reader) reader = csv.DictReader(csv_file, fi...
将指定的 csv 文件转换为 list 返回; :param: * csv_filename: (string) csv 文件的长文件名 * deli: (string) csv 文件分隔符,默认为逗号 * del_blank_row: (string) 是否要删除空行,默认为删除 * encode: (string) 文件编码 :return: * csv_data: (dict) 读取后的数据 举例如下:: from fishbase.fish_file import * from fis...
362,372
def simulate_linear_model(A, x0, v, ts_length): r A = np.asarray(A) n = A.shape[0] x = np.empty((n, ts_length)) x[:, 0] = x0 for t in range(ts_length-1): for i in range(n): x[i, t+1] = v[i, t] for j in range(n): x[i, t+1...
r""" This is a separate function for simulating a vector linear system of the form .. math:: x_{t+1} = A x_t + v_t given :math:`x_0` = x0 Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n. The purpose of separating this functionality out is to target it for ...
362,373
def gen_binary(table, output, ascii_props=False, append=False, prefix=""): categories = [] binary_props = ( (, None), (, None), (, (, )) ) binary = {} for filename, include in binary_props: with codecs.open(os.path.join(HOME, , UNIVERSION, filename), , ) as uf: ...
Generate binary properties.
362,374
def download_and_install_dependencies(): try: import requests except ImportError: raise ValueError("Python 3.6+ is required.") dependencies = {"hmm_databases": HMM_URL} if sys.platform.startswith("linux") or "bsd" in sys.platform: dependencies["prodigal"] = "{}.linux".fo...
Setup URLS and download dependencies for Python 3.6+
362,375
def project_deidentify_template_path(cls, project, deidentify_template): return google.api_core.path_template.expand( "projects/{project}/deidentifyTemplates/{deidentify_template}", project=project, deidentify_template=deidentify_template, )
Return a fully-qualified project_deidentify_template string.
362,376
def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): bad_matrix = "invalid scoring matrix" s = s.rstrip( "\n" ) lines = s.split( "\n" ) rows = [] symbols2 = lines.pop(0).split() symbols1 = None rows_have_syms = False a_la_blastz = True for i,...
Initialize scoring scheme from a blastz style text blob, first line specifies the bases for each row/col, subsequent lines contain the corresponding scores. Slaw extensions allow for unusual and/or asymmetric alphabets. Symbols can be two digit hex, and each row begins with symbol. Note that a row co...
362,377
def tri_to_am(tri): r lil = sprs.lil_matrix((tri.npoints, tri.npoints)) indices, indptr = tri.vertex_neighbor_vertices for k in range(tri.npoints): lil.rows[k] = indptr[indices[k]:indices[k+1]] lil.data = lil.rows coo = lil.tocoo() am = am.tocoo() retur...
r""" Given a Delaunay Triangulation object from Scipy's ``spatial`` module, converts to a sparse adjacency matrix network representation. Parameters ---------- tri : Delaunay Triangulation Object This object is produced by ``scipy.spatial.Delaunay`` Returns ------- A sparse adj...
362,378
def min_tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float: a, b = set(x), set(y) if not a or not b: return 0.0 return len(a & b) / min(len(a), len(b))
Calculate the tanimoto set similarity using the minimum size. :param set x: A set :param set y: Another set :return: The similarity between
362,379
def _greater_or_close(a, value, **kwargs): r return (a > value) | np.isclose(a, value, **kwargs)
r"""Compare values for greater or close to boolean masks. Returns a boolean mask for values greater than or equal to a target within a specified absolute or relative tolerance (as in :func:`numpy.isclose`). Parameters ---------- a : array-like Array of values to be compared value : flo...
362,380
def download_page(url, data=None): conn = urllib2.urlopen(url, data) resp = conn.read() conn.close() return resp
Returns the response for the given url. The optional data argument is passed directly to urlopen.
362,381
def get_labels(self, field): return {c: self.cluster_meta.get(field, c) for c in self.clustering.cluster_ids}
Return the labels of all clusters, for a given field.
362,382
def should_indent(code): last = rem_comment(code.splitlines()[-1]) return last.endswith(":") or last.endswith("\\") or paren_change(last) < 0
Determines whether the next line should be indented.
362,383
def copy_to_clipboard(self, copy=True): urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) clipboard = QtWidgets.QApplication.clipboard() clipboard.setMimeData(mime)
Copies the selected items to the clipboard :param copy: True to copy, False to cut.
362,384
def get_dot_properties(prefix, props, remove_prefix): result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot_keys: if remove_prefix: new_key = dot_key[len(prefix) + 1 :] else: ...
Gets the properties starting with the given prefix
362,385
def multiple_replace(dict, text): regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
Replace in 'text' all occurences of any key in the given dictionary by its corresponding value. Returns the new string.
362,386
def start_in_sync(self): while True: agent_signal = self._signal_conn.recv() if agent_signal == DagParsingSignal.TERMINATE_MANAGER: self.terminate() break elif agent_signal == DagParsingSignal.END_MANAGER: self.end() ...
Parse DAG files in a loop controlled by DagParsingSignal. Actual DAG parsing loop will run once upon receiving one agent heartbeat message and will report done when finished the loop.
362,387
def completelist(self, text): path = os.path.expanduser(text) if len(path) == 0 or path[0] != os.path.sep: path = os.path.join(os.getcwd(), path) if text == : dpath = dtext = bpath = files = [] elif text.startswith() and text.fin...
Return a list of potential matches for completion n.b. you want to complete to a file in the current working directory that starts with a ~, use ./~ when typing in. Paths that start with ~ are magical and specify users' home paths
362,388
def data(self, index, role): if not index.isValid(): return None column = index.column() item = index.internalPointer() if role == self.ITEM_ROLE: return item elif role == Qt.DisplayRole: if column == 0: return item...
Return data for *index* according to *role*.
362,389
def solve(self,stops, method="POST", barriers=None, polylineBarriers=None, polygonBarriers=None, travelMode=None, attributeParameterValues=None, returnDirections=None, returnRoutes=True, returnS...
The solve operation is performed on a network layer resource. The solve operation is supported on a network layer whose layerType is esriNAServerRouteLayer. You can provide arguments to the solve route operation as query parameters. Inputs: stops - The set of stops loaded as ...
362,390
def replay_paths(self, replay_dir): replay_dir = self.abs_replay_path(replay_dir) if replay_dir.lower().endswith(".sc2replay"): yield replay_dir return for f in gfile.ListDir(replay_dir): if f.lower().endswith(".sc2replay"): yield os.path.join(replay_dir, f)
A generator yielding the full path to the replays under `replay_dir`.
362,391
def edge_length_sum(self, terminal=True, internal=True): if not isinstance(terminal, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") return sum(node.edge_length for node in self.travers...
Compute the sum of all selected edge lengths in this ``Tree`` Args: ``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False`` Returns: ``float``: Sum of al...
362,392
def replace(self, **kwargs): data = { : self._model, : self._filters, : self._order_by, : self._limit, : self._select, } data.update(**kwargs) return Query(**data)
Copy the Query object, optionally replacing the filters, order_by, or limit information on the copy. This is mostly an internal detail that you can ignore.
362,393
def _index_scan_prefix_impl(self, idx_name, val_prefix, retfunc): idx = self._index(idx_name)[] val_prefix = idx(val_prefix) idx_name = idx_name.encode() s = (val_prefix, idx_name) e = (val_prefix + , idx_name) keys = self.kvl.scan_keys(self.INDEX_TABLE, (s, e))...
Implementation for index_scan_prefix and index_scan_prefix_and_return_key, parameterized on return value function. retfunc gets passed a key tuple from the index: (index name, index value, content_id)
362,394
def adjust_for_custom_base_image(self): plugins = [] if self.is_custom_base_image(): plugins.append(("prebuild_plugins", "pull_base_image")) plugins.append(("prebuild_plugins", "koji_parent")) plugins.append(("prebuild_plugins", "inject_parent_im...
Disable plugins to handle builds depending on whether or not this is a build from a custom base image.
362,395
def reorder(self,*args,**kwargs): /my/dir/my_files_pattern*.nc trange_str = self.time_range()[0] cycle_list = self.cycle_list() track_list=self.track_list() precision=np.finfo(self.lon.dtype).precision-2 self.lon=self.lon.round(decimals=p...
Reorders data vectors in 2D (ie. with dimensions (CYCLE,RECORD)). This is useful to get a hovmoller-type matrix of each variable. :example: To plot a hovmoller for a given variable, do :: .. code-block:: pyhton data=alti_data('/my/dir/my_files_p...
362,396
def Main(): argument_parser = argparse.ArgumentParser(description=( )) argument_parser.add_argument( , dest=, type=str, help=( )) argument_parser.add_argument( , type=str, help=( )) options = argument_parser.parse_args() if not os.path.isdir(o...
The main program function. Returns: bool: True if successful or False if not.
362,397
def get_consensus_tree(self, cutoff=0.0, best_tree=None): if best_tree: raise NotImplementedError("best_tree option not yet supported.") cons = ConsensusTree(self.treelist, cutoff) cons.update() return cons.ttree
Returns an extended majority rule consensus tree as a Toytree object. Node labels include 'support' values showing the occurrence of clades in the consensus tree across trees in the input treelist. Clades with support below 'cutoff' are collapsed into polytomies. If you enter an option...
362,398
def qteGetMacroObject(self, macroName: str, widgetObj: QtGui.QWidget): if hasattr(widgetObj, ): app_signature = widgetObj._qteAdmin.appletSignature wid_signature = widgetObj._qteAdmin.widgetSignature ...
Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to ...
362,399
def ParseRecord(self, parser_mediator, key, structure): if key not in (, ): raise errors.ParseError( .format(key)) if key == : self._ParseLogline(parser_mediator, structure) elif key == : self._ParseNoHeaderSingleLine(parser_mediator, structure)
Parse each record structure and return an EventObject if applicable. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens. structure (pyparsing.ParseResults): struc...