code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_subgraph_by_annotations(graph, annotations, or_=None): """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 a...
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...
def _validate_label(self, label): """Validates label, raising error if invalid.""" 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(n...
Validates label, raising error if invalid.
def wrap_form_params(func): """ 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. """ @functools.wraps(fu...
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.
def extract_features_and_generate_model(essays, algorithm=util_functions.AlgorithmTypes.regression): """ 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 return...
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
def json_format(out, graph): """Outputs the graph in a machine readable JSON format.""" 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.
def _get_prep_params(data): """Retrieve configuration parameters with defaults for preparing BAM files. """ 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.
def update_permission(obj, data): """Update object permissions.""" full_permissions = get_all_perms(obj) def apply_perm(perm_func, perms, entity): """Apply permissions using given ``perm_func``. ``perm_func`` is intended to be ``assign_perms`` or ``remove_perms`` shortcut function ...
Update object permissions.
def user_has(ability, get_user=import_user): """ Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability """ def wrapper(func): @wraps(func) def inner(*args, **kwargs): from .models import Ability desir...
Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability
def request(self, method, path, params=None, headers=None, body=None): """ Base method for making a Losant API request """ if not headers: headers = {} if not params: params = {} headers["Accept"] = "application/json" headers["Accept-Version"] = "^1.15.0"...
Base method for making a Losant API request
def get_dimensions_from_user(self, no_dim): """Queries grid dimensions in a model dialog and returns n-tuple Parameters ---------- no_dim: Integer \t Number of grid dimensions, currently must be 3 """ # Grid dimension dialog if no_dim != 3: ...
Queries grid dimensions in a model dialog and returns n-tuple Parameters ---------- no_dim: Integer \t Number of grid dimensions, currently must be 3
async def _move(self, target_position: 'OrderedDict[Axis, float]', speed: float = None, home_flagged_axes: bool = True): """ 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 ...
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...
def from_cryptography_key(cls, crypto_key): """ 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 """ pkey ...
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
def find_home_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``. """ ...
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``.
def get_environ(cls, 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. """ return ((key[len(prefix) + 1:], value) ...
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.
def parse(line): """ 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. - que...
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...
def detect_batch(self, batch): """ Return detections for batch :param batch: :return: """ self.mod.forward(batch, is_train=False) detections = self.mod.get_outputs()[0] positive_detections = Detector.filter_positive_detections(detections) return po...
Return detections for batch :param batch: :return:
def plotEz(self,*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) """ if...
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)
def from_image(cls, image, filename): """ Filename is 1-8 alphanumeric characters to identify the GRF in ZPL. """ source = Image.open(BytesIO(image)) source = source.convert('1') width = int(math.ceil(source.size[0] / 8.0)) data = [] for line in _chunked...
Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.
def GetHasherNamesFromString(cls, hasher_names_string): """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, ...
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...
def get_dbg_brk_linux32(): ''' Return the current brk value in the debugged process (only x86 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\xcd\x80' # int 0x80 eax = debugger.get_reg("eax") ...
Return the current brk value in the debugged process (only x86 Linux)
def is_frond(u, v, dfs_data): """Determines if the edge uv is a frond ("backedge").""" d_u = D(u, dfs_data) d_v = D(v, dfs_data) edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(u, v) return True if dfs_data['edge_lookup'][edge_id] == 'backedge' and d_v < d_u else False
Determines if the edge uv is a frond ("backedge").
def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' 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
def deprecated(conditional=True): """ 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 -------...
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...
def fuzzy_match(image, template, normed_tolerance=None, raw_tolerance=None, method='correlation'): """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 i...
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...
def formatTimeFromNow(secs=None): """ 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 """ return d...
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
def read(self, b=-1): """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 """ remaining_byte...
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
def update_devices(self, selection=None): """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...
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.
def handle(cls, value, context, **kwargs): """Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key> """ try: hook_name, key = value.split("::") except ValueError: raise ValueError("Invalid value for hoo...
Returns the value of a key for a given hook in hook_data. Format of value: <hook_name>::<key>
def delete_individual(self, ind_obj): """Delete a case from the database Args: ind_obj (puzzle.models.Individual): initialized individual model """ logger.info("Deleting individual {0} from database" .format(ind_obj.ind_id)) self.session.delete(in...
Delete a case from the database Args: ind_obj (puzzle.models.Individual): initialized individual model
def query_record_useful_review(comID, value): """ 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 """ # retrieve nb_useful votes query1 = """...
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
def to_pinyin(s, accented=True): """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. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s i...
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.
def helical_turbulent_Nu_Mori_Nakayama(Re, Pr, Di, Dc): 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`: .. ma...
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...
def disable_contactgroup_svc_notifications(self, contactgroup): """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 con...
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
def delete_vm_image(self, vm_image_name, delete_vhd=False): ''' 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 ...
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.
def encodeBinaryData(dataArray, bitEncoding, compression): """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 :ret...
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
def get_default(self, node): """ Unless specified otherwise, intr fields are implicitly stickybit """ if node.inst.properties.get("intr", False): # Interrupt is set! # Default is implicitly stickybit, unless the mutually-exclusive # sticky property was...
Unless specified otherwise, intr fields are implicitly stickybit
def write_table(self): """ |write_table|. .. note:: - |None| values are written as an empty string. """ 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.
def start(self): ''' Listen to messages and publish them. ''' self._setup_ipc() # Start suicide polling thread thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),)) thread.start() signal.signal(signal.SIGTERM, self._exit...
Listen to messages and publish them.
def _qualify_map(key, content): """ 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. """ if not isinstance(key, basestring): return key, content ...
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.
def getheader (self, name, default=None): """Get decoded header value. @return: decoded header value or default of not found @rtype: unicode or type of default """ value = self.headers.get(name) if value is None: return default return unicode_safe(val...
Get decoded header value. @return: decoded header value or default of not found @rtype: unicode or type of default
def download_memory_dump(self, sha256, environment_id, dest_dir): """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.""" dest_path = os.path.join(dest_dir, 'memory.zip') if...
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.
async def unsafe_ask_async(self, patch_stdout: bool = False) -> Any: """Ask the question using asyncio and return user response. Does not catch keyboard interrupts.""" if not utils.ACTIVATED_ASYNC_MODE: await utils.activate_prompt_toolkit_async_mode() if patch_stdout: ...
Ask the question using asyncio and return user response. Does not catch keyboard interrupts.
def generate_import_code(pipeline, operators, impute=False): """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 : b...
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...
def get_config(): """Get the configurations from .tldrrc and return it as a dict.""" config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if not path.exists(config_path): sys.exit("Can't find config file at: {0}. You may use `tldr init` " ...
Get the configurations from .tldrrc and return it as a dict.
def from_envvar(self, variable_name, silent=False): """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_SETTING...
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...
def create_layer(self, lipid_indices=None, flip_orientation=False): """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, defau...
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...
def to_satoshis(input_quantity, input_type): ''' convert to satoshis, no rounding ''' assert input_type in UNIT_CHOICES, input_type # convert to satoshis if input_type in ('btc', 'mbtc', 'bit'): satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per']) elif input_t...
convert to satoshis, no rounding
def setup(self): """ Create mask list. Consists of all tuples between which this filter accepts lines. """ # get start and end of the mask and set a start_limit if not self.mask_source.start: raise SystemExit("Can't parse format of %s. Is this a log file or "...
Create mask list. Consists of all tuples between which this filter accepts lines.
def get_proteins_psms_for_map(self): """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""" fields = ['p.gene_acc', 'sets.set_name', 'pep.sequence'...
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
def set_timestamp(self,timestamp=None): """ Set the timestamp of the linguistic processor, set to None for the current time @type timestamp:string @param timestamp: version of the linguistic processor """ if timestamp is None: import time 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
def segment(filenames, format, **options): """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: ...
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 ...
def sign(self, M, t=None, h=None, mgf=None, sLen=None): """ 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...
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...
def fit(ts, fs=[], all_params=[], fit_vars=None, alg='leastsq', make_bounded=True): """ Use a minimization algorithm to fit a AstonSeries with analytical functions. """ if fit_vars is None: fit_vars = [f._peakargs for f in fs] initc = [min(ts.values)] for f, peak_params, to_f...
Use a minimization algorithm to fit a AstonSeries with analytical functions.
def _sync(self, timeout_ms=30000): """ Reimplements MatrixClient._sync, add 'account_data' support to /sync """ 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: ...
Reimplements MatrixClient._sync, add 'account_data' support to /sync
def polyline(self, arr): """Draw a set of lines""" 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
def add_input(self, **kwargs): """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 i...
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'`). ...
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)): '''Return given point rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis. ''' assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i,...
Return given point rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis.
def get_items(self, url, container, container_object, local_object): """Get an objects from a container. :param url: :param container: """ headers, container_uri = self._return_base_data( url=url, container=container, container_object=contain...
Get an objects from a container. :param url: :param container:
def update_translations(self, project_id, file_path=None, language_code=None, overwrite=False, fuzzy_trigger=None): """ Updates translations overwrite: set it to True if you want to overwrite definitions fuzzy_trigger: set it to True to mark corresponding tra...
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
def wsvg(paths=None, colors=None, filename=os_path.join(getcwd(), 'disvg_output.svg'), 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_pa...
Convenience function; identical to disvg() except that openinbrowser=False by default. See disvg() docstring for more info.
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" 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: br...
Yields all links with the given relations
def constrain_property(self,prop,**kwargs): """ Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments passed to that function for each population. """ if prop not in self.constraints: self.constraint...
Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments passed to that function for each population.
def get_reply(session, url, post=False, data=None, headers=None, quiet=False): """ 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...
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...
def _remove(self, client_kwargs): """ Remove an object. args: client_kwargs (dict): Client arguments. """ with _handle_azure_exception(): # File if 'file_name' in client_kwargs: return self.client.delete_file( ...
Remove an object. args: client_kwargs (dict): Client arguments.
def request_instance(vm_=None, call=None): ''' 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 ''' if call == 'function': # Technically this function may be called other w...
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
def center_of_mass(self, scalars_weight=False): """ 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 ------ ...
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...
def is_mapped_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 """ _, dirs, _ = next(os.walk( '/sys/class/block/{}/holders/' .format(os.path.basename(os....
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
def get_command_instance(name, parent=None, checkexists=True): """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 usin...
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...
def _parse_request(self): ''' Parse the request ''' self.req_method = 'unknown' self.req_params = {} self.req_rpc_version = '2.0' self.req_id = 0 self.data = self.rfile.read(int(self.headers.get('content-length'))) data_dict = json.loads(self.data)...
Parse the request
def _prepare_record(record, index, doc_type): """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. """ if current_app.con...
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.
def _get_longest_hit_at_ref_end(self, nucmer_hits, hits_to_exclude=None): '''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''' if hits_to_exclude is None: hits_to_exclude = set() hits_at_end = [hi...
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
def csv2dict(csv_filename, deli=',', encoding=None, key_is_header=False): """ 将指定的 csv 文件转换为 list 返回; :param: * csv_filename: (string) csv 文件的长文件名 * deli: (string) csv 文件分隔符,默认为逗号 * del_blank_row: (string) 是否要删除空行,默认为删除 * encode: (string) 文件编码 :return: * csv_dat...
将指定的 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...
def simulate_linear_model(A, x0, v, ts_length): 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 separa...
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 ...
def gen_binary(table, output, ascii_props=False, append=False, prefix=""): """Generate binary properties.""" categories = [] binary_props = ( ('DerivedCoreProperties.txt', None), ('PropList.txt', None), ('DerivedNormalizationProps.txt', ('Changes_When_NFKC_Casefolded', 'Full_Composi...
Generate binary properties.
def download_and_install_dependencies(): """Setup URLS and download dependencies for Python 3.6+ """ 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 ...
Setup URLS and download dependencies for Python 3.6+
def project_deidentify_template_path(cls, project, deidentify_template): """Return a fully-qualified project_deidentify_template string.""" return google.api_core.path_template.expand( "projects/{project}/deidentifyTemplates/{deidentify_template}", project=project, de...
Return a fully-qualified project_deidentify_template string.
def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): """ 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 al...
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...
def tri_to_am(tri): 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 ...
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...
def min_tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float: """Calculate the tanimoto set similarity using the minimum size. :param set x: A set :param set y: Another set :return: The similarity between """ a, b = set(x), set(y) if not a or not b: return 0.0 ...
Calculate the tanimoto set similarity using the minimum size. :param set x: A set :param set y: Another set :return: The similarity between
def _greater_or_close(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 ...
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...
def download_page(url, data=None): '''Returns the response for the given url. The optional data argument is passed directly to urlopen.''' 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.
def get_labels(self, field): """Return the labels of all clusters, for a given 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.
def should_indent(code): """Determines whether the next line should be indented.""" 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.
def copy_to_clipboard(self, copy=True): """ Copies the selected items to the clipboard :param copy: True to copy, False to cut. """ urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) c...
Copies the selected items to the clipboard :param copy: True to copy, False to cut.
def get_dot_properties(prefix, props, remove_prefix): # type: (str, Dict[str, Any], bool) -> Dict[str, Any] """ Gets the properties starting with the given prefix """ result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot...
Gets the properties starting with the given prefix
def multiple_replace(dict, text): """ Replace in 'text' all occurences of any key in the given dictionary by its corresponding value. Returns the new string.""" # Function by Xavier Defrang, originally found at: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # Create a regular ex...
Replace in 'text' all occurences of any key in the given dictionary by its corresponding value. Returns the new string.
def start_in_sync(self): """ 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. """ while True: agent_signal = self._signal_con...
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.
def completelist(self, text): """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 """ ...
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
def data(self, index, role): '''Return data for *index* according to *role*.''' if not index.isValid(): return None column = index.column() item = index.internalPointer() if role == self.ITEM_ROLE: return item elif role == Qt.DisplayRole: ...
Return data for *index* according to *role*.
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 ...
def replay_paths(self, replay_dir): """A generator yielding the full path to the replays under `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(...
A generator yielding the full path to the replays under `replay_dir`.
def edge_length_sum(self, terminal=True, internal=True): '''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, ot...
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...
def replace(self, **kwargs): ''' 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. ''' data = { 'model': self._model, 'filters': self._filters...
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.
def _index_scan_prefix_impl(self, idx_name, val_prefix, retfunc): '''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) '...
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)
def adjust_for_custom_base_image(self): """ Disable plugins to handle builds depending on whether or not this is a build from a custom base image. """ plugins = [] if self.is_custom_base_image(): # Plugins irrelevant to building base images. plugin...
Disable plugins to handle builds depending on whether or not this is a build from a custom base image.
def reorder(self,*args,**kwargs): ''' 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 ...
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...
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Plots memory usage from profiling data.')) argument_parser.add_argument( '--output', dest='output_file', type=str, help=( 'path ...
The main program function. Returns: bool: True if successful or False if not.
def get_consensus_tree(self, cutoff=0.0, best_tree=None): """ 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 suppor...
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...
def qteGetMacroObject(self, macroName: str, widgetObj: QtGui.QWidget): """ 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...
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 ...
def ParseRecord(self, parser_mediator, key, 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 struc...
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...