code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _set_original_fields(instance): """ Save fields value, only for non-m2m fields. """ original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), F...
Save fields value, only for non-m2m fields.
def drag(self, point): """Update the tracball during a drag. Parameters ---------- point : (2,) int The current x and y pixel coordinates of the mouse during a drag. This will compute a movement for the trackball with the relative motion between this ...
Update the tracball during a drag. Parameters ---------- point : (2,) int The current x and y pixel coordinates of the mouse during a drag. This will compute a movement for the trackball with the relative motion between this point and the one marked by down()...
def announcement_posted_hook(request, obj): """Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object """ logger.debug("Announcement posted") if obj.notify_post: logger.debug("Announcement notify on") announcement_posted_twit...
Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selec...
Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned.
def get_options(config_options, local_options, cli_options): """ Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_op...
Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_options specified in the config file at the base * DEFAULT_OPTIONS h...
def _grads(self, x): """ Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the paramete...
Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the parameters of the model. :type x: np.arra...
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs): """ Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. """ cls.validate(data) ...
Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service.
def run(self): """The method called by the threading library to start the thread.""" while not self._abort: hashes = self._GetHashes(self._hash_queue, self.hashes_per_batch) if hashes: time_before_analysis = time.time() hash_analyses = self.Analyze(hashes) current_time = time...
The method called by the threading library to start the thread.
def execute_function(self, func, *nargs, **kwargs): """ Execute a function object within the execution context. @returns The result of the function call. """ # makes a copy of the func import types fn = types.FunctionType(func.func_code, ...
Execute a function object within the execution context. @returns The result of the function call.
def eval_table(tbl, expression, vm='python', blen=None, storage=None, create='array', vm_kwargs=None, **kwargs): """Evaluate `expression` against columns of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) length = len(columns[0]) ...
Evaluate `expression` against columns of a table.
def delete_statement(cls, prop_nr): """ This serves as an alternative constructor for WDBaseDataType with the only purpose of holding a WD property number and an empty string value in order to indicate that the whole statement with this property number of a WD item should be deleted. ...
This serves as an alternative constructor for WDBaseDataType with the only purpose of holding a WD property number and an empty string value in order to indicate that the whole statement with this property number of a WD item should be deleted. :param prop_nr: A WD property number as string ...
def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, ...
Middle part of slicenet, connecting encoder and decoder.
def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message = u"{0} is not a valid URL".format(value) if url_regex.search('http://' + value): message += u". Di...
Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError
def _netid_subscription_url(netid, subscription_codes): """ Return UWNetId resource for provided netid and subscription code or code list """ return "{0}/{1}/subscription/{2}".format( url_base(), netid, (','.join([str(n) for n in subscription_codes]) if isinstance(subscripti...
Return UWNetId resource for provided netid and subscription code or code list
def _set_rc(self): """Method to set the rcparams and defaultParams for this plotter""" base_str = self._get_rc_strings() # to make sure that the '.' is not interpreted as a regex pattern, # we specify the pattern_base by ourselves pattern_base = map(lambda s: s.replace('.', '\.')...
Method to set the rcparams and defaultParams for this plotter
def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar' ''' fullname = salt.utils.data.decode(fullname) pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' doe...
Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar'
def make_innermost_setter(setter): """Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as so...
Wraps a setter so it applies to the inner-most results in `kernel_results`. The wrapped setter unwraps `kernel_results` and applies `setter` to the first results without an `inner_results` attribute. Args: setter: A callable that takes the kernel results as well as some `*args` and `**kwargs` and retu...
def _set_keepalive(self, v, load=False): """ Setter method for keepalive, mapped from YANG variable /interface/tunnel/keepalive (container) If this variable is read-only (config: false) in the source YANG file, then _set_keepalive is considered as a private method. Backends looking to populate this ...
Setter method for keepalive, mapped from YANG variable /interface/tunnel/keepalive (container) If this variable is read-only (config: false) in the source YANG file, then _set_keepalive is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ke...
def getExtentAddress(self, zoom, extent=None, contained=False): """ Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom...
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom -- the zoom for which we want the bounding addresses extent (optional) ...
def read_namespaced_resource_quota(self, name, namespace, **kwargs): """ read the specified ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_resource_quota(name...
read the specified ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_resource_quota(name, namespace, async_req=True) >>> result = thread.get() :param async_req ...
def create_pattern(cls, userdata): """Create a user data instance with all values the same.""" empty = cls.create_empty(None) userdata_dict = cls.normalize(empty, userdata) return Userdata(userdata_dict)
Create a user data instance with all values the same.
def _stage(self, accepted, count=0): """This is a repeated state in the state removal algorithm""" new5 = self._combine_rest_push() new1 = self._combine_push_pop() new2 = self._combine_push_rest() new3 = self._combine_pop_rest() new4 = self._combine_rest_rest() ne...
This is a repeated state in the state removal algorithm
def grid(self, **kw): """ Position a widget in the parent widget in a grid. :param column: use cell identified with given column (starting with 0) :type column: int :param columnspan: this widget will span several columns :type columnspan: int :param in\...
Position a widget in the parent widget in a grid. :param column: use cell identified with given column (starting with 0) :type column: int :param columnspan: this widget will span several columns :type columnspan: int :param in\_: widget to use as container :typ...
def create_packet(header, data): """Creates an IncomingPacket object from header and data This method is for testing purposes """ packet = IncomingPacket() packet.header = header packet.data = data if len(header) == HeronProtocol.HEADER_SIZE: packet.is_header_read = True if len...
Creates an IncomingPacket object from header and data This method is for testing purposes
def get(self): """ method to fetch all contents as a list :return: list """ ret_list = [] if hasattr(self, "font"): ret_list.append(self.font) if hasattr(self, "size"): ret_list.append(self.size) if hasattr(self, "text"): ...
method to fetch all contents as a list :return: list
def seed_response(self, command, response): # type: (Text, dict) -> MockAdapter """ Sets the response that the adapter will return for the specified command. You can seed multiple responses per command; the adapter will put them into a FIFO queue. When a request comes i...
Sets the response that the adapter will return for the specified command. You can seed multiple responses per command; the adapter will put them into a FIFO queue. When a request comes in, the adapter will pop the corresponding response off of the queue. Example: .. c...
def getEntityType(self, found = None): ''' Method to recover the value of the entity in case it may vary. :param found: The expression to be analysed. :return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]...
Method to recover the value of the entity in case it may vary. :param found: The expression to be analysed. :return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]com.
def find_log_files(self, sp_key, filecontents=True, filehandles=False): """ Return matches log files of interest. :param sp_key: Search pattern key specified in config :param filehandles: Set to true to return a file handle instead of slurped file contents :return: Yields a dict ...
Return matches log files of interest. :param sp_key: Search pattern key specified in config :param filehandles: Set to true to return a file handle instead of slurped file contents :return: Yields a dict with filename (fn), root directory (root), cleaned sample name generated fr...
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to imple...
Returns AF_INET4 or AF_INET6 depending on where to connect to.
def length_prefix(length, offset): """Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list """ if length < 56: return chr(offset + leng...
Construct the prefix to lists or strings denoting their length. :param length: the length of the item in bytes :param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a list
def louvain(adjacency_matrix): """ Performs community embedding using the LOUVAIN method. Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory an...
Performs community embedding using the LOUVAIN method. Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory and Experiment, 2008(10), P10008. Inputs...
def str_if_nested_or_str(s): """Turn input into a native string if possible.""" if isinstance(s, ALL_STRING_TYPES): return str(s) if isinstance(s, (list, tuple)): return type(s)(map(str_if_nested_or_str, s)) if isinstance(s, (dict, )): return stringify_dict_contents(s) return...
Turn input into a native string if possible.
def quantile_normalize(matrix, inplace=False, target=None): """Quantile normalization, allowing for missing values (NaN). In case of nan values, this implementation will calculate evenly distributed quantiles and fill in the missing data with those values. Quantile normalization is then performed on th...
Quantile normalization, allowing for missing values (NaN). In case of nan values, this implementation will calculate evenly distributed quantiles and fill in the missing data with those values. Quantile normalization is then performed on the filled-in matrix, and the nan values are restored afterwards....
def on_message(self, message): """Process a message received from remote.""" if self.ws.closed: return None try: safe_call(self.logger.debug, '< %s %r', self, message) # process individual messages for data in self.ddp_frames_from_message(message)...
Process a message received from remote.
def validate(self): """Ensure that the CoerceType block is valid.""" if not (isinstance(self.target_class, set) and all(isinstance(x, six.string_types) for x in self.target_class)): raise TypeError(u'Expected set of string target_class, got: {} {}'.format( typ...
Ensure that the CoerceType block is valid.
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has oc...
Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolea...
def _nextNonSpaceColumn(block, column): """Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards. """ textAfter = block.text()[column:] if textAfter.strip(): spaceLen = len(textAfter) - len(textAfter.lstrip())...
Returns the column with a non-whitespace characters starting at the given cursor position and searching forwards.
def cli(env, package_keyname, required): """List the categories of a package. :: # List the categories of Bare Metal servers slcli order category-list BARE_METAL_SERVER # List the required categories for Bare Metal servers slcli order category-list BARE_METAL_SERVER --required...
List the categories of a package. :: # List the categories of Bare Metal servers slcli order category-list BARE_METAL_SERVER # List the required categories for Bare Metal servers slcli order category-list BARE_METAL_SERVER --required
def ParseFileObject(self, parser_mediator, file_object): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. ""...
Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def _fix_channels(self, op, attrs, inputs): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. """ if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]: ...
A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number.
def create_binary_annotation(key, value, annotation_type, host): """ Create a zipkin binary annotation object :param key: name of the annotation, such as 'http.uri' :param value: value of the annotation, such as a URI :param annotation_type: type of annotation, such as AnnotationType.I32 :param...
Create a zipkin binary annotation object :param key: name of the annotation, such as 'http.uri' :param value: value of the annotation, such as a URI :param annotation_type: type of annotation, such as AnnotationType.I32 :param host: zipkin endpoint object :returns: zipkin binary annotation object
def _set_below(self, v, load=False): """ Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container) If this variable is read-only (config: false) in the source YANG file, then _set_below is considered as a private method. Backends l...
Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container) If this variable is read-only (config: false) in the source YANG file, then _set_below is considered as a private method. Backends looking to populate this variable should do so...
def print_usage(self, file=None): """ Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout. """ optparse.OptionParser.print_usage(self, file) file.flush()
Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
def _compute_delta_beta(self, X, T, E, weights, index=None): """ approximate change in betas as a result of excluding ith row. Good for finding outliers / specific subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them. """ score_...
approximate change in betas as a result of excluding ith row. Good for finding outliers / specific subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them.
def check_many(self, domains): """ Check availability for a number of domains. Returns a dictionary mapping the domain names to their statuses as a string ("active"/"free"). """ return dict((item.domain, item.status) for item in self.check_domain_request(domains))
Check availability for a number of domains. Returns a dictionary mapping the domain names to their statuses as a string ("active"/"free").
def analytic_kl_builder(posterior, prior, sample): """A pre-canned builder for the analytic kl divergence.""" del sample return tf.reduce_sum(tfp.distributions.kl_divergence(posterior, prior))
A pre-canned builder for the analytic kl divergence.
def serialize(self): """ Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog. """ import yaml output = {"metadata": self.metadata, "sources": {}, "name": self...
Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog.
def switch_bucket(self, bucket_key, data_shapes, label_shapes=None): """Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tupl...
Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tuple) Typically ``data_batch.provide_data``. label_shapes : lis...
def find_block_end(row, line_list, sentinal, direction=1): """ Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs """ import re row_ = row line_ = line_list[row_] flag1 = row_ == 0 or row_ == len(line_list) - 1 flag2 = re.match...
Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs
def choicebox(message='Pick something.', title='', choices=['program logic error - no choices specified']): """Original doc: Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. """ return psidialogs.choice(message...
Original doc: Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection.
def extract_parameters(pil, keys=None): """Extract and return parameter names and values from a pil object Parameters ---------- pil : `Pil` object keys : list List of parameter names, if None, extact all parameters Returns ------- out_dict : dict Dictionary with par...
Extract and return parameter names and values from a pil object Parameters ---------- pil : `Pil` object keys : list List of parameter names, if None, extact all parameters Returns ------- out_dict : dict Dictionary with parameter name, value pairs
def _serialize_to_many(self, key, vals, rlink): """ Make a to_many JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param vals: array of dict's containing `rid`...
Make a to_many JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param vals: array of dict's containing `rid` & `rtype` keys for the to_many, empty array if ...
def all_terms(self): """Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms""" for s_name, s in self.sections.items(): # Yield the section header if s.name != 'Root': yield s ...
Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms
def send_last_message(self, msg, connection_id=None): """ Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and s...
Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message
def is_element_in_database(element='', database='ENDF_VII'): """will try to find the element in the folder (database) specified Parameters: ========== element: string. Name of the element. Not case sensitive database: string (default is 'ENDF_VII'). Name of folder that has the list of elements ...
will try to find the element in the folder (database) specified Parameters: ========== element: string. Name of the element. Not case sensitive database: string (default is 'ENDF_VII'). Name of folder that has the list of elements Returns: ======= bool: True if element was found in the dat...
def type_search(self, basetype, symbolstr, origin): """Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e....
Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Mo...
def _find_glob_matches(in_files, metadata): """Group files that match by globs for merging, rather than by explicit pairs. """ reg_files = copy.deepcopy(in_files) glob_files = [] for glob_search in [x for x in metadata.keys() if "*" in x]: cur = [] for fname in in_files: ...
Group files that match by globs for merging, rather than by explicit pairs.
def is_molecular_function(self, go_term): """ Returns True is go_term has is_a, part_of ancestor of molecular function GO:0003674 """ mf_root = "GO:0003674" if go_term == mf_root: return True ancestors = self.get_isa_closure(go_term) if mf_root in ance...
Returns True is go_term has is_a, part_of ancestor of molecular function GO:0003674
def fix_axon_peri_v2(hobj): """Replace reconstructed axon with a stub :param hobj: hoc object """ for i,sec in enumerate(hobj.axon): if i < 2: sec.L = 30 sec.diam = 1 else: sec.L = 1e-6 sec.diam = 1 h.define_shape()
Replace reconstructed axon with a stub :param hobj: hoc object
def _minimal_common_integer(si_0, si_1): """ Calculates the minimal integer that appears in both StridedIntervals. As a wrapper method of _minimal_common_integer_splitted(), this method takes arbitrary StridedIntervals. For more information, please refer to the comment of _minimal_common...
Calculates the minimal integer that appears in both StridedIntervals. As a wrapper method of _minimal_common_integer_splitted(), this method takes arbitrary StridedIntervals. For more information, please refer to the comment of _minimal_common_integer_splitted(). :param si_0: the first Stride...
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for res...
Parse a Marathon response into an object or list of objects.
def search_for_port(port_glob, req, expected_res): ''' Find the serial port the arm is connected to. ''' # Check that the USB port actually exists, based on the known vendor and # product ID. if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None: return None # Find ports matching the...
Find the serial port the arm is connected to.
def expand_multirow_data(data): """ Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights """ num_cols = len(data[0]) # number of columns # calculates row heights row_heights = [] for mlrow in...
Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights
def get_pltpat(self, plt_ext="svg"): """Return png pattern: {BASE}.png {BASE}_pruned.png {BASE}_upper_pruned.png""" if self.ntplt.desc == "": return ".".join(["{BASE}", plt_ext]) return "".join(["{BASE}_", self.ntplt.desc, ".", plt_ext])
Return png pattern: {BASE}.png {BASE}_pruned.png {BASE}_upper_pruned.png
async def _handle_bad_server_salt(self, message): """ Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadM...
Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
def _split_column_and_labels(self, column_or_label): """Return the specified column and labels of other columns.""" column = None if column_or_label is None else self._get_column(column_or_label) labels = [label for i, label in enumerate(self.labels) if column_or_label not in (i, label)] ...
Return the specified column and labels of other columns.
def status_server(self, port): ''' Starts the progress bar TCP service on the specified port. This service will only be started once per instance, regardless of the number of times this method is invoked. Failure to start the status service is considered non-critical; that is, ...
Starts the progress bar TCP service on the specified port. This service will only be started once per instance, regardless of the number of times this method is invoked. Failure to start the status service is considered non-critical; that is, a warning will be displayed to the user, but...
def Jacobian_re_im(self, pars): r""" :math:`J` >>> import sip_models.res.cc as cc >>> import numpy as np >>> f = np.logspace(-3, 3, 20) >>> pars = [100, 0.1, 0.04, 0.8] >>> obj = cc.cc(f) >>> J = obj.Jacobian_re_im(pars) """ partials = [] ...
r""" :math:`J` >>> import sip_models.res.cc as cc >>> import numpy as np >>> f = np.logspace(-3, 3, 20) >>> pars = [100, 0.1, 0.04, 0.8] >>> obj = cc.cc(f) >>> J = obj.Jacobian_re_im(pars)
def cmdloop(self): """Start CLI REPL.""" while True: cmdline = input(self.prompt) tokens = shlex.split(cmdline) if not tokens: if self.last_cmd: tokens = self.last_cmd else: print('No previous com...
Start CLI REPL.
def get_url(self, *paths, **params): """ Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request """ path_stack = self._attribute_stack[:] if paths: ...
Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request
def displayName( self ): """ Return the user friendly name for this node. if the display name \ is not implicitly set, then the words for the object name \ will be used. :return <str> """ if ( not self._displayName ): return projex.text.p...
Return the user friendly name for this node. if the display name \ is not implicitly set, then the words for the object name \ will be used. :return <str>
def get_psf_sky(self, ra, dec): """ Determine the local psf at a given sky location. The psf is returned in degrees. Parameters ---------- ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The p...
Determine the local psf at a given sky location. The psf is returned in degrees. Parameters ---------- ra, dec : float The sky position (degrees). Returns ------- a, b, pa : float The psf semi-major axis, semi-minor axis, and position an...
def Registry(address='https://index.docker.io', **kwargs): """ :return: """ registry = None try: try: registry = V1(address, **kwargs) registry.ping() except RegistryException: registry = V2(address, **kwargs) registry.ping() except...
:return:
def import_vmesh(file): """ Imports NURBS volume(s) from volume mesh (vmesh) file(s). :param file: path to a directory containing mesh files or a single mesh file :type file: str :return: list of NURBS volumes :rtype: list :raises GeomdlException: an error occurred reading the file """ ...
Imports NURBS volume(s) from volume mesh (vmesh) file(s). :param file: path to a directory containing mesh files or a single mesh file :type file: str :return: list of NURBS volumes :rtype: list :raises GeomdlException: an error occurred reading the file
def write_static_networks(gtfs, output_dir, fmt=None): """ Parameters ---------- gtfs: gtfspy.GTFS output_dir: (str, unicode) a path where to write fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead """...
Parameters ---------- gtfs: gtfspy.GTFS output_dir: (str, unicode) a path where to write fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead
def get_groups_of_user(config, fas, username): ''' Return the list of (pkgdb) groups to which the user belongs. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg username: the name of a user for which we wa...
Return the list of (pkgdb) groups to which the user belongs. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg username: the name of a user for which we want to retrieve groups :return: a list of FAS groups...
def check_data(cls, name, dims, is_unstructured): """ A validation method for the data shape The default method does nothing and should be subclassed to validate the results. If the plotter accepts a :class:`InteractiveList`, it should accept a list for name and dims Pa...
A validation method for the data shape The default method does nothing and should be subclassed to validate the results. If the plotter accepts a :class:`InteractiveList`, it should accept a list for name and dims Parameters ---------- name: str or list of str ...
def _inject_format_spec(self, value, format_spec): """ value: '{x}', format_spec: 'f' -> '{x:f}' """ t = type(value) return value[:-1] + t(u':') + format_spec + t(u'}')
value: '{x}', format_spec: 'f' -> '{x:f}'
def cminus(a, b): ''' cminus(a, b) returns the difference a - b as a numpy array object. Like numpy's subtract function or a - b syntax, minus will thread over the latest dimension possible. ''' # adding/subtracting a constant to/from a sparse array is an error... spa = sps.issparse(a) spb...
cminus(a, b) returns the difference a - b as a numpy array object. Like numpy's subtract function or a - b syntax, minus will thread over the latest dimension possible.
def fetch(self): """ Fetch a AvailableAddOnExtensionInstance :returns: Fetched AvailableAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance """ params = values.of({}) payload ...
Fetch a AvailableAddOnExtensionInstance :returns: Fetched AvailableAddOnExtensionInstance :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance
def dump_guest_stack(self, cpu_id): """Produce a simple stack dump using the current guest state. This feature is not implemented in the 4.0.0 release but may show up in a dot release. in cpu_id of type int The identifier of the Virtual CPU. return stack of...
Produce a simple stack dump using the current guest state. This feature is not implemented in the 4.0.0 release but may show up in a dot release. in cpu_id of type int The identifier of the Virtual CPU. return stack of type str String containing the for...
def open(self): """Open a comm to the frontend if one isn't already open.""" if self.comm is None: state, buffer_paths, buffers = _remove_buffers(self.get_state()) args = dict(target_name='jupyter.widget', data={'state': state, 'buffer_paths': buffer_path...
Open a comm to the frontend if one isn't already open.
def _update_new_ordered_reqs_count(self): """ Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise """ last_num_ordered = self._last_performance...
Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise
def fulfill(self, method, *args, **kwargs): """ Fulfill an HTTP request to Keen's API. """ return getattr(self.session, method)(*args, **kwargs)
Fulfill an HTTP request to Keen's API.
def _copy_artifact(self, tgt, jar, version, typename, suffix='', extension='jar', artifact_ext='', override_name=None): """Copy the products for a target into the artifact path for the jar/version""" genmap = self.context.products.get(typename) product_mapping = genmap.get(tgt) if p...
Copy the products for a target into the artifact path for the jar/version
def initialize(self): """Initialize croniter and related times""" if self.croniter is None: self.time = time.time() self.datetime = datetime.now(self.tz) self.loop_time = self.loop.time() self.croniter = croniter(self.spec, start_time=self.datetime)
Initialize croniter and related times
def _get_struct_gradientbevelfilter(self): """Get the values for the GRADIENTBEVELFILTER record.""" obj = _make_object("GradientBevelFilter") obj.NumColors = num_colors = unpack_ui8(self._src) obj.GradientColors = [self._get_struct_rgba() for _ in range(num_...
Get the values for the GRADIENTBEVELFILTER record.
def _width(self): """For ``self.width``.""" layout = self._instruction.get(GRID_LAYOUT) if layout is not None: width = layout.get(WIDTH) if width is not None: return width return self._instruction.number_of_consumed_meshes
For ``self.width``.
def chained_get(container, path, default=None): """Helper function to perform a series of .get() methods on a dictionary and return a default object type in the end. Parameters ---------- container : dict The dictionary on which the .get() methods should be performed. path : list or tu...
Helper function to perform a series of .get() methods on a dictionary and return a default object type in the end. Parameters ---------- container : dict The dictionary on which the .get() methods should be performed. path : list or tuple The list of keys that should be searched fo...
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9....
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.135...
def open_data(self, url, data=None): """Use "data" URL.""" if not isinstance(url, str): raise URLError('data error: proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [...
Use "data" URL.
def _insert_vars(self, path: str, data: dict) -> str: """Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled """ data = data.copy() while True: ...
Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled
def independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_mat...
r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) ...
def summary(self): """ A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user. """ print("Type: %s" % self.__class__.__name__) print("Batch Name: %r" % self.ba...
A succinct summary of the Launcher configuration. Unlike the repr, a summary does not have to be complete but must supply key information relevant to the user.
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' result = {} try: # get labels from filesystem for entry in os.scandir(diskdir): if entry.name.startswith('.'): continue if islink(entry.path): targe...
Find volume labels from filesystem and return in dict format.
def set_action_name(self, name): """ Set the name of the top group, if present. """ if self._open and name is not None: self._open[-1].name = name self.notify()
Set the name of the top group, if present.
def hook_up(self, router: UrlDispatcher): """ Dynamically hooks the right webhook paths """ router.add_get(self.webhook_path, self.check_hook) router.add_post(self.webhook_path, self.receive_events)
Dynamically hooks the right webhook paths
def run(cli_args): """ Split the functionality into 2 methods. One for parsing the cli and one that runs the application. """ from .core import Core c = Core( source_file=cli_args["--data-file"], schema_files=cli_args["--schema-file"], extensions=cli_args['--extension']...
Split the functionality into 2 methods. One for parsing the cli and one that runs the application.
def _run_morfologik(self, words): """ Runs morfologik java jar and assumes that input and output is UTF-8 encoded. """ p = subprocess.Popen( ['java', '-jar', self.jar_path, 'plstem', '-ie', 'UTF-8', '-oe', 'UTF-8'], bufsize=-1, ...
Runs morfologik java jar and assumes that input and output is UTF-8 encoded.
def get_events(self): """Get events from the cloud node.""" to_send = {'limit': 50} response = self._send_data('POST', 'admin', 'get-events', to_send) output = {'message': ""} for event in response['events']: desc = "Source IP: {ip}\n" desc += "Datetime: ...
Get events from the cloud node.