positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def save(self, fname: str): """ Saves this Config (without the frozen state) to a file called fname. :param fname: Name of file to store this Config in. """ obj = copy.deepcopy(self) obj.__del_frozen() with open(fname, 'w') as out: yaml.dump(obj, out,...
Saves this Config (without the frozen state) to a file called fname. :param fname: Name of file to store this Config in.
def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') ip_address = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') if x_forwarded_for and ',' not in x_...
Makes the best attempt to get the client's real IP or return the loopback
def get_all(self): """Return all equipments in database :return: Dictionary with the following structure: :: {'equipaments': {'name' :< name_equipament >}, {... demais equipamentos ...} } :raise DataBaseError: Networkapi failed to access the database. :raise XMLErr...
Return all equipments in database :return: Dictionary with the following structure: :: {'equipaments': {'name' :< name_equipament >}, {... demais equipamentos ...} } :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to gener...
def get(self, obj_id): """ Get a single item :param obj_id: int :return: dict|str """ response = self._client.session.get( '{url}/{id}'.format( url=self.endpoint_url, id=obj_id ) ) return self.process_response(respo...
Get a single item :param obj_id: int :return: dict|str
def _run(self, bundle, container_id=None, empty_process=False, log_path=None, pid_file=None, sync_socket=None, command="run", log_format="kubernetes"): ''' _run is the base function for run and create, the onl...
_run is the base function for run and create, the only difference between the two being that run does not have an option for sync_socket. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ========== bundle: th...
def get_events(self, **kwargs): """Retrieve events from server.""" force = kwargs.pop('force', False) response = api.request_sync_events(self.blink, self.network_id, force=force) try: return...
Retrieve events from server.
def _setup_chassis(self): """ Sets up the router with the corresponding chassis (create slots and insert default adapters). """ self._create_slots(2) self._slots[0] = self.integrated_adapters[self._chassis]()
Sets up the router with the corresponding chassis (create slots and insert default adapters).
def add_to_capabilities(self, capabilities): """ Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added. """ proxy_caps = {} proxy_caps['proxyType'] = self.proxyType['string'] ...
Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added.
def build_tokens_line(self): """Build a logical line from tokens.""" logical = [] comments = [] length = 0 prev_row = prev_col = mapping = None for token_type, text, start, end, line in self.tokens: if token_type in SKIP_TOKENS: continue ...
Build a logical line from tokens.
def set(self, num): """ Sets current value to num """ if self.validate(num) is not None: self.index = self.allowed.index(num) IntegerEntry.set(self, num)
Sets current value to num
def write(nml, nml_path, force=False, sort=False): """Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is...
Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is equivalent to the ``write`` function of the ``Namelist`` ...
def build_view_from_tag(self, tag): """ Build a view of group of Symbols based on their tag. Parameters ---------- tag : str Use '%' to enable SQL's "LIKE" functionality. Note ---- This function is written...
Build a view of group of Symbols based on their tag. Parameters ---------- tag : str Use '%' to enable SQL's "LIKE" functionality. Note ---- This function is written without SQLAlchemy, so it only tested on Postgre...
def checkIsReachable(rh): """ Check if a virtual machine is reachable. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'ISREACHABLE' userid - userid of the virtual machine Output: Request Handle updated with th...
Check if a virtual machine is reachable. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'ISREACHABLE' userid - userid of the virtual machine Output: Request Handle updated with the results. overallRC - 0: deter...
def print_plot_line(function, popt, xs, ys, name, tol=0.05, extra=''): """ print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters """ idp = id_generator() f = open('convdat.'+str(idp), mode='w') for n in range(0, len(ys), 1): f.write(str(x...
print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters
def _normalize_array(array, domain=(0, 1)): """Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults ...
Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a dtype of uint8 and a domain of 0-255. Args: array: NumPy array representing the image domain: expected range of values in array, defaults to (0, 1), if explicitly set to None will use the...
def main(args=None): """The main function.""" parser = argparse.ArgumentParser( description='Fritz!Box Smarthome CLI tool.') parser.add_argument('-v', action='store_true', dest='verbose', help='be more verbose') parser.add_argument('-f', '--fritzbox', type=str, dest='host...
The main function.
def download_url(self, timeout=60, name=None): """ Trigger a browse download :param timeout: int - Time in seconds to expire the download :param name: str - for LOCAL only, to rename the file being downloaded :return: str """ if "local" in self.driver.name.lower()...
Trigger a browse download :param timeout: int - Time in seconds to expire the download :param name: str - for LOCAL only, to rename the file being downloaded :return: str
def tcc(text: str) -> str: """ TCC generator, generates Thai Character Clusters :param str text: text to be tokenized to character clusters :return: subword (character cluster) """ if not text or not isinstance(text, str): return "" p = 0 while p < len(text): m = PAT_TCC...
TCC generator, generates Thai Character Clusters :param str text: text to be tokenized to character clusters :return: subword (character cluster)
def save(self, mark): """Save a position in this collection. :param mark: The position to save :type mark: Mark :raises: DBError, NoTrackingCollection """ self._check_exists() obj = mark.as_dict() try: # Make a 'filter' to find/update existing...
Save a position in this collection. :param mark: The position to save :type mark: Mark :raises: DBError, NoTrackingCollection
def unauthenticate(self): """ Clears out any credentials, tokens, and service catalog info. """ self.username = "" self.password = "" self.tenant_id = "" self.tenant_name = "" self.token = "" self.expires = None self.region = "" sel...
Clears out any credentials, tokens, and service catalog info.
def create_halton_samples(order, dim=1, burnin=-1, primes=()): """ Create Halton sequence. For ``dim == 1`` the sequence falls back to Van Der Corput sequence. Args: order (int): The order of the Halton sequence. Defines the number of samples. dim (int): The num...
Create Halton sequence. For ``dim == 1`` the sequence falls back to Van Der Corput sequence. Args: order (int): The order of the Halton sequence. Defines the number of samples. dim (int): The number of dimensions in the Halton sequence. burnin (int): ...
def write_hdf5_array(array, h5g, path=None, attrs=None, append=False, overwrite=False, compression='gzip', **kwargs): """Write the ``array`` to an `h5py.Dataset` Parameters ---------- array : `gwpy.types.Array` the data object to write h5g : `str`,...
Write the ``array`` to an `h5py.Dataset` Parameters ---------- array : `gwpy.types.Array` the data object to write h5g : `str`, `h5py.Group` a file path to write to, or an `h5py.Group` in which to create a new dataset path : `str`, optional the path inside the grou...
def to_dict(obj): """ If value wasn't isn't a primitive scalar or collection then it needs to either implement to_dict (instances of Serializable) or has member data matching each required arg of __init__. """ if isinstance(obj, dict): return obj elif hasattr(obj, "to_dict"): ...
If value wasn't isn't a primitive scalar or collection then it needs to either implement to_dict (instances of Serializable) or has member data matching each required arg of __init__.
def rnn(name, input, state, kernel, bias, new_state, number_of_gates = 2): ''' - Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) ''' nn = Build(name) nn.tanh( nn.mad(kernel=kernel, bias=bias, x=nn.concat(input, state)), out=new_state); return nn.layers;
- Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi)
def download_pic(self, filename: str, url: str, mtime: datetime, filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool: """Downloads and saves picture with given url under given directory with given timestamp. Returns true, if file was actually downloaded, i.e. updated."...
Downloads and saves picture with given url under given directory with given timestamp. Returns true, if file was actually downloaded, i.e. updated.
def visit_Call(self, node): ''' Resulting node alias to the return_alias of called function, if the function is already known by Pythran (i.e. it's an Intrinsic) or if Pythran already computed it's ``return_alias`` behavior. >>> from pythran import passmanager >>> pm = p...
Resulting node alias to the return_alias of called function, if the function is already known by Pythran (i.e. it's an Intrinsic) or if Pythran already computed it's ``return_alias`` behavior. >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> fun =...
def _handle_temporary_connection(self, old_sink, new_sink, of_target=True): """Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink...
Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink (if existing) :param gaphas.aspect.ConnectionSink new_sink: New sink (if exist...
def access_view(name, **kwargs): """ Shows ACL for the specified service. """ ctx = Context(**kwargs) ctx.execute_action('access:view', **{ 'unicorn': ctx.repo.create_secure_service('unicorn'), 'service': name, })
Shows ACL for the specified service.
def cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth, verticalPadding, horizontalPadding, verticalStride, horizontalStride): """" Initialize a 2D pooling descriptor. This function initializes a previously created pooling descriptor object. Parame...
Initialize a 2D pooling descriptor. This function initializes a previously created pooling descriptor object. Parameters ---------- poolingDesc : cudnnPoolingDescriptor Handle to a previously created pooling descriptor. mode : cudnnPoolingMode Enumerant to specify the pooling mode....
def is_uncertainty_edition_allowed(self, analysis_brain): """Checks if the edition of the uncertainty field is allowed :param analysis_brain: Brain that represents an analysis :return: True if the user can edit the result field, otherwise False """ # Only allow to edit the unce...
Checks if the edition of the uncertainty field is allowed :param analysis_brain: Brain that represents an analysis :return: True if the user can edit the result field, otherwise False
def load_swagger_spec(self, filepath=None): """ Loads the origin_spec from a local JSON file. If `filepath` is not provided, then the class `file_spec` format will be used to create the file-path value. """ if filepath is True or filepath is None: filepath = ...
Loads the origin_spec from a local JSON file. If `filepath` is not provided, then the class `file_spec` format will be used to create the file-path value.
def dict_conf(filename): """ Return dict object for *.conf file """ f, ext = os.path.splitext(filename) ext = ext.lower() if ext == "conf" or ext == "ini": # python config via config parser config = ConfigParser() config.optionxform=str config.read(filename) rv = {} for section in...
Return dict object for *.conf file
def fetch_samples(proj, selector_attribute=None, selector_include=None, selector_exclude=None): """ Collect samples of particular protocol(s). Protocols can't be both positively selected for and negatively selected against. That is, it makes no sense and is not allowed to specify both selector_incl...
Collect samples of particular protocol(s). Protocols can't be both positively selected for and negatively selected against. That is, it makes no sense and is not allowed to specify both selector_include and selector_exclude protocols. On the other hand, if neither is provided, all of the Project's Samp...
def __end_of_list(self, ast_token): """Handle end of a list.""" self.list_level -= 1 if self.list_level == 0: if self.list_entry is not None: self.final_ast_tokens.append(self.list_entry) self.list_entry = None self.final_ast_tokens.append(...
Handle end of a list.
def maxCtxSubtable(maxCtx, tag, lookupType, st): """Calculate usMaxContext based on a single lookup table (and an existing max value). """ # single positioning, single / multiple substitution if (tag == 'GPOS' and lookupType == 1) or ( tag == 'GSUB' and lookupType in (1, 2, 3)): max...
Calculate usMaxContext based on a single lookup table (and an existing max value).
def locate_arcgis(): ''' Find the path to the ArcGIS Desktop installation. Keys to check: HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use that to go to HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version We may need to check HKLM/SOFTWARE/Wow6432Node/...
Find the path to the ArcGIS Desktop installation. Keys to check: HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use that to go to HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version We may need to check HKLM/SOFTWARE/Wow6432Node/ESRI instead
def validate_polygon(obj): """ Make sure an input can be returned as a valid polygon. Parameters ------------- obj : shapely.geometry.Polygon, str (wkb), or (n, 2) float Object which might be a polygon Returns ------------ polygon : shapely.geometry.Polygon Valid polygon ob...
Make sure an input can be returned as a valid polygon. Parameters ------------- obj : shapely.geometry.Polygon, str (wkb), or (n, 2) float Object which might be a polygon Returns ------------ polygon : shapely.geometry.Polygon Valid polygon object Raises ------------- ...
def stop_process(self): """ Stop the process (by killing it). """ if self.process is not None: self._user_stop = True self.process.kill() self.setReadOnly(True) self._running = False
Stop the process (by killing it).
def _format_url(handler, host=None, core_name=None, extra=None): ''' PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (...
PRIVATE METHOD Formats the URL based on parameters, and if cores are used or not handler : str The request handler to hit. host : str (None) The solr host to query. __opts__['host'] is default core_name : str (None) The name of the solr core if using cores. Leave this blank if y...
def cmd_move(db=None): """Rename a database within a server. When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of place in the form DEST_old_YYYYMMDD (unless --no-backup is specified). """ if db is None: db = connect() pg_m...
Rename a database within a server. When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of place in the form DEST_old_YYYYMMDD (unless --no-backup is specified).
def _handle_response(self, request: Request, response: Response): '''Process a response.''' self._item_session.update_record_value(status_code=response.reply.code) is_listing = isinstance(response, ListingResponse) if is_listing and not self._processor.fetch_params.remove_listing or \ ...
Process a response.
def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs): """Find TableRateShipping Return single instance of TableRateShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> th...
Find TableRateShipping Return single instance of TableRateShipping by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True) ...
def VcardFieldsEqual(field1, field2): """Handle comparing vCard fields where inputs are lists of components. Handle parameters? Are any used aside from 'TYPE'? Note: force cast to string to compare sub-objects like Name and Address """ field1_vals = set([ str(f.value) for f in field1 ]) field2...
Handle comparing vCard fields where inputs are lists of components. Handle parameters? Are any used aside from 'TYPE'? Note: force cast to string to compare sub-objects like Name and Address
def _variable_parts(self, line, codeline): """Return variable parts of the codeline, given the static parts.""" var_subs = [] # codeline has pattern and then has the outputs in different versions if codeline: var_subs = self._find_variable(codeline.pattern, line) else...
Return variable parts of the codeline, given the static parts.
def bootstrap_histogram_1D( values, intervals, uncertainties=None, normalisation=False, number_bootstraps=None, boundaries=None): ''' Bootstrap samples a set of vectors :param numpy.ndarray values: The data values :param numpy.ndarray intervals: The bin edges :param ...
Bootstrap samples a set of vectors :param numpy.ndarray values: The data values :param numpy.ndarray intervals: The bin edges :param numpy.ndarray uncertainties: The standard deviations of each observation :param bool normalisation: If True then returns the histogram as ...
def _add_hook(self, socket, callback): """Generic hook. The passed socket has to be "receive only". """ self._hooks.append(socket) self._hooks_cb[socket] = callback if self.poller: self.poller.register(socket, POLLIN)
Generic hook. The passed socket has to be "receive only".
def writeInfo(self, location=None, masters=None): """ Write font into the current instance. Note: the masters attribute is ignored at the moment. """ if self.currentInstance is None: return infoElement = ET.Element("info") if location is not None: ...
Write font into the current instance. Note: the masters attribute is ignored at the moment.
def clean(self): ''' TinyMCE adds a placeholder <br> if no data is inserted. In this case, remove it. ''' cleaned_data = super(ManagerForm, self).clean() compensation = cleaned_data.get("compensation") duties = cleaned_data.get("duties") if compensation == '<br data-mce-bogus="1...
TinyMCE adds a placeholder <br> if no data is inserted. In this case, remove it.
def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs): # type: (List['User'], str, str, Optional[str], Optional[str], Optional[Configuration], Any) -> None """Email a list of users Args: users (List[User]): List of users su...
Email a list of users Args: users (List[User]): List of users subject (str): Email subject text_body (str): Plain text email body html_body (str): HTML email body sender (Optional[str]): Email sender. Defaults to SMTP username. configurati...
def get_account_by_b58_address(self, b58_address: str, password: str) -> Account: """ :param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return: """ acct = self.get_account_data_by_b58_address(b58_...
:param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return:
def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.append(self) return result
Activate a patch, returning any created mock.
def romanize(text: str) -> str: """ Rendering Thai words in the Latin alphabet or "romanization", using the Royal Thai General System of Transcription (RTGS), which is the official system published by the Royal Institute of Thailand. ถอดเสียงภาษาไทยเป็นอักษรละติน :param str text: Thai text to be...
Rendering Thai words in the Latin alphabet or "romanization", using the Royal Thai General System of Transcription (RTGS), which is the official system published by the Royal Institute of Thailand. ถอดเสียงภาษาไทยเป็นอักษรละติน :param str text: Thai text to be romanized :return: A string of Thai wor...
def parse_line(text): """ :param text: :type text: str :return: """ indent,text = calculate_indent(text) results = line_parser.parseString(text, parseAll=True).asList() return indent,results[0]
:param text: :type text: str :return:
def update_list_function(self, list_name, list_func): """ Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function. ...
Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function.
def enable_aliases_autocomplete(_, **kwargs): """ Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list. """ external_completions = kwargs.get('external_completions', []) prefix = kwargs.get('cword_prefix', []) cur_commands = kwargs.get('comp_words', []) alias_t...
Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list.
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: ...
Returns the data stored under the given role for the item. O
def predict(self, trial_history): """predict the value of target position Parameters ---------- trial_history: list The history performance matrix of each trial. Returns ------- float expected final result performance of this hype...
predict the value of target position Parameters ---------- trial_history: list The history performance matrix of each trial. Returns ------- float expected final result performance of this hyperparameter config
def properties(self): """ Property for accessing property (doh!) manager of the current job. :return: instance of :class:`yagocd.resources.property.PropertyManager` :rtype: yagocd.resources.property.PropertyManager """ return PropertyManager( session=self._se...
Property for accessing property (doh!) manager of the current job. :return: instance of :class:`yagocd.resources.property.PropertyManager` :rtype: yagocd.resources.property.PropertyManager
def _patch_property(self, name, value): """Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :me...
Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param...
def end_comma(self, value): """Validate and set the comma termination flag.""" if not isinstance(value, bool): raise TypeError('end_comma attribute must be a logical type.') self._end_comma = value
Validate and set the comma termination flag.
def format_listeners(elb_settings=None, env='dev', region='us-east-1'): """Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, ...
Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, "i_port": 8080, "lb_port": 80, "s...
def predict_density(self, Fmu, Fvar, Y): r""" Given a Normal distribution for the latent function, and a datum Y, compute the log predictive density of Y. i.e. if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes t...
r""" Given a Normal distribution for the latent function, and a datum Y, compute the log predictive density of Y. i.e. if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes the predictive density \log \int p(y=...
def watts2pascal(watts, cfm, fan_tot_eff): """convert and return inputs for E+ in pascal and m3/s""" bhp = watts2bhp(watts) return bhp2pascal(bhp, cfm, fan_tot_eff)
convert and return inputs for E+ in pascal and m3/s
def server_doc(self_or_cls, obj, doc=None): """ Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance. """ if not isinstance(obj, (Plot, BokehServerWidgets)): ...
Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance.
def merge(dst, src, separator="/", afilter=None, flags=MERGE_ADDITIVE, _path=""): """Merge source into destination. Like dict.update() but performs deep merging. flags is an OR'ed combination of MERGE_ADDITIVE, MERGE_REPLACE, or MERGE_TYPESAFE. * MERGE_ADDITIVE : List objects are combined onto ...
Merge source into destination. Like dict.update() but performs deep merging. flags is an OR'ed combination of MERGE_ADDITIVE, MERGE_REPLACE, or MERGE_TYPESAFE. * MERGE_ADDITIVE : List objects are combined onto one long list (NOT a set). This is the default flag. * MERGE_REPLACE : ...
def _store_documentation(self, path, html, overwrite, quiet): """ Stores all documents on the file system. Target location is **path**. File name is the lowercase name of the document + .rst. """ echo("Storing groundwork application documents\n") echo("Application: %s" ...
Stores all documents on the file system. Target location is **path**. File name is the lowercase name of the document + .rst.
def _eval_args(args): """Internal helper for get_args.""" res = [] for arg in args: if not isinstance(arg, tuple): res.append(arg) elif is_callable_type(arg[0]): callable_args = _eval_args(arg[1:]) if len(arg) == 2: res.append(Callable[[], ...
Internal helper for get_args.
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'): return str[1:-1] return str
Remove quotes from a string.
def make_transient(std, DMmax, Amin=6., Amax=20., rmax=20., rmin=0., DMmin=0.): """ Produce a mock transient pulse source for the purposes of characterizing the detection success of the current pipeline. Assumes - Code to inject the transients does so by inserting at an array index - Noise lev...
Produce a mock transient pulse source for the purposes of characterizing the detection success of the current pipeline. Assumes - Code to inject the transients does so by inserting at an array index - Noise level at the center of the data array is characteristic of the noise level throughout...
def network(n): """Validate a |Network|. Checks the TPM and connectivity matrix. """ tpm(n.tpm) connectivity_matrix(n.cm) if n.cm.shape[0] != n.size: raise ValueError("Connectivity matrix must be NxN, where N is the " "number of nodes in the network.") retur...
Validate a |Network|. Checks the TPM and connectivity matrix.
def write_base (self, url_data): """Write url_data.base_ref.""" self.writeln(u"<tr><td>"+self.part("base")+u"</td><td>"+ cgi.escape(url_data.base_ref)+u"</td></tr>")
Write url_data.base_ref.
def calculate_anim(infiles, org_lengths): """Returns ANIm result dataframes for files in input directory. - infiles - paths to each input file - org_lengths - dictionary of input sequence lengths, keyed by sequence Finds ANI by the ANIm method, as described in Richter et al (2009) Proc Natl Acad S...
Returns ANIm result dataframes for files in input directory. - infiles - paths to each input file - org_lengths - dictionary of input sequence lengths, keyed by sequence Finds ANI by the ANIm method, as described in Richter et al (2009) Proc Natl Acad Sci USA 106: 19126-19131 doi:10.1073/pnas.09064121...
def resolve_path( self, path, root_id='0', objects=False ): '''Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of it's ancestors, or raises DoesNotExists error. Requires a lot of calls to resolve each name in path, so use with care. roo...
Return id (or metadata) of an object, specified by chain (iterable or fs-style path string) of "name" attributes of it's ancestors, or raises DoesNotExists error. Requires a lot of calls to resolve each name in path, so use with care. root_id parameter allows to specify path relative to some folder_i...
def get_revision_history(brain_or_object): """Get the revision history for the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Workflow history :rtype: obj """ obj = get...
Get the revision history for the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Workflow history :rtype: obj
def plotwrapper(f): """ This decorator allows for PyMC arguments of various types to be passed to the plotting functions. It identifies the type of object and locates its trace(s), then passes the data to the wrapped plotting function. """ def wrapper(pymc_obj, *args, **kwargs): start ...
This decorator allows for PyMC arguments of various types to be passed to the plotting functions. It identifies the type of object and locates its trace(s), then passes the data to the wrapped plotting function.
def CallMethod(self, method, controller, request, response_class, done): '''Call the RPC method. The naming doesn't confirm PEP8, since it's a method called by protobuf ''' try: self.validate_request(request) if not self.sock: self.get_connection(...
Call the RPC method. The naming doesn't confirm PEP8, since it's a method called by protobuf
def _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def['type'] == 'lazy': self.build_index(idx_name) for index_name, values in self.indexes.items(): for value in values: if n...
Clean index values after loading.
def get_shapes_intersecting_geometry( feed: "Feed", geometry, geo_shapes=None, *, geometrized: bool = False ) -> DataFrame: """ Return the slice of ``feed.shapes`` that contains all shapes that intersect the given Shapely geometry, e.g. a Polygon or LineString. Parameters ---------- feed : ...
Return the slice of ``feed.shapes`` that contains all shapes that intersect the given Shapely geometry, e.g. a Polygon or LineString. Parameters ---------- feed : Feed geometry : Shapley geometry, e.g. a Polygon Specified in WGS84 coordinates geo_shapes : GeoPandas GeoDataFrame ...
def get_port_channel_detail_output_lacp_partner_system_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_det...
Auto Generated Code
def hide_routemap_holder_route_map_content_set_automatic_tag_tag_empty(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.Sub...
Auto Generated Code
def __rv_french(self, word, vowels): """ Return the region RV that is used by the French stemmer. If the word begins with two vowels, RV is the region after the third letter. Otherwise, it is the region after the first vowel not at the beginning of the word, or the end of the wo...
Return the region RV that is used by the French stemmer. If the word begins with two vowels, RV is the region after the third letter. Otherwise, it is the region after the first vowel not at the beginning of the word, or the end of the word if these positions cannot be found. (Exception...
def load(path, include_core=True, path_in_arc=''): """ Loads a IOSystem or Extension previously saved with pymrio This function can be used to load a IOSystem or Extension specified in a metadata file (as defined in DEFAULT_FILE_NAMES['filepara']: metadata.json) DataFrames (tables) are loaded from tex...
Loads a IOSystem or Extension previously saved with pymrio This function can be used to load a IOSystem or Extension specified in a metadata file (as defined in DEFAULT_FILE_NAMES['filepara']: metadata.json) DataFrames (tables) are loaded from text or binary pickle files. For the latter, the extension...
def _list_ids(path_to_data): """List raw data IDs grouped by symbol ID from a pickle file ``path_to_data``.""" loaded = pickle.load(open(path_to_data, "rb")) raw_datasets = loaded['handwriting_datasets'] raw_ids = {} for raw_dataset in raw_datasets: raw_data_id = raw_dataset['handwrit...
List raw data IDs grouped by symbol ID from a pickle file ``path_to_data``.
def add(self,attrlist,attrvalues): ''' add an attribute :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist ''' for i,d in enumerate(attrlist): self[d] = attrvalues[i]
add an attribute :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist
def visual_callback_2d(background, fig=None): """ Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. Only works for 2D images. Parameters ---------...
Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. Only works for 2D images. Parameters ---------- background : (M, N) array Image to be plotte...
def cached_property(getter): """ Decorator that converts a method into memoized property. The decorator works as expected only for classes with attribute '__dict__' and immutable properties. """ @wraps(getter) def decorator(self): key = "_cached_property_" + getter.__name__ ...
Decorator that converts a method into memoized property. The decorator works as expected only for classes with attribute '__dict__' and immutable properties.
def getDownloadUrls(self): """Return a list of the urls to download from""" data = self.searchIndex(False) fileUrls = [] for datum in data: fileUrl = self.formatDownloadUrl(datum[0]) fileUrls.append(fileUrl) return fileUrls
Return a list of the urls to download from
def error(self, message): """Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the foll...
Override superclass to support customized error message. Error message needs to be rewritten in order to display visible commands only, when invalid command is called by user. Otherwise, hidden commands will be displayed in stderr, which is not expected. Refer the following argparse python documentati...
def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol, queOut): """Spatially convolve boxcar functions with 2D Gaussian. Parameters ---------- idxPrc : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. aryBoxCar : float, positive ...
Spatially convolve boxcar functions with 2D Gaussian. Parameters ---------- idxPrc : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. aryBoxCar : float, positive Description of input 2. aryMdlParamsChnk : 2d numpy array, shape [n_samples, n_measurements] ...
def export(self, class_name, method_name, export_data=False, export_dir='.', export_filename='data.json', export_append_checksum=False, **kwargs): """ Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :pa...
Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string The name of the method in the returned result. :param expor...
def max(self, array, role = None): """ Return the maximum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. ...
Return the maximum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: >>> salaries = household.mem...
def bipartite_vertex_cover(bigraph): """Bipartite minimum vertex cover by Koenig's theorem :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph) :returns: boolean table for U, b...
Bipartite minimum vertex cover by Koenig's theorem :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph) :returns: boolean table for U, boolean table for V :comment: selected ve...
def mine_urls(urls, params=None, callback=None, **kwargs): """Concurrently retrieve URLs. :param urls: A set of URLs to concurrently retrieve. :type urls: iterable :param params: (optional) The URL parameters to send with each request. :type params: dict :param callback: (o...
Concurrently retrieve URLs. :param urls: A set of URLs to concurrently retrieve. :type urls: iterable :param params: (optional) The URL parameters to send with each request. :type params: dict :param callback: (optional) A callback function to be called on each ...
def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [...
Merges two numpy arrays by calculating all possible combinations of rows
def remove(self, item): """ Remove an item from the set, returning if it was present """ with self.lock: if item in self.set: self.set.remove(item) return True return False
Remove an item from the set, returning if it was present
def get_string(self, sort_keys=False, pretty=False): """ Returns a string representation of the INCAR. The reason why this method is different from the __str__ method is to provide options for pretty printing. Args: sort_keys (bool): Set to True to sort the INCAR pa...
Returns a string representation of the INCAR. The reason why this method is different from the __str__ method is to provide options for pretty printing. Args: sort_keys (bool): Set to True to sort the INCAR parameters alphabetically. Defaults to False. p...
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type], None, None]: """ Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class. ...
Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class.
def get_resource(self, session, query, api_type, obj_id): """ Fetch a resource. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: Type of the resource :param obj_id: ID of the resource """ resource = self._fetch_resource...
Fetch a resource. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: Type of the resource :param obj_id: ID of the resource
def getattr(self, name, context=None, class_context=True): """Get an attribute from this class, using Python's attribute semantic. This method doesn't look in the :attr:`instance_attrs` dictionary since it is done by an :class:`Instance` proxy at inference time. It may return an :class:...
Get an attribute from this class, using Python's attribute semantic. This method doesn't look in the :attr:`instance_attrs` dictionary since it is done by an :class:`Instance` proxy at inference time. It may return an :class:`Uninferable` object if the attribute has not been fou...