code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def sf01(arr): """ swap and then flatten axes 0 and 1 """ s = arr.shape return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
swap and then flatten axes 0 and 1
def propose_unif(self): """Propose a new live point by sampling *uniformly* within the ellipsoid.""" while True: # Sample a point from the ellipsoid. u = self.ell.sample(rstate=self.rstate) # Check if `u` is within the unit cube. if unitcheck(u, ...
Propose a new live point by sampling *uniformly* within the ellipsoid.
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True): # pylint: disable = attribute-defined-outside-init,arguments-differ """ Fit gradient boosting classifier Parameters ---------- X : array_like ...
Fit gradient boosting classifier Parameters ---------- X : array_like Feature matrix y : array_like Labels sample_weight : array_like Weight for each instance eval_set : list, optional A list of (X, y) pairs to use as a val...
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): """ Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed o...
Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode) index_col: Column(s) to...
def bgr2rgb(self): """ Converts data using the cv conversion. """ new_data = cv2.cvtColor(self.raw_data, cv2.COLOR_BGR2RGB) return ColorImage(new_data, frame=self.frame, encoding='rgb8')
Converts data using the cv conversion.
def customData( self, key, default = None ): """ Return the custom data that is stored on this node for the \ given key, returning the default parameter if none was found. :param key <str> :param default <variant> :return <varia...
Return the custom data that is stored on this node for the \ given key, returning the default parameter if none was found. :param key <str> :param default <variant> :return <variant>
def read_wait_cell(self): """Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist. """ table_state = self.bt_table.read_row( TABLE_STATE, filter_=bigtable_row_filters.ColumnRange...
Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist.
def set_header(self, msg): """ Set second head line text """ self.s.move(1, 0) self.overwrite_line(msg, attr=curses.A_NORMAL)
Set second head line text
def create(context, name): """create(context, name) Create a tag. >>> dcictl tag-create [OPTIONS] :param string name: Name of the tag [required] """ result = tag.create(context, name=name) utils.format_output(result, context.format)
create(context, name) Create a tag. >>> dcictl tag-create [OPTIONS] :param string name: Name of the tag [required]
def dist_calc_matrix(surf, cortex, labels, exceptions = ['Unknown', 'Medial_wall'], verbose = True): """ Calculate exact geodesic distance along cortical surface from set of source nodes. "labels" specifies the freesurfer label file to use. All values will be used other than those specified in "exceptio...
Calculate exact geodesic distance along cortical surface from set of source nodes. "labels" specifies the freesurfer label file to use. All values will be used other than those specified in "exceptions" (default: 'Unknown' and 'Medial_Wall'). returns: dist_mat: symmetrical nxn matrix of minimum dista...
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from nested setting.
def _build_row(self, row, parent, align, border): """ Given a row of text, build table cells. """ tr = etree.SubElement(parent, 'tr') tag = 'td' if parent.tag == 'thead': tag = 'th' cells = self._split_row(row, border) # We use align here rather than ce...
Given a row of text, build table cells.
def _convert_md_type(self, type_to_convert: str): """Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29 ...
Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29
def create(cls, interface_id, address=None, network_value=None, nodeid=1, **kw): """ :param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a c...
:param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a cluster, identifies which node this is for :rtype: dict
def get_scanner_param_mandatory(self, param): """ Returns if a scanner parameter is mandatory. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get('mandatory')
Returns if a scanner parameter is mandatory.
def search_subscriptions(self, **kwargs): """ Search for all subscriptions by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/subscription?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().ge...
Search for all subscriptions by parameters
def check(text): """Suggest the preferred forms.""" err = "pinker.latin" msg = "Use English. '{}' is the preferred form." list = [ ["other things being equal", ["ceteris paribus"]], ["among other things", ["inter alia"]], ["in and of itself", ...
Suggest the preferred forms.
def BSR_Get_Row(A, i): """Return row i in BSR matrix A. Only nonzero entries are returned Parameters ---------- A : bsr_matrix Input matrix i : int Row number Returns ------- z : array Actual nonzero values for row i colindx Array of column indices for the ...
Return row i in BSR matrix A. Only nonzero entries are returned Parameters ---------- A : bsr_matrix Input matrix i : int Row number Returns ------- z : array Actual nonzero values for row i colindx Array of column indices for the nonzeros of row i ...
def get_t_factor(t1, t2): """Time difference between two datetimes, expressed as decimal year """ t_factor = None if t1 is not None and t2 is not None and t1 != t2: dt = t2 - t1 year = timedelta(days=365.25) t_factor = abs(dt.total_seconds() / year.total_seconds()) return...
Time difference between two datetimes, expressed as decimal year
def CheckCondition(condition, check_object): """Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: Co...
Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: ConditionError: If condition is bad.
def print_all(self, out=sys.stdout): """ Prints all of the thread profiler results to a given file. (stdout by default) """ THREAD_FUNC_NAME_LEN = 25 THREAD_NAME_LEN = 13 THREAD_ID_LEN = 15 THREAD_SCHED_CNT_LEN = 10 out.write(CRLF) out.write("name...
Prints all of the thread profiler results to a given file. (stdout by default)
def decimal_field_data(field, **kwargs): """ Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(r...
Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99') (True, True)
def raw_sign(message, secret): """Sign a message.""" digest = hmac.new(secret, message, hashlib.sha256).digest() return base64.b64encode(digest)
Sign a message.
def get_history_tags(self, exp, rep=0): """ returns all available tags (logging keys) of the given experiment repetition. Note: Technically, each repetition could have different tags, therefore the rep number can be passed in as parameter, even tho...
returns all available tags (logging keys) of the given experiment repetition. Note: Technically, each repetition could have different tags, therefore the rep number can be passed in as parameter, even though usually all repetitions have the same tags. The ...
def gen_zonal_stats( vectors, raster, layer=0, band=1, nodata=None, affine=None, stats=None, all_touched=False, categorical=False, category_map=None, add_stats=None, zone_func=None, raster_out=False, prefix=None, ...
Zonal statistics of raster values aggregated to vector geometries. Parameters ---------- vectors: path to an vector source or geo-like python objects raster: ndarray or path to a GDAL raster source If ndarray is passed, the ``affine`` kwarg is required. layer: int or string, optional ...
def batch( self, owner, action=None, attribute_write_type=None, halt_on_error=False, playbook_triggers_enabled=None, ): """Return instance of Batch""" from .tcex_ti_batch import TcExBatch return TcExBatch( self, owner, action, attr...
Return instance of Batch
def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret['retcode'] == ...
List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... }
def construct_all(templates, **unbound_var_values): """Constructs all the given templates in a single pass without redundancy. This is useful when the templates have a common substructure and you want the smallest possible graph. Args: templates: A sequence of templates. **unbound_var_values: The unbo...
Constructs all the given templates in a single pass without redundancy. This is useful when the templates have a common substructure and you want the smallest possible graph. Args: templates: A sequence of templates. **unbound_var_values: The unbound_var values to replace. Returns: A list of resul...
def async_func(self, function): """Decorator for let a normal function return the NewFuture""" @wraps(function) def wrapped(*args, **kwargs): return self.submit(function, *args, **kwargs) return wrapped
Decorator for let a normal function return the NewFuture
def within_bounding_box(self, limits): """ Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) ...
Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) - max y (latitude) :returns: ...
def read_rle_bit_packed_hybrid(file_obj, width, length=None): """Read values from `fo` using the rel/bit-packed hybrid encoding. If length is not specified, then a 32-bit int is read first to grab the length of the encoded data. """ debug_logging = logger.isEnabledFor(logging.DEBUG) io_obj = fi...
Read values from `fo` using the rel/bit-packed hybrid encoding. If length is not specified, then a 32-bit int is read first to grab the length of the encoded data.
def tyn_calus_scaling(target, DABo, To, mu_o, viscosity='pore.viscosity', temperature='pore.temperature'): r""" Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest Parameters ---------- target : OpenPNM Obj...
r""" Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and al...
def recache(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o=i.get('out','') # Listing all repos r=ck.access({'action'...
Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 }
def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(TSDBHandler, self).get_default_config_help() config.update({ 'host': '', 'port': '', 'timeout': '', 'tag...
Returns the help text for the configuration options for this handler
def insertBulkBlock(self, blockDump): """ API to insert a bulk block :param blockDump: Output of the block dump command, example can be found in https://svnweb.cern.ch/trac/CMSDMWM/browser/DBS/trunk/Client/tests/dbsclient_t/unittests/blockdump.dict :type blockDump: dict """ ...
API to insert a bulk block :param blockDump: Output of the block dump command, example can be found in https://svnweb.cern.ch/trac/CMSDMWM/browser/DBS/trunk/Client/tests/dbsclient_t/unittests/blockdump.dict :type blockDump: dict
def _set_loam_show_debug_information(self, v, load=False): """ Setter method for loam_show_debug_information, mapped from YANG variable /loam_show_debug_state/loam_show_debug_information (container) If this variable is read-only (config: false) in the source YANG file, then _set_loam_show_debug_informat...
Setter method for loam_show_debug_information, mapped from YANG variable /loam_show_debug_state/loam_show_debug_information (container) If this variable is read-only (config: false) in the source YANG file, then _set_loam_show_debug_information is considered as a private method. Backends looking to populate...
def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ try: return super(EnvironmentKernelSpecManager, self).get_kernel_spec(k...
Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found.
def touch(self, filepath): """Touches the specified file so that its modified time changes.""" if self.is_ssh(filepath): self._check_ssh() remotepath = self._get_remote(filepath) stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath)) ...
Touches the specified file so that its modified time changes.
def _warn_if_not_at_expected_pos(self, expected_pos, end_of, start_of): """ Helper function to warn about unknown bytes found in the file""" diff = expected_pos - self.stream.tell() if diff != 0: logger.warning( "There are {} bytes between {} and {}".format(diff, end_...
Helper function to warn about unknown bytes found in the file
def get_cso_dataframe(self): """ get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npar). The equ...
get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npar). The equation is cso_j = ((Q^1/2*J*J^T*Q^1/2)^1/2)_jj/(NP...
def daemons(self): """ List of daemons for this module """ for attr in dir(self): field = getattr(self, attr) if isinstance(field, Daemon): yield field
List of daemons for this module
def _create_packet(self, request): """Create a formatted packet from a request. :type request: str :param request: Formatted zabbix request :rtype: str :return: Data packet for zabbix """ data_len = struct.pack('<Q', len(request)) packet = b'ZBXD\x01' +...
Create a formatted packet from a request. :type request: str :param request: Formatted zabbix request :rtype: str :return: Data packet for zabbix
def validate(self, value): """ Accepts: str, unicode Returns: list of tuples in the format (ip, port) """ val = super(SlavesValue, self).validate(value) slaves = val.replace(" ", "") slaves = filter(None, slaves.split(',')) slaves = [x.split(":") for x in...
Accepts: str, unicode Returns: list of tuples in the format (ip, port)
def stmt_lambda_proc(self, inputstring, **kwargs): """Add statement lambda definitions.""" regexes = [] for i in range(len(self.stmt_lambdas)): name = self.stmt_lambda_name(i) regex = compile_regex(r"\b%s\b" % (name,)) regexes.append(regex) out = [] ...
Add statement lambda definitions.
def play_song(self, song, tempo=120, delay=0.05): """ Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and...
Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive lis...
async def logs( self, service_id: str, *, details: bool = False, follow: bool = False, stdout: bool = False, stderr: bool = False, since: int = 0, timestamps: bool = False, is_tty: bool = False, tail: str = "all" ) -> Union[str,...
Retrieve logs of the given service Args: details: show service context and extra details provided to logs follow: return the logs as a stream. stdout: return logs from stdout stderr: return logs from stderr since: return logs since this time, as a UNI...
def min_geodetic_distance(a, b): """ Compute the minimum distance between first mesh and each point of the second mesh when both are defined on the earth surface. :param a: a pair of (lons, lats) or an array of cartesian coordinates :param b: a pair of (lons, lats) or an array of cartesian coordina...
Compute the minimum distance between first mesh and each point of the second mesh when both are defined on the earth surface. :param a: a pair of (lons, lats) or an array of cartesian coordinates :param b: a pair of (lons, lats) or an array of cartesian coordinates
def webify(v: Any, preserve_newlines: bool = True) -> str: """ Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` fo...
Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` for blank input.
def calmarnorm(sharpe, T, tau = 1.0): ''' Multiplicator for normalizing calmar ratio to period tau ''' return calmar(sharpe,tau)/calmar(sharpe,T)
Multiplicator for normalizing calmar ratio to period tau
def set_exit_handler(self): """Set the signal handler to manage_signal (defined in this class) Only set handlers for signal.SIGTERM, signal.SIGINT, signal.SIGUSR1, signal.SIGUSR2 :return: None """ signal.signal(signal.SIGINT, self.manage_signal) signal.signal(signal.SIGT...
Set the signal handler to manage_signal (defined in this class) Only set handlers for signal.SIGTERM, signal.SIGINT, signal.SIGUSR1, signal.SIGUSR2 :return: None
def format_name(format, name, target_type, prop_set): """ Given a target, as given to a custom tag rule, returns a string formatted according to the passed format. Format is a list of properties that is represented in the result. For each element of format the corresponding target informatio...
Given a target, as given to a custom tag rule, returns a string formatted according to the passed format. Format is a list of properties that is represented in the result. For each element of format the corresponding target information is obtained and added to the result string. For all, but the...
def loadStructuredPoints(filename): """Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_ """ reader = vtk.vtkStructuredPointsReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtk...
Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_
def addSibling(self, elem): """Add a new element @elem to the list of siblings of @cur merging adjacent TEXT nodes (@elem may be freed) If the new element was already inserted in a document it is first unlinked from its existing context. """ if elem is None: elem__o = None...
Add a new element @elem to the list of siblings of @cur merging adjacent TEXT nodes (@elem may be freed) If the new element was already inserted in a document it is first unlinked from its existing context.
def _get_compute_func(self, nmr_samples, thinning, return_output): """Get the MCMC algorithm as a computable function. Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kerne...
Get the MCMC algorithm as a computable function. Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kernel should return output Returns: mot.lib.cl_function.CLFun...
def buildlist(self, enabled): """Run dialog buildlist """ choice = [] for item in self.data: choice.append((item, False)) for item in enabled: choice.append((item, True)) items = [(tag, tag, sta) for (tag, sta) in choice] code, self.tags = ...
Run dialog buildlist
def nsamples_to_hourminsec(x, pos): '''Convert axes labels to experiment duration in hours/minutes/seconds Notes ----- Matplotlib FuncFormatter function https://matplotlib.org/examples/pylab_examples/custom_ticker1.html ''' h, m, s = hourminsec(x/16.0) return '{:.0f}h {:2.0f}′ {:2.1f}″...
Convert axes labels to experiment duration in hours/minutes/seconds Notes ----- Matplotlib FuncFormatter function https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
def create_ospf_profile(): """ An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (AB...
An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, ...
def to_wire(self, name, file, compress=None, origin=None, override_rdclass=None, want_shuffle=True): """Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the ...
Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the wire format data will be appended @type file: file @param compress: The compression table to use; the default is...
def add_parameter(self, field_name, param_name, param_value): """ Add a parameter to a field into script_fields The ScriptFields object will be returned, so calls to this can be chained. """ try: self.fields[field_name]['params'][param_name] = param_value exc...
Add a parameter to a field into script_fields The ScriptFields object will be returned, so calls to this can be chained.
def sendtoaddress(self, recv_addr, amount, comment=""): """send ammount to address, with optional comment. Returns txid. sendtoaddress(ADDRESS, AMMOUNT, COMMENT)""" return self.req("sendtoaddress", [recv_addr, amount, comment])
send ammount to address, with optional comment. Returns txid. sendtoaddress(ADDRESS, AMMOUNT, COMMENT)
def summary(self): """Return a formatted string giving a quick summary of the results.""" res = ("nlive: {:d}\n" "niter: {:d}\n" "ncall: {:d}\n" "eff(%): {:6.3f}\n" "logz: {:6.3f} +/- {:6.3f}" .format(self.nlive, self.ni...
Return a formatted string giving a quick summary of the results.
def get_distribution_path(venv, distribution): ''' Return the path to a distribution installed inside a virtualenv .. versionadded:: 2016.3.0 venv Path to the virtualenv. distribution Name of the distribution. Note, all non-alphanumeric characters will be converted to dashe...
Return the path to a distribution installed inside a virtualenv .. versionadded:: 2016.3.0 venv Path to the virtualenv. distribution Name of the distribution. Note, all non-alphanumeric characters will be converted to dashes. CLI Example: .. code-block:: bash sal...
def _choice_getter(self): """ Return a function object suitable for the "get" side of the property descriptor. """ def get_group_member_element(obj): return obj.first_child_found_in(*self._member_nsptagnames) get_group_member_element.__doc__ = ( 'R...
Return a function object suitable for the "get" side of the property descriptor.
def UpdateAcqEraEndDate(self, acquisition_era_name ="", end_date=0): """ Input dictionary has to have the following keys: acquisition_era_name, end_date. """ if acquisition_era_name =="" or end_date==0: dbsExceptionHandler('dbsException-invalid-input', "acquisition_er...
Input dictionary has to have the following keys: acquisition_era_name, end_date.
def get_repo_parent(path): """ Returns parent repo or input path if none found. :return: grit.Local or path """ # path is a repository if is_repo(path): return Local(path) # path is inside a repository elif not os.path.isdir(path): _rel = '' while path and path ...
Returns parent repo or input path if none found. :return: grit.Local or path
def send_invoice_email(self, invoice_id, email_dict): """ Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the...
Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the email dict :return dict
def _make_connect(module, args, kwargs): """ Returns a function capable of making connections with a particular driver given the supplied credentials. """ # pylint: disable-msg=W0142 return functools.partial(module.connect, *args, **kwargs)
Returns a function capable of making connections with a particular driver given the supplied credentials.
def _print_stats(self, env, stats): """ Prints statistic information using io stream. `env` ``Environment`` object. `stats` Tuple of task stats for each date. """ def _format_time(mins): """ Generates formatted time string...
Prints statistic information using io stream. `env` ``Environment`` object. `stats` Tuple of task stats for each date.
def register(self, prefix, viewset, base_name=None): """Add any registered route into a global API directory. If the prefix includes a path separator, store the URL in the directory under the first path segment. Otherwise, store it as-is. For example, if there are two registere...
Add any registered route into a global API directory. If the prefix includes a path separator, store the URL in the directory under the first path segment. Otherwise, store it as-is. For example, if there are two registered prefixes, 'v1/users' and 'groups', `directory` will lo...
def furthest_from_root(self): '''Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0 Returns: ``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding dis...
Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0 Returns: ``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding distance
def uint64(self, val): """append a frame containing a uint64""" try: self.msg += [pack("!Q", val)] except struct.error: raise ValueError("Expected uint64") return self
append a frame containing a uint64
def add_lat_lon(self, lat, lon, precision=1e7): """Add lat, lon to gps (lat, lon in float).""" self._ef["GPS"][piexif.GPSIFD.GPSLatitudeRef] = "N" if lat > 0 else "S" self._ef["GPS"][piexif.GPSIFD.GPSLongitudeRef] = "E" if lon > 0 else "W" self._ef["GPS"][piexif.GPSIFD.GPSLongitude] = de...
Add lat, lon to gps (lat, lon in float).
def _list_objects(self, client_kwargs, path, max_request_entries): """ Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned ...
Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned by request. Returns: generator of tuple: object name str, object ...
def acquire_read(self): """ Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks. """ self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self...
Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks.
def _set_disable_res(self, v, load=False): """ Setter method for disable_res, mapped from YANG variable /ha/process_restart/disable_res (container) If this variable is read-only (config: false) in the source YANG file, then _set_disable_res is considered as a private method. Backends looking to popu...
Setter method for disable_res, mapped from YANG variable /ha/process_restart/disable_res (container) If this variable is read-only (config: false) in the source YANG file, then _set_disable_res is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
def connections_from_graph(env, G, edge_data=False): """Create connections for agents in the given environment from the given NetworkX graph structure. :param env: Environment where the agents live. The environment should be derived from :class:`~creamas.core.environment.Environment`, ...
Create connections for agents in the given environment from the given NetworkX graph structure. :param env: Environment where the agents live. The environment should be derived from :class:`~creamas.core.environment.Environment`, :class:`~creamas.mp.MultiEnvironment` or :class:`...
def SubtractFromBalance(self, assetId, fixed8_val): """ Subtract amount to the specified balance. Args: assetId (UInt256): fixed8_val (Fixed8): amount to add. """ found = False for key, balance in self.Balances.items(): if key == asset...
Subtract amount to the specified balance. Args: assetId (UInt256): fixed8_val (Fixed8): amount to add.
def load(self, graphic): """ Loads information for this item from the xml data. :param graphic | <XWalkthroughItem> """ for prop in graphic.properties(): key = prop.name() value = prop.value() if key == 'cap...
Loads information for this item from the xml data. :param graphic | <XWalkthroughItem>
def continue_oauth(self, oauth_callback_data=None): """ Continuation of OAuth procedure. Method must be explicitly called in order to complete OAuth. This allows external entities, e.g. websites, to provide tokens through callback URLs directly. :param oauth_callback_data: The callback U...
Continuation of OAuth procedure. Method must be explicitly called in order to complete OAuth. This allows external entities, e.g. websites, to provide tokens through callback URLs directly. :param oauth_callback_data: The callback URL received to a Web app :type oauth_callback_data: bytes ...
def search_archives(query): """ Return list of :class:`.DBArchive` which match all properties that are set (``not None``) using AND operator to all of them. Example: result = storage_handler.search_publications( DBArchive(isbn="azgabash") ) Args: query (obj): :c...
Return list of :class:`.DBArchive` which match all properties that are set (``not None``) using AND operator to all of them. Example: result = storage_handler.search_publications( DBArchive(isbn="azgabash") ) Args: query (obj): :class:`.DBArchive` with `some` of the pro...
def write_to_socket(self, frame_data): """Write data to the socket. :param str frame_data: :return: """ self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: ...
Write data to the socket. :param str frame_data: :return:
def add_listener_policy(self, json_data): """Attaches listerner policies to an ELB Args: json_data (json): return data from ELB upsert """ env = boto3.session.Session(profile_name=self.env, region_name=self.region) elbclient = env.client('elb') # create stic...
Attaches listerner policies to an ELB Args: json_data (json): return data from ELB upsert
def _to_dict_fixed_width_arrays(self, var_len_str=True): """A dict of arrays that stores data and annotation. It is sufficient for reconstructing the object. """ self.strings_to_categoricals() obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str) var_rec, ...
A dict of arrays that stores data and annotation. It is sufficient for reconstructing the object.
def more(value1, value2): """ Checks if first value is greater than the second one. The operation can be performed over numbers or strings. :param value1: the first value to compare :param value2: the second value to compare :return: true if the first value is greater ...
Checks if first value is greater than the second one. The operation can be performed over numbers or strings. :param value1: the first value to compare :param value2: the second value to compare :return: true if the first value is greater than second and false otherwise.
def popular(self, **kwargs): """ Get the list of popular movies on The Movie Database. This list refreshes every day. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A di...
Get the list of popular movies on The Movie Database. This list refreshes every day. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the A...
def trunk_update(request, trunk_id, old_trunk, new_trunk): """Handle update to a trunk in (at most) three neutron calls. The JavaScript side should know only about the old and new state of a trunk. However it should not know anything about how the old and new are meant to be diffed and sent to neutron....
Handle update to a trunk in (at most) three neutron calls. The JavaScript side should know only about the old and new state of a trunk. However it should not know anything about how the old and new are meant to be diffed and sent to neutron. We handle that here. This code was adapted from Heat, see: h...
def usearch_cluster_error_correction( fasta_filepath, output_filepath=None, output_uc_filepath=None, percent_id_err=0.97, sizein=True, sizeout=True, w=64, slots=16769023, maxrejects=64, log_name="usearch_cluster_err_corrected.log", ...
Cluster for err. correction at percent_id_err, output consensus fasta fasta_filepath = input fasta file, generally a dereplicated fasta output_filepath = output error corrected fasta filepath percent_id_err = minimum identity percent. sizein = not defined in usearch helpstring sizeout = not defined...
async def _auth_handler_post_get_auth(self): ''' If the user supplied auth does rely on a response (is a PostResponseAuth object) then we call the auth's __call__ returning a dict to update the request's headers with, as long as there is an appropriate 401'd response object to ca...
If the user supplied auth does rely on a response (is a PostResponseAuth object) then we call the auth's __call__ returning a dict to update the request's headers with, as long as there is an appropriate 401'd response object to calculate auth details from.
def get_subsamples(data, samples, force): """ Apply state, ncluster, and force filters to select samples to be run. """ subsamples = [] for sample in samples: if not force: if sample.stats.state >= 5: print("""\ Skipping Sample {}; Already has consens reads. ...
Apply state, ncluster, and force filters to select samples to be run.
def tvBrowserHazard_selection_changed(self): """Update layer description label.""" (is_compatible, desc) = self.get_layer_description_from_browser( 'hazard') self.lblDescribeBrowserHazLayer.setText(desc) self.lblDescribeBrowserHazLayer.setEnabled(is_compatible) self.p...
Update layer description label.
def appendAnchor(self, name=None, position=None, color=None, anchor=None): """ Append an anchor to this glyph. >>> anchor = glyph.appendAnchor("top", (10, 20)) This will return a :class:`BaseAnchor` object representing the new anchor in the glyph. ``name`` indicated the nam...
Append an anchor to this glyph. >>> anchor = glyph.appendAnchor("top", (10, 20)) This will return a :class:`BaseAnchor` object representing the new anchor in the glyph. ``name`` indicated the name to be assigned to the anchor. It must be a :ref:`type-string` or ``None``. ``...
def get_definition_properties(self, project, definition_id, filter=None): """GetDefinitionProperties. [Preview API] Gets properties for a definition. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :param [str] filter: A comma-de...
GetDefinitionProperties. [Preview API] Gets properties for a definition. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :param [str] filter: A comma-delimited list of properties. If specified, filters to these specific properties. ...
def OpenServerEndpoint(self, path, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): """Search thr...
Search through all the base URLs to connect to one that works. This is a thin wrapper around requests.request() so most parameters are documented there. Args: path: The URL path to access in this endpoint. verify_cb: A callback which should return True if the response is reasonable. Th...
def x_plus(self, dx=None): """ Mutable x addition. Defaults to set delta value. """ if dx is None: self.x += self.dx else: self.x = self.x + dx
Mutable x addition. Defaults to set delta value.
def getManager(self, force=False): """Extract the YadisServiceManager for this object's URL and suffix from the session. @param force: True if the manager should be returned regardless of whether it's a manager for self.url. @return: The current YadisServiceManager, if it's for...
Extract the YadisServiceManager for this object's URL and suffix from the session. @param force: True if the manager should be returned regardless of whether it's a manager for self.url. @return: The current YadisServiceManager, if it's for this URL, or else None
def remove_father(self, father): """ Remove the father node. Do nothing if the node is not a father Args: fathers: list of fathers to add """ self._fathers = [x for x in self._fathers if x.node_id != father.node_id]
Remove the father node. Do nothing if the node is not a father Args: fathers: list of fathers to add
def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: ...
.. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual netw...
def setup_suspend(self): """Setup debugger to "suspend" execution """ self.frame_calling = None self.frame_stop = None self.frame_return = None self.frame_suspend = True self.pending_stop = True self.enable_tracing() return
Setup debugger to "suspend" execution
def prune_cached(values): """Remove the items that have already been cached.""" import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): return values cached = [x.strip() for x in open(file_path,...
Remove the items that have already been cached.
def _unary_op(name, doc="unary operator"): """ Create a method for given unary operator """ def _(self): jc = getattr(self._jc, name)() return Column(jc) _.__doc__ = doc return _
Create a method for given unary operator