code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def forward_substitution(matrix_l, matrix_b): """ Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular mat...
Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular matrix :type matrix_l: list, tuple :param matrix_...
def _get_qvm_based_on_real_device(name: str, device: Device, noisy: bool, connection: ForestConnection = None, qvm_type: str = 'qvm'): """ A qvm with a based on a real device. This is the most realistic QVM. :param name: The full name...
A qvm with a based on a real device. This is the most realistic QVM. :param name: The full name of this QVM :param device: The device from :py:func:`get_lattice`. :param noisy: Whether to construct a noisy quantum computer by using the device's associated noise model. :param connection: An...
def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()""" if self.id in postdata and postdata[self.id] != '': retur...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()
def compute(cls, observation, prediction): """Compute a Cohen's D from an observation and a prediction.""" assert isinstance(observation, dict) assert isinstance(prediction, dict) p_mean = prediction['mean'] # Use the prediction's mean. p_std = prediction['std'] o_mean =...
Compute a Cohen's D from an observation and a prediction.
def _line_wrapper(self,diffs): """Returns iterator that splits (wraps) mdiff text lines""" # pull from/to data and flags from mdiff iterator for fromdata,todata,flag in diffs: # check for context separators and pass them through if flag is None: yield fro...
Returns iterator that splits (wraps) mdiff text lines
def svd(g, svdcut=1e-12, wgts=False, add_svdnoise=False): """ Apply SVD cuts to collection of |GVar|\s in ``g``. Standard usage is, for example, :: svdcut = ... gmod = svd(g, svdcut=svdcut) where ``g`` is an array of |GVar|\s or a dictionary containing |GVar|\s and/or arrays of |GVar|...
Apply SVD cuts to collection of |GVar|\s in ``g``. Standard usage is, for example, :: svdcut = ... gmod = svd(g, svdcut=svdcut) where ``g`` is an array of |GVar|\s or a dictionary containing |GVar|\s and/or arrays of |GVar|\s. When ``svdcut>0``, ``gmod`` is a copy of ``g`` whose |GVar...
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32, batch_size=1): """Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, ...
Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, this should live in tf.estimator.export. Testing here first. Args: shape: list representing target size of a single example....
def walk(self, basedir): """Walk all the directories of basedir except hidden directories :param basedir: string, the directory to walk :returns: generator, same as os.walk """ system_d = SitePackagesDir() filter_system_d = system_d and os.path.commonprefix([system_d, ba...
Walk all the directories of basedir except hidden directories :param basedir: string, the directory to walk :returns: generator, same as os.walk
def on_play_speed(self, *args): """Change the interval at which ``self.play`` is called to match my current ``play_speed``. """ Clock.unschedule(self.play) Clock.schedule_interval(self.play, 1.0 / self.play_speed)
Change the interval at which ``self.play`` is called to match my current ``play_speed``.
def NRTL(xs, taus, alphas): r'''Calculates the activity coefficients of each species in a mixture using the Non-Random Two-Liquid (NRTL) method, given their mole fractions, dimensionless interaction parameters, and nonrandomness constants. Those are normally correlated with temperature in some form, and...
r'''Calculates the activity coefficients of each species in a mixture using the Non-Random Two-Liquid (NRTL) method, given their mole fractions, dimensionless interaction parameters, and nonrandomness constants. Those are normally correlated with temperature in some form, and need to be calculated separ...
def resolve_object(self, object_arg_name, resolver): """ A helper decorator to resolve object instance from arguments (e.g. identity). Example: >>> @namespace.route('/<int:user_id>') ... class MyResource(Resource): ... @namespace.resolve_object( ... obj...
A helper decorator to resolve object instance from arguments (e.g. identity). Example: >>> @namespace.route('/<int:user_id>') ... class MyResource(Resource): ... @namespace.resolve_object( ... object_arg_name='user', ... resolver=lambda kwargs: User.quer...
def _get(self, uri, params={}): """ HTTP GET function :param uri: REST endpoint :param params: optional HTTP params to pass to the endpoint :return: list of results (usually a list of dicts) Example: ret = cli.get('/search', params={ 'q': 'example.org' }) ...
HTTP GET function :param uri: REST endpoint :param params: optional HTTP params to pass to the endpoint :return: list of results (usually a list of dicts) Example: ret = cli.get('/search', params={ 'q': 'example.org' })
def _parse_csv_col_rules(self): """ splits the CSV line of the current format and puts into local class variables - mainly for testing, though this is not the best method long term. (TODO - fix this) """ self.cols = self.csv_line.split(',') self.table = self.extr...
splits the CSV line of the current format and puts into local class variables - mainly for testing, though this is not the best method long term. (TODO - fix this)
def _join(segments): """simply list by joining adjacent segments.""" new = [] start = segments[0][0] end = segments[0][1] for i in range(len(segments)-1): if segments[i+1][0] != segments[i][1]: new.append((start, end)) start = segments[i+1][0] end = segments[i...
simply list by joining adjacent segments.
def timestr_mod24(timestr: str) -> int: """ Given a GTFS HH:MM:SS time string, return a timestring in the same format but with the hours taken modulo 24. """ try: hours, mins, secs = [int(x) for x in timestr.split(":")] hours %= 24 result = f"{hours:02d}:{mins:02d}:{secs:02d}...
Given a GTFS HH:MM:SS time string, return a timestring in the same format but with the hours taken modulo 24.
def write_template(fn, lang="python"): """ Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language """ with open(fn, "wb") as fh: if lang == "python": fh.wri...
Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(Ren...
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
def get_link_name (self, tag, attrs, attr): """Parse attrs for link name. Return name of link.""" if tag == 'a' and attr == 'href': # Look for name only up to MAX_NAMELEN characters data = self.parser.peek(MAX_NAMELEN) data = data.decode(self.parser.encoding, "ignore"...
Parse attrs for link name. Return name of link.
def memory_read16(self, addr, num_halfwords, zone=None): """Reads memory from the target system in units of 16-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_halfwords (int): number of half words to read zone (str): me...
Reads memory from the target system in units of 16-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_halfwords (int): number of half words to read zone (str): memory zone to read from Returns: List of halfwords...
def cli(env, identifier, name, all, note): """Capture one or all disks from a virtual server to a SoftLayer image.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') capture = vsi.capture(vs_id, name, all, note) table = formatting.KeyValueTable(...
Capture one or all disks from a virtual server to a SoftLayer image.
def _get_position(self, position, prev=False): """Return the next/previous position or raise IndexError.""" if position == self.POSITION_LOADING: if prev: raise IndexError('Reached last position') else: return self._conversation.events[0].id_ ...
Return the next/previous position or raise IndexError.
def store(self, deferred_result): """ Store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object. """ self._counter += 1 self._stored[self._counter] = deferred_result return self._counter
Store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object.
def mean_abs_tree_shap(model, data): """ mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid """ def f(X): v = TreeExplainer(model).shap_values(X) if isinstance(v, list): return [np.tile(np.abs(sv).mean(0), (X.shape[0], 1)) for sv in v] else: ...
mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid
def changelist_view(self, request, extra_context=None): """ Get object currently tracked and add a button to get back to it """ extra_context = extra_context or {} if 'object' in request.GET.keys(): value = request.GET['object'].split(':') content_type = get_object_or_404...
Get object currently tracked and add a button to get back to it
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get...
Receives a Response. Returns a generator of Responses or Requests.
def _initialize(self, chain, length): """Create an SQL table. """ if self._getfunc is None: self._getfunc = self.db.model._funs_to_tally[self.name] # Determine size try: self._shape = np.shape(self._getfunc()) except TypeError: self._...
Create an SQL table.
def _read_execute_info(path, parents): """Read the ExecuteInfo.txt file and return the base directory.""" path = os.path.join(path, "StarCraft II/ExecuteInfo.txt") if os.path.exists(path): with open(path, "rb") as f: # Binary because the game appends a '\0' :(. for line in f: parts = [p.strip()...
Read the ExecuteInfo.txt file and return the base directory.
def Clift(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < ...
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < 20$}\\ \fra...
def list_clusters(self): """List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_instance] :end-before: [END bigtable_list_clusters_on_instance] :rtype: tuple :returns: ...
List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_instance] :end-before: [END bigtable_list_clusters_on_instance] :rtype: tuple :returns: (clusters, failed_locations), whe...
def scaleToSeconds(requestContext, seriesList, seconds): """ Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolu...
Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolution for arbitrary retentions
def get_pull_request_query(self, queries, repository_id, project=None): """GetPullRequestQuery. [Preview API] This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pu...
GetPullRequestQuery. [Preview API] This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pull requests that have ever merged a particular commit. The input is a list of quer...
def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None): """ Returns a pandas DataFrame containing all of the data for a punchcard. * day_of_week * hour_of_day * author / committer ...
Returns a pandas DataFrame containing all of the data for a punchcard. * day_of_week * hour_of_day * author / committer * lines * insertions * deletions * net :param branch: the branch to return commits for :param limit: (optional, default...
def __draw_cmp(self, obj1, obj2): """Defines how our drawable objects should be sorted""" if obj1.draw_order > obj2.draw_order: return 1 elif obj1.draw_order < obj2.draw_order: return -1 else: return 0
Defines how our drawable objects should be sorted
def destroy_iam(app='', env='dev', **_): """Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion. """ session = boto3.Session(profile_name=env) client = ses...
Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion.
def undersampling(X, y, cost_mat=None, per=0.5): """Under-sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shap...
Under-sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4], optional (default=None) ...
def respond_from_question(self, question, user_question, importance): """Copy the answer given in `question` to the logged in user's profile. :param question: A :class:`~.Question` instance to copy. :param user_question: An instance of :class:`~.UserQuestion` that ...
Copy the answer given in `question` to the logged in user's profile. :param question: A :class:`~.Question` instance to copy. :param user_question: An instance of :class:`~.UserQuestion` that corresponds to the same question as `question`. ...
def unpublish(namespace, name, version, registry=None): ''' Try to unpublish a recently published version. Return any errors that occur. ''' registry = registry or Registry_Base_URL url = '%s/%s/%s/versions/%s' % ( registry, namespace, name, version ) he...
Try to unpublish a recently published version. Return any errors that occur.
def solarzenithangle(time: datetime, glat: float, glon: float, alt_m: float) -> tuple: """ Input: t: scalar or array of datetime """ time = totime(time) obs = EarthLocation(lat=glat*u.deg, lon=glon*u.deg, height=alt_m*u.m) times = Time(time, scale='ut1') sun = get_sun(times) sunobs...
Input: t: scalar or array of datetime
def is_ancestor_of_bin(self, id_, bin_id): """Tests if an ``Id`` is an ancestor of a bin. arg: id (osid.id.Id): an ``Id`` arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if this ``id`` is an ancestor of ``bin_id,`` ``false`` otherwise ...
Tests if an ``Id`` is an ancestor of a bin. arg: id (osid.id.Id): an ``Id`` arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if this ``id`` is an ancestor of ``bin_id,`` ``false`` otherwise raise: NotFound - ``bin_id`` is not found ...
def report_question(self, concern, pub_name, ext_name, question_id): """ReportQuestion. [Preview API] Flags a concern with an existing question for an extension. :param :class:`<Concern> <azure.devops.v5_1.gallery.models.Concern>` concern: User reported concern with a question for the extension....
ReportQuestion. [Preview API] Flags a concern with an existing question for an extension. :param :class:`<Concern> <azure.devops.v5_1.gallery.models.Concern>` concern: User reported concern with a question for the extension. :param str pub_name: Name of the publisher who published the extension....
def spearmanr(x, y): """ Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> round(spearmanr(x, y), 4) ...
Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> round(spearmanr(x, y), 4) 0.4 >>> round(spearmanr(x...
def form_user_label_matrix(user_twitter_list_keywords_gen, id_to_node, max_number_of_labels): """ Forms the user-label matrix to be used in multi-label classification. Input: - user_twitter_list_keywords_gen: - id_to_node: A Twitter id to node map as a python dictionary. Outputs: - use...
Forms the user-label matrix to be used in multi-label classification. Input: - user_twitter_list_keywords_gen: - id_to_node: A Twitter id to node map as a python dictionary. Outputs: - user_label_matrix: A user-to-label matrix in scipy sparse matrix format. - annotated_nodes: A nu...
def _mapping_to_tuple_pairs(d): """ Convert a mapping object (such as a dictionary) to tuple pairs, using its keys and values to generate the pairs and then generating all possible combinations between those e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),)) """ # order t...
Convert a mapping object (such as a dictionary) to tuple pairs, using its keys and values to generate the pairs and then generating all possible combinations between those e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),))
def set_record(self, record, **kw): """ check the record is valid and set keys in the dict parameters ---------- record: string Dict representing a record or a string representing a FITS header card """ if isstring(record): ca...
check the record is valid and set keys in the dict parameters ---------- record: string Dict representing a record or a string representing a FITS header card
def assert_strong_password(username, password, old_password=None): """Raises ValueError if the password isn't strong. Returns the password otherwise.""" # test the length try: minlength = settings.MIN_PASSWORD_LENGTH except AttributeError: minlength = 12 if len(password) < minl...
Raises ValueError if the password isn't strong. Returns the password otherwise.
def libvlc_audio_set_format(mp, format, rate, channels): '''Set decoded audio format. This only works in combination with L{libvlc_audio_set_callbacks}(), and is mutually exclusive with L{libvlc_audio_set_format_callbacks}(). @param mp: the media player. @param format: a four-characters string ident...
Set decoded audio format. This only works in combination with L{libvlc_audio_set_callbacks}(), and is mutually exclusive with L{libvlc_audio_set_format_callbacks}(). @param mp: the media player. @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param rat...
def event_update_status(self, event_id, status, scores=[], account=None, **kwargs): """ Update the status of an event. This needs to be **proposed**. :param str event_id: Id of the event to update :param str status: Event status :param list scores: List of strings that repre...
Update the status of an event. This needs to be **proposed**. :param str event_id: Id of the event to update :param str status: Event status :param list scores: List of strings that represent the scores of a match (defaults to []) :param str account: (opt...
def _get_first_urn(self, urn): """ Provisional route for GetFirstUrn request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetFirstUrn response """ urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) ...
Provisional route for GetFirstUrn request :param urn: URN to filter the resource :param inv: Inventory Identifier :return: GetFirstUrn response
def _startMqtt(self): """ The client start method. Starts the thread for the MQTT Client and publishes the connected message. """ LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port)) try: # self._mqttc.connect_async(str(self._server), in...
The client start method. Starts the thread for the MQTT Client and publishes the connected message.
def get(self, request, provider=None): """prepare the social friend model""" # Get the social auth connections if USING_ALLAUTH: self.social_auths = request.user.socialaccount_set.all() else: self.social_auths = request.user.social_auth.all() ...
prepare the social friend model
def rates_angles(fk_candidate_observations): """ :param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted """ detections = fk_candidate_observations.get_sources() for detection in detections: measures = detection.get_readings() for measure i...
:param fk_candidate_observations: name of the fk*reals.astrom file to check against Object.planted
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to their mean. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask a...
The model is revaluated for each test sample with the non-important features set to their mean.
def logpdf(self, mu): """ Log PDF for t prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - log(p(mu)) """ if self.transform is not None: mu = self.t...
Log PDF for t prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - log(p(mu))
def linear_elasticity(grid, spacing=None, E=1e5, nu=0.3, format=None): """Linear elasticity problem discretizes with Q1 finite elements on a regular rectangular grid. Parameters ---------- grid : tuple length 2 tuple of grid sizes, e.g. (10, 10) spacing : tuple length 2 tuple of gri...
Linear elasticity problem discretizes with Q1 finite elements on a regular rectangular grid. Parameters ---------- grid : tuple length 2 tuple of grid sizes, e.g. (10, 10) spacing : tuple length 2 tuple of grid spacings, e.g. (1.0, 0.1) E : float Young's modulus nu : flo...
def get_meta_image_url(request, image): """ Resize an image for metadata tags, and return an absolute URL to it. """ rendition = image.get_rendition(filter='original') return request.build_absolute_uri(rendition.url)
Resize an image for metadata tags, and return an absolute URL to it.
def StartAFF4Flow(args=None, runner_args=None, parent_flow=None, sync=True, token=None, **kwargs): """The main factory function for creating and executing a new flow. Args: args: An arg protocol buffer which is an instanc...
The main factory function for creating and executing a new flow. Args: args: An arg protocol buffer which is an instance of the required flow's args_type class attribute. runner_args: an instance of FlowRunnerArgs() protocol buffer which is used to initialize the runner for this flow. parent_...
def _handle_chat_name(self, data): """Handle user name changes""" self.room.user.nick = data self.conn.enqueue_data("user", self.room.user)
Handle user name changes
def get_PSD(self, NPerSegment=1000000, window="hann", timeStart=None, timeEnd=None, override=False): """ Extracts the power spectral density (PSD) from the data. Parameters ---------- NPerSegment : int, optional Length of each segment used in scipy.welch ...
Extracts the power spectral density (PSD) from the data. Parameters ---------- NPerSegment : int, optional Length of each segment used in scipy.welch default = 1000000 window : str or tuple or array_like, optional Desired window to use. See get_windo...
def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == 'cancelled': raise UserError( _('You need to cancel it before reopening.')) if not (rec.am_i_owner or rec.am_i_approver): raise Use...
Set a change request as draft
def extract(data, items, out_dir=None): """Extract germline calls for the given sample, if tumor only. """ if vcfutils.get_paired_phenotype(data): if len(items) == 1: germline_vcf = _remove_prioritization(data["vrn_file"], data, out_dir) germline_vcf = vcfutils.bgzip_and_inde...
Extract germline calls for the given sample, if tumor only.
def on_failure(self, exc, task_id, args, kwargs, einfo): """on_failure http://docs.celeryproject.org/en/latest/userguide/tasks.html#task-inheritance :param exc: exception :param task_id: task id :param args: arguments passed into task :param kwargs: keyword arguments pa...
on_failure http://docs.celeryproject.org/en/latest/userguide/tasks.html#task-inheritance :param exc: exception :param task_id: task id :param args: arguments passed into task :param kwargs: keyword arguments passed into task :param einfo: exception info
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None): """ Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user. """ def wrapper(fn): @wraps(fn) def decorated(*args, **...
Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
def check(self, **kwargs): """ In addition to parent class' checks, also ensure that MULTITENANT_STATICFILES_DIRS is a tuple or a list. """ errors = super().check(**kwargs) multitenant_staticfiles_dirs = settings.MULTITENANT_STATICFILES_DIRS if not isinstance(mul...
In addition to parent class' checks, also ensure that MULTITENANT_STATICFILES_DIRS is a tuple or a list.
def draft_pick(self): """Returns when in the draft the player was picked. :returns: TODO """ doc = self.get_main_doc() try: p_tags = doc('div#meta p') draft_p_tag = next(p for p in p_tags.items() if p.text().lower().startswith('draft')) draft_p...
Returns when in the draft the player was picked. :returns: TODO
def log_train_metric(period, auto_reset=False): """Callback to log the training evaluation result every period. Parameters ---------- period : int The number of batch to log the training evaluation metric. auto_reset : bool Reset the metric after each log. Returns ------- ...
Callback to log the training evaluation result every period. Parameters ---------- period : int The number of batch to log the training evaluation metric. auto_reset : bool Reset the metric after each log. Returns ------- callback : function The callback function th...
def get_attributes(file, *, attributes=None, mime_type=None, force_document=False, voice_note=False, video_note=False, supports_streaming=False): """ Get a list of attributes for the given file and the mime type as a tuple ([attribute], mime_type). """ # Note: `...
Get a list of attributes for the given file and the mime type as a tuple ([attribute], mime_type).
def delimited_file( self, hdfs_dir, schema, name=None, database=None, delimiter=',', na_rep=None, escapechar=None, lineterminator=None, external=True, persist=False, ): """ Interpret delimited text files (CSV / T...
Interpret delimited text files (CSV / TSV / etc.) as an Ibis table. See `parquet_file` for more exposition on what happens under the hood. Parameters ---------- hdfs_dir : string HDFS directory name containing delimited text files schema : ibis Schema name : st...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.t...
Return a json dictionary representing this model.
def ImportConfig(filename, config): """Reads an old config file and imports keys and user accounts.""" sections_to_import = ["PrivateKeys"] entries_to_import = [ "Client.executable_signing_public_key", "CA.certificate", "Frontend.certificate" ] options_imported = 0 old_config = grr_config.CONFIG...
Reads an old config file and imports keys and user accounts.
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode: """ Returns a new `IGraphNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. ...
Returns a new `IGraphNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. external_id (Optional[str]): The external ID of the node.
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'a...
Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12
def from_points(cls, iterable_of_points): """ Creates a MultiPoint from an iterable collection of `pyowm.utils.geo.Point` instances :param iterable_of_points: iterable whose items are `pyowm.utils.geo.Point` instances :type iterable_of_points: iterable :return: a *MultiPoint* ins...
Creates a MultiPoint from an iterable collection of `pyowm.utils.geo.Point` instances :param iterable_of_points: iterable whose items are `pyowm.utils.geo.Point` instances :type iterable_of_points: iterable :return: a *MultiPoint* instance
def es_version(self, url): """Get Elasticsearch version. Get the version of Elasticsearch. This is useful because Elasticsearch and Kibiter are paired (same major version for 5, 6). :param url: Elasticseearch url hosting Kibiter indices :returns: major version, as string ...
Get Elasticsearch version. Get the version of Elasticsearch. This is useful because Elasticsearch and Kibiter are paired (same major version for 5, 6). :param url: Elasticseearch url hosting Kibiter indices :returns: major version, as string
def get_iam_policy(self): """Return the current IAM policy as a json-serialized string""" checker = AwsLimitChecker() policy = checker.get_required_iam_policy() return json.dumps(policy, sort_keys=True, indent=2)
Return the current IAM policy as a json-serialized string
def default_project(self, value): """ Setter for **self.__default_project** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, \ "'{0}' attribute: '{1}' type is not 'unicode...
Setter for **self.__default_project** attribute. :param value: Attribute value. :type value: unicode
def ConsumeCommentOrTrailingComment(self): """Consumes a comment, returns a 2-tuple (trailing bool, comment str).""" # Tokenizer initializes _previous_line and _previous_column to 0. As the # tokenizer starts, it looks like there is a previous token on the line. just_started = self._line == 0 and self....
Consumes a comment, returns a 2-tuple (trailing bool, comment str).
def run(self): """Method representing the process’s activity.""" random.seed(self.seed) np.random.seed(self.np_seed) if not isinstance(self, multiprocessing.Process): # Calling mxnet methods in a subprocess will raise an exception if # mxnet is built with GPU supp...
Method representing the process’s activity.
def process_frame(self, f, frame_str): """ :param Frame f: Frame object :param bytes frame_str: Raw frame content """ frame_type = f.cmd.lower() if frame_type in ['disconnect']: return if frame_type == 'send': frame_type = 'message' ...
:param Frame f: Frame object :param bytes frame_str: Raw frame content
def rmd_options_to_metadata(options): """ Parse rmd options and return a metadata dictionary :param options: :return: """ options = re.split(r'\s|,', options, 1) if len(options) == 1: language = options[0] chunk_options = [] else: language, others = options ...
Parse rmd options and return a metadata dictionary :param options: :return:
def add_file(self, name, filename, compress_hint=True): """Saves the actual file in the store. ``compress_hint`` suggests whether the file should be compressed before transfer Works like :meth:`add_stream`, but ``filename`` is the name of an existing file in the fil...
Saves the actual file in the store. ``compress_hint`` suggests whether the file should be compressed before transfer Works like :meth:`add_stream`, but ``filename`` is the name of an existing file in the filesystem.
def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones...
Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str``
def view_cancel_edit(name=None): """Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the p...
Cancel the edition of an existing page. Then render the last modification status .. note:: this is a bottle view if no page name is given, do nothing (it may leave some .tmp. files in the directory). Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bot...
def timezone(self, value=0.0): """Corresponds to IDD Field `timezone` Time relative to GMT. Args: value (float): value for IDD Field `timezone` Unit: hr - not on standard units list??? Default value: 0.0 value >= -12.0 value <=...
Corresponds to IDD Field `timezone` Time relative to GMT. Args: value (float): value for IDD Field `timezone` Unit: hr - not on standard units list??? Default value: 0.0 value >= -12.0 value <= 12.0 if `value` is None i...
def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False): """Use NGLviewer to display a structure in a Jupyter notebook Args: only_chains (str, list): Chain ID or IDs to display opacity (float): Opacity of the structure recolor (bool): If str...
Use NGLviewer to display a structure in a Jupyter notebook Args: only_chains (str, list): Chain ID or IDs to display opacity (float): Opacity of the structure recolor (bool): If structure should be cleaned and recolored to silver gui (bool): If the NGLview GUI sh...
def upload_feature_value_file(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, filename, index_col): '''Uploads feature values for the given :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` at the specified :class:`Site <tmlib.models.site...
Uploads feature values for the given :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` at the specified :class:`Site <tmlib.models.site.Site>`. Parameters ---------- mapobject_type_name: str type of the segmented objects plate_name: str ...
def answer (self, headers, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API headers tell Tropo headers launch your code. Arguments: headers is a String. Argument: **options is a set of optional keyword arguments. See h...
Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API headers tell Tropo headers launch your code. Arguments: headers is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/answer
def semilocal_linear_trend_transition_matrix(autoregressive_coef): """Build the transition matrix for a semi-local linear trend model.""" # We want to write the following 2 x 2 matrix: # [[1., 1., ], # level(t+1) = level(t) + slope(t) # [0., ar_coef], # slope(t+1) = ar_coef * slope(t) # but it's slightl...
Build the transition matrix for a semi-local linear trend model.
def __handle_changed_state(self, state): """ we need to pack a struct with the following five numbers: tv_sec, tv_usec, ev_type, code, value then write it using __write_to_character_device seconds, mircroseconds, ev_type, code, value time we just use now ev_type...
we need to pack a struct with the following five numbers: tv_sec, tv_usec, ev_type, code, value then write it using __write_to_character_device seconds, mircroseconds, ev_type, code, value time we just use now ev_type we look up code we look up value is 0 or 1 f...
def update_title_to_proceeding(self): """Move title info from 245 to 111 proceeding style.""" titles = record_get_field_instances(self.record, tag="245") for title in titles: subs = field_get_subfields(title) new_subs = [] ...
Move title info from 245 to 111 proceeding style.
def popup(self, title, callfn, initialdir=None): """Let user select a directory.""" super(DirectorySelection, self).popup(title, callfn, initialdir)
Let user select a directory.
def after_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint. """ self.record_once(lambda s: s.app.after_request_funcs .setdefault(self.name, [])...
Like :meth:`Flask.after_request` but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint.
def load_directory(self, directory, ext=None): """Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is `...
Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is ``[".rive", ".rs"]``.
def _preprocess(df): """ given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise. """ df = df.stack() df.index.rename(["id", "time"], inplace=True) # .reset_index() df.name = "value" df = df.reset_index() return df
given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise.
def receive_loop_with_callback(self, queue_name, callback): """ Process incoming messages with callback until close is called. :param queue_name: str: name of the queue to poll :param callback: func(ch, method, properties, body) called with data when data arrives :return: ...
Process incoming messages with callback until close is called. :param queue_name: str: name of the queue to poll :param callback: func(ch, method, properties, body) called with data when data arrives :return:
def install_python_package(self, arch, name=None, env=None, is_dir=True): '''Automate the installation of a Python package (or a cython package where the cython components are pre-built).''' if env is None: env = self.get_recipe_env(arch) with current_directory(self.get_buil...
Automate the installation of a Python package (or a cython package where the cython components are pre-built).
def _generate_main_scripts(self): """ Include the scripts used by solutions. """ head = self.parser.find('head').first_result() if head is not None: common_functions_script = self.parser.find( '#' + AccessibleEventImplementation.ID_SCR...
Include the scripts used by solutions.
def translate(self, dx, dy): """ Move the polygons from one place to another Parameters ---------- dx : number distance to move in the x-direction dy : number distance to move in the y-direction Returns ------- out : ``Pol...
Move the polygons from one place to another Parameters ---------- dx : number distance to move in the x-direction dy : number distance to move in the y-direction Returns ------- out : ``PolygonSet`` This object.
def project(self, **kwargs: Dict[str, Any]) -> Union[Hist, Dict[str, Hist]]: """ Perform the requested projection(s). Note: All cuts on the original histograms will be reset when this function is completed. Args: kwargs (dict): Additional named args to be passed to proj...
Perform the requested projection(s). Note: All cuts on the original histograms will be reset when this function is completed. Args: kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...) Returns: The projected hist...
def pretty_exe_doc(program, parser, stack=1, under='-'): """ Takes the name of a script and a parser that will give the help message for it. The module that called this function will then add a header to the docstring of the script, followed immediately by the help message generated by the OptionPar...
Takes the name of a script and a parser that will give the help message for it. The module that called this function will then add a header to the docstring of the script, followed immediately by the help message generated by the OptionParser :param str program: Name of the program that we want to make...
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): ...
Sets up the process environment.