code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update(self): """Update hook """ super(AnalysisProfileAnalysesView, self).update() self.allow_edit = self.is_edit_allowed() self.configuration = self.get_configuration()
Update hook
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", formatter=optparse.TitledHelpFormatter()) parser....
Parse argv for options and arguments, and start schema generation.
def eval_fitness(self, chromosome): """ Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map. """ # convert DNA to represented sprinkler coordinates sx, sy = self.translator.translate_chromosome(chromosome)...
Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map.
def list_types_view(request, semester, profile=None): """ View the details of a particular WorkshiftType. """ page_name = "Workshift Types" full_management = utils.can_manage(request.user, semester) any_management = utils.can_manage(request.user, semester, any_pool=True) types = WorkshiftTy...
View the details of a particular WorkshiftType.
def formatex(ex, msg='[!?] Caught exception', prefix=None, key_list=[], locals_=None, iswarning=False, tb=False, N=0, keys=None, colored=None): r""" Formats an exception with relevant info Args: ex (Exception): exception to print msg (unicode): a message to displa...
r""" Formats an exception with relevant info Args: ex (Exception): exception to print msg (unicode): a message to display to the user (default = u'[!?] Caught exception') keys (None): a list of strings denoting variables or expressions of interest (default = []) iswarning (bool...
def parse(self, commands): """ Parse a list of commands. """ # Get rid of dummy objects that represented deleted objects in # the last parsing round. to_delete = [] for id_, val in self._objects.items(): if val == JUST_DELETED: to_delete.appen...
Parse a list of commands.
def insert(self, thread): """Process a thread and insert its comments in the DB.""" thread_id = thread['id'] title = thread['title'] self.db.threads.new(thread_id, title) comments = list(map(self._build_comment, thread['comments'])) comments.sort(key=lambda comment: comm...
Process a thread and insert its comments in the DB.
def get_default_connection(): """Returns the default datastore connection. Defaults endpoint to helper.get_project_endpoint_from_env() and credentials to helper.get_credentials_from_env(). Use set_options to override defaults. """ tid = id(threading.current_thread()) conn = _conn_holder.get(tid) if no...
Returns the default datastore connection. Defaults endpoint to helper.get_project_endpoint_from_env() and credentials to helper.get_credentials_from_env(). Use set_options to override defaults.
def percept(self, agent): """The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None'). Unlike the TrivialVacuumEnvironment, location is NOT perceived.""" status = if_(self.some_things_at(agent.location, Dirt), 'Dirty', 'Clean') bump = if_(agent.bump, 'Bump', ...
The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None'). Unlike the TrivialVacuumEnvironment, location is NOT perceived.
def text(draw, xy, txt, fill=None, font=None): """ Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the prescribed fill and font. :param draw: A valid canvas to draw the text onto. :type draw: PIL.ImageDraw :param txt: The text string to display (must be ASCII only). :type tx...
Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the prescribed fill and font. :param draw: A valid canvas to draw the text onto. :type draw: PIL.ImageDraw :param txt: The text string to display (must be ASCII only). :type txt: str :param xy: An ``(x, y)`` tuple denoting the top-...
def verify_retry_data(self, retry_data): ''' verifies the specified retry data ''' retry_defaults = { 'until': True, 'attempts': 2, 'splay': 0, 'interval': 30, } expected_data = { 'until': bool, ...
verifies the specified retry data
def clean_stats(self): '''Stats with topics and channels keyed on topic and channel names''' stats = self.stats() if 'topics' in stats: # pragma: no branch topics = stats['topics'] topics = dict((t.pop('topic_name'), t) for t in topics) for topic, data in top...
Stats with topics and channels keyed on topic and channel names
def get_value(self, element): """ | Returns the given element value. | If multiple elements with the same name exists, only the first encountered will be returned. Usage:: >>> plist_file_parser = PlistFileParser("standard.plist") >>> plist_file_parser.parse() ...
| Returns the given element value. | If multiple elements with the same name exists, only the first encountered will be returned. Usage:: >>> plist_file_parser = PlistFileParser("standard.plist") >>> plist_file_parser.parse() True >>> plist_file_parser.g...
def close(self, reply_code=0, reply_text='', class_id=0, method_id=0): ''' Close this channel. Routes to channel.close. ''' # In the off chance that we call this twice. A good example is if # there's an error in close listeners and so we're still inside a # single call t...
Close this channel. Routes to channel.close.
def keyReleaseEvent(self, event): """ Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_released.emit(event) i...
Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent
def get_candles(self, market, tick_interval): """ Used to get all tick candles for a market. Endpoint: 1.1 NO EQUIVALENT 2.0 /pub/market/GetTicks Example :: { success: true, message: '', result: [ { O: 421.20630125...
Used to get all tick candles for a market. Endpoint: 1.1 NO EQUIVALENT 2.0 /pub/market/GetTicks Example :: { success: true, message: '', result: [ { O: 421.20630125, H: 424.03951276, L: 421.20...
def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None): """ Set the DC Subject literal value :param value: Value of the subject node :param lang: Language in which the value is """ return self.metadata.add(key=DC.subject, value=value, lang=lang)
Set the DC Subject literal value :param value: Value of the subject node :param lang: Language in which the value is
def require_debian_packages(packages: List[str]) -> None: """ Ensure specific packages are installed under Debian. Args: packages: list of packages Raises: ValueError: if any are missing """ present = are_debian_packages_installed(packages) missing_packages = [k for k, v i...
Ensure specific packages are installed under Debian. Args: packages: list of packages Raises: ValueError: if any are missing
def isspecword(somestr): """ Checks that some string is a special word :param str somestr: It is some string that will be checked for special word. The special word is a string that contains only alphabetic characters, its length not less 1 character and not more 2 characters and a...
Checks that some string is a special word :param str somestr: It is some string that will be checked for special word. The special word is a string that contains only alphabetic characters, its length not less 1 character and not more 2 characters and also noone characters does not re...
def build(self, field: Field) -> Mapping[str, Any]: """ Build a swagger parameter from a marshmallow field. """ builder_types = self.builder_types() + [ # put default last self.default_builder_type() ] builders: List[ParameterBuilder] = [ ...
Build a swagger parameter from a marshmallow field.
def fromtimestamp(cls, timestamp, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) converter = _time.localtime if tz is None else _time.gmtime self = cls._from_timestam...
Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well.
def deploy_from_template(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context): """ :param cancellation_context: :param reservation_id: :param si: :param logger: :type data_holder: DeployFromTemplateDetails :type vcenter_data_mod...
:param cancellation_context: :param reservation_id: :param si: :param logger: :type data_holder: DeployFromTemplateDetails :type vcenter_data_model :rtype DeployAppResult: :return:
def _create_entry(entry: dict, source: Source = None) -> dict: """Filter and normalize the output of pipdeptree entry.""" entry["package_name"] = entry["package"].pop("package_name") entry["package_version"] = entry["package"].pop("installed_version") if source: entry["index_url"] = source.url ...
Filter and normalize the output of pipdeptree entry.
def complete_command(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]: """Complete the command using the argparse metadata and provided argument dictionary""" # Count which positional argument index we're at now. Loop through all tokens on the command line so far ...
Complete the command using the argparse metadata and provided argument dictionary
def recent(self): ''' List recent wiki. ''' kwd = { 'pager': '', 'title': 'Recent Pages', } self.render('wiki_page/wiki_list.html', view=MWiki.query_recent(), format_date=tools.format_date, ...
List recent wiki.
def reset_ctx(self, ctx): """Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context...
Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context.
def format(self, show_enabled=True): '''format display item''' what = '' if show_enabled: if self.enabled: what += ' y ' else: what += ' n ' pass pass if self.fmt: what += self.fmt + ' ' ...
format display item
def check_split_ratio(split_ratio): """Check that the split ratio argument is not malformed""" valid_ratio = 0. if isinstance(split_ratio, float): # Only the train set relative ratio is provided # Assert in bounds, validation size is zero assert 0. < split_ratio < 1., ( "...
Check that the split ratio argument is not malformed
def head(self, path, query=None, data=None, redirects=True): """ HEAD request wrapper for :func:`request()` """ return self.request('HEAD', path, query, None, redirects)
HEAD request wrapper for :func:`request()`
def main(): '''This is the main function of this script. The current script args are shown below :: Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY] [--filterby FILTERBY] [--splitout SPLITOUT] [--outprefix OUTPREFIX] [--maxkeyworke...
This is the main function of this script. The current script args are shown below :: Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY] [--filterby FILTERBY] [--splitout SPLITOUT] [--outprefix OUTPREFIX] [--maxkeyworkers MAXKEYWORKERS] ...
def get_webhook(self, scaling_group, policy, webhook): """ Gets the detail for the specified webhook. """ return self._manager.get_webhook(scaling_group, policy, webhook)
Gets the detail for the specified webhook.
def get_or_wait(self, path, name): """Get data of node under path, or wait for it.""" # First, get children and watch folder. d, watch = self.get_children_and_watch(path) deferred = Deferred() path += "/" + name @watch.addCallback def _notify(event): ...
Get data of node under path, or wait for it.
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .....
Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)...
def fix_line_range(source_code, start, end, options): """Apply autopep8 (and docformatter) between the lines start and end of source.""" # TODO confirm behaviour outside range (indexing starts at 1) start = max(start, 1) options.line_range = [start, end] from autopep8 import fix_code fixed ...
Apply autopep8 (and docformatter) between the lines start and end of source.
def queryName(self, queryName): """Specifies the name of the :class:`StreamingQuery` that can be started with :func:`start`. This name must be unique among all the currently active queries in the associated SparkSession. .. note:: Evolving. :param queryName: unique name for the...
Specifies the name of the :class:`StreamingQuery` that can be started with :func:`start`. This name must be unique among all the currently active queries in the associated SparkSession. .. note:: Evolving. :param queryName: unique name for the query >>> writer = sdf.writeStrea...
def get_msms_annotations_parallelize(self, sc, representatives_only=True, force_rerun=False): """Run MSMS on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-msms']`` Args: ...
Run MSMS on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-msms']`` Args: representative_only (bool): If analysis should only be run on the representative structure ...
def make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype='band'): """ Generates the b and a coefficients for a butterworth bandpass IIR filter. Parameters ---------- CenterFreq : float central frequency of bandpass bandwidth : float width of the bandpa...
Generates the b and a coefficients for a butterworth bandpass IIR filter. Parameters ---------- CenterFreq : float central frequency of bandpass bandwidth : float width of the bandpass from centre to edge SampleFreq : float Sample frequency of filter order : int, optiona...
def format(self, date): """ Given a datetime.datetime object, return a string representing this date/time, formatted according to this dateformat. """ context = {'date': date} for handler in self.format_chain: handler(self, date, context) return eval(s...
Given a datetime.datetime object, return a string representing this date/time, formatted according to this dateformat.
def parse_metric_family(self, response, scraper_config): """ Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric """ ...
Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric
def post(self, request, *args, **kwargs): """Creates new mongoengine records.""" # TODO - make sure to check the rights of the poster #self.get_queryset() # TODO - write something that grabs the document class better form_class = self.get_form_class() form = self.get_form(form_cl...
Creates new mongoengine records.
def visit((prefix, strip, found), dirname, names): """ Visit directory, create distutil tuple Add distutil tuple for each directory using this format: (destination, [dirname/file1, dirname/file2, ...]) distutil will copy later file1, file2, ... info destination. """ files = [] # Iterate ...
Visit directory, create distutil tuple Add distutil tuple for each directory using this format: (destination, [dirname/file1, dirname/file2, ...]) distutil will copy later file1, file2, ... info destination.
def visit_Call(self, node): """ Function call depend on all function use in the call. >> a = foo(bar(c) or foobar(d)) Return type depend on [foo, bar] or [foo, foobar] """ args = [self.visit(arg) for arg in node.args] func = self.visit(node.func) params ...
Function call depend on all function use in the call. >> a = foo(bar(c) or foobar(d)) Return type depend on [foo, bar] or [foo, foobar]
def consoleLabel(deduper): # pragma: no cover ''' Command line interface for presenting and labeling training pairs by the user Argument : A deduper object ''' finished = False use_previous = False fields = unique(field.field for field in de...
Command line interface for presenting and labeling training pairs by the user Argument : A deduper object
def get_or_set_hash(name, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'): ''' Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys tha...
Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys that are specific to a single minion that don't need to be stored somewhere centrally. State Example: .. code-bloc...
def get_queryset(self): """ Returns a queryset of models for the month requested """ qs = super(BaseCalendarMonthView, self).get_queryset() year = self.get_year() month = self.get_month() date_field = self.get_date_field() end_date_field = self.get_end_d...
Returns a queryset of models for the month requested
def RGB(self, val): """Set the color using an Nx3 array of RGB uint8 values""" # need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255. self.rgba = val
Set the color using an Nx3 array of RGB uint8 values
def _match_elements(dom, matches): """ Find location of elements matching patterns specified in `matches`. Args: dom (obj): HTMLElement DOM tree. matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``. Returns: dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}...
Find location of elements matching patterns specified in `matches`. Args: dom (obj): HTMLElement DOM tree. matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``. Returns: dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}, ..}``
def unpack(self, fmt, length=1): """ Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of byte...
Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of bytes to read. Returns: variable: th...
def zhang_huang_solar(alt, cloud_cover, relative_humidity, dry_bulb_present, dry_bulb_t3_hrs, wind_speed, irr_0=1355): """Calculate global horizontal solar irradiance using the Zhang-Huang model. Note: [1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typ...
Calculate global horizontal solar irradiance using the Zhang-Huang model. Note: [1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2. Args: alt: A solar altitude in degrees. cl...
def raise_exit_downtime_log_entry(self): """Raise CONTACT DOWNTIME ALERT entry (info level) Format is : "CONTACT DOWNTIME ALERT: *get_name()*;STOPPED; Contact has entered a period of scheduled downtime" Example : "CONTACT DOWNTIME ALERT: test_contact;STOPPED; ...
Raise CONTACT DOWNTIME ALERT entry (info level) Format is : "CONTACT DOWNTIME ALERT: *get_name()*;STOPPED; Contact has entered a period of scheduled downtime" Example : "CONTACT DOWNTIME ALERT: test_contact;STOPPED; Contact has entered a period of scheduled down...
def to_potential(f): ''' to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to a potential function, that conversion is performed then the result is yielded. to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the ide...
to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to a potential function, that conversion is performed then the result is yielded. to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the identity function). to_potential...
def factory(data): """ Try to reconstruct the APIResource from its data. :param data: The APIResource data :type data: dict :return: The guessed APIResource :raise exceptions.UnkownAPIResource when it's impossible to reconstruct the APIResource from its dat...
Try to reconstruct the APIResource from its data. :param data: The APIResource data :type data: dict :return: The guessed APIResource :raise exceptions.UnkownAPIResource when it's impossible to reconstruct the APIResource from its data.
def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True): '''Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : N...
Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : None or int Step size for each slice. If `None`, then the default ...
def img(self): '''return a cv image for the thumbnail''' if self._img is not None: return self._img self._img = cv2.cvtColor(self.original_img, cv2.COLOR_BGR2RGB) if self.border_width and self.border_colour is not None: cv2.rectangle(self._img, (0, 0), (self.widt...
return a cv image for the thumbnail
def observers(self): """the players who are actually observers""" ret = [] for player in self.players: try: if player.observer: ret.append(player) except: pass # ignore PlayerRecords which don't have an observer attribute return ret
the players who are actually observers
def update_nio(self, port_number, nio): """ Update an nio on this node :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ bridge_name = "{}-{}".format(self._id, port_number) if self._ubridge_hypervisor and self._ubridge_hypervis...
Update an nio on this node :param nio: NIO instance to add :param port_number: port to allocate for the NIO
def move_to_other_side(self, init_slab, index_of_sites): """ This method will Move a set of sites to the other side of the slab (opposite surface). Arg: init_slab (structure): A structure object representing a slab. index_of_sites (list of ints): The list of indi...
This method will Move a set of sites to the other side of the slab (opposite surface). Arg: init_slab (structure): A structure object representing a slab. index_of_sites (list of ints): The list of indices representing the sites we want to move to the other side....
def view_global_gmfs(token, dstore): """ Display GMFs averaged on everything for debugging purposes """ imtls = dstore['oqparam'].imtls row = dstore['gmf_data/data']['gmv'].mean(axis=0) return rst_table([row], header=imtls)
Display GMFs averaged on everything for debugging purposes
def subplots(figures,shape=None, shared_xaxes=False, shared_yaxes=False, start_cell='top-left', theme=None,base_layout=None, **kwargs): """ Generates a subplot view for a set of figures This is a wrapper for plotly.tools.make_subplots Parameters: ----------- figures : [Figures] List of Plot...
Generates a subplot view for a set of figures This is a wrapper for plotly.tools.make_subplots Parameters: ----------- figures : [Figures] List of Plotly Figures shape : (rows,cols) Tuple indicating the size of rows and columns If omitted then the layout is automatically set shared_xaxes : bool As...
def run_bcl2fastq(run_folder, ss_csv, config): """Run bcl2fastq for de-multiplexing and fastq generation. run_folder -- directory of Illumina outputs ss_csv -- Samplesheet CSV file describing samples. """ bc_dir = os.path.join(run_folder, "Data", "Intensities", "BaseCalls") output_dir = os.path....
Run bcl2fastq for de-multiplexing and fastq generation. run_folder -- directory of Illumina outputs ss_csv -- Samplesheet CSV file describing samples.
def rescale(self, fun): """ perform raster computations with custom functions and assign them to the existing raster object in memory Parameters ---------- fun: function the custom function to compute on the data Examples -------- >>> with Ra...
perform raster computations with custom functions and assign them to the existing raster object in memory Parameters ---------- fun: function the custom function to compute on the data Examples -------- >>> with Raster('filename') as ras: >>> ras...
def delete_trigger(self, trigger): """ Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: ...
Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: `pyowm.alertapi30.trigger.Trigger` :returns: `N...
def open_args(subparsers): """ The `mp open` command will open a resource with the system application, such as Excel or OpenOffice """ parser = subparsers.add_parser( 'open', help='open a CSV resoruce with a system application', description=open_args.__doc__, formatter_c...
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
def emission_lock(self, name): """Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: ...
Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: class Foo(Dispatcher): ...
def read_dotenv(dotenv=None, override=False): """ Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find manage.py and then find the dotenv. If tests rely on .env files, setting the overwrite flag to True is a safe way to ensure tes...
Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find manage.py and then find the dotenv. If tests rely on .env files, setting the overwrite flag to True is a safe way to ensure tests run consistently across all environments. :param o...
def delete_secret(namespace, name, apiserver_url=None, force=True): ''' .. versionadded:: 2016.3.0 Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name. CLI Example: .. code-block:: bash salt '*' k8s.delete_secret namespace_name secret_n...
.. versionadded:: 2016.3.0 Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name. CLI Example: .. code-block:: bash salt '*' k8s.delete_secret namespace_name secret_name salt '*' k8s.delete_secret namespace_name secret_name http://kube-m...
def get_ini(self, incl_unset=False): """Return the config dictionary in INI format Args: incl_unset (bool): include variables with no defaults. Returns: str: string of the config file in INI format """ configp = configparser.ConfigParser(allow_no_value=...
Return the config dictionary in INI format Args: incl_unset (bool): include variables with no defaults. Returns: str: string of the config file in INI format
def prune_clusters(clusters, index, n=3): """ Delete clusters with fewer than n elements. """ torem = set(c for c in clusters if c.size < n) pruned_clusters = [c for c in clusters if c.size >= n] terms_torem = [] for term, clusters in index.items(): index[term] = clusters - torem ...
Delete clusters with fewer than n elements.
def setCenter(self, loc): """ Move this region so it is centered on ``loc`` """ offset = self.getCenter().getOffset(loc) # Calculate offset from current center return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
Move this region so it is centered on ``loc``
def BuildApprovalUrn(self, approval_id): """Builds approval object urn.""" event = rdf_events.AuditEvent( user=self.token.username, action="CLIENT_APPROVAL_REQUEST", client=self.subject_urn, description=self.reason) events.Events.PublishEvent("Audit", event, token=self.token)...
Builds approval object urn.
def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None, vcount_limits=None, smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot", figure_key=...
Use at own risk, requires ipyvolume
def stake(self, confidence, value, tournament=1): """Participate in the staking competition. Args: confidence (float or str): your confidence (C) value value (float or str): amount of NMR you are willing to stake tournament (int): ID of the tournament (optional, defa...
Participate in the staking competition. Args: confidence (float or str): your confidence (C) value value (float or str): amount of NMR you are willing to stake tournament (int): ID of the tournament (optional, defaults to 1) Returns: dict: stake informat...
def validate_queues(queues): """ Validate the queues configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format. """ if not isinstance(queues, dict): raise exceptions.ConfigurationException( "'queues' must ...
Validate the queues configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format.
def get_parsed_query(self): """ Returns string with last query parsed. Assuming called after search_datasets.""" return '{} OR {}'.format( self.backend.dataset_index.get_parsed_query()[0], self.backend.partition_index.get_parsed_query()[0])
Returns string with last query parsed. Assuming called after search_datasets.
def checkout(cwd, remote, target=None, user=None, username=None, password=None, *opts): ''' Download a working copy of the remote Subversion repository directory or file cwd The path to the Subversion repository ...
Download a working copy of the remote Subversion repository directory or file cwd The path to the Subversion repository remote : None URL to checkout target : None The name to give the file or directory working copy Default: svn uses the remote basename user : Non...
def send(self, topic, kmsg): """ Send the message into the given topic :param str topic: a kafka topic :param ksr.transport.Message kmsg: Message to serialize :return: Execution result :rtype: kser.result.Result """ try: self.client.do_request( ...
Send the message into the given topic :param str topic: a kafka topic :param ksr.transport.Message kmsg: Message to serialize :return: Execution result :rtype: kser.result.Result
def duplicate_statements(model, oldorigin, neworigin, rfilter=None): ''' Take links with a given origin, and create duplicate links with the same information but a new origin :param model: Versa model to be updated :param oldres: resource IRI to be duplicated :param newres: origin resource IRI for ...
Take links with a given origin, and create duplicate links with the same information but a new origin :param model: Versa model to be updated :param oldres: resource IRI to be duplicated :param newres: origin resource IRI for duplication :return: None
def convert_error(exc_src, exc_dest): """A decorator for reraising exceptions with a different type. Mostly useful for IOError. Args: exc_src (type): The source exception type exc_dest (type): The target exception type. """ def wrap(func): @wraps(func) def wrapper(...
A decorator for reraising exceptions with a different type. Mostly useful for IOError. Args: exc_src (type): The source exception type exc_dest (type): The target exception type.
def get_instance(self, payload): """ Build an instance of SampleInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance """ ...
Build an instance of SampleInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
def _iter_qs(self): """Iterate over the Q values """ # work out how many Qs we need cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.) nplanes = int(max(ceil(cumum / self.deltam), 1)) dq = cumum / nplanes # pylint: disable=invalid-name for i in xrange(nplan...
Iterate over the Q values
def setModelData(self, spinBox, model, index): """Gets data from the editor widget and stores it in the specified model at the item index. Args: spinBox (QDoubleSpinBox): editor widget. model (QAbstractItemModel): parent model. index (QModelIndex): model data index. ...
Gets data from the editor widget and stores it in the specified model at the item index. Args: spinBox (QDoubleSpinBox): editor widget. model (QAbstractItemModel): parent model. index (QModelIndex): model data index.
def open(self, filename, mode='r'): """Returns file object from given filename.""" self._raise_if_none() fn = path_join(self.path, filename) return open(fn, mode)
Returns file object from given filename.
def extended_euclid(a, b): """ It calculates the GCD of a and b, and two values x and y such that: a*x + b*y = GCD(a,b). This code has been taken from the project sympy. :param a: first integer :param b: second integer :return: x,y and the GCD of a and b ...
It calculates the GCD of a and b, and two values x and y such that: a*x + b*y = GCD(a,b). This code has been taken from the project sympy. :param a: first integer :param b: second integer :return: x,y and the GCD of a and b
def currencies(self) -> CurrenciesAggregate: """ Returns the Currencies aggregate """ if not self.__currencies_aggregate: self.__currencies_aggregate = CurrenciesAggregate(self.book) return self.__currencies_aggregate
Returns the Currencies aggregate
def factorize(self): """Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1 """ # compute new coefficients for reconstructing data points self.update_w() # for CHNMF it is sometimes useful to only ...
Do factorization s.t. data = dot(dot(data,beta),H), under the convexity constraint beta >=0, sum(beta)=1, H >=0, sum(H)=1
def get_meta_data_index_at_scan_parameter(meta_data_array, scan_parameter_name): '''Takes the analyzed meta_data table and returns the indices where the scan parameter changes Parameters ---------- meta_data_array : numpy.recordarray scan_parameter_name : string Returns ------- numpy.n...
Takes the analyzed meta_data table and returns the indices where the scan parameter changes Parameters ---------- meta_data_array : numpy.recordarray scan_parameter_name : string Returns ------- numpy.ndarray: first dimension: scan parameter value second dimension: index wh...
def is_valid_pid_to_be_updated(did): """Assert that ``did`` is the PID of an object that can be updated (obsoleted) with MNStorage.update()""" if not d1_gmn.app.did.is_valid_pid_to_be_updated(did): raise d1_common.types.exceptions.InvalidRequest( 0, 'Object cannot be updated ...
Assert that ``did`` is the PID of an object that can be updated (obsoleted) with MNStorage.update()
def ppp_value(simdata, trueval, round=3): """ Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text...
Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic o...
def initialize(self, timestamp=None, user=None, comment=None, filename=None, source=None, size=None): self.timestamp = none_or(timestamp, Timestamp) """ Upload timestamp : mwtypes.Timestamp | None """ self.user = none_or(user, User) """ Contri...
Upload timestamp : mwtypes.Timestamp | None
def error_map_source(self, kwargs_source, x_grid, y_grid, cov_param): """ variance of the linear source reconstruction in the source plane coordinates, computed by the diagonal elements of the covariance matrix of the source reconstruction as a sum of the errors of the basis set. ...
variance of the linear source reconstruction in the source plane coordinates, computed by the diagonal elements of the covariance matrix of the source reconstruction as a sum of the errors of the basis set. :param kwargs_source: keyword arguments of source model :param x_grid: x-axis of...
def getSolutions(self): """ Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All sol...
Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All solutions for the problem @rtype: list ...
def disconnect(self, driver): """Disconnect using the protocol specific method.""" self.log("SSH disconnect") try: self.device.ctrl.sendline('\x03') self.device.ctrl.sendline('\x04') except OSError: self.log("Protocol already disconnected")
Disconnect using the protocol specific method.
def vn_allocate(call=None, kwargs=None): ''' Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used ...
Allocates a new virtual network in OpenNebula. .. versionadded:: 2016.3.0 path The path to a file containing the template of the virtual network to allocate. Syntax within the file can be the usual attribute=value or XML. Can be used instead of ``data``. data Contains the ...
def largest_connected_component(volume): """Return the largest connected component of a 3D array. Parameters ----------- volume: numpy.array 3D boolean array. Returns -------- volume: numpy.array 3D boolean array with only one connected component. """ # We use asarr...
Return the largest connected component of a 3D array. Parameters ----------- volume: numpy.array 3D boolean array. Returns -------- volume: numpy.array 3D boolean array with only one connected component.
def error(self, text): """ Ajout d'un message de log de type ERROR """ self.logger.error("{}{}".format(self.message_prefix, text))
Ajout d'un message de log de type ERROR
def top1(scores: mx.nd.NDArray, offset: mx.nd.NDArray) -> Tuple[mx.nd.NDArray, mx.nd.NDArray, mx.nd.NDArray]: """ Get the single lowest element per sentence from a `scores` matrix. Expects that beam size is 1, for greedy decoding. NOTE(mathmu): The current implementation of argmin in MXNet muc...
Get the single lowest element per sentence from a `scores` matrix. Expects that beam size is 1, for greedy decoding. NOTE(mathmu): The current implementation of argmin in MXNet much slower than topk with k=1. :param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabula...
def update_callback(self, handle, events): """Update the event mask for a callback.""" if self._poll is None: raise RuntimeError('poll instance is closed') if not has_callback(self, handle): raise ValueError('no such callback') if events & ~(READABLE|WRITABLE): ...
Update the event mask for a callback.
def _get_module(self, line): """Finds the name of the module and retrieves it from the parser cache.""" #Finding the module name is trivial; start at the beginning of #the module and iterate lines until we find the module. for sline in self._source: if len(sline) > 0 and slin...
Finds the name of the module and retrieves it from the parser cache.
def propinquity_fn_to_study_tree(inp_fn, strip_extension=True): """This should only be called by propinquity - other code should be treating theses filenames (and the keys that are based on them) as opaque strings. Takes a filename (or key if strip_extension is False), returns (study_id, tree_id) prop...
This should only be called by propinquity - other code should be treating theses filenames (and the keys that are based on them) as opaque strings. Takes a filename (or key if strip_extension is False), returns (study_id, tree_id) propinquity provides a map to look up the study ID and tree ID (and git SHA...
def fg(self) -> np.array: """A uint8 array with the shape (height, width, 3). You can change the consoles foreground colors by using this array. Index this array with ``console.fg[i, j, channel] # order='C'`` or ``console.fg[x, y, channel] # order='F'``. """ fg = self...
A uint8 array with the shape (height, width, 3). You can change the consoles foreground colors by using this array. Index this array with ``console.fg[i, j, channel] # order='C'`` or ``console.fg[x, y, channel] # order='F'``.