code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def marker(self, marker_name=None, label=None, color=None, retina=False): """Returns a single marker image without any background map. Parameters ---------- marker_name : str The marker's shape and size. label : str, optional T...
Returns a single marker image without any background map. Parameters ---------- marker_name : str The marker's shape and size. label : str, optional The marker's alphanumeric label. Options are a through z, 0 through 99, or the ...
def logical_xor(self, other): """logical_xor(t) = self(t) ^ other(t).""" return self.operation(other, lambda x, y: int(bool(x) ^ bool(y)))
logical_xor(t) = self(t) ^ other(t).
def process_raw_file(self, raw_file_name, field_names): """ takes the filename to be read and uses the maps setup on class instantiation to process the file. This is a top level function and uses self.maps which should be the column descriptions (in order). """ ...
takes the filename to be read and uses the maps setup on class instantiation to process the file. This is a top level function and uses self.maps which should be the column descriptions (in order).
def gmres_mgs(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, M=None, callback=None, residuals=None, reorth=False): """Generalized Minimum Residual Method (GMRES) based on MGS. GMRES iteratively refines the initial solution guess to the system Ax = b Modified Gram-Schmidt ...
Generalized Minimum Residual Method (GMRES) based on MGS. GMRES iteratively refines the initial solution guess to the system Ax = b Modified Gram-Schmidt version Parameters ---------- A : array, matrix, sparse matrix, LinearOperator n x n, linear system to solve b : array, matrix ...
def logout(config): """Remove and forget your Bugzilla credentials""" state = read(config.configfile) if state.get("BUGZILLA"): remove(config.configfile, "BUGZILLA") success_out("Forgotten") else: error_out("No stored Bugzilla credentials")
Remove and forget your Bugzilla credentials
def flatten(l, types=(list, )): """ Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple -...
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple - the original input is returned as a list
def Percentile(pmf, percentage): """Computes a percentile of a given Pmf. percentage: float 0-100 """ p = percentage / 100.0 total = 0 for val, prob in pmf.Items(): total += prob if total >= p: return val
Computes a percentile of a given Pmf. percentage: float 0-100
def detect_version(env, cc): """Return the version of the GNU compiler, or None if it is not a GNU compiler.""" cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Uti...
Return the version of the GNU compiler, or None if it is not a GNU compiler.
def calculate_lvgd_voltage_current_stats(nw): """ LV Voltage and Current Statistics for an arbitrary network Note ---- Aggregated Load Areas are excluded. Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- pandas.Data...
LV Voltage and Current Statistics for an arbitrary network Note ---- Aggregated Load Areas are excluded. Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- pandas.DataFrame nodes_df : Dataframe containing voltage, res...
def jco_from_pestpp_runstorage(rnj_filename,pst_filename): """ read pars and obs from a pest++ serialized run storage file (e.g., .rnj) and return pyemu.Jco. This can then be passed to Jco.to_binary or Jco.to_coo, etc., to write jco file in a subsequent step to avoid memory resource issues associated with...
read pars and obs from a pest++ serialized run storage file (e.g., .rnj) and return pyemu.Jco. This can then be passed to Jco.to_binary or Jco.to_coo, etc., to write jco file in a subsequent step to avoid memory resource issues associated with very large problems. Parameters ---------- rnj_filena...
def find_file_regex(root_dir,re_expression,return_abs_path = True,search_sub_directories = True): ''' Finds all the files with the specified root directory with the name matching the regex expression. Args : root_dir : The root directory. re_expression ...
Finds all the files with the specified root directory with the name matching the regex expression. Args : root_dir : The root directory. re_expression : The regex expression. return_abs_path : If set to true, returns the absolute path of th...
def regression(): """ Run regression testing - lint and then run all tests. """ # HACK: Start using hitchbuildpy to get around this. Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run() storybook = _storybook({}).only_uninherited() #storybook.with_params(**{"pyt...
Run regression testing - lint and then run all tests.
def check_dataset(dataset): """Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK.""" if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4: check_dataset_shape(dataset) check_dataset_range(dataset) else: # must be a list of arrays or a 4D NumPy array ...
Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK.
def get(self, sid): """ Constructs a FaxMediaContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext """ return FaxMediaContex...
Constructs a FaxMediaContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext
def create_bv_bitmap(dot_product_vector: str, dot_product_bias: str) -> Dict[str, str]: """ This function creates a map from bitstring to function value for a boolean formula :math:`f` with a dot product vector :math:`a` and a dot product bias :math:`b` .. math:: f:\\{0,1\\}^n\\rightarr...
This function creates a map from bitstring to function value for a boolean formula :math:`f` with a dot product vector :math:`a` and a dot product bias :math:`b` .. math:: f:\\{0,1\\}^n\\rightarrow \\{0,1\\} \\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2} ...
def _node_add_with_peer_list(self, child_self, child_other): '''_node_add_with_peer_list Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are list nodes. Element child_self will be modified during the pro...
_node_add_with_peer_list Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are list nodes. Element child_self will be modified during the process. RFC6020 section 7.8.6 is a reference of this method. ...
def evaluate_scpd_xml(url): """ Get and evaluate SCPD XML to identified URLs. Returns dictionary with keys "host", "modelName", "friendlyName" and "presentationURL" if a Denon AVR device was found and "False" if not. """ # Get SCPD XML via HTTP GET try: res = requests.get(url, timeo...
Get and evaluate SCPD XML to identified URLs. Returns dictionary with keys "host", "modelName", "friendlyName" and "presentationURL" if a Denon AVR device was found and "False" if not.
def delete_rich_menu(self, rich_menu_id, timeout=None): """Call delete rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server ...
Call delete rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (conne...
def deactivate(self): """ Deactivates the Component. :return: Method success. :rtype: bool """ LOGGER.debug("> Deactivating '{0}' Component.".format(self.__class__.__name__)) self.__engine = None self.__settings = None self.__settings_section = ...
Deactivates the Component. :return: Method success. :rtype: bool
def adduser(username, uid=None, system=False, no_login=True, no_password=False, group=False, gecos=None, **kwargs): """ Formats an ``adduser`` command. :param username: User name. :type username: unicode | str :param uid: Optional user id to use. :type uid: long | int :param system: Create ...
Formats an ``adduser`` command. :param username: User name. :type username: unicode | str :param uid: Optional user id to use. :type uid: long | int :param system: Create a system user account. :type system: bool :param no_login: Disable the login for this user. Not compatible with CentOS. ...
def transaction(self): """ Sets up a context where all the statements within it are ran within a single database transaction. For internal use only. """ # The idea here is to fake the nesting of transactions. Only when # we've gotten back to the topmost transaction contex...
Sets up a context where all the statements within it are ran within a single database transaction. For internal use only.
def slides(self): """ |Slides| object containing the slides in this presentation. """ sldIdLst = self._element.get_or_add_sldIdLst() self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst]) return Slides(sldIdLst, self)
|Slides| object containing the slides in this presentation.
def job_conf(self, job_id): """ A job configuration resource contains information about the job configuration for this job. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ pa...
A job configuration resource contains information about the job configuration for this job. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
def get_agg_data(cls, obj, category=None): """ Reduces any Overlay or NdOverlay of Elements into a single xarray Dataset that can be aggregated. """ paths = [] if isinstance(obj, Graph): obj = obj.edgepaths kdims = list(obj.kdims) vdims = list(...
Reduces any Overlay or NdOverlay of Elements into a single xarray Dataset that can be aggregated.
def list_spiders(self, project): """ Lists all known spiders for a specific project. First class, maps to Scrapyd's list spiders endpoint. """ url = self._build_url(constants.LIST_SPIDERS_ENDPOINT) params = {'project': project} json = self.client.get(url, params=p...
Lists all known spiders for a specific project. First class, maps to Scrapyd's list spiders endpoint.
def retry(func, exception_type, quit_event): """ Run the function, retrying when the specified exception_type occurs. Poll quit_event on each iteration, to be responsive to an external exit request. """ while True: if quit_event.is_set(): raise StopIteration try: ...
Run the function, retrying when the specified exception_type occurs. Poll quit_event on each iteration, to be responsive to an external exit request.
def eigh(a, eigvec=True, rcond=None): """ Eigenvalues and eigenvectors of symmetric matrix ``a``. Args: a: Two-dimensional, square Hermitian matrix/array of numbers and/or :class:`gvar.GVar`\s. Array elements must be real-valued if `gvar.GVar`\s are involved (i.e., symmetric ...
Eigenvalues and eigenvectors of symmetric matrix ``a``. Args: a: Two-dimensional, square Hermitian matrix/array of numbers and/or :class:`gvar.GVar`\s. Array elements must be real-valued if `gvar.GVar`\s are involved (i.e., symmetric matrix). eigvec (bool): If ``...
def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records already exist in the module mapping list, # it likely means that a package declared multiple keys for the # same package name...
Store the records in a way that permit lookup by package
def get_params(self, deep=False): """ returns a dict of all of the object's user-facing parameters Parameters ---------- deep : boolean, default: False when True, also gets non-user-facing paramters Returns ------- dict """ at...
returns a dict of all of the object's user-facing parameters Parameters ---------- deep : boolean, default: False when True, also gets non-user-facing paramters Returns ------- dict
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The ident...
Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :ret...
def parse_uniprot_txt_file(infile): """Parse a raw UniProt metadata file and return a dictionary. Args: infile: Path to metadata file Returns: dict: Metadata dictionary """ uniprot_metadata_dict = {} metadata = old_parse_uniprot_txt_file(infile) metadata_keys = list(metad...
Parse a raw UniProt metadata file and return a dictionary. Args: infile: Path to metadata file Returns: dict: Metadata dictionary
def splitEkmDate(dateint): """Break out a date from Omnimeter read. Note a corrupt date will raise an exception when you convert it to int to hand to this method. Args: dateint (int): Omnimeter datetime as int. Returns: tuple: Named tuple which breaks ...
Break out a date from Omnimeter read. Note a corrupt date will raise an exception when you convert it to int to hand to this method. Args: dateint (int): Omnimeter datetime as int. Returns: tuple: Named tuple which breaks out as followws: ========...
def rsa_base64_decrypt(self, cipher, b64=True): """ 先base64 解码 再rsa 解密数据 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) _cip = PKCS1_v1_5.new(key_) cipher = base64.b64decode(cipher) if b64 else cipher plain = _cip.d...
先base64 解码 再rsa 解密数据
def clearAdvancedActions( self ): """ Clears out the advanced action map. """ self._advancedMap.clear() margins = list(self.getContentsMargins()) margins[2] = 0 self.setContentsMargins(*margins)
Clears out the advanced action map.
def select_if(df, fun): """Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns """ def _filter_f(col): try: return fun(df[col]) except: return False cols = list(filter(_filter_f, df.columns)) return df[c...
Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs): """Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting function ``fc_func``, optionally including the calculated seasonality. This is an additive model, Y[t] = T[t] + S[t] + e[t] Args: ...
Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting function ``fc_func``, optionally including the calculated seasonality. This is an additive model, Y[t] = T[t] + S[t] + e[t] Args: stl (a modified statsmodels.tsa.seasonal.DecomposeResult): STL decomposi...
def all(self): """ :return: array of file objects (200 status code) """ url = "{url_base}/resource/{pid}/files/".format(url_base=self.hs.url_base, pid=self.pid) r = self.hs._request('GET', url) ...
:return: array of file objects (200 status code)
def make_jira_blueprint( base_url, consumer_key=None, rsa_key=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with JIRA using OAuth 1. This requires a consumer key...
Make a blueprint for authenticating with JIRA using OAuth 1. This requires a consumer key and RSA key for the JIRA application link. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`JIRA_OAUTH_CONSUMER_KEY` and :e...
def deletePartials(self): """ Delete any old partial uploads/downloads in path. """ if self.dryrun: self._client.listPartials() else: self._client.deletePartials()
Delete any old partial uploads/downloads in path.
def items(iterable): """ Iterates over the items of a sequence. If the sequence supports the dictionary protocol (iteritems/items) then we use that. Otherwise we use the enumerate built-in function. """ if hasattr(iterable, 'iteritems'): return (p for p in iterable.iteritems()) e...
Iterates over the items of a sequence. If the sequence supports the dictionary protocol (iteritems/items) then we use that. Otherwise we use the enumerate built-in function.
def get_part_name(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `part_name` record is not found. Returns: str: Name of the part of the series. or `undefined` if `part_name`\ is not foun...
Args: undefined (optional): Argument, which will be returned if the `part_name` record is not found. Returns: str: Name of the part of the series. or `undefined` if `part_name`\ is not found.
def register_phonon_task(self, *args, **kwargs): """Register a phonon task.""" kwargs["task_class"] = PhononTask return self.register_task(*args, **kwargs)
Register a phonon task.
def get_default_saver(max_to_keep: int=3) -> tf.train.Saver: """ Creates Tensorflow Saver object with 3 recent checkpoints to keep. :param max_to_keep: Maximum number of recent checkpoints to keep, defaults to 3 """ return tf.train.Saver(max_to_keep=max_to_keep)
Creates Tensorflow Saver object with 3 recent checkpoints to keep. :param max_to_keep: Maximum number of recent checkpoints to keep, defaults to 3
def generate_stimfunction(onsets, event_durations, total_time, weights=[1], timing_file=None, temporal_resolution=100.0, ): """Return the function for the timec...
Return the function for the timecourse events When do stimuli onset, how long for and to what extent should you resolve the fMRI time course. There are two ways to create this, either by supplying onset, duration and weight information or by supplying a timing file (in the three column format used by F...
def to_text(self, tree, force_root=False): """ Extract text from tags. Skip any selectors specified and include attributes if specified. Ignored tags will not have their attributes scanned either. """ self.extract_tag_metadata(tree) text = [] attributes...
Extract text from tags. Skip any selectors specified and include attributes if specified. Ignored tags will not have their attributes scanned either.
def find_analyses(ar_or_sample): """ This function is used to find keywords that are not on the analysis but keywords that are on the interim fields. This function and is is_keyword function should probably be in resultsimport.py or somewhere central where it can be used by other in...
This function is used to find keywords that are not on the analysis but keywords that are on the interim fields. This function and is is_keyword function should probably be in resultsimport.py or somewhere central where it can be used by other instrument interfaces.
def match_similar(base, items): """Get the most similar matching item from a list of items. @param base: base item to locate best match @param items: list of items for comparison @return: most similar matching item or None """ finds = list(find_similar(base, items)) if finds: retur...
Get the most similar matching item from a list of items. @param base: base item to locate best match @param items: list of items for comparison @return: most similar matching item or None
def dcounts(self): """ :return: a data frame with names and distinct counts and fractions for all columns in the database """ print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr) sys.stderr.flush() data = [] for t in self...
:return: a data frame with names and distinct counts and fractions for all columns in the database
def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly): """Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extr...
Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extracted. islitlet : int Slitlet number. csu_bar_slit_center : float CSU bar slit center. params : :class:`~lmfit...
def CreateJarBuilder(env): """The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package int...
The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package into the jar.
def _init_data_map(self): """ OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions """ if self._data_map is not None: return # Initiation happens once # Parse and validate the ArcGIS metadata root if self._xml_tree is None: agis_...
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions
def printBoundingBox(self): '''Print the bounding box that this DEM covers''' print ("Bounding Latitude: ") print (self.startlatitude) print (self.endlatitude) print ("Bounding Longitude: ") print (self.startlongitude) print (self.endlongitude)
Print the bounding box that this DEM covers
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None, **kw): """Returns a ProcessingChain which needs to be passed to Receive if Send is being called consecutively. """ url = url or self.url cookies = None if chain is not None: ...
Returns a ProcessingChain which needs to be passed to Receive if Send is being called consecutively.
def __delete_action(self, revision): """ Handle a delete action to a partiular master id via the revision. :param dict revision: :return: """ delete_response = yield self.collection.delete(revision.get("master_id")) if delete_response.get("n") == 0: r...
Handle a delete action to a partiular master id via the revision. :param dict revision: :return:
def columnSchema(self): """ Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0 """ if self._columnSchema i...
Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0
def update(self, unique_name=values.unset, default_ttl=values.unset, callback_url=values.unset, geo_match_level=values.unset, number_selection_behavior=values.unset, intercept_callback_url=values.unset, out_of_session_callback_url=values.unset, ...
Update the ServiceInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :param unicode default_ttl: Default TTL for a Session, in seconds :param unicode callback_url: The URL we should call when the interaction status changes :param Ser...
def get_lazystring_encoder(app): """Return a JSONEncoder for handling lazy strings from Babel. Installed on Flask application by default by :class:`InvenioI18N`. """ from speaklater import _LazyString class JSONEncoder(app.json_encoder): def default(self, o): if isinstance(o, ...
Return a JSONEncoder for handling lazy strings from Babel. Installed on Flask application by default by :class:`InvenioI18N`.
def clear(self, exclude=None): """ Remove all elements in the cache. """ if exclude is None: self.cache = {} else: self.cache = {k: v for k, v in self.cache.items() if k in exclude}
Remove all elements in the cache.
def on_message(self, message): """ Receiving a message from the websocket, parse, and act accordingly. """ msg = tornado.escape.json_decode(message) if msg['type'] == 'config_file': if self.application.verbose: print(msg['data']) self.config = list(yam...
Receiving a message from the websocket, parse, and act accordingly.
def cleanup_dead_jobs(): """ This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant to cleanup jobs that have been lost due to a server crash or some other reason a job is in limbo. """ from .models import WooeyJob # Get active tasks from Celery ins...
This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant to cleanup jobs that have been lost due to a server crash or some other reason a job is in limbo.
def partial_fit(self, X, y=None, classes=None, **fit_params): """Fit the module. If the module is initialized, it is not re-initialized, which means that this method should be used if you want to continue training a model (warm start). Parameters ---------- X : ...
Fit the module. If the module is initialized, it is not re-initialized, which means that this method should be used if you want to continue training a model (warm start). Parameters ---------- X : input data, compatible with skorch.dataset.Dataset By default, ...
def compute_number_edges(function): """ Compute the number of edges of the CFG Args: function (core.declarations.function.Function) Returns: int """ n = 0 for node in function.nodes: n += len(node.sons) return n
Compute the number of edges of the CFG Args: function (core.declarations.function.Function) Returns: int
def reversed(self): """returns a copy of the Arc object with its orientation reversed.""" return Arc(self.end, self.radius, self.rotation, self.large_arc, not self.sweep, self.start)
returns a copy of the Arc object with its orientation reversed.
def resolve_identifier(self, name, expected_type=None): """Resolve an identifier to an object. There is a single namespace for identifiers so the user also should pass an expected type that will be checked against what the identifier actually resolves to so that there are no surprises. ...
Resolve an identifier to an object. There is a single namespace for identifiers so the user also should pass an expected type that will be checked against what the identifier actually resolves to so that there are no surprises. Args: name (str): The name that we want to res...
def log_event(self, text, timestamp=None): """Add an arbitrary message to the log file as a global marker. :param str text: The group name of the marker. :param float timestamp: Absolute timestamp in Unix timestamp format. If not given, the marker will be pla...
Add an arbitrary message to the log file as a global marker. :param str text: The group name of the marker. :param float timestamp: Absolute timestamp in Unix timestamp format. If not given, the marker will be placed along the last message.
def dict_dot(d, k, val=None, default=None): """Get or set value using a dot-notation key in a multilevel dict.""" if val is None and k == '': return d def set_default(dict_or_model, key, default_value): """Set default field value.""" if isinstance(dict_or_model, models.Model): ...
Get or set value using a dot-notation key in a multilevel dict.
def q12d_local(vertices, lame, mu): """Local stiffness matrix for two dimensional elasticity on a square element. Parameters ---------- lame : Float Lame's first parameter mu : Float shear modulus See Also -------- linear_elasticity Notes ----- Vertices sho...
Local stiffness matrix for two dimensional elasticity on a square element. Parameters ---------- lame : Float Lame's first parameter mu : Float shear modulus See Also -------- linear_elasticity Notes ----- Vertices should be listed in counter-clockwise order:: ...
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): """Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data ...
Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data column is column 1. :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it...
def diagonal_line(xi=None, yi=None, *, ax=None, c=None, ls=None, lw=None, zorder=3): """Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken...
Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken from axis limits. Default is None. ax : axis (optional) Axis to plot on. If non...
def notify( self, force_notify=None, use_email=None, use_sms=None, email_body_template=None, **kwargs, ): """Notify / send an email and/or SMS. Main entry point. This notification class (me) knows from whom and to whom the notificatio...
Notify / send an email and/or SMS. Main entry point. This notification class (me) knows from whom and to whom the notifications will be sent. See signals and kwargs are: * history_instance * instance * user
def trace(): """Enables and disables request tracing.""" def fget(self): return self._options.get('trace', None) def fset(self, value): self._options['trace'] = value return locals()
Enables and disables request tracing.
def parse_acl(acl_string): """ Parse raw string :acl_string: of RAML-defined ACLs. If :acl_string: is blank or None, all permissions are given. Values of ACL action and principal are parsed using `actions` and `special_principals` maps and are looked up after `strip()` and `lower()`. ACEs in :...
Parse raw string :acl_string: of RAML-defined ACLs. If :acl_string: is blank or None, all permissions are given. Values of ACL action and principal are parsed using `actions` and `special_principals` maps and are looked up after `strip()` and `lower()`. ACEs in :acl_string: may be separated by new...
def orcid_uri_to_orcid(value): "Strip the uri schema from the start of ORCID URL strings" if value is None: return value replace_values = ['http://orcid.org/', 'https://orcid.org/'] for replace_value in replace_values: value = value.replace(replace_value, '') return value
Strip the uri schema from the start of ORCID URL strings
def __iter_read_spectrum_meta(self): """ This method should only be called by __init__. Reads the data formats, coordinates and offsets from the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum metadata is pruned, i.e. the <spectrumLi...
This method should only be called by __init__. Reads the data formats, coordinates and offsets from the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty. Supported ...
def delete_eventtype(self, test_type_str=None): """Action: create dialog to delete event type.""" if test_type_str: answer = test_type_str, True else: answer = QInputDialog.getText(self, 'Delete Event Type', 'Enter event\'s name t...
Action: create dialog to delete event type.
def introspect_access_token(self, access_token_value): # type: (str) -> Dict[str, Union[str, List[str]]] """ Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>. """ if acces...
Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>.
def _reload(self): """ Gets every registered form's field value.\ If a field name is found in the db, it will load it from there.\ Otherwise, the initial value from the field form is used """ ConfigModel = apps.get_model('djconfig.Config') cache = {} data ...
Gets every registered form's field value.\ If a field name is found in the db, it will load it from there.\ Otherwise, the initial value from the field form is used
def open(self): """Open the subtitle file into an Aeidon project.""" try: self.project.open_main(self.filename) except UnicodeDecodeError: with open(self.filename, 'rb') as openfile: encoding = get_encoding(openfile.read()) try: ...
Open the subtitle file into an Aeidon project.
def from_gpx(gpx_segment): """ Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment` """ points = [] for point in gpx_segment.points: points...
Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment`
def get_options(self): """Process the command line. """ args = self.parse_options(self.args) if args: self.directory = args[0] if self.develop: self.skiptag = True if not self.develop: self.develop = self.defaults.develop if n...
Process the command line.
def _get_mean(self, vs30, mag, rrup, imt, scale_fac): """ Compute and return mean """ C_HR, C_BC, C_SR, SC = self._extract_coeffs(imt) rrup = self._clip_distances(rrup) f0 = self._compute_f0_factor(rrup) f1 = self._compute_f1_factor(rrup) f2 = self._comp...
Compute and return mean
def plot_forest( data, kind="forestplot", model_names=None, var_names=None, combined=False, credible_interval=0.94, rope=None, quartiles=True, ess=False, r_hat=False, colors="cycle", textsize=None, linewidth=None, markersize=None, ridgeplot_alpha=None, rid...
Forest plot to compare credible intervals from a number of distributions. Generates a forest plot of 100*(credible_interval)% credible intervals from a trace or list of traces. Parameters ---------- data : obj or list[obj] Any object that can be converted to an az.InferenceData object ...
def _timeout_thread(self, remain): """Timeout before releasing every thing, if nothing was returned""" time.sleep(remain) if not self._ended: self._ended = True self._release_all()
Timeout before releasing every thing, if nothing was returned
def raise_if(self, exception, message, *args, **kwargs): """ If current exception has smaller priority than minimum, subclass of this class only warns user, otherwise normal exception will be raised. """ if issubclass(exception, self.minimum_defect): raise exception(*...
If current exception has smaller priority than minimum, subclass of this class only warns user, otherwise normal exception will be raised.
def k8s_ports_to_metadata_ports(k8s_ports): """ :param k8s_ports: list of V1ServicePort :return: list of str, list of exposed ports, example: - ['1234/tcp', '8080/udp'] """ ports = [] for k8s_port in k8s_ports: if k8s_port.protocol is not None: ports.append("%s/...
:param k8s_ports: list of V1ServicePort :return: list of str, list of exposed ports, example: - ['1234/tcp', '8080/udp']
def set_widgets(self): """Set widgets on the Aggregation Layer Origin Type tab.""" # First, list available layers in order to check if there are # any available layers. Note This will be repeated in # set_widgets_step_fc_agglayer_from_canvas because we need # to list them again a...
Set widgets on the Aggregation Layer Origin Type tab.
def summary(self): """ Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model trained on the training set. An exception is thrown if `trainingSummary is None`. """ if self.hasSummary: if self.numClasses <= 2: return...
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model trained on the training set. An exception is thrown if `trainingSummary is None`.
def set_creator(self, value: Union[Literal, Identifier, str], lang: str= None): """ Set the DC Creator literal value :param value: Value of the creator node :param lang: Language in which the value is """ self.metadata.add(key=DC.creator, value=value, lang=lang)
Set the DC Creator literal value :param value: Value of the creator node :param lang: Language in which the value is
def get_clan(self, tag: crtag, timeout: int=None): """Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that over...
Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that overwrites Client.timeout
def CSWAP(control, target_1, target_2): """Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits:: CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], ...
Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits:: CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], ...
def whitelisted(argument=None): """Decorates a method requiring that the requesting IP address is whitelisted. Requires a whitelist value as a list in the Application.settings dictionary. IP addresses can be an individual IP address or a subnet. Examples: ['10.0.0.0/8','192.168.1.0/24', '1....
Decorates a method requiring that the requesting IP address is whitelisted. Requires a whitelist value as a list in the Application.settings dictionary. IP addresses can be an individual IP address or a subnet. Examples: ['10.0.0.0/8','192.168.1.0/24', '1.2.3.4/32'] :param list argument: L...
def insertDataset(self, businput): """ input dictionary must have the following keys: dataset, primary_ds_name(name), processed_ds(name), data_tier(name), acquisition_era(name), processing_version It may have following keys: physics_group(name), xtcrosssection, creation_d...
input dictionary must have the following keys: dataset, primary_ds_name(name), processed_ds(name), data_tier(name), acquisition_era(name), processing_version It may have following keys: physics_group(name), xtcrosssection, creation_date, create_by, last_modification_date, last_m...
def _get_model(vehicle): """Clean the model field. Best guess.""" model = vehicle['model'] model = model.replace(vehicle['year'], '') model = model.replace(vehicle['make'], '') return model.strip().split(' ')[0]
Clean the model field. Best guess.
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): """ Has no returnvalue (just like WebHDFS) """ if not parents or raise_if_exists: warnings.warn('webhdfs mkdir: parents/raise_if_exists not implemented') permission = int(oct(mode)[2:]) # Convert...
Has no returnvalue (just like WebHDFS)
def cur_time(typ='date', tz=DEFAULT_TZ, trading=True, cal='US'): """ Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date ...
Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(t...
def _worker_queue_scheduled_tasks(self): """ Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution. This should be called periodically. """ queues = set(self._filter_queues(self.connection.smembers( sel...
Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution. This should be called periodically.
def insertTopLevelItem( self, index, item ): """ Inserts the inputed item at the given index in the tree. :param index | <int> item | <XGanttWidgetItem> """ self.treeWidget().insertTopLevelItem(index, item) if self....
Inserts the inputed item at the given index in the tree. :param index | <int> item | <XGanttWidgetItem>
def make_symbols(symbols, *args): """Return a list of uppercase strings like "GOOG", "$SPX, "XOM"... Arguments: symbols (str or list of str): list of market ticker symbols to normalize If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols Returns: ...
Return a list of uppercase strings like "GOOG", "$SPX, "XOM"... Arguments: symbols (str or list of str): list of market ticker symbols to normalize If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols Returns: list of str: list of cananical ticker sy...
def win_menu_select_item(title, *items, **kwargs): """ Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return: """ text = kwargs.get("text", "") if not (0 < len(items) < 8): raise ValueError("accepted ...
Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return:
def handle_no_start_state(self): """Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state if the the state machine w...
Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state if the the state machine was stopped.