positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _finish_fragment(self): """ Creates fragment """ if self.fragment: self.fragment.finish() if self.fragment.headers: # Regardless of what's been seen to this point, if we encounter a headers fragment, # all the previous fragments should...
Creates fragment
def default_vsan_policy_configured(name, policy): ''' Configures the default VSAN policy on a vCenter. The state assumes there is only one default VSAN policy on a vCenter. policy Dict representation of a policy ''' # TODO Refactor when recurse_differ supports list_differ # It's goi...
Configures the default VSAN policy on a vCenter. The state assumes there is only one default VSAN policy on a vCenter. policy Dict representation of a policy
def register(self, plugin): """Add the plugin to our set of listeners for each message that it listens to, tell it to use our messages Queue for communication, and start it up. """ for listener in plugin.listeners: self.listeners[listener].add(plugin) self.plu...
Add the plugin to our set of listeners for each message that it listens to, tell it to use our messages Queue for communication, and start it up.
def perturb(model, verbose=False, steady_state=None, eigmax=1.0-1e-6, solve_steady_state=False, order=1, details=True): """Compute first order approximation of optimal controls Parameters: ----------- model: NumericModel Model to be solved verbose: boolean ...
Compute first order approximation of optimal controls Parameters: ----------- model: NumericModel Model to be solved verbose: boolean If True: displays number of contracting eigenvalues steady_state: ndarray Use supplied steady-state value to compute the approximation. ...
def send(self, s, end=os.linesep, signal=False): """Sends the given string or signal to std_in.""" if self.blocking: raise RuntimeError('send can only be used on non-blocking commands.') if not signal: if self._uses_subprocess: return self.subprocess.com...
Sends the given string or signal to std_in.
def add(self, tensor, tf_sess=None, key=None, **kwargs): """ Adds a new root *tensor* for a *key* which, if *None*, defaults to a consecutive number. When *tensor* is not an instance of :py:class:`Tensor` but an instance of ``tensorflow.Tensor``, it is converted first. In that case, *tf_...
Adds a new root *tensor* for a *key* which, if *None*, defaults to a consecutive number. When *tensor* is not an instance of :py:class:`Tensor` but an instance of ``tensorflow.Tensor``, it is converted first. In that case, *tf_sess* should be a valid tensorflow session and *kwargs* are forwarded...
def error (logname, msg, *args, **kwargs): """Log an error. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.ERROR): _log(log.error, msg, args, **kwargs)
Log an error. return: None
def netmask_long(self): """ Network netmask derived from subnet size, as long. >>> localnet = Network('127.0.0.1/8') >>> print(localnet.netmask_long()) 4278190080 """ if self.version() == 4: return (MAX_IPV4 >> (32 - self.mask)) << (32 - self.mask) ...
Network netmask derived from subnet size, as long. >>> localnet = Network('127.0.0.1/8') >>> print(localnet.netmask_long()) 4278190080
def merge_dict(a, b): """ Recursively merges and returns dict a with dict b. Any list values will be combined and returned sorted. :param a: dictionary object :param b: dictionary object :return: merged dictionary object """ if not isinstance(b, dict): return b result = de...
Recursively merges and returns dict a with dict b. Any list values will be combined and returned sorted. :param a: dictionary object :param b: dictionary object :return: merged dictionary object
async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( ...
Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data.
def filter_by_attrs(self, **kwargs): """Returns a ``Dataset`` with variables that match specific conditions. Can pass in ``key=value`` or ``key=callable``. A Dataset is returned containing only the variables for which all the filter tests pass. These tests are either ``key=value`` for ...
Returns a ``Dataset`` with variables that match specific conditions. Can pass in ``key=value`` or ``key=callable``. A Dataset is returned containing only the variables for which all the filter tests pass. These tests are either ``key=value`` for which the attribute ``key`` has the exac...
def _validate_planar_fault_geometry(self, node, _float_re): """ Validares a node representation of a planar fault geometry """ valid_spacing = node["spacing"] for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]: lon = getattr(node, key)["lon"] ...
Validares a node representation of a planar fault geometry
def universal_transformer_base_range(rhp): """Range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_discrete("num_rec_steps", [6, 8, 10]) rhp.set_discrete("hidden_size", [1024, 2048, 4096]) rhp.set_discrete("filter_size", [2048, 4096, 8192]) rhp.set_discrete("nu...
Range of hyperparameters.
def remove(path): """ Removes given path. :param path: Path to remove. :type path: unicode :return: Method success. :rtype: bool """ try: if os.path.isfile(path): LOGGER.debug("> Removing '{0}' file.".format(path)) os.remove(path) elif os.path.is...
Removes given path. :param path: Path to remove. :type path: unicode :return: Method success. :rtype: bool
def getscript(self, name): """Download a script from the server See MANAGESIEVE specifications, section 2.9 :param name: script's name :rtype: string :returns: the script's content on succes, None otherwise """ code, data, content = self.__send_command( ...
Download a script from the server See MANAGESIEVE specifications, section 2.9 :param name: script's name :rtype: string :returns: the script's content on succes, None otherwise
def stop_motor(self): '''stop motor''' if not self.valid_starter_settings(): return self.motor_t1 = time.time() self.starting_motor = False self.stopping_motor = True self.old_override = self.module('rc').get_override_chan(self.gasheli_settings.ignition_chan-1...
stop motor
def check_expected_errors(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:fu...
This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:func:`.expected_error_messages`, :py:func:`.allowed_error_me...
def dark(cls): "Make the current foreground color dark." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes)
Make the current foreground color dark.
def assign_job_record(self, tree_node): """ - looks for an existing job record in the DB, and if not found - creates a job record in STATE_EMBRYO and bind it to the given tree node """ try: job_record = self.job_dao.get_one(tree_node.process_name, tree_node.timeperiod) ex...
- looks for an existing job record in the DB, and if not found - creates a job record in STATE_EMBRYO and bind it to the given tree node
def refill_random(self): ''' refill the list of random_umis ''' self.random_umis = np.random.choice( list(self.umis.keys()), self.random_fill_size, p=self.prob) self.random_ix = 0
refill the list of random_umis
def map_field(fn, m) : """ Maps a field name, given a mapping file. Returns input if fieldname is unmapped. """ if m is None: return fn if fn in m: return m[fn] else: return fn
Maps a field name, given a mapping file. Returns input if fieldname is unmapped.
def inserir(self, user, pwd, name, email, user_ldap): """Inserts a new User and returns its identifier. The user will be created with active status. :param user: Username. String with a minimum 3 and maximum of 45 characters :param pwd: User password. String with a minimum 3 and maximu...
Inserts a new User and returns its identifier. The user will be created with active status. :param user: Username. String with a minimum 3 and maximum of 45 characters :param pwd: User password. String with a minimum 3 and maximum of 45 characters :param name: User name. String with a ...
def energy(self) -> ErrorValue: """X-ray energy""" return (ErrorValue(*(scipy.constants.physical_constants['speed of light in vacuum'][0::2])) * ErrorValue(*(scipy.constants.physical_constants['Planck constant in eV s'][0::2])) / scipy.constants.nano / sel...
X-ray energy
def _ir_calibrate(self, data): """Calibrate IR channels to BT.""" fk1 = float(self["planck_fk1"]) fk2 = float(self["planck_fk2"]) bc1 = float(self["planck_bc1"]) bc2 = float(self["planck_bc2"]) res = (fk2 / xu.log(fk1 / data + 1) - bc1) / bc2 res.attrs = data.att...
Calibrate IR channels to BT.
def _check_key(self, key): """ Ensures well-formedness of a key. """ if not len(key) == 2: raise TypeError('invalid key: %r' % key) elif key[1] not in TYPES: raise TypeError('invalid datatype: %s' % key[1])
Ensures well-formedness of a key.
def getQueryEngineDescription(self, queryEngine, **kwargs): """See Also: getQueryEngineDescriptionResponse() Args: queryEngine: **kwargs: Returns: """ response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs) return self._read_dataone...
See Also: getQueryEngineDescriptionResponse() Args: queryEngine: **kwargs: Returns:
def __render(template, state, index=0): """ Given a /template/ string, a parser /state/, and a starting offset (/index/), return the rendered version of the template. """ # Find a Match match = state.tag_re.search(template, index) if not match: return template[index:] info = get...
Given a /template/ string, a parser /state/, and a starting offset (/index/), return the rendered version of the template.
def iupacify(self): """Give the IUPAC conform representation. Mathematically speaking the angles in a zmatrix are representations of an equivalence class. We will denote an equivalence relation with :math:`\\sim` and use :math:`\\alpha` for an angle and :math:`\\delta` for a dih...
Give the IUPAC conform representation. Mathematically speaking the angles in a zmatrix are representations of an equivalence class. We will denote an equivalence relation with :math:`\\sim` and use :math:`\\alpha` for an angle and :math:`\\delta` for a dihedral angle. Then the f...
def register(self, fd, events): """ Register an USB-unrelated fd to poller. Convenience method. """ if fd in self.__fd_set: raise ValueError( 'This fd is a special USB event fd, it cannot be polled.' ) self.__poller.register(fd, eve...
Register an USB-unrelated fd to poller. Convenience method.
def pretty_print_post(req): """Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request. """ print(('{}\n{}\n{}\n\n{}'.format( '---...
Helper to print a "prepared" query. Useful to debug a POST query. However pay attention at the formatting used in this function because it is programmed to be pretty printed and may differ from the actual request.
def _get_imported_module(self, module_name): """try to get imported module reference by its name""" # if imported module on module_set add to list imp_mod = self.by_name.get(module_name) if imp_mod: return imp_mod # last part of import section might not be a module ...
try to get imported module reference by its name
def _create_event(instance, action): """ Create a new event, getting the use if django-cuser is available. """ user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user...
Create a new event, getting the use if django-cuser is available.
def send_animation( self, chat_id: Union[int, str], animation: str, caption: str = "", parse_mode: str = "", duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, disable_notification: bool = None, reply_to_message_...
Use this method to send animation files (animation or H.264/MPEG-4 AVC video without sound). Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) you can simply use "me" or "self". ...
def start(self): """Start the connector state machine.""" if self.started: raise ConnectorStartedError() self.started = True try: self.connect_watcher.start() self.timeout_watcher.start() self.sock.connect(self.addr) except IOErro...
Start the connector state machine.
def save(self): """Save current draft state.""" response = self.session.request("save:Message", [ self.data ]) self.data = response self.message_id = self.data["id"] return self
Save current draft state.
def UpdateNumberOfWarnings( self, number_of_consumed_warnings, number_of_produced_warnings): """Updates the number of warnings. Args: number_of_consumed_warnings (int): total number of warnings consumed by the process. number_of_produced_warnings (int): total number of warnings prod...
Updates the number of warnings. Args: number_of_consumed_warnings (int): total number of warnings consumed by the process. number_of_produced_warnings (int): total number of warnings produced by the process. Returns: bool: True if either number of warnings has increased. ...
def spdhg(x, f, g, A, tau, sigma, niter, **kwargs): r"""Computes a saddle point with a stochastic PDHG. This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that (x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x) where g : X -> IR_infty and f[i] : Y[i] -> IR_infty are convex...
r"""Computes a saddle point with a stochastic PDHG. This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that (x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x) where g : X -> IR_infty and f[i] : Y[i] -> IR_infty are convex, l.s.c. and proper functionals. For this algorithm,...
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem, **solver_options): """ Solve a boundary value problem using the collocation method. Parameters ---------- basis_kwargs : dict Dictionary of keyword arguments used to build basis...
Solve a boundary value problem using the collocation method. Parameters ---------- basis_kwargs : dict Dictionary of keyword arguments used to build basis functions. coefs_array : numpy.ndarray Array of coefficients for basis functions defining the initial ...
def node_copy(self, astr_pathInTree, **kwargs): """ Typically called by the explore()/recurse() methods and of form: f(pathInTree, **kwargs) and returns dictionary of which one element is 'status': True|False recursion continuation fl...
Typically called by the explore()/recurse() methods and of form: f(pathInTree, **kwargs) and returns dictionary of which one element is 'status': True|False recursion continuation flag is returned: 'continue': True|False to sign...
def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
Whether a give base directory is on the system exex prefix
def _init_go_sets(self, go_fins): """Get lists of GO IDs.""" go_sets = [] assert go_fins, "EXPECTED FILES CONTAINING GO IDs" assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format( L=' '.join(go_fins)) obj = GetGOs(self.godag) for fin in go_fins: ...
Get lists of GO IDs.
def format_auto_patching_settings(result): ''' Formats the AutoPatchingSettings object removing arguments that are empty ''' from collections import OrderedDict # Only display parameters that have content order_dict = OrderedDict() if result.enable is not None: order_dict['enable'] =...
Formats the AutoPatchingSettings object removing arguments that are empty
def setDuration( self, duration ): """ Changes the number of days that this item represents. This will move the end date the appropriate number of days away from the start date. The duration is calculated as the 1 plus the number of days from start to end, so a duration of ...
Changes the number of days that this item represents. This will move the end date the appropriate number of days away from the start date. The duration is calculated as the 1 plus the number of days from start to end, so a duration of 1 will have the same start and end date. The du...
def mark_current_profile_as_pending(self): """Mark the current profile as pending by colouring the text red. """ index = self.profile_combo.currentIndex() item = self.profile_combo.model().item(index) item.setForeground(QtGui.QColor('red'))
Mark the current profile as pending by colouring the text red.
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
Play like Spock, except breaking ties by drunk_value.
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 compute_venn3_regions(centers, radii): ''' Given the 3x2 matrix with circle center coordinates, and a 3-element list (or array) with circle radii [as returned from solve_venn3_circles], returns the 7 regions, comprising the venn diagram, as VennRegion objects. Regions are returned in order (Abc, aB...
Given the 3x2 matrix with circle center coordinates, and a 3-element list (or array) with circle radii [as returned from solve_venn3_circles], returns the 7 regions, comprising the venn diagram, as VennRegion objects. Regions are returned in order (Abc, aBc, ABc, abC, AbC, aBC, ABC) >>> centers, radii = s...
def _multicall(hook_impls, caller_kwargs, firstresult=False): """Execute a call into multiple python functions/methods and return the result(s). ``caller_kwargs`` comes from _HookCaller.__call__(). """ __tracebackhide__ = True results = [] excinfo = None try: # run impl and wrapper set...
Execute a call into multiple python functions/methods and return the result(s). ``caller_kwargs`` comes from _HookCaller.__call__().
def hash_id(salt, user_id, requester, state): """ Sets a user id to the internal_response, in the format specified by the internal response :type salt: str :type user_id: str :type requester: str :type state: satosa.state.State :rtype: str :param...
Sets a user id to the internal_response, in the format specified by the internal response :type salt: str :type user_id: str :type requester: str :type state: satosa.state.State :rtype: str :param salt: A salt string for the ID hashing :param user_id: th...
def landsat_c1_toa_cloud_mask(input_img, snow_flag=False, cirrus_flag=False, cloud_confidence=2, shadow_confidence=3, snow_confidence=3, cirrus_confidence=3): """Extract cloud mask from the Landsat Collection 1 TOA BQA band Parameters ---------- ...
Extract cloud mask from the Landsat Collection 1 TOA BQA band Parameters ---------- input_img : ee.Image Image from a Landsat Collection 1 TOA collection with a BQA band (e.g. LANDSAT/LE07/C01/T1_TOA). snow_flag : bool If true, mask snow pixels (the default is False). cirrus...
def GetEntry(self, entry): """ Get an entry. Tree collections are reset (see ``rootpy.tree.treeobject``) Parameters ---------- entry : int entry index Returns ------- ROOT.TTree.GetEntry : int The number of bytes read ...
Get an entry. Tree collections are reset (see ``rootpy.tree.treeobject``) Parameters ---------- entry : int entry index Returns ------- ROOT.TTree.GetEntry : int The number of bytes read
def update(self, story, params={}, **options): """Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. P...
Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. Parameters ---------- story : {Id} Globally ...
def create(self, **kwargs): """Create a new instance of this resource type. As a general rule, the identifier should have been provided, but in some subclasses the identifier is server-side-generated. Those classes have to overload this method to deal with that scenario. """ ...
Create a new instance of this resource type. As a general rule, the identifier should have been provided, but in some subclasses the identifier is server-side-generated. Those classes have to overload this method to deal with that scenario.
def toSet(self, flags): """ Generates a flag value based on the given set of values. :param values: <set> :return: <int> """ return {key for key, value in self.items() if value & flags}
Generates a flag value based on the given set of values. :param values: <set> :return: <int>
def constructor(cls, *args, **kwargs): """ :param args: The contract constructor arguments as positional arguments :param kwargs: The contract constructor arguments as keyword arguments :return: a contract constructor object """ if cls.bytecode is None: raise ...
:param args: The contract constructor arguments as positional arguments :param kwargs: The contract constructor arguments as keyword arguments :return: a contract constructor object
def to_enum(gtype, value): """Turn a string into an enum value ready to be passed into libvips. """ if isinstance(value, basestring if _is_PY2 else str): enum_value = vips_lib.vips_enum_from_nick(b'pyvips', gtype, _to_bytes(valu...
Turn a string into an enum value ready to be passed into libvips.
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( o...
Binary search to approach the boundary.
def plot_sfs_folded_scaled(*args, **kwargs): """Plot a folded scaled site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes/2,) Site frequency spectrum. yscale : string, optional Y axis scale. bins : int or array_like, int, optional Alle...
Plot a folded scaled site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes/2,) Site frequency spectrum. yscale : string, optional Y axis scale. bins : int or array_like, int, optional Allele count bins. n : int, optional Number ...
def _run_hooked_methods(self, hook: str): """ Iterate through decorated methods to find those that should be triggered by the current hook. If conditions exist, check them before running otherwise go ahead and run. """ for method in self._potentially_hooked_me...
Iterate through decorated methods to find those that should be triggered by the current hook. If conditions exist, check them before running otherwise go ahead and run.
def find_tags(self): """Find information about the tags in the repository.""" listing = self.context.capture('hg', 'tags') for line in listing.splitlines(): tokens = line.split() if len(tokens) >= 2 and ':' in tokens[1]: revision_number, revision_id = toke...
Find information about the tags in the repository.
def resolvePrefix(self, prefix, default=Namespace.default): """ Resolve the specified prefix to a namespace. The I{nsprefixes} is searched. If not found, it walks up the tree until either resolved or the top of the tree is reached. Searching up the tree provides for inherited ...
Resolve the specified prefix to a namespace. The I{nsprefixes} is searched. If not found, it walks up the tree until either resolved or the top of the tree is reached. Searching up the tree provides for inherited mappings. @param prefix: A namespace prefix to resolve. @type pr...
def from_shakemap(cls, shakemap_array): """ Build a site collection from a shakemap array """ self = object.__new__(cls) self.complete = self n = len(shakemap_array) dtype = numpy.dtype([(p, site_param_dt[p]) for p in 'sids lon lat dep...
Build a site collection from a shakemap array
def _convert_point(self, metric, ts, point, sd_point): """Convert an OC metric point to a SD point.""" if (metric.descriptor.type == metric_descriptor.MetricDescriptorType .CUMULATIVE_DISTRIBUTION): sd_dist_val = sd_point.value.distribution_value sd_dist_val.coun...
Convert an OC metric point to a SD point.
def warning(message, code='WARNING'): """Display Warning. Method prints the warning message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.color...
Display Warning. Method prints the warning message, message being given as an input. Arguments: message {string} -- The message to be displayed.
def ProcessLine(filename, linenumber, clean_lines, errors): """ Arguments: filename the name of the file linenumber the line number index clean_lines CleansedLines instance errors the error handling function """ CheckLintPragma(filename, linenumber, clean_lines.raw_lines...
Arguments: filename the name of the file linenumber the line number index clean_lines CleansedLines instance errors the error handling function
def _calc_fwhm(volume, mask, voxel_size=[1.0, 1.0, 1.0], ): """ Calculate the FWHM of a volume Estimates the FWHM (mm) of a volume's non-masked voxels Parameters ---------- volume : 3 dimensional array Functional data to have the FWHM measured. ...
Calculate the FWHM of a volume Estimates the FWHM (mm) of a volume's non-masked voxels Parameters ---------- volume : 3 dimensional array Functional data to have the FWHM measured. mask : 3 dimensional array A binary mask of the brain voxels in volume voxel_size : length 3 li...
def absent(name, user=None, config=None): ''' Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you wil...
Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you will need one Salt state for each. user The ...
def main(argv=None): """ Print accuracies """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print_accuracies(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, nb_iter=FLAGS.nb_it...
Print accuracies
def getProfile(self): """Get information about this object (label, owner, date created, etc.). :rtype: :class:`ObjectProfile` """ if self._create: return ObjectProfile() else: if self._profile is None: r = self.api.getObjectProfile(self.pi...
Get information about this object (label, owner, date created, etc.). :rtype: :class:`ObjectProfile`
def _check_dataset(self, features, target, sample_weight=None): """Check if a dataset has a valid feature set and labels. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} or None List of clas...
Check if a dataset has a valid feature set and labels. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} or None List of class labels for prediction sample_weight: array-like {n_samples} (opti...
def coerce_to_specific(datum): """ Coerces datum to the most specific data type possible Order of preference: datetime, boolean, integer, decimal, float, string >>> coerce_to_specific('-000000001854.60') Decimal('-1854.60') >>> coerce_to_specific(7.2) Decimal('7.2') >>> coerce_to_specif...
Coerces datum to the most specific data type possible Order of preference: datetime, boolean, integer, decimal, float, string >>> coerce_to_specific('-000000001854.60') Decimal('-1854.60') >>> coerce_to_specific(7.2) Decimal('7.2') >>> coerce_to_specific("Jan 17 2012") datetime.datetime(201...
def patched_nested_parse(self, *args, **kwargs): """Sets match_titles then calls stored_nested_parse.""" kwargs["match_titles"] = True return self.stored_nested_parse(*args, **kwargs)
Sets match_titles then calls stored_nested_parse.
def bind(self, destination='', source='', routing_key='', virtual_host='/', arguments=None): """Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virt...
Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: R...
def authcode_post(self, path, **kwargs): """Perform an HTTP POST to okcupid.com using this profiles session where the authcode is automatically added as a form item. """ kwargs.setdefault('data', {})['authcode'] = self.authcode return self._session.okc_post(path, **kwargs)
Perform an HTTP POST to okcupid.com using this profiles session where the authcode is automatically added as a form item.
def search_project_root(): """ Search your Django project root. returns: - path:string Django project root path """ while True: current = os.getcwd() if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file(): ...
Search your Django project root. returns: - path:string Django project root path
def rbac_policy_update(request, policy_id, **kwargs): """Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(r...
Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object
def add_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to internal state. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable ...
Adds `filepaths` to internal state. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted...
async def write(self, writer: Any, close_boundary: bool=True) -> None: """Write body.""" if not self._parts: return for part, encoding, te_encoding in self._parts: await writer.write(b'--' + self._boundary + b'\r\n') await writer.write(par...
Write body.
def _drop_definition(self): """Remove footer definition (footer part) associated with this section.""" rId = self._sectPr.remove_footerReference(self._hdrftr_index) self._document_part.drop_rel(rId)
Remove footer definition (footer part) associated with this section.
def info(job_name_or_id): """ View detailed information of a job. """ try: experiment = ExperimentClient().get(normalize_job_name(job_name_or_id)) except FloydException: experiment = ExperimentClient().get(job_name_or_id) task_instance_id = get_module_task_instance_id(experiment...
View detailed information of a job.
def compile(stream_spec, cmd='ffmpeg', overwrite_output=False): """Build command-line for invoking ffmpeg. The :meth:`run` function uses this to build the commnad line arguments and should work in most cases, but calling this function directly is useful for debugging or if you need to invoke ffmpeg ...
Build command-line for invoking ffmpeg. The :meth:`run` function uses this to build the commnad line arguments and should work in most cases, but calling this function directly is useful for debugging or if you need to invoke ffmpeg manually for whatever reason. This is the same as calling :meth:`...
def set_cookie(self, name: str, value: str, *, expires: Optional[str]=None, domain: Optional[str]=None, max_age: Optional[Union[int, str]]=None, path: str='/', secure: Optional[str]=None, httponly: Optional...
Set or update response cookie. Sets new cookie or updates existent with new value. Also updates only those params which are not None.
def quote_for_pydot(string): """ takes a string (or int) and encloses it with "-chars. if the string contains "-chars itself, they will be escaped. """ if isinstance(string, int): string = str(string) escaped_str = QUOTE_RE.sub(r'\\"', string) return u'"{}"'.format(escaped_str)
takes a string (or int) and encloses it with "-chars. if the string contains "-chars itself, they will be escaped.
def call_runtime(self): ''' Execute the runtime ''' cache = self.gather_cache() chunks = self.get_chunks() interval = self.opts['thorium_interval'] recompile = self.opts.get('thorium_recompile', 300) r_start = time.time() while True: ev...
Execute the runtime
def factory(cls, **kwargs): """ Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class. """ for name, obj in inspect...
Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class.
def read_redo_file(self, redo_file): """ Reads a .redo formated file and replaces all current interpretations with interpretations taken from the .redo file Parameters ---------- redo_file : path to .redo file to read """ if not self.clear_interpretations...
Reads a .redo formated file and replaces all current interpretations with interpretations taken from the .redo file Parameters ---------- redo_file : path to .redo file to read
def strip_position(self): """The current position of the strip, normalized to the range [0, 1], with 0 being the top/left-most point in the tablet's current logical orientation. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a terminating event with a value of -...
The current position of the strip, normalized to the range [0, 1], with 0 being the top/left-most point in the tablet's current logical orientation. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a terminating event with a value of -1 when the finger is lifted f...
def do_run(self, line): """run Perform each operation in the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().execute() self._print_info_if_verbose( "All operations in the write queue were successfully executed" ...
run Perform each operation in the queue of write operations.
def recalculate_attributes(self, force=False): # type: (bool) -> None """ Update all computed attributes. It is only needed if you need to access computed attributes after :meth:`patrial_fit` was called. """ if not self._attributes_dirty and not force: return ...
Update all computed attributes. It is only needed if you need to access computed attributes after :meth:`patrial_fit` was called.
def save(self, filename, encoding ='ISO-8859-1', standalone='no'): """ Stores any element in a svg file (including header). Calling this method only makes sense if the root element is an svg elemnt """ f = codecs.open(filename, 'w', encoding) s = self.wrap_xml(self.getXM...
Stores any element in a svg file (including header). Calling this method only makes sense if the root element is an svg elemnt
def detach(self): """ Detaches the instance from its history. Similar to creating a new object with the same field values. The id and identity fields are set to a new value. The returned object has not been saved, call save() afterwards when you are ready to persist the ...
Detaches the instance from its history. Similar to creating a new object with the same field values. The id and identity fields are set to a new value. The returned object has not been saved, call save() afterwards when you are ready to persist the object. ManyToMany and revers...
def get_named_queries(self): """ returns the named queries stored in the database. :rtype: dict (str -> str) mapping alias to full query string """ db = Database(path=self.path) return {k[6:]: v for k, v in db.get_configs('query.')}
returns the named queries stored in the database. :rtype: dict (str -> str) mapping alias to full query string
def allowance(self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded""" for line in self.rulelines: if line.applies_to(filename): return line.allowance return True
Preconditions: - our agent applies to this entry - filename is URL decoded
def _write_private_key_file(self, filename, key, format, password=None): """ Write an SSH2-format private key file in a form that can be read by paramiko or openssh. If no password is given, the key is written in a trivially-encoded format (base64) which is completely insecure. If ...
Write an SSH2-format private key file in a form that can be read by paramiko or openssh. If no password is given, the key is written in a trivially-encoded format (base64) which is completely insecure. If a password is given, DES-EDE3-CBC is used. :param str tag: ``"RSA"``...
def config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' Configures the node with the specified commands. This method is used to send configuration commands to the node....
Configures the node with the specified commands. This method is used to send configuration commands to the node. It will take either a string or a list and prepend the necessary commands to put the session into config mode. Returns the diff after the configuration commands are loaded. config_fil...
def read_frames(self, frame_size, hop_size, offset=0, duration=None, block_size=None): """ Generator that reads and returns the samples of the track in frames. Args: frame_size (int): The number of samples per frame. hop_size (int): The number of samp...
Generator that reads and returns the samples of the track in frames. Args: frame_size (int): The number of samples per frame. hop_size (int): The number of samples between two frames. offset (float): The time in seconds, from where to start readin...
def unlisten_to_node(self, id_): """Stop listening to a job Parameters ---------- id_ : str An ID to remove Returns -------- str or None The ID removed or None if the ID was not removed """ id_pubsub = _pubsub_key(id_) ...
Stop listening to a job Parameters ---------- id_ : str An ID to remove Returns -------- str or None The ID removed or None if the ID was not removed
async def release(self, connection, *, timeout=None): """Release a database connection back to the pool. :param Connection connection: A :class:`~asyncpg.connection.Connection` object to release. :param float timeout: A timeout for releasing the connection. If not speci...
Release a database connection back to the pool. :param Connection connection: A :class:`~asyncpg.connection.Connection` object to release. :param float timeout: A timeout for releasing the connection. If not specified, defaults to the timeout provided in the corresp...
def absent(name, auth=None, **kwargs): ''' Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from ''' rule_id = kwargs['rule_id'] ret = {'n...
Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from
def create(self, typ, identifier, parent=None): """Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int ...
Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int :param parent: the parent refobject :type paren...