code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def with_claims(self, issuer=None, subject=None, additional_claims=None): """Returns a copy of these credentials with modified claims. Args: issuer (str): The `iss` claim. If unspecified the current issuer claim will be used. subject (str): The `sub` claim. If un...
Returns a copy of these credentials with modified claims. Args: issuer (str): The `iss` claim. If unspecified the current issuer claim will be used. subject (str): The `sub` claim. If unspecified the current subject claim will be used. additio...
def unpack_from_dict(fmt, names, data, offset=0): """Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`. """ return CompiledFormatDict(fmt, names).unpack_from(data, offset)
Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`.
def plot_all(self, fig=None, iabscissa=1, iteridx=None, foffset=1e-19, x_opt=None, fontsize=9): """ plot data from a `CMADataLogger` (using the files written by the logger). Arguments --------- `fig` figure number, by default 425 `iab...
plot data from a `CMADataLogger` (using the files written by the logger). Arguments --------- `fig` figure number, by default 425 `iabscissa` ``0==plot`` versus iteration count, ``1==plot`` versus function evaluation number ...
def build(self, input_filepath_list, output_filepath, combine_type, input_volumes=None): '''Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath_list : list of str List of paths to input audio files. outp...
Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath_list : list of str List of paths to input audio files. output_filepath : str Path to desired output file. If a file already exists at the given path,...
def spectrogram(self, ref=None, segmentLengthMultiplier=1, window='hann'): """ analyses the source to generate a spectrogram :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :return: t : ndarray ...
analyses the source to generate a spectrogram :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :return: t : ndarray Array of time slices. f : ndarray Array of sample frequencies. ...
def find_cycle(graph): """ Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes. """ ...
Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes.
def parse(s): """Parse a string representation back into the Vector. >>> Vectors.parse('[2,1,2 ]') DenseVector([2.0, 1.0, 2.0]) >>> Vectors.parse(' ( 100, [0], [2])') SparseVector(100, {0: 2.0}) """ if s.find('(') == -1 and s.find('[') != -1: return...
Parse a string representation back into the Vector. >>> Vectors.parse('[2,1,2 ]') DenseVector([2.0, 1.0, 2.0]) >>> Vectors.parse(' ( 100, [0], [2])') SparseVector(100, {0: 2.0})
def circuit_to_dag(circuit): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. Return: DAGCircuit: the DAG representing the input circuit. """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name for register ...
Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. Return: DAGCircuit: the DAG representing the input circuit.
def get_by_entityid(self, entityid): """ Returns the entity with the given entity ID as a dict """ data = self.list(entityid=entityid) if len(data) == 0: return None eid = int( next(iter(data)) ) entity = self.get(eid) self.debug(0x01,entity) return entity
Returns the entity with the given entity ID as a dict
def map_function(self, func, *arg_lists): """Map a function to all grid_stack in a grid-stack""" return GridStack(*[func(*args) for args in zip(self, *arg_lists)])
Map a function to all grid_stack in a grid-stack
def debug(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ ...
Log msg with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
def reconstruct_srls(edm, all_points, W=None, print_out=False, n=1, rescale=False, z=None): """ Reconstruct point set using S(quared)R(ange)L(east)S(quares) method. """ from .lateration import SRLS, get_lateration_parameters Y = all_points.copy() indices = range(n) for index...
Reconstruct point set using S(quared)R(ange)L(east)S(quares) method.
def temporary_dir(root_dir=None, cleanup=True, suffix='', permissions=None, prefix=tempfile.template): """ A with-context that creates a temporary directory. :API: public You may specify the following keyword args: :param string root_dir: The parent directory to create the temporary directory. :...
A with-context that creates a temporary directory. :API: public You may specify the following keyword args: :param string root_dir: The parent directory to create the temporary directory. :param bool cleanup: Whether or not to clean up the temporary directory. :param int permissions: If provided, ...
def do_call(self, path, method, body=None, headers=None): """ Send an HTTP request to the REST API. :param string path: A URL :param string method: The HTTP method (GET, POST, etc.) to use in the request. :param string body: A string representing any data to be sent ...
Send an HTTP request to the REST API. :param string path: A URL :param string method: The HTTP method (GET, POST, etc.) to use in the request. :param string body: A string representing any data to be sent in the body of the HTTP request. :param dictionary headers...
def config(self, **kwargs): """ Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~ItemsCanvas.keys`. See :meth:`~ItemsCanvas.__init__` for a description of the widget specific option. """ self._canvaswidth = kwargs.pop...
Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~ItemsCanvas.keys`. See :meth:`~ItemsCanvas.__init__` for a description of the widget specific option.
def form_valid(self,form): ''' Create the gift certificate voucher with the indicated information and send the email as directed. ''' emailTo = form.cleaned_data.get('emailTo') emailType = form.cleaned_data.get('emailType') recipientName = form.cleaned_data.get('r...
Create the gift certificate voucher with the indicated information and send the email as directed.
def shepp_logan_ellipsoids(ndim, modified=False): """Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions. Parameters ---------- ndim : {2, 3} Dimension of the space the ellipsoids should be in. modified : bool, optional True if the modified Shepp-Logan phantom shoul...
Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions. Parameters ---------- ndim : {2, 3} Dimension of the space the ellipsoids should be in. modified : bool, optional True if the modified Shepp-Logan phantom should be given. The modified phantom has greatly ampl...
def add(msgid, transtr, fuzzy): """ Add a non-fuzzy translation to the dictionary. """ global MESSAGES if not fuzzy and transtr and not transtr.startswith('\0'): MESSAGES[msgid] = transtr
Add a non-fuzzy translation to the dictionary.
def loadd(self, ava, base64encode=False): """ Sets attributes, children, extension elements and extension attributes of this element instance depending on what is in the given dictionary. If there are already values on properties those will be overwritten. If the keys in the dict...
Sets attributes, children, extension elements and extension attributes of this element instance depending on what is in the given dictionary. If there are already values on properties those will be overwritten. If the keys in the dictionary does not correspond to known attributes/childre...
def multi_ops(data_stream, *funcs): """ fork a generator with multiple operations/functions data_stream - an iterable data structure (ie: list/generator/tuple) funcs - every function that will be applied to the data_stream """ assert all(callable(func) for func in funcs), 'multi_ops ...
fork a generator with multiple operations/functions data_stream - an iterable data structure (ie: list/generator/tuple) funcs - every function that will be applied to the data_stream
def verify_key_in_shelve(file_name, save_key, file_location): """ Function to check for a key in a shelve Args: file_name: Shelve storage file name save_key: The name of the key the item is stored in file_location: The location of the file, derive from the os module Returns: ret...
Function to check for a key in a shelve Args: file_name: Shelve storage file name save_key: The name of the key the item is stored in file_location: The location of the file, derive from the os module Returns: returns true or false
def __step5(self): """ Construct a series of alternating primed and starred zeros as follows. Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero in the row of Z1 (there will always...
Construct a series of alternating primed and starred zeros as follows. Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero in the row of Z1 (there will always be one). Continue until the se...
def find_id3v1(fileobj, v2_version=4, known_frames=None): """Returns a tuple of (id3tag, offset_to_end) or (None, 0) offset mainly because we used to write too short tags in some cases and we need the offset to delete them. v2_version: Decides whether ID3v2.3 or ID3v2.4 tags should be ...
Returns a tuple of (id3tag, offset_to_end) or (None, 0) offset mainly because we used to write too short tags in some cases and we need the offset to delete them. v2_version: Decides whether ID3v2.3 or ID3v2.4 tags should be returned. Must be 3 or 4. known_frames (Dict[`mutagen.text`,...
def xml(self): """Calls the overridden method. :returns: XML representation of the metadata. :rtype: str """ root = super(GenericLayerMetadata, self).xml return prettify_xml(ElementTree.tostring(root))
Calls the overridden method. :returns: XML representation of the metadata. :rtype: str
def drafts(files, stack): "Filter out any files marked 'draft'" for path, post in list(files.items()): if post.get('draft'): del files[path]
Filter out any files marked 'draft
def augustus(args): """ %prog augustus species gffile fastafile Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from: <http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html> """ p = OptionParser(augustus.__doc__) p.add_option("--autotrain", d...
%prog augustus species gffile fastafile Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from: <http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html>
def ignore_callback(instance, *props): """ Temporarily ignore any callbacks from one or more callback properties This is a context manager. Within the context block, no callbacks will be issued. In contrast with :func:`~echo.delay_callback`, no callbakcs will be called on exiting the context manage...
Temporarily ignore any callbacks from one or more callback properties This is a context manager. Within the context block, no callbacks will be issued. In contrast with :func:`~echo.delay_callback`, no callbakcs will be called on exiting the context manager Parameters ---------- instance ...
def make_mine(self, request, queryset): """ Set the entries to the current user. """ author = Author.objects.get(pk=request.user.pk) for entry in queryset: if author not in entry.authors.all(): entry.authors.add(author) self.message_user( ...
Set the entries to the current user.
def wrap(cls, app): """ Adds test live server capability to a Flask app module. :param app: A :class:`flask.Flask` app instance. """ host, port = cls.parse_args() ssl = cls._argument_parser.parse_args().ssl ssl_context = None if host...
Adds test live server capability to a Flask app module. :param app: A :class:`flask.Flask` app instance.
def create_file_and_add_volume(self, runtime, # type: List[Text] volume, # type: MapperEnt host_outdir_tgt, # type: Optional[Text] secret_store, # type: Opt...
Create the file and add a mapping.
def insert_seperator_results(results): """Given a sequence of BenchmarkResults, return a new sequence where a "seperator" BenchmarkResult has been placed between differing benchmarks to provide a visual difference.""" sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS]) last_bm = None f...
Given a sequence of BenchmarkResults, return a new sequence where a "seperator" BenchmarkResult has been placed between differing benchmarks to provide a visual difference.
def insert_vlan( self, environment_id, name, number, description, acl_file, acl_file_v6, network_ipv4, network_ipv6, vrf=None): """Create new VLAN :param environment_id: ID for Enviro...
Create new VLAN :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :par...
def cduffy(z, M, vir='200crit', relaxed=True): """ NFW conc from Duffy 08 Table 1 for halo mass and redshift""" if(vir == '200crit'): if relaxed: params = [6.71, -0.091, -0.44] else: params = [5.71, -0.084, -0.47] elif(vir == 'tophat'): if relaxed: ...
NFW conc from Duffy 08 Table 1 for halo mass and redshift
def _binop_handler(nodetype): """ Factory function for binary operator handlers. """ def _handler(toplevel, stack_builders): right = make_expr(stack_builders) left = make_expr(stack_builders) return ast.BinOp(left=left, op=nodetype(), right=right) return _handler
Factory function for binary operator handlers.
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def set_bios_settings(self, data=None, only_allowed_settings=True): """Sets current BIOS settings to the provided data. :param: only_allowed_settings: True when only allowed BIOS settings are to be set. If False, all the BIOS settings supported by iLO and present in the ...
Sets current BIOS settings to the provided data. :param: only_allowed_settings: True when only allowed BIOS settings are to be set. If False, all the BIOS settings supported by iLO and present in the 'data' are set. :param: data: a dictionary of BIOS settings to be appli...
def fetchAllUsers(self): """ Gets all users the client is currently chatting with :return: :class:`models.User` objects :rtype: list :raises: FBchatException if request failed """ data = {"viewer": self._uid} j = self._post( self.req_url.ALL_U...
Gets all users the client is currently chatting with :return: :class:`models.User` objects :rtype: list :raises: FBchatException if request failed
def touching(self, canvas, side=None): """ Returns True if touching any pixels [on specified side]. 0 = Bottom 1 = Left 2 = Top 3 = Right None = All This works by creating a list of the image rotated so all the ...
Returns True if touching any pixels [on specified side]. 0 = Bottom 1 = Left 2 = Top 3 = Right None = All This works by creating a list of the image rotated so all the requested sides are facing up, then it finds the top edge for ...
def get_version(self, state=None, date=None): """ Get a particular version of an item :param state: The state you want to get. :param date: Get a version that was published before or on this date. """ version_model = self._meta._version_model q = version_model.o...
Get a particular version of an item :param state: The state you want to get. :param date: Get a version that was published before or on this date.
def recall(Ntp, Nref, eps=numpy.spacing(1)): """Recall. Wikipedia entry https://en.wikipedia.org/wiki/Precision_and_recall Parameters ---------- Ntp : int >=0 Number of true positives. Nref : int >=0 Amount of reference. eps : float eps. Default value nump...
Recall. Wikipedia entry https://en.wikipedia.org/wiki/Precision_and_recall Parameters ---------- Ntp : int >=0 Number of true positives. Nref : int >=0 Amount of reference. eps : float eps. Default value numpy.spacing(1) Returns ------- recall: fl...
def setMovie( self, movie ): """ Sets the movie for this icon. :param movie | <QMovie> || None """ if ( self._movie ): self._movie.frameChanged.disconnect(self.updateIcon) self._movie = movie if ( self._movie ): ...
Sets the movie for this icon. :param movie | <QMovie> || None
def make_spo(sub, prd, obj): ''' Decorates the three given strings as a line of ntriples ''' # To establish string as a curie and expand, # we use a global curie_map(.yaml) # sub are allways uri (unless a bnode) # prd are allways uri (unless prd is 'a') # should fail loudly if curie do...
Decorates the three given strings as a line of ntriples
def score(self, outcomes, modelparams, expparams, return_L=False): r""" Returns the numerically computed score of the likelihood function, defined as: .. math:: q(d, \vec{x}; \vec{e}) = \vec{\nabla}_{\vec{x}} \log \Pr(d | \vec{x}; \vec{e}). ...
r""" Returns the numerically computed score of the likelihood function, defined as: .. math:: q(d, \vec{x}; \vec{e}) = \vec{\nabla}_{\vec{x}} \log \Pr(d | \vec{x}; \vec{e}). Calls are represented as a four-index tensor ``score[idx_model...
def is_done(self): """Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean`` """ if not self.is_ready(): return False done = (self._state.content['isDone'] == '1') return done
Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean``
def _addLoggingOptions(addOptionFn): """ Adds logging options """ # BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH # optparse AND argparse FOR EXAMPLE, YOU MAY NOT USE default=%default OR default=%(default)s defaultLogLevelName = logging....
Adds logging options
def get_addresses(self, account_id, **params): """https://developers.coinbase.com/api/v2#list-addresses""" response = self._get('v2', 'accounts', account_id, 'addresses', params=params) return self._make_api_object(response, Address)
https://developers.coinbase.com/api/v2#list-addresses
def doPoolUpgrade(self, upgrade: Upgrade): """ Used to send a new code upgrade :param upgrade: upgrade data :return: number of pending txns """ key = upgrade.key self._upgrades[key] = upgrade req = upgrade.ledgerRequest() if req: self.p...
Used to send a new code upgrade :param upgrade: upgrade data :return: number of pending txns
def perlin(self, stat='perlin'): """Apply Perlin noise to my nodes, and return myself. I'll try to use the name of the node as its spatial position for this purpose, or use its stats 'x', 'y', and 'z', or skip the node if neither are available. z is assumed 0 if not provided for...
Apply Perlin noise to my nodes, and return myself. I'll try to use the name of the node as its spatial position for this purpose, or use its stats 'x', 'y', and 'z', or skip the node if neither are available. z is assumed 0 if not provided for a node. Result will be stored in a...
def _find_rule_no(self, mac): """Find rule number associated with a given mac.""" ipt_cmd = ['iptables', '-L', '--line-numbers'] cmdo = dsl.execute(ipt_cmd, self._root_helper, log_output=False) for o in cmdo.split('\n'): if mac in o.lower(): rule_no = o.split...
Find rule number associated with a given mac.
def active_processes(self, use_cache=True): """Return a list of all active processes, pruning dead ones :rtype: list """ LOGGER.debug('Checking active processes (cache: %s)', use_cache) if self.can_use_process_cache(use_cache): return self._active_cache[1] a...
Return a list of all active processes, pruning dead ones :rtype: list
def tritonast2arybo(e, use_exprs=True, use_esf=False, context=None): ''' Convert a subset of Triton's AST into Arybo's representation Args: e: Triton AST use_esf: use ESFs when creating the final expression context: dictionnary that associates Triton expression ID to arybo expressions ...
Convert a subset of Triton's AST into Arybo's representation Args: e: Triton AST use_esf: use ESFs when creating the final expression context: dictionnary that associates Triton expression ID to arybo expressions Returns: An :class:`arybo.lib.MBAVariable` object
def main(recordFilenames, fastaFilename, title, xRange, bitRange): """ Print reads that match in a specified X-axis and bit score range. @param recordFilenames: A C{list} of C{str} file names contain results of a BLAST run, in JSON format. @param fastaFilename: The C{str} name of the FASTA file...
Print reads that match in a specified X-axis and bit score range. @param recordFilenames: A C{list} of C{str} file names contain results of a BLAST run, in JSON format. @param fastaFilename: The C{str} name of the FASTA file that was originally BLASTed. @param title: The C{str} title of the...
def add(self): """ Add a pool. """ # Adding to NIPAP if request.method == 'POST': p = Pool() p.name = request.params.get('name') p.description = request.params.get('description') p.default_type = request.params.get('default_type') ...
Add a pool.
def call(self, method, params=None): """Check authentication and perform actual API request and relogin if needed""" start_time = time() self.check_auth() self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method) self.log(DEBUG, '\twith parameters: %...
Check authentication and perform actual API request and relogin if needed
def getResult(self, queue, uid, suid=None): """ Retrieve the result of a job from its ID """ if suid: r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid)) else: r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid)) if r: ...
Retrieve the result of a job from its ID
def ensure_on(): """ Start the DbServer if it is off """ if get_status() == 'not-running': if config.dbserver.multi_user: sys.exit('Please start the DbServer: ' 'see the documentation for details') # otherwise start the DbServer automatically; NB: I tried...
Start the DbServer if it is off
def __install_node_dependencies(kudu_client): """Installs Node.js dependencies at `site/wwwroot/` for Node.js bots. This method is only called when the detected bot is a Node.js bot. :return: Dictionary with results of the HTTP Kudu request """ if not kudu_client._KuduClient__initialized: # pylin...
Installs Node.js dependencies at `site/wwwroot/` for Node.js bots. This method is only called when the detected bot is a Node.js bot. :return: Dictionary with results of the HTTP Kudu request
def _initialize_connection(api_key, app_key): ''' Initialize Datadog connection ''' if api_key is None: raise SaltInvocationError('api_key must be specified') if app_key is None: raise SaltInvocationError('app_key must be specified') options = { 'api_key': api_key, ...
Initialize Datadog connection
def get_indels( self, one_based=True ): """Return a data structure containing all indels in the read. Returns the tuple (insertions, deletions) insertions = [(pos1,ins1), (pos2,ins2)] posN = start position (preceding base, VCF-style) insN = length of inserted sequence (not includ...
Return a data structure containing all indels in the read. Returns the tuple (insertions, deletions) insertions = [(pos1,ins1), (pos2,ins2)] posN = start position (preceding base, VCF-style) insN = length of inserted sequence (not including preceding base) deletions = [(pos1,del1...
def servers_with_roles(self, roles, env=None, match_all=False): """ Get servers with the given roles. If env is given, then the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or mor...
Get servers with the given roles. If env is given, then the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or more of the given roles.
def show_output_dynamic(pcnn_output_dynamic, separate_representation = False): """! @brief Shows output dynamic (output of each oscillator) during simulation. @param[in] pcnn_output_dynamic (pcnn_dynamic): Output dynamic of the pulse-coupled neural network. @param[in] separ...
! @brief Shows output dynamic (output of each oscillator) during simulation. @param[in] pcnn_output_dynamic (pcnn_dynamic): Output dynamic of the pulse-coupled neural network. @param[in] separate_representation (list): Consists of lists of oscillators where each such list consists o...
def tasks_missing_predicate( service_name, old_task_ids, task_predicate=None ): """ Returns whether any of old_task_ids are no longer present :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by g...
Returns whether any of old_task_ids are no longer present :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use when searchin...
def krb5_unparse_principal_name(name): """Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal n...
Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal name :return: (service, host, realm) or (No...
def get_dict_from_obj(obj): ''' Edit to get the dict even when the object is a GenericRelatedObjectManager. Added the try except. ''' obj_dict = obj.__dict__ obj_dict_result = obj_dict.copy() for key, value in obj_dict.items(): if key.endswith('_id'): key2 = key.replace('...
Edit to get the dict even when the object is a GenericRelatedObjectManager. Added the try except.
def pause_debugplot(debugplot, optional_prompt=None, pltshow=False, tight_layout=True): """Ask the user to press RETURN to continue after plotting. Parameters ---------- debugplot : int Determines whether intermediate computations and/or plots are displayed: ...
Ask the user to press RETURN to continue after plotting. Parameters ---------- debugplot : int Determines whether intermediate computations and/or plots are displayed: 00 : no debug, no plots 01 : no debug, plots without pauses 02 : no debug, plots with pauses ...
def get_reader_input_fn(train_config, preprocess_output_dir, model_type, data_paths, batch_size, shuffle, num_epochs=None): """Builds input layer for training.""" def get_input_features(): """Read the input features from the given data paths.""" _, examples = util.read_examples( ...
Builds input layer for training.
def get_checks(self, position=None): """Gets the checks at the position.""" if position is None: position = self.position return self.checkdefs[position][0]
Gets the checks at the position.
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse arr...
construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows
def lr_padding(self, terms): ''' Pad doc from the left and right before adding, depending on what's in self.lpad and self.rpad If any of them is '', then don't pad there. ''' lpad = rpad = [] if self.lpad: lpad = [self.lpad] * (self.n - 1) if...
Pad doc from the left and right before adding, depending on what's in self.lpad and self.rpad If any of them is '', then don't pad there.
def append(self, item, select=False): """Add an item to the end of the list. :param item: The item to be added :param select: Whether the item should be selected after adding """ if item in self: raise ValueError("item %s already in list" % item) modeliter = ...
Add an item to the end of the list. :param item: The item to be added :param select: Whether the item should be selected after adding
def to_datetime_string(self) -> str: """ Returns a human-readable string representation with iso date and time Example: 2018-12-06 12:32:56 """ date_display = self.to_iso_date_string() time_display = self.to_long_time_string() return f"{date_display} {time_display}"
Returns a human-readable string representation with iso date and time Example: 2018-12-06 12:32:56
def _state_removal_init(self): """State Removal Operation Initialization""" # First, we remove all multi-edges: for state_i in self.mma.states: for state_j in self.mma.states: if state_i.stateid == state_j.stateid: self.l_transitions[ ...
State Removal Operation Initialization
def get_current_line(self): """Return current line's text""" cursor = self.textCursor() cursor.select(QTextCursor.BlockUnderCursor) return to_text_string(cursor.selectedText())
Return current line's text
def is_private(self): """Property that checks if the specified window is private or not. Returns: bool: True if this is a Private Browsing window. """ self.switch_to() with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.selenium.execute...
Property that checks if the specified window is private or not. Returns: bool: True if this is a Private Browsing window.
def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module for app...
Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want.
def update_subnet_db_info(self, tenant_id, direc, net_id, subnet_id): """Update the subnet DB with Net and Subnet ID, given the subnet. """ subnet_dict = self.retrieve_dcnm_subnet_info(tenant_id, direc) if not subnet_dict: LOG.error("Subnet dict not found for tenant %s", tenant_id) ...
Update the subnet DB with Net and Subnet ID, given the subnet.
def is_correct(self): """ Check if the items list configuration is correct :: * check if duplicate items exist in the list and warn about this * set alias and display_name property for each item in the list if they do not exist * check each item in the list * log all pre...
Check if the items list configuration is correct :: * check if duplicate items exist in the list and warn about this * set alias and display_name property for each item in the list if they do not exist * check each item in the list * log all previous warnings * log all previous ...
def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """ if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
Takes a object and produces a dict-like representation :param obj: the object to serialize
def _process_connect_init(self): """ Process INFO received from the server and CONNECT to the server with authentication. It is also responsible of setting up the reading and ping interval tasks from the client. """ self._status = Client.CONNECTING connection_co...
Process INFO received from the server and CONNECT to the server with authentication. It is also responsible of setting up the reading and ping interval tasks from the client.
def __decode_time(self, t): """ Decode a timestamp retrieved from the timeclock copied from zkemsdk.c - DecodeTime """ t = unpack("<I", t)[0] second = t % 60 t = t // 60 minute = t % 60 t = t // 60 hour = t % 24 t = t // 24 ...
Decode a timestamp retrieved from the timeclock copied from zkemsdk.c - DecodeTime
def delete_quota(self, tenant_id): ''' Delete the specified tenant's quota value ''' ret = self.network_conn.delete_quota(tenant_id=tenant_id) return ret if ret else True
Delete the specified tenant's quota value
def removeReadGroupSet(self, readGroupSet): """ Removes the specified readGroupSet from this repository. This performs a cascading removal of all items within this readGroupSet. """ for readGroupSetRecord in models.Readgroupset.select().where( models.Readg...
Removes the specified readGroupSet from this repository. This performs a cascading removal of all items within this readGroupSet.
def future_get_request(self, name, update=None): """Get the request object. Check if we have information for this request, if not connect to server and update (if allowed). Parameters ---------- name : string Name of the request. update : bool or Non...
Get the request object. Check if we have information for this request, if not connect to server and update (if allowed). Parameters ---------- name : string Name of the request. update : bool or None, optional True allow inspect client to inspect...
def get_network_resource_property_entry(resource, prop): """ Factory method for creating get functions. """ def get_func(cmd, resource_group_name, resource_name, item_name): client = getattr(network_client_factory(cmd.cli_ctx), resource) items = getattr(client.get(resource_group_name, resource_...
Factory method for creating get functions.
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter.
def is_outside_bounds(self, val): """Returns whether the value is outside the bounds or not.""" return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound))
Returns whether the value is outside the bounds or not.
def chunks(f): """Split read PNG image data into chunks""" while 1: try: length = struct.unpack(b"!I", f.read(4))[0] tag = f.read(4) data = f.read(length) crc = struct.unpack(b"!I", f.read(4))[0] except struct.error:...
Split read PNG image data into chunks
def update(vm, from_file=None, key='uuid', **kwargs): ''' Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwar...
Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwargs : string|int|... options to update for the vm CLI ...
def mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'): """ Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region. Parameters ---------- regionfile : str...
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The catalogue...
def remove_by_hash(hashval: str): """ Remove the key whose md5 sum matches hashval. :raises: KeyError if the hashval wasn't found """ key_details = get_keys() with authorized_keys('w') as ak: for keyhash, key in key_details: if keyhash != hashval: ak.write(f'{key...
Remove the key whose md5 sum matches hashval. :raises: KeyError if the hashval wasn't found
def worker_activated(name, workers=None, profile='default'): ''' Activate all the workers in the modjk load balancer Example: .. code-block:: yaml loadbalancer: modjk.worker_activated: - workers: - app1 - app2 ''' if workers is None: ...
Activate all the workers in the modjk load balancer Example: .. code-block:: yaml loadbalancer: modjk.worker_activated: - workers: - app1 - app2
def merge(self, other): """Merge other (dict or OrderedSet) into this environment. Only works for basic types: str, list, tuple, dict and OrderedSet. """ for key, value in other.items(): if not key in self: self[key] = value elif isinstance(value,...
Merge other (dict or OrderedSet) into this environment. Only works for basic types: str, list, tuple, dict and OrderedSet.
def get_domain_config(self, domain): """Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _doma...
Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomain...
def drain(self, tab_key): ''' Return all messages in waiting for the websocket connection. ''' self.log.debug("Draining transport") ret = [] while len(self.messages[tab_key]): ret.append(self.messages[tab_key].pop(0)) self.log.debug("Polling socket") tmp = self.___recv(tab_key) while tmp is not N...
Return all messages in waiting for the websocket connection.
def sens_atmos_send(self, TempAmbient, Humidity, force_mavlink1=False): ''' Atmospheric sensors (temperature, humidity, ...) TempAmbient : Ambient temperature [degrees Celsius] (float) Humidity : Relative humidity [%] (float...
Atmospheric sensors (temperature, humidity, ...) TempAmbient : Ambient temperature [degrees Celsius] (float) Humidity : Relative humidity [%] (float)
def graph_key_from_tag(tag, entity_index): """Returns a key from a tag entity Args: tag (tag) : this is the tag selected to get the key from entity_index (int) : this is the index of the tagged entity Returns: str : String representing the key for the given tagged entity. """ ...
Returns a key from a tag entity Args: tag (tag) : this is the tag selected to get the key from entity_index (int) : this is the index of the tagged entity Returns: str : String representing the key for the given tagged entity.
def GetCursorPos() -> tuple: """ GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y).
def config_dict(name: str) -> Dict[str, Any]: """Load a JSON configuration dict from Guesslang config directory. :param name: the JSON file name. :return: configuration """ try: content = resource_string(PACKAGE, DATADIR.format(name)).decode() except DistributionNotFound as error: ...
Load a JSON configuration dict from Guesslang config directory. :param name: the JSON file name. :return: configuration
def release(self, key, owner): """Release lock with given name. `key` - lock name `owner` - name of application/component/whatever which held a lock Raises `MongoLockException` if no such a lock. """ status = self.collection.find_and_modify( {'_id': key, '...
Release lock with given name. `key` - lock name `owner` - name of application/component/whatever which held a lock Raises `MongoLockException` if no such a lock.
def _parse_ethtool_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} if 'autoneg' in opts: if opts...
Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting.