code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def cnmfrm(cname, lenout=_default_len_out): """ Retrieve frame ID code and name to associate with an object. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html :param cname: Name of the object to find a frame for. :type cname: int :param lenout: Maximum length available for ...
Retrieve frame ID code and name to associate with an object. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html :param cname: Name of the object to find a frame for. :type cname: int :param lenout: Maximum length available for frame name. :type lenout: int :return: ...
def contains (self, point): """contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2, 3) ) False """ return...
contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2, 3) ) False
def get_model(self): """ Returns an instance of Bayesian Model. """ model = BayesianModel() model.add_nodes_from(self.variables) model.add_edges_from(self.edges) model.name = self.model_name tabular_cpds = [] for var, values in self.variable_CPD.i...
Returns an instance of Bayesian Model.
def container_clone(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /container-xxxx/clone API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone """ return DXHTTPRequest('/%s/clone' % object_id, input...
Invokes the /container-xxxx/clone API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone
def create(zone, brand, zonepath, force=False): ''' Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. cod...
Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ...
def default_help_formatter(quick_helps): """Apply default formatting for help messages :param quick_helps: list of tuples containing help info """ ret = '' for line in quick_helps: cmd_path, param_hlp, cmd_hlp = line ret += ' '.join(cmd_path) + ' ' if param_hlp: ...
Apply default formatting for help messages :param quick_helps: list of tuples containing help info
def get_port_at(self, tile_id, direction): """ If no port is found, a new none port is made and added to self.ports. Returns the port. :param tile_id: :param direction: :return: Port """ for port in self.ports: if port.tile_id == tile_id and ...
If no port is found, a new none port is made and added to self.ports. Returns the port. :param tile_id: :param direction: :return: Port
def get_unique_nonzeros(arr): """ Return a sorted list of the non-zero unique values of arr. Parameters ---------- arr: numpy.ndarray The data array Returns ------- list of items of arr. """ rois = np.unique(arr) rois = rois[np.nonzero(rois)] rois.sort() return...
Return a sorted list of the non-zero unique values of arr. Parameters ---------- arr: numpy.ndarray The data array Returns ------- list of items of arr.
def upgrade(): """Upgrade database.""" op.create_table( 'oaiserver_set', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('spec', sa.String(length=255), nulla...
Upgrade database.
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None): """ Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method ...
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method must be called before any oscrypto submodules are imported. :param libcrypt...
def on_failure(self, exc, task_id, args, kwargs, einfo): """ Capture the exception that caused the task to fail, if any. """ log.error('[{}] failed due to {}'.format(task_id, getattr(einfo, 'traceback', None))) super(LoggedTask, self).on_failure(exc, task_id, args, kwargs, einfo)
Capture the exception that caused the task to fail, if any.
def _walk_through(job_dir): ''' Walk though the jid dir and look for jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) if not os.path.exists(t_path): continue for final in os.listdir(t_path): ...
Walk though the jid dir and look for jobs
def save_csv( self, name, address=True, class_param=None, class_name=None, matrix_save=True, normalize=False): """ Save ConfusionMatrix in CSV file. :param name: filename :type name : str :param ...
Save ConfusionMatrix in CSV file. :param name: filename :type name : str :param address: flag for address return :type address : bool :param class_param : class parameters list for save, Example : ["TPR","TNR","AUC"] :type class_param : list :param class_name : c...
def calc_ag_v1(self): """Sum the through flown area of the total cross section. Required flux sequences: |AM| |AV| |AVR| Calculated flux sequence: |AG| Example: >>> from hydpy.models.lstream import * >>> parameterstep() >>> fluxes.am = 1.0 >>> ...
Sum the through flown area of the total cross section. Required flux sequences: |AM| |AV| |AVR| Calculated flux sequence: |AG| Example: >>> from hydpy.models.lstream import * >>> parameterstep() >>> fluxes.am = 1.0 >>> fluxes.av= 2.0, 3.0 >...
def refweights(self): """A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([ 0.2, 0.2, 0.2, 0.2, 0.2]) ...
A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([ 0.2, 0.2, 0.2, 0.2, 0.2])
def update_chain(graph, loc, du, ud): """ Updates the DU chain of the instruction located at loc such that there is no more reference to it so that we can remove it. When an instruction is found to be dead (i.e it has no side effect, and the register defined is not used) we have to update the DU cha...
Updates the DU chain of the instruction located at loc such that there is no more reference to it so that we can remove it. When an instruction is found to be dead (i.e it has no side effect, and the register defined is not used) we have to update the DU chain of all the variables that may me used by th...
def convert_args_to_list(args): """Convert all iterable pairs of inputs into a list of list""" list_of_pairs = [] if len(args) == 0: return [] if any(isinstance(arg, (list, tuple)) for arg in args): # Domain([[1, 4]]) # Domain([(1, 4)]) # Domain([(1, 4), (5, 8)]) ...
Convert all iterable pairs of inputs into a list of list
def load_font(self, font_path, font_size): """Load the specified font from a file.""" self.__font_path = font_path self.__font_size = font_size if font_path != "": self.__font = pygame.font.Font(font_path, font_size) self.__set_text(self.__text)
Load the specified font from a file.
def _dens(self,R,z,phi=0.,t=0.): """ NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the densi...
NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the density HISTORY: 2015-12-04 - Started -...
def update_todo_menu(self): """Update todo list menu""" editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() self.todo_menu.clear() filename = self.get_current_filename() for text, line0 in results: icon = ima.icon('todo...
Update todo list menu
def refresh(): """ Refreshes an existing JWT by creating a new one that is a copy of the old except that it has a refrehsed access expiration. .. example:: $ curl http://localhost:5000/refresh -X GET \ -H "Authorization: Bearer <your_token>" """ old_token = guard.read_token_from...
Refreshes an existing JWT by creating a new one that is a copy of the old except that it has a refrehsed access expiration. .. example:: $ curl http://localhost:5000/refresh -X GET \ -H "Authorization: Bearer <your_token>"
def _set_remote(self, stream=False): """ Call :py:meth:`~._args_for_remote`; if the return value is not None, execute 'terraform remote config' with those arguments and ensure it exits 0. :param stream: whether or not to stream TF output in realtime :type stream: bool ...
Call :py:meth:`~._args_for_remote`; if the return value is not None, execute 'terraform remote config' with those arguments and ensure it exits 0. :param stream: whether or not to stream TF output in realtime :type stream: bool
def _Dispatch(ps, server, SendResponse, SendFault, post, action, nsdict={}, **kw): '''Send ParsedSoap instance to ServiceContainer, which dispatches to appropriate service via post, and method via action. Response is a self-describing pyobj, which is passed to a SoapWriter. Call SendResponse or SendFa...
Send ParsedSoap instance to ServiceContainer, which dispatches to appropriate service via post, and method via action. Response is a self-describing pyobj, which is passed to a SoapWriter. Call SendResponse or SendFault to send the reply back, appropriately. server -- ServiceContainer instance
def rst2html(rst_src, **kwargs): """ Convert a reStructuredText string into a unicode HTML fragment. For `kwargs`, see `default_rst_opts` and http://docutils.sourceforge.net/docs/user/config.html """ pub = rst2pub(rst_src, settings_overrides=kwargs, writer_name='html') return pu...
Convert a reStructuredText string into a unicode HTML fragment. For `kwargs`, see `default_rst_opts` and http://docutils.sourceforge.net/docs/user/config.html
def _include_module(self, module, mn): """ See if a module should be included or excluded based upon included_packages and excluded_packages. As some packages have the following format: scipy.special.specfun scipy.linalg Where the top-level package name is just a prefi...
See if a module should be included or excluded based upon included_packages and excluded_packages. As some packages have the following format: scipy.special.specfun scipy.linalg Where the top-level package name is just a prefix to a longer package name, we don't want t...
def _concat_datetimetz(to_concat, name=None): """ concat DatetimeIndex with the same tz all inputs must be DatetimeIndex it is used in DatetimeIndex.append also """ # Right now, internals will pass a List[DatetimeArray] here # for reductions like quantile. I would like to disentangle # a...
concat DatetimeIndex with the same tz all inputs must be DatetimeIndex it is used in DatetimeIndex.append also
def _get(self, url): """ Helper method: GET data from given URL on TBA's API. :param url: URL string to get data from. :return: Requested data in JSON format. """ return self.session.get(self.READ_URL_PRE + url).json()
Helper method: GET data from given URL on TBA's API. :param url: URL string to get data from. :return: Requested data in JSON format.
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ if gate.qubit_nb != 1: raise ValueError('Expected 1-qubit gate') q, = gate.qubits U = asarray(gate.asoperator()) U /= np.linalg.det(U) ** (1/2) # SU(2) if ab...
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
def register_type(klass, type_url=None): """Register a klass as the factory for a given type URL. :type klass: :class:`type` :param klass: class to be used as a factory for the given type :type type_url: str :param type_url: (Optional) URL naming the type. If not provided, inf...
Register a klass as the factory for a given type URL. :type klass: :class:`type` :param klass: class to be used as a factory for the given type :type type_url: str :param type_url: (Optional) URL naming the type. If not provided, infers the URL from the type descriptor. :rais...
def load_single_dict(pinyin_dict, style='default'): """载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}`` :param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type pinyin_dict: dict """ if style == 'tone2': for k, v in pinyin_dict.items(): v = _replace_t...
载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}`` :param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type pinyin_dict: dict
def edit_message_reply_markup( self, chat_id: Union[int, str], message_id: int, reply_markup: "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message": """Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). ...
Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). 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 "m...
def create_classifier(self, name, positive_examples, negative_examples=None, negative_examples_filename=None, **kwargs): """ Create a classifier. Train a new multi-f...
Create a classifier. Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive or negative examples. Include at least two sets of examples, either two positive example files or one positive and one negative file. You can upload a maximu...
def sqrt_with_finite_grads(x, name=None): """A sqrt function whose gradient at zero is very large but finite. Args: x: a `Tensor` whose sqrt is to be computed. name: a Python `str` prefixed to all ops created by this function. Default `None` (i.e., "sqrt_with_finite_grads"). Returns: sqrt: the...
A sqrt function whose gradient at zero is very large but finite. Args: x: a `Tensor` whose sqrt is to be computed. name: a Python `str` prefixed to all ops created by this function. Default `None` (i.e., "sqrt_with_finite_grads"). Returns: sqrt: the square root of `x`, with an overridden gradien...
def _shuffled(seq): """Deterministically shuffle identically under both py2 + py3.""" fixed_random = random.Random() if six.PY2: # pragma: no cover (py2) fixed_random.seed(FIXED_RANDOM_SEED) else: # pragma: no cover (py3) fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(...
Deterministically shuffle identically under both py2 + py3.
def coords(self): """ A tuple of two `~numpy.ndarray` containing the ``y`` and ``x`` pixel coordinates of unmasked pixels within the source segment. Non-finite pixel values (e.g. NaN, infs) are excluded (automatically masked). If all pixels are masked, ``coords`` will b...
A tuple of two `~numpy.ndarray` containing the ``y`` and ``x`` pixel coordinates of unmasked pixels within the source segment. Non-finite pixel values (e.g. NaN, infs) are excluded (automatically masked). If all pixels are masked, ``coords`` will be a tuple of two empty arrays.
def all(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ if iterable is None: return _iter_decorator...
Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric
def _set_range(self, v, load=False): """ Setter method for range, mapped from YANG variable /rbridge_id/router/ospf/area/range (list) If this variable is read-only (config: false) in the source YANG file, then _set_range is considered as a private method. Backends looking to populate this variable s...
Setter method for range, mapped from YANG variable /rbridge_id/router/ospf/area/range (list) If this variable is read-only (config: false) in the source YANG file, then _set_range is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_range() ...
def hdel(self, name, *keys): """ Delete one or more hash field. :param name: str the name of the redis key :param keys: on or more members to remove from the key. :return: Future() """ with self.pipe as pipe: m_encode = self.memberparse.encode ...
Delete one or more hash field. :param name: str the name of the redis key :param keys: on or more members to remove from the key. :return: Future()
def create_awslambda(self): """Create security groups as defined in the configs.""" utils.banner("Creating Lambda Function") awslambdaobj = awslambda.LambdaFunction( app=self.app, env=self.env, region=self.region, prop_path=self.json_path) awslambdaobj.create_lambda_function(...
Create security groups as defined in the configs.
def copy_session(session: requests.Session) -> requests.Session: """Duplicates a requests.Session.""" new = requests.Session() new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies)) new.headers = session.headers.copy() return new
Duplicates a requests.Session.
def get_auth(host, app_name, database_name): """ Authentication hook to allow plugging in custom authentication credential providers """ from .hooks import _get_auth_hook return _get_auth_hook(host, app_name, database_name)
Authentication hook to allow plugging in custom authentication credential providers
def _fire(self, layers, things, the_plot): """Launches a new bolt from the player.""" # We don't fire if the player fired another bolt just now. if the_plot.get('last_player_shot') == the_plot.frame: return the_plot['last_player_shot'] = the_plot.frame # We start just above the player. row, col ...
Launches a new bolt from the player.
def integer( element_name, # type: Text attribute=None, # type: Optional[Text] required=True, # type: bool alias=None, # type: Optional[Text] default=0, # type: Optional[int] omit_empty=False, # type: bool hooks=None # type: Optional[Hooks] ): # type: (...
Create a processor for integer values. See also :func:`declxml.boolean`
def add_file(self, fileGrp, mimetype=None, url=None, ID=None, pageId=None, force=False, local_filename=None, **kwargs): """ Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_. Arguments: fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute ...
Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_. Arguments: fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute mimetype (string): url (string): ID (string): pageId (string): force (boolean): Whethe...
def constraint(self, n=-1, fid=0): """Obtain the set of orthogonal equations that make the solution of the rank deficient normal equations possible. :param fid: the id of the sub-fitter (numerical) """ c = self._getval("constr", fid) if n < 0 or n > self.deficiency(fid)...
Obtain the set of orthogonal equations that make the solution of the rank deficient normal equations possible. :param fid: the id of the sub-fitter (numerical)
def toJson(self, data=None, pretty=False): """convert the flattened dictionary into json""" if data==None: data = self.attrs data = self.flatten(data) # don't send objects as str in json #if pretty: ret = json.dumps(data, indent=4, sort_keys=True) #self.inflate() # restor...
convert the flattened dictionary into json
def dump(rt, from_date, with_json=True, latest_only=False, **kwargs): """Dump the remote tokens as a list of dictionaries. :param ra: Remote toekn to be dumped. :type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]` :returns: Remote tokens serialized to dictionary. :rtype: dict """ ...
Dump the remote tokens as a list of dictionaries. :param ra: Remote toekn to be dumped. :type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]` :returns: Remote tokens serialized to dictionary. :rtype: dict
def clear(self): """ Calls `_clear` abstract method which must be implemented by descendants. :raises: GPflowError exception when parent of the node is built. """ parent = self.parent if parent is not self and parent.is_built_coherence(self.graph) is Build.YES: ...
Calls `_clear` abstract method which must be implemented by descendants. :raises: GPflowError exception when parent of the node is built.
def _findOptionValueAdvAudit(option): ''' Get the Advanced Auditing policy as configured in ``C:\\Windows\\Security\\Audit\\audit.csv`` Args: option (str): The name of the setting as it appears in audit.csv Returns: bool: ``True`` if successful, otherwise ``False`` ''' if '...
Get the Advanced Auditing policy as configured in ``C:\\Windows\\Security\\Audit\\audit.csv`` Args: option (str): The name of the setting as it appears in audit.csv Returns: bool: ``True`` if successful, otherwise ``False``
def score_pairwise(aseq, bseq): """Compute pairwise distances between two sequences (raw strings).""" assert len(aseq) == len(bseq) # Affine gap penalties -- default values from EMBOSS needle/water GAP_OPEN = -10.0 GAP_EXTEND = -0.5 GAP_CHARS = frozenset('-.') score = 0.0 in_gap = True...
Compute pairwise distances between two sequences (raw strings).
def hessian(self, x, y, Rs, theta_Rs, r_core, center_x=0, center_y=0): """ :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :param center_y: :return...
:param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :param center_y: :return:
async def monitor_status(self, alarm_status_callback=None, zone_changed_callback=None, output_changed_callback=None): """Start monitoring of the alarm status. Send command to satel integra to start sending updates. Read in a loop and cal...
Start monitoring of the alarm status. Send command to satel integra to start sending updates. Read in a loop and call respective callbacks when received messages.
def register_site(self): """Function to register the site and generate a unique ID for the site Returns: **string:** The ID of the site (also called client id) if the registration is successful Raises: **OxdServerError:** If the site registration fails. """ ...
Function to register the site and generate a unique ID for the site Returns: **string:** The ID of the site (also called client id) if the registration is successful Raises: **OxdServerError:** If the site registration fails.
def _process_file(self, obj, fobj, field): """ obj is record object fobj is data field is FileField instance """ from uliweb import settings paths = [] upload_to = self.upload_to or self._get_upload_path(field, 'upload_to', obj) ...
obj is record object fobj is data field is FileField instance
def _set_foreign_attributes_for_create(self, model): """ Set the foreign ID and type for creation a related model. """ model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key()) model.set_attribute(self.get_plain_morph_type(), self._morph_name)
Set the foreign ID and type for creation a related model.
def make_tf_example(features, pi, value): """ Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float """ return tf.train.Example(features=tf.train.Features(feature={ 'x': tf.train.Feature( bytes_list=tf.train.Bytes...
Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float
def ping(proxy=None, hostport=None): """ rpc_ping Returns {'alive': True} on succcess Returns {'error': ...} on error """ schema = { 'type': 'object', 'properties': { 'status': { 'type': 'string' }, }, 'required': [ ...
rpc_ping Returns {'alive': True} on succcess Returns {'error': ...} on error
def paste_action_callback(self, *event): """Callback method for paste action""" if react_to_event(self.view, self.oc_list_ctrl.tree_view, event) and self.oc_list_ctrl.active_entry_widget is None: global_clipboard.paste(self.model, limited=['outcomes']) return True
Callback method for paste action
def TakeWhile(self: dict, f): """ [ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ] """ if is_to_destruct(f): f = destruct_func(f) for e in self.items(): if not f(e): ...
[ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ]
def get_pd_by_id(self, id): """ Get ScaleIO ProtectionDomain object by its id :param name: ID of ProtectionDomain :return: ScaleIO ProctectionDomain object :raise KeyError: No ProtectionDomain with specified name found :rtype: ProtectionDomain object """ f...
Get ScaleIO ProtectionDomain object by its id :param name: ID of ProtectionDomain :return: ScaleIO ProctectionDomain object :raise KeyError: No ProtectionDomain with specified name found :rtype: ProtectionDomain object
def call_jira_rest(self, url, user, password, method="GET", data=None): """ Make JIRA REST call :param data: data for rest call :param method: type of call: GET or POST for now :param url: url to call :param user: user for authentication :param password: password ...
Make JIRA REST call :param data: data for rest call :param method: type of call: GET or POST for now :param url: url to call :param user: user for authentication :param password: password for authentication :return:
def min_cost(self): """ Returns the cost of the best assignment """ if self._min_cost: return self._min_cost self._min_cost = np.sum(self.c[np.arange(self.nx), self.solution]) return self._min_cost
Returns the cost of the best assignment
def save_archive(archive): """ Save `archive` into database and into proper indexes. Attr: archive (obj): Instance of the :class:`.DBArchive`. Returns: obj: :class:`.DBArchive` without data. Raises: InvalidType: When the `archive` is not instance of :class:`.DBArchive`. ...
Save `archive` into database and into proper indexes. Attr: archive (obj): Instance of the :class:`.DBArchive`. Returns: obj: :class:`.DBArchive` without data. Raises: InvalidType: When the `archive` is not instance of :class:`.DBArchive`. UnindexablePublication: When ther...
def show_popup(self, *args, **kwargs): """Show a popup with a textedit :returns: None :rtype: None :raises: None """ self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog) self.mw.setWindowTitle(self.popuptitle) self.mw.setWindowModality(QtCore.Qt.A...
Show a popup with a textedit :returns: None :rtype: None :raises: None
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.api.v2010.acc...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAcce...
def eig_seg(mask, img_list, apply_segmentation_to_images=False, cthresh=0, smooth=1): """ Segment a mask into regions based on the max value in an image list. At a given voxel the segmentation label will contain the index to the image that has the largest value. If the 3rd image has the greatest value, ...
Segment a mask into regions based on the max value in an image list. At a given voxel the segmentation label will contain the index to the image that has the largest value. If the 3rd image has the greatest value, the segmentation label will be 3 at that voxel. Arguments --------- mask : ANTsIm...
def _fmt_metric(value, show_stdv=True): """format metric string""" if len(value) == 2: return '%s:%g' % (value[0], value[1]) if len(value) == 3: if show_stdv: return '%s:%g+%g' % (value[0], value[1], value[2]) return '%s:%g' % (value[0], value[1]) raise ValueError("wr...
format metric string
def translify(text): """Translify russian text""" try: res = translit.translify(smart_text(text, encoding)) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
Translify russian text
def delete_keyvault_secret(access_token, vault_uri, secret_name): '''Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret...
Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret to add. Returns: HTTP response. 200 OK.
def list_logical_volumes(select_criteria=None, path_mode=False): ''' List logical volumes :param select_criteria: str: Limit list to those volumes matching this criteria (see 'lvs -S help' for more details) :param path_mode: bool: return logical volume name in 'vg/lv' f...
List logical volumes :param select_criteria: str: Limit list to those volumes matching this criteria (see 'lvs -S help' for more details) :param path_mode: bool: return logical volume name in 'vg/lv' format, this format is required for some commands ...
def fromseconds(cls, seconds): """Return a |Period| instance based on a given number of seconds.""" try: seconds = int(seconds) except TypeError: seconds = int(seconds.flatten()[0]) return cls(datetime.timedelta(0, int(seconds)))
Return a |Period| instance based on a given number of seconds.
def emit(self, **kwargs): """Emit signal by calling all connected slots. The arguments supplied have to match the signal definition. Args: kwargs: Keyword arguments to be passed to connected slots. Raises: :exc:`InvalidEmit`: If arguments don't match signal spe...
Emit signal by calling all connected slots. The arguments supplied have to match the signal definition. Args: kwargs: Keyword arguments to be passed to connected slots. Raises: :exc:`InvalidEmit`: If arguments don't match signal specification.
def limit_disk_io(self, uuid, media, totalbytessecset=False, totalbytessec=0, readbytessecset=False, readbytessec=0, writebytessecset=False, writebytessec=0, totaliopssecset=False, totaliopssec=0, readiopssecset=False, readiopssec=0, writeiopssecset=False, writeiopssec=0, tot...
Remove a nic from a machine :param uuid: uuid of the kvm container (same as the used in create) :param media: the media to limit the diskio :return:
def get_occurrence(event_id, occurrence_id=None, year=None, month=None, day=None, hour=None, minute=None, second=None, tzinfo=None): """ Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the...
Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the occurrence can be retrieved with an id. If it is not persisted it takes a date to retrieve it. This function returns an event and occurrence regardless of which method i...
def get_item_list(self, item_list_url): """ Retrieve an item list from the server as an ItemList object :type item_list_url: String or ItemList :param item_list_url: URL of the item list to retrieve, or an ItemList object :rtype: ItemList :returns: The ItemList ...
Retrieve an item list from the server as an ItemList object :type item_list_url: String or ItemList :param item_list_url: URL of the item list to retrieve, or an ItemList object :rtype: ItemList :returns: The ItemList :raises: APIError if the request was not succes...
def fast_deepcopy(obj): """This is a faster implementation of deepcopy via pickle. It is meant primarily for sets of Statements with complex hierarchies but can be used for any object. """ with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) ...
This is a faster implementation of deepcopy via pickle. It is meant primarily for sets of Statements with complex hierarchies but can be used for any object.
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ dev = ctx.obj['dev'] def prompt_new_lo...
Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value.
def apply(self, vpc): """ returns a list of new security groups that will be added """ assert vpc is not None # make sure we're up to date self.reload_remote_groups() vpc_groups = self.vpc_groups(vpc) self._apply_groups(vpc) # reloads groups from...
returns a list of new security groups that will be added
def setup(self): """Setup list widget content.""" if len(self.plugins_tabs) == 0: self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handle...
Setup list widget content.
def get_asset_from_edit_extension_draft(self, publisher_name, draft_id, asset_type, extension_name, **kwargs): """GetAssetFromEditExtensionDraft. [Preview API] :param str publisher_name: :param str draft_id: :param str asset_type: :param str extension_name: :rtype...
GetAssetFromEditExtensionDraft. [Preview API] :param str publisher_name: :param str draft_id: :param str asset_type: :param str extension_name: :rtype: object
def bitop_xor(self, dest, key, *keys): """Perform bitwise XOR operations between strings.""" return self.execute(b'BITOP', b'XOR', dest, key, *keys)
Perform bitwise XOR operations between strings.
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def change_registration(registered_object, unregistered_object): if registered_object and registered_object.uuid == self.parent_uuid: self...
Override from PersistentObject.
def best_training_job(self): """Return name of the best training job for the latest hyperparameter tuning job. Raises: Exception: If there is no best training job available for the hyperparameter tuning job. """ self._ensure_last_tuning_job() tuning_job_describe_res...
Return name of the best training job for the latest hyperparameter tuning job. Raises: Exception: If there is no best training job available for the hyperparameter tuning job.
def set_error_page(self, loadbalancer, html): """ A single custom error page may be added per account load balancer with an HTTP protocol. Page updates will override existing content. If a custom error page is deleted, or the load balancer is changed to a non-HTTP protocol, the d...
A single custom error page may be added per account load balancer with an HTTP protocol. Page updates will override existing content. If a custom error page is deleted, or the load balancer is changed to a non-HTTP protocol, the default error page will be restored.
def structure_recursion(self, struct, folder): """ From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE...
From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE structure :type struct: dict :param folder: name o...
def get_droplet(self, droplet_id): """ Return a Droplet by its ID. """ return Droplet.get_object(api_token=self.token, droplet_id=droplet_id)
Return a Droplet by its ID.
def get_inspector(): """Reuse inspector""" global _INSPECTOR if _INSPECTOR: return _INSPECTOR else: bind = op.get_bind() _INSPECTOR = sa.engine.reflection.Inspector.from_engine(bind) return _INSPECTOR
Reuse inspector
def write_format_data(self, format_dict): """Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``io.stdout``. Subclasses should override this method to send the entire `format_dict` to the ...
Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``io.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. Parameters ---------- ...
async def wait_tasks(tasks, flatten=True): '''Gather a list of asynchronous tasks and wait their completion. :param list tasks: A list of *asyncio* tasks wrapped in :func:`asyncio.ensure_future`. :param bool flatten: If ``True`` the returned results are flattened into one list if the ...
Gather a list of asynchronous tasks and wait their completion. :param list tasks: A list of *asyncio* tasks wrapped in :func:`asyncio.ensure_future`. :param bool flatten: If ``True`` the returned results are flattened into one list if the tasks return iterable objects. The parameter doe...
def create_database(self, dbname, partitioned=False, **kwargs): """ Creates a new database on the remote server with the name provided and adds the new database object to the client's locally cached dictionary before returning it to the caller. The method will optionally throw a...
Creates a new database on the remote server with the name provided and adds the new database object to the client's locally cached dictionary before returning it to the caller. The method will optionally throw a CloudantClientException if the database exists remotely. :param st...
def _cmp_models(self, m1, m2): """Compare two models from different swagger APIs and tell if they are equal (return 0), or not (return != 0)""" # Don't alter m1/m2 by mistake m1 = copy.deepcopy(m1) m2 = copy.deepcopy(m2) # Remove keys added by bravado-core def _...
Compare two models from different swagger APIs and tell if they are equal (return 0), or not (return != 0)
def get_canonical_and_alternates_urls( url, drop_ln=True, washed_argd=None, quote_path=False): """ Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument strippe...
Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given...
def call_parallel(self, cdata, low): ''' Call the state defined in the given cdata in parallel ''' # There are a number of possibilities to not have the cdata # populated with what we might have expected, so just be smart # enough to not raise another KeyError as the name...
Call the state defined in the given cdata in parallel
def start(parallel, items, config, dirs=None, name=None, multiplier=1, max_multicore=None): """Start a parallel cluster or machines to be used for running remote functions. Returns a function used to process, in parallel items with a given function. Allows sharing of a single cluster across ...
Start a parallel cluster or machines to be used for running remote functions. Returns a function used to process, in parallel items with a given function. Allows sharing of a single cluster across multiple functions with identical resource requirements. Uses local execution for non-distributed clu...
def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() ...
Return the serializer instance that should be used for validating and deserializing input, and for serializing output.
def list_icmp_block(zone, permanent=True): ''' List ICMP blocks on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewlld.list_icmp_block zone ''' cmd = '--zone={0} --list-icmp-blocks'.format(zone) if permanent: cmd += ' --permanent' ...
List ICMP blocks on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewlld.list_icmp_block zone
def ttl(self, response): """Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public ...
Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public no-cache no-store ...
def _send_event(self, event): """! @brief Process event objects and decide when to send to event sink. This method handles the logic to associate a timestamp event with the prior other event. A list of pending events is built up until either a timestamp or overflow event is gene...
! @brief Process event objects and decide when to send to event sink. This method handles the logic to associate a timestamp event with the prior other event. A list of pending events is built up until either a timestamp or overflow event is generated, at which point all pending events ...
def headerize(provenances): """Create a header for each keyword. :param provenances: The keywords. :type provenances: dict :return: New keywords with header for every keyword. :rtype: dict """ special_case = { 'Inasafe': 'InaSAFE', 'Qgis': 'QGIS', 'Pyqt': 'PyQt', ...
Create a header for each keyword. :param provenances: The keywords. :type provenances: dict :return: New keywords with header for every keyword. :rtype: dict
def dataset_search(self, dataset_returning_query): """ Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the...
Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the results of the query. :rtype: :class:`DatasetSearchResult`