code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _cache_key(self, attr_name): """ Memcache keys can't have spaces in them, so we'll remove them from the DN for maximum compatibility. """ dn = self._ldap_user.dn return valid_cache_key( "auth_ldap.{}.{}.{}".format(self.__class__.__name__, attr_name, dn) ...
Memcache keys can't have spaces in them, so we'll remove them from the DN for maximum compatibility.
def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} ...
Updates an existing record.
def _get_bandgap_from_bands(energies, nelec): """Compute difference in conduction band min and valence band max""" nelec = int(nelec) valence = [x[nelec-1] for x in energies] conduction = [x[nelec] for x in energies] return max(min(conduction) - max(valence), 0.0)
Compute difference in conduction band min and valence band max
def file_download_using_requests(self,url): '''It will download file specified by url using requests module''' file_name=url.split('/')[-1] if os.path.exists(os.path.join(os.getcwd(),file_name)): print 'File already exists' return #print 'Downloading file %s '%file_name #print 'Downloading from %s'%url...
It will download file specified by url using requests module
def _copy_dist_from_dir(link_path, location): """Copy distribution files in `link_path` to `location`. Invoked when user requests to install a local directory. E.g.: pip install . pip install ~/dev/git-repos/python-prompt-toolkit """ # Note: This is currently VERY SLOW if you have a ...
Copy distribution files in `link_path` to `location`. Invoked when user requests to install a local directory. E.g.: pip install . pip install ~/dev/git-repos/python-prompt-toolkit
async def eventuallyAll(*coroFuncs: FlexFunc, # (use functools.partials if needed) totalTimeout: float, retryWait: float=0.1, acceptableExceptions=None, acceptableFails: int=0, override_timeout_limit...
:param coroFuncs: iterable of no-arg functions :param totalTimeout: :param retryWait: :param acceptableExceptions: :param acceptableFails: how many of the passed in coroutines can ultimately fail and still be ok :return:
def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if inspect.isclass(object): mro = (object,) + inspect.getmro(object) else: mro = () results = [] pr...
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
def sr(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): """Send and receive packets at layer 3""" s = conf.L3socket(promisc=promisc, filter=filter, iface=iface, nofilter=nofilter) result = sndrcv(s, x, *args, **kargs) s.close() return result
Send and receive packets at layer 3
def _ensure_api_keys(task_desc, failure_ret=None): """Wrap Elsevier methods which directly use the API keys. Ensure that the keys are retrieved from the environment or config file when first called, and store global scope. Subsequently use globally stashed results and check for required ids. """ ...
Wrap Elsevier methods which directly use the API keys. Ensure that the keys are retrieved from the environment or config file when first called, and store global scope. Subsequently use globally stashed results and check for required ids.
def multi_reciprocal_extra(xs, ys, noise=False): """ Calculates for a series of powers ns the parameters for which the last two points are at the curve. With these parameters measure how well the other data points fit. return the best fit. """ ns = np.linspace(0.5, 6.0, num=56) best = ['', n...
Calculates for a series of powers ns the parameters for which the last two points are at the curve. With these parameters measure how well the other data points fit. return the best fit.
def p_param_args_noname(self, p): 'param_args_noname : param_args_noname COMMA param_arg_noname' p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
param_args_noname : param_args_noname COMMA param_arg_noname
def set_pos(self, pos): """ set the position of this column in the Table """ self.pos = pos if pos is not None and self.typ is not None: self.typ._v_pos = pos return self
set the position of this column in the Table
def construct_infrastructure_factory(self, *args, **kwargs): """ :rtype: InfrastructureFactory """ factory_class = self.infrastructure_factory_class assert issubclass(factory_class, InfrastructureFactory) return factory_class( record_manager_class=self.record_...
:rtype: InfrastructureFactory
def to_html(self): """Returns attributes formatted as html.""" id, classes, kvs = self.id, self.classes, self.kvs id_str = 'id="{}"'.format(id) if id else '' class_str = 'class="{}"'.format(' '.join(classes)) if classes else '' key_str = ' '.join('{}={}'.format(k, v) for k, v in ...
Returns attributes formatted as html.
def update_location(self, text=''): """Update text of location.""" self.text_project_name.setEnabled(self.radio_new_dir.isChecked()) name = self.text_project_name.text().strip() if name and self.radio_new_dir.isChecked(): path = osp.join(self.location, name) ...
Update text of location.
def go_to_place(self, place, weight=''): """Assuming I'm in a :class:`Place` that has a :class:`Portal` direct to the given :class:`Place`, schedule myself to travel to the given :class:`Place`, taking an amount of time indicated by the ``weight`` stat on the :class:`Portal`, if given; e...
Assuming I'm in a :class:`Place` that has a :class:`Portal` direct to the given :class:`Place`, schedule myself to travel to the given :class:`Place`, taking an amount of time indicated by the ``weight`` stat on the :class:`Portal`, if given; else 1 turn. Return the number of tu...
def _twofilter_smoothing_ON(self, t, ti, info, phi, lwinfo, return_ess, modif_forward, modif_info): """O(N) version of two-filter smoothing. This method should not be called directly, see twofilter_smoothing. """ if modif_info is not None: lwin...
O(N) version of two-filter smoothing. This method should not be called directly, see twofilter_smoothing.
def download_object(self, container, obj, directory, structure=True): """ Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz...
Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz.txt", that folder structure will be created in the target directory by default. I...
def iftrain(self, then_branch, else_branch): """ Execute `then_branch` when training. """ return ifelse(self._training_flag, then_branch, else_branch, name="iftrain")
Execute `then_branch` when training.
def console(loop, log): """Connect to receiver and show events as they occur. Pulls the following arguments from the command line (not method arguments): :param host: Hostname or IP Address of the device. :param port: TCP port number of the device. :param verbose: Show debu...
Connect to receiver and show events as they occur. Pulls the following arguments from the command line (not method arguments): :param host: Hostname or IP Address of the device. :param port: TCP port number of the device. :param verbose: Show debug logging.
def sample_stats_to_xarray(self): """Extract sample_stats from PyMC3 trace.""" rename_key = {"model_logp": "lp"} data = {} for stat in self.trace.stat_names: name = rename_key.get(stat, stat) data[name] = np.array(self.trace.get_sampler_stats(stat, combine=False))...
Extract sample_stats from PyMC3 trace.
def container_running(self, container_name): """ Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container] """ ...
Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container]
def list(self, request, *args, **kwargs): """ To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching u...
To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching used for searching - ?type=<type> - choices: OpenStack,...
def add_ephemeral_listener(self, callback, event_type=None): """Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: ...
Add a callback handler for ephemeral events going to this room. Args: callback (func(room, event)): Callback called when an ephemeral event arrives. event_type (str): The event_type to filter for. Returns: uuid.UUID: Unique id of the listener, can be used to identify...
def top_segment_proportions(mtx, ns): """ Calculates total percentage of counts in top ns genes. Parameters ---------- mtx : `Union[np.array, sparse.spmatrix]` Matrix, where each row is a sample, each column a feature. ns : `Container[Int]` Positions to calculate cumulative prop...
Calculates total percentage of counts in top ns genes. Parameters ---------- mtx : `Union[np.array, sparse.spmatrix]` Matrix, where each row is a sample, each column a feature. ns : `Container[Int]` Positions to calculate cumulative proportion at. Values are considered 1-indexed...
def next_history(self, e): # (C-n) u'''Move forward through the history list, fetching the next command. ''' self._history.next_history(self.l_buffer) self.finalize()
u'''Move forward through the history list, fetching the next command.
def getTextBlocks(page, images=False): """Return the text blocks on a page. Notes: Lines in a block are concatenated with line breaks. Args: images: (bool) also return meta data of any images. Image data are never returned with this method. Returns: A list of the blo...
Return the text blocks on a page. Notes: Lines in a block are concatenated with line breaks. Args: images: (bool) also return meta data of any images. Image data are never returned with this method. Returns: A list of the blocks. Each item contains the containing rectang...
def crc16(data): """ Calculate an ISO13239 CRC checksum of the input buffer (bytestring). """ m_crc = 0xffff for this in data: m_crc ^= ord_byte(this) for _ in range(8): j = m_crc & 1 m_crc >>= 1 if j: m_crc ^= 0x8408 return m_c...
Calculate an ISO13239 CRC checksum of the input buffer (bytestring).
def get_list_information(self, query_params=None): ''' Get information for this list. Returns a dictionary of values. ''' return self.fetch_json( uri_path=self.base_uri, query_params=query_params or {} )
Get information for this list. Returns a dictionary of values.
def previous_sibling(self): """The previous sibling statement. :returns: The previous sibling statement node. :rtype: NodeNG or None """ stmts = self.parent.child_sequence(self) index = stmts.index(self) if index >= 1: return stmts[index - 1] ...
The previous sibling statement. :returns: The previous sibling statement node. :rtype: NodeNG or None
def write_molden(*args, **kwargs): """Deprecated, use :func:`~chemcoord.xyz_functions.to_molden` """ message = 'Will be removed in the future. Please use to_molden().' with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(message, DeprecationWarning) return to...
Deprecated, use :func:`~chemcoord.xyz_functions.to_molden`
def observer(self, component_type=ComponentType): """ You can use ``@broker.observer()`` as a decorator to your callback instead of :func:`Broker.add_observer`. """ def inner(func): self.add_observer(func, component_type) return func return inner
You can use ``@broker.observer()`` as a decorator to your callback instead of :func:`Broker.add_observer`.
def dictmerge(x, y): """ merge two dictionaries """ z = x.copy() z.update(y) return z
merge two dictionaries
def interact(self, banner=None): """Closely emulate the interactive Python console. This method overwrites its superclass' method to specify a different help text and to enable proper handling of the debugger status line. Args: banner: Text to be displayed on interpreter startup. """ sys...
Closely emulate the interactive Python console. This method overwrites its superclass' method to specify a different help text and to enable proper handling of the debugger status line. Args: banner: Text to be displayed on interpreter startup.
def _prob_match(self, features): """Compute match probabilities. Parameters ---------- features : numpy.ndarray The data to train the model on. Returns ------- numpy.ndarray The match probabilties. """ # compute the proba...
Compute match probabilities. Parameters ---------- features : numpy.ndarray The data to train the model on. Returns ------- numpy.ndarray The match probabilties.
def kernel_restarted_message(self, msg): """Show kernel restarted/died messages.""" if not self.is_error_shown: # If there are kernel creation errors, jupyter_client will # try to restart the kernel and qtconsole prints a # message about it. # So we ...
Show kernel restarted/died messages.
def digest(self, elimseq=False, notrunc=False): """ Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises Intern...
Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error
def voip_play2(s1, **kargs): """ Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets. """ dsp, rd = os.popen2(sox_base % "-c 2") global x1, ...
Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets.
def directions(self, origin, destination, mode=None, alternatives=None, waypoints=None, optimize_waypoints=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, sensor=None): """Get direction...
Get directions between locations :param origin: Origin location - string address; (latitude, longitude) two-tuple, dict with ("lat", "lon") keys or object with (lat, lon) attributes :param destination: Destination location - type same as origin :param mode: Travel mode a...
def shift(self, modelResult): """Shift the model result and return the new instance. Queues up the T(i+1) prediction value and emits a T(i) input/prediction pair, if possible. E.g., if the previous T(i-1) iteration was learn-only, then we would not have a T(i) prediction in our FIFO and would not b...
Shift the model result and return the new instance. Queues up the T(i+1) prediction value and emits a T(i) input/prediction pair, if possible. E.g., if the previous T(i-1) iteration was learn-only, then we would not have a T(i) prediction in our FIFO and would not be able to emit a meaningful input/pre...
def create(self, validated_data): """ Create a new email and send a confirmation to it. Returns: The newly creating ``EmailAddress`` instance. """ email_query = models.EmailAddress.objects.filter( email=self.validated_data["email"] ) if e...
Create a new email and send a confirmation to it. Returns: The newly creating ``EmailAddress`` instance.
def htmlFormat(output, pathParts = (), statDict = None, query = None): """Formats as HTML, writing to the given object.""" statDict = statDict or scales.getStats() if query: statDict = runQuery(statDict, query) _htmlRenderDict(pathParts, statDict, output)
Formats as HTML, writing to the given object.
def get_variable_scope_name(value): """Returns the name of the variable scope indicated by the given value. Args: value: String, variable scope, or object with `variable_scope` attribute (e.g., Sonnet module). Returns: The name (a string) of the corresponding variable scope. Raises: ValueErro...
Returns the name of the variable scope indicated by the given value. Args: value: String, variable scope, or object with `variable_scope` attribute (e.g., Sonnet module). Returns: The name (a string) of the corresponding variable scope. Raises: ValueError: If `value` does not identify a variabl...
def formfield_for_dbfield(self, db_field, **kwargs): ''' Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.''' if db_field.name == "gradings": request=kwargs['request'] try: #TODO: MockRequst object fro...
Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.
def add_filehandler(level, fmt, filename, mode, backup_count, limit, when): """Add a file handler to the global logger.""" kwargs = {} # If the filename is not set, use the default filename if filename is None: filename = getattr(sys.modules['__main__'], '__file__', 'log.py') filename ...
Add a file handler to the global logger.
def svd_convolution(inp, outmaps, kernel, r, pad=None, stride=None, dilation=None, uv_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): """SVD convolution is a low rank approximation of the convolution layer. It can be seen as a depth w...
SVD convolution is a low rank approximation of the convolution layer. It can be seen as a depth wise convolution followed by a 1x1 convolution. The flattened kernels for the i-th input map are expressed by their low rank approximation. The kernels for the i-th input :math:`{\\mathbf W_i}` are appro...
def _merge_statement_lists(stmsA: List["HdlStatement"], stmsB: List["HdlStatement"])\ -> List["HdlStatement"]: """ Merge two lists of statements into one :return: list of merged statements """ if stmsA is None and stmsB is None: return None tmp =...
Merge two lists of statements into one :return: list of merged statements
def get_new_call(group_name, app_name, search_path, filename, require_load, version, secure): # type: (str, str, Optional[str], str, bool, Optional[str], bool) -> str ''' Build a call to use the new ``get_config`` function from args passed to ``Config.__init__``. ''' new_call_kw...
Build a call to use the new ``get_config`` function from args passed to ``Config.__init__``.
def from_rgb(cls, r: int, g: int, b: int) -> 'ColorCode': """ Return a ColorCode from a RGB tuple. """ c = cls() c._init_rgb(r, g, b) return c
Return a ColorCode from a RGB tuple.
def verify(self, type_): """ Check whether a type implements ``self``. Parameters ---------- type_ : type The type to check. Raises ------ TypeError If ``type_`` doesn't conform to our interface. Returns ------- ...
Check whether a type implements ``self``. Parameters ---------- type_ : type The type to check. Raises ------ TypeError If ``type_`` doesn't conform to our interface. Returns ------- None
def pix2canvas(self, pt): """Takes a 2-tuple of (x, y) in window coordinates and gives the (cx, cy, cz) coordinates on the canvas. """ x, y = pt[:2] #print('p2c in', x, y) mm = gl.glGetDoublev(gl.GL_MODELVIEW_MATRIX) pm = gl.glGetDoublev(gl.GL_PROJECTION_MATRIX) ...
Takes a 2-tuple of (x, y) in window coordinates and gives the (cx, cy, cz) coordinates on the canvas.
def get_parser(): """Return the parser object for this script.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-m", "--model", ...
Return the parser object for this script.
def real_time_statistics(self): """ Access the real_time_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRe...
Access the real_time_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsList
def from_cmdstan( posterior=None, *, posterior_predictive=None, prior=None, prior_predictive=None, observed_data=None, observed_data_var=None, log_likelihood=None, coords=None, dims=None ): """Convert CmdStan data into an InferenceData object. Parameters ---------- ...
Convert CmdStan data into an InferenceData object. Parameters ---------- posterior : List[str] List of paths to output.csv files. CSV file can be stacked csv containing all the chains cat output*.csv > combined_output.csv posterior_predictive : str, List[Str] Poste...
def get_path(self, path, query=None): """Make a GET request, optionally including a query, to a relative path. The path of the request includes a path on top of the base URL assigned to the endpoint. Parameters ---------- path : str The path to request, rela...
Make a GET request, optionally including a query, to a relative path. The path of the request includes a path on top of the base URL assigned to the endpoint. Parameters ---------- path : str The path to request, relative to the endpoint query : DataQuery, o...
def mapfi(ol,map_func_args,**kwargs): ''' #mapfi 共享相同的o,v不作为map_func参数 # share common other_args,NOT take value as a param for map_func #map_func diff_func(index,*common_args) ''' diff_funcs_arr = kwargs['map_funcs'] lngth = ol.__len__() rsl...
#mapfi 共享相同的o,v不作为map_func参数 # share common other_args,NOT take value as a param for map_func #map_func diff_func(index,*common_args)
def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch', 'develop') common.assert_branch_type('feature') commo...
Update the feature with updates committed to develop. This will merge current develop into the current branch.
def copyText( self ): """ Copies the selected text to the clipboard. """ view = self.currentWebView() QApplication.clipboard().setText(view.page().selectedText())
Copies the selected text to the clipboard.
def setupTable_head(self): """ Make the head table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "head" not in self.tables: return ...
Make the head table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
def reserve(self, doc): """Reserve a DOI (amounts to upload metadata, but not to mint). :param doc: Set metadata for DOI. :returns: `True` if is reserved successfully. """ # Only registered PIDs can be updated. try: self.pid.reserve() self.api.met...
Reserve a DOI (amounts to upload metadata, but not to mint). :param doc: Set metadata for DOI. :returns: `True` if is reserved successfully.
def get_current_structure(self): """ Returns a dictionary with model field objects. :return: dict """ struct = self.__class__.get_structure() struct.update(self.__field_types__) return struct
Returns a dictionary with model field objects. :return: dict
def ticket_tags(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tags#show-tags" api_path = "/api/v2/tickets/{id}/tags.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/tags#show-tags
def _estimate_centers_widths( self, unique_R, inds, X, W, init_centers, init_widths, template_centers, template_widths, template_centers_mean_cov, template_widths_mean_var_reci): "...
Estimate centers and widths Parameters ---------- unique_R : a list of array, Each element contains unique value in one dimension of coordinate matrix R. inds : a list of array, Each element contains the indices to reconstruct one dimens...
def run(self): """Run thread to listen for jobs and reschedule successful ones.""" try: self.listen() except Exception as e: logger.critical("JobListener instence crashed. Error: %s", str(e)) logger.critical(traceback.format_exc())
Run thread to listen for jobs and reschedule successful ones.
def merge_tops(self, tops): ''' Cleanly merge the top files ''' top = collections.defaultdict(OrderedDict) orders = collections.defaultdict(OrderedDict) for ctops in six.itervalues(tops): for ctop in ctops: for saltenv, targets in six.iteritems...
Cleanly merge the top files
def _compile_models(models): """ Convert ``models`` into a list of tasks. Each task is tuple ``(name, data)`` where ``name`` indicates the task task and ``data`` is the relevant data for that task. Supported tasks and data: - ``'fit'`` and list of models - ``'...
Convert ``models`` into a list of tasks. Each task is tuple ``(name, data)`` where ``name`` indicates the task task and ``data`` is the relevant data for that task. Supported tasks and data: - ``'fit'`` and list of models - ``'update-kargs'`` and ``None`` ...
def polygon(self): '''return a polygon for the fence''' points = [] for fp in self.points[1:]: points.append((fp.lat, fp.lng)) return points
return a polygon for the fence
def backoff( max_tries=constants.BACKOFF_DEFAULT_MAXTRIES, delay=constants.BACKOFF_DEFAULT_DELAY, factor=constants.BACKOFF_DEFAULT_FACTOR, exceptions=None): """Implements an exponential backoff decorator which will retry decorated function upon given exceptions. This implementati...
Implements an exponential backoff decorator which will retry decorated function upon given exceptions. This implementation is based on `Retry <https://wiki.python.org/moin/PythonDecoratorLibrary#Retry>`_ from the *Python Decorator Library*. :param int max_tries: Number of tries before give up. Defaults...
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: FeedbackContext for this FeedbackInstance :rtype: twilio.rest.api.v2010.account.call.feedback.Fee...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FeedbackContext for this FeedbackInstance :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext
def get_or_create_candidate(self, row, party, race): """ Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person o...
Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person object to pass to Django.
def find_related(self, fullname): """ Return a list of non-stdlib modules that are imported directly or indirectly by `fullname`, plus their parents. This method is like :py:meth:`find_related_imports`, but also recursively searches any modules which are imported by `fullname`. ...
Return a list of non-stdlib modules that are imported directly or indirectly by `fullname`, plus their parents. This method is like :py:meth:`find_related_imports`, but also recursively searches any modules which are imported by `fullname`. :param fullname: Fully qualified name of an _...
def set_release_description(self, description, **kwargs): """Set the release notes on the tag. If the release doesn't exist yet, it will be created. If it already exists, its description will be updated. Args: description (str): Description of the release. **kwa...
Set the release notes on the tag. If the release doesn't exist yet, it will be created. If it already exists, its description will be updated. Args: description (str): Description of the release. **kwargs: Extra options to send to the server (e.g. sudo) Raises:...
def with_metaclass(meta, *bases): """ Create a base class with a metaclass. For example, if you have the metaclass >>> class Meta(type): ... pass Use this as the metaclass by doing >>> from symengine.compatibility import with_metaclass >>> class MyClass(with_metaclass(Meta, objec...
Create a base class with a metaclass. For example, if you have the metaclass >>> class Meta(type): ... pass Use this as the metaclass by doing >>> from symengine.compatibility import with_metaclass >>> class MyClass(with_metaclass(Meta, object)): ... pass This is equivalent ...
def _find_v1_settings(self, settings): """Parse a v1 module_settings.json file. V1 is the older file format that requires a modules dictionary with a module_name and modules key that could in theory hold information on multiple modules in a single directory. """ if 'mod...
Parse a v1 module_settings.json file. V1 is the older file format that requires a modules dictionary with a module_name and modules key that could in theory hold information on multiple modules in a single directory.
def _create(self): """Create new callback resampler.""" from samplerate.lowlevel import ffi, src_callback_new, src_delete from samplerate.exceptions import ResamplingError state, handle, error = src_callback_new( self._callback, self._converter_type.value, self._channels) ...
Create new callback resampler.
def setcontents(source, identifier, pointer): """Patch existing bibliographic record.""" record = Record.get_record(identifier) Document(record, pointer).setcontents(source)
Patch existing bibliographic record.
def get_nn_info(self, structure, n): """ Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the closest relative neighbor distance-based method with VIRE atomic/ionic radii. Args: structure (Structure): in...
Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the closest relative neighbor distance-based method with VIRE atomic/ionic radii. Args: structure (Structure): input structure. n (integer): index of site for...
def convert_table(self, block): """"Converts a table to grid table format""" lines_orig = block.split('\n') lines_orig.pop() # Remove extra newline at end of block widest_cell = [] # Will hold the width of the widest cell for each column widest_word = [] # Will hold the width of ...
Converts a table to grid table format
def dev_null_wrapper(func, *a, **kwargs): """ Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null. This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases. """ os.dup2(dev_null, sys.stdout.fileno()) return_object = f...
Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null. This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases.
def prepare(self): """Behaves like a middleware between raw request and handling process, If `PREPARES` is defined on handler class, which should be a list, for example, ['auth', 'context'], method whose name is constitute by prefix '_prepare_' and string in this list will be ex...
Behaves like a middleware between raw request and handling process, If `PREPARES` is defined on handler class, which should be a list, for example, ['auth', 'context'], method whose name is constitute by prefix '_prepare_' and string in this list will be executed by sequence. In this ex...
def randstr(self): """ -> #str result of :func:gen_rand_str """ return gen_rand_str( 4, 10, use=self.random, keyspace=list(string.ascii_letters))
-> #str result of :func:gen_rand_str
def ceilpow2(n): """convenience function to determine a power-of-2 upper frequency limit""" signif,exponent = frexp(n) if (signif < 0): return 1; if (signif == 0.5): exponent -= 1; return (1) << exponent;
convenience function to determine a power-of-2 upper frequency limit
def lint(filename, options=()): """Pylint the given file. When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylin...
Pylint the given file. When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylint will classify it as a failed import. ...
def _start_element (self, tag, attrs, end): """ Print HTML element with end string. @param tag: tag name @type tag: string @param attrs: tag attributes @type attrs: dict @param end: either > or /> @type end: string @return: None """ ...
Print HTML element with end string. @param tag: tag name @type tag: string @param attrs: tag attributes @type attrs: dict @param end: either > or /> @type end: string @return: None
def cee_map_priority_table_map_cos1_pgid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop...
Auto Generated Code
def members(self): """ Access the members :returns: twilio.rest.chat.v1.service.channel.member.MemberList :rtype: twilio.rest.chat.v1.service.channel.member.MemberList """ if self._members is None: self._members = MemberList( self._version, ...
Access the members :returns: twilio.rest.chat.v1.service.channel.member.MemberList :rtype: twilio.rest.chat.v1.service.channel.member.MemberList
def get_folders(self): """Return list of user's folders. :rtype: list """ path = 'folders/list' response = self.request(path) items = response['data'] folders = [] for item in items: if item.get('type') == 'error': raise Except...
Return list of user's folders. :rtype: list
def _set_offset_base1(self, v, load=False): """ Setter method for offset_base1, mapped from YANG variable /uda_key/profile/uda_profile_offsets/offset_base1 (uda-offset-base-type) If this variable is read-only (config: false) in the source YANG file, then _set_offset_base1 is considered as a private ...
Setter method for offset_base1, mapped from YANG variable /uda_key/profile/uda_profile_offsets/offset_base1 (uda-offset-base-type) If this variable is read-only (config: false) in the source YANG file, then _set_offset_base1 is considered as a private method. Backends looking to populate this variable shoul...
def setBackground(self,bg): """ Sets the background of the Container. Similar to :py:meth:`peng3d.gui.SubMenu.setBackground()`\ , but only effects the region covered by the Container. """ self.bg = bg if isinstance(bg,list) or isinstance(bg,tuple): if...
Sets the background of the Container. Similar to :py:meth:`peng3d.gui.SubMenu.setBackground()`\ , but only effects the region covered by the Container.
def check_style(value): """ Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this func...
Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this function accepts the logging format styl...
def detect_complexity(bam_in, genome, out): """ genome coverage of small RNA """ if not genome: logger.info("No genome given. skipping.") return None out_file = op.join(out, op.basename(bam_in) + "_cov.tsv") if file_exists(out_file): return None fai = genome + ".fai" ...
genome coverage of small RNA
def sign_decorated(self, data): """Sign a bytes-like object and return the decorated signature. Sign a bytes-like object by signing the data using the signing (private) key, and return a decorated signature, which includes the last four bytes of the public key as a signature hint to go ...
Sign a bytes-like object and return the decorated signature. Sign a bytes-like object by signing the data using the signing (private) key, and return a decorated signature, which includes the last four bytes of the public key as a signature hint to go along with the signature as an XDR ...
def lookup_ids(self, keys): """Lookup the integer ID associated with each (namespace, key) in the keys list""" keys_len = len(keys) ids = {namespace_key: None for namespace_key in keys} start = 0 bulk_insert = self.bulk_insert query = 'SELECT namespace, key, id FR...
Lookup the integer ID associated with each (namespace, key) in the keys list
def column_coordinates(self, X): """The column principal coordinates.""" utils.validation.check_is_fitted(self, 'V_') _, _, _, col_names = util.make_labels_and_names(X) if isinstance(X, pd.SparseDataFrame): X = X.to_coo() elif isinstance(X, pd.DataFrame): ...
The column principal coordinates.
def from_frame(klass, frame, connection): """ Create a new BuildStateChange event from a Stompest Frame. """ event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] build = Build.fromDict(info) build.connection = connection r...
Create a new BuildStateChange event from a Stompest Frame.
def _buildvgrid(self,R,phi,nsigma,t,sigmaR1,sigmaT1,meanvR,meanvT, gridpoints,print_progress,integrate_method,deriv): """Internal function to grid the vDF at a given location""" out= evolveddiskdfGrid() out.sigmaR1= sigmaR1 out.sigmaT1= sigmaT1 out.meanvR= mea...
Internal function to grid the vDF at a given location
def routes(family=None): ''' Return currently configured routes from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' netwo...
Return currently configured routes from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.routes
def report_parsing_problems(parsing_out): """Output message about potential parsing problems.""" _, empty, faulty = parsing_out if CONFIG_FILE in empty or CONFIG_FILE in faulty: print('Unable to read global config file', CONFIG_FILE, file=sys.stderr) print('Please run stagpy co...
Output message about potential parsing problems.
def set_locs(self, locs): 'Sets the locations of the ticks' # don't actually use the locs. This is just needed to work with # matplotlib. Force to use vmin, vmax _check_implicitly_registered() self.locs = locs (vmin, vmax) = vi = tuple(self.axis.get_view_interval()) ...
Sets the locations of the ticks
def get(self, key, value): """Get a single record by id Supports resource cache .. versionchanged:: 2.17.0 Added option to retrieve record by tracking_id Keyword Args: id (str): Full record ID tracking_id (str): Record Tracking ID Returns:...
Get a single record by id Supports resource cache .. versionchanged:: 2.17.0 Added option to retrieve record by tracking_id Keyword Args: id (str): Full record ID tracking_id (str): Record Tracking ID Returns: Record: Matching Record i...