code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _load_user_dn(self): """ Populates self._user_dn with the distinguished name of our user. This will either construct the DN from a template in AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it. If we have to search, we'll cache the DN. """ ...
Populates self._user_dn with the distinguished name of our user. This will either construct the DN from a template in AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it. If we have to search, we'll cache the DN.
def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictiona...
Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictionary Returns: None
def check(self, func=None, name=None): """ A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: ...
A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except Sl...
def generate_daterange(report): """ Creates a date_range timestamp with format YYYY-MM-DD-T-HH:MM:SS based on begin and end dates for easier parsing in Kibana. Move to utils to avoid duplication w/ elastic? """ metadata = report["report_metadata"] begin_date = h...
Creates a date_range timestamp with format YYYY-MM-DD-T-HH:MM:SS based on begin and end dates for easier parsing in Kibana. Move to utils to avoid duplication w/ elastic?
def metastable_sets(self): """ Crisp clustering using PCCA. This is only recommended for visualization purposes. You *cannot* compute any actual quantity of the coarse-grained kinetics without employing the fuzzy memberships! Returns ------- A list of length equal to meta...
Crisp clustering using PCCA. This is only recommended for visualization purposes. You *cannot* compute any actual quantity of the coarse-grained kinetics without employing the fuzzy memberships! Returns ------- A list of length equal to metastable states. Each element is an array with mi...
async def dict(self, full): ''' Open a HiveDict at the given full path. ''' node = await self.open(full) return await HiveDict.anit(self, node)
Open a HiveDict at the given full path.
def retry(self): """Retry to connect to deCONZ.""" self.state = STATE_STARTING self.loop.call_later(RETRY_TIMER, self.start) _LOGGER.debug('Reconnecting to deCONZ in %i.', RETRY_TIMER)
Retry to connect to deCONZ.
def get_histories_over_repetitions(self, exp, tags, aggregate): """ this function gets all histories of all repetitions using get_history() on the given tag(s), and then applies the function given by 'aggregate' to all corresponding values in each history over all iterations. Typical agg...
this function gets all histories of all repetitions using get_history() on the given tag(s), and then applies the function given by 'aggregate' to all corresponding values in each history over all iterations. Typical aggregate functions could be 'mean' or 'max'.
def parse(self): """ Parse metafile and check pre-conditions. """ try: if not os.path.getsize(self.ns.pathname): # Ignore 0-byte dummy files (Firefox creates these while downloading) self.job.LOG.warn("Ignoring 0-byte metafile '%s'" % (self.ns.pathname...
Parse metafile and check pre-conditions.
def from_keras_log(csv_path, output_dir_path, **kwargs): """Plot accuracy and loss from a Keras CSV log. Args: csv_path: The path to the CSV log with the actual data. output_dir_path: The path to the directory where the resultings plots should end up. """ # automatically get...
Plot accuracy and loss from a Keras CSV log. Args: csv_path: The path to the CSV log with the actual data. output_dir_path: The path to the directory where the resultings plots should end up.
def content_written(generator, content): """ create a url and call make posts (which has less information) """ url = "%s/%s" % (generator.settings.get('SITEURL', 'http://localhost:8000'), content.url) make_posts(generator, content.metadata, url)
create a url and call make posts (which has less information)
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None): ''' Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with ne...
Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemo...
def find_or_create_role(self, name, **kwargs): """Returns a role matching the given name or creates it with any additionally provided parameters. """ kwargs["name"] = name return self.find_role(name) or self.create_role(**kwargs)
Returns a role matching the given name or creates it with any additionally provided parameters.
def _populate_alternate_kwargs(kwargs): """ Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands. """ resource_namespace = kwargs['namespace'] resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type'] ...
Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands.
def organizations(self, user, include=None): """ Retrieve the organizations for this user. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param user: User object or id """ ...
Retrieve the organizations for this user. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param user: User object or id
def incoming(self, packet): """ Callback for data received from the copter. """ # This might be done prettier ;-) console_text = packet.data.decode('UTF-8') self.receivedChar.call(console_text)
Callback for data received from the copter.
async def info(self, token): """Queries the policy of a given token. Parameters: token (ObjectID): Token ID Returns: ObjectMeta: where value is token Raises: NotFound: It returns a body like this:: { "CreateIndex"...
Queries the policy of a given token. Parameters: token (ObjectID): Token ID Returns: ObjectMeta: where value is token Raises: NotFound: It returns a body like this:: { "CreateIndex": 3, "ModifyIndex": 3, ...
def check_status(self, **kwargs): """ Check the status of the works in self. Args: show: True to show the status of the flow. kwargs: keyword arguments passed to show_status """ for work in self: work.check_status() if kwargs.pop("sho...
Check the status of the works in self. Args: show: True to show the status of the flow. kwargs: keyword arguments passed to show_status
def tags(self, resource_id=None): """Tag endpoint for this resource with optional tag name. This method will set the resource endpoint for working with Tags. The HTTP GET method will return all tags applied to this resource or if a resource id (tag name) is provided it will return the p...
Tag endpoint for this resource with optional tag name. This method will set the resource endpoint for working with Tags. The HTTP GET method will return all tags applied to this resource or if a resource id (tag name) is provided it will return the provided tag if it has been applied, w...
def local_services(self): """Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure ...
Get a list of id, name pairs for all of the known synced services. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that it cannot change while t...
def check(projects): """Check the specified projects for Python 3 compatibility.""" log = logging.getLogger('ciu') log.info('{0} top-level projects to check'.format(len(projects))) print('Finding and checking dependencies ...') blockers = dependencies.blockers(projects) print('') for line i...
Check the specified projects for Python 3 compatibility.
def data_from_file(self, file, apple_fix=False): """ Read iCal data from file. :param file: file to read :param apple_fix: fix wrong Apple tzdata in iCal :return: decoded (and fixed) iCal data """ with open(file, mode='rb') as f: content = f.read() ...
Read iCal data from file. :param file: file to read :param apple_fix: fix wrong Apple tzdata in iCal :return: decoded (and fixed) iCal data
def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires i...
Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires.
def receive_message(self, msg): """Receive a message sent to this device.""" _LOGGER.debug('Starting X10Device.receive_message') if hasattr(msg, 'isack') and msg.isack: _LOGGER.debug('Got Message ACK') if self._send_msg_lock.locked(): self._send_msg_lock.r...
Receive a message sent to this device.
def good(txt): """Print, emphasized 'good', the given 'txt' message""" print("%s# %s%s%s" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC)) sys.stdout.flush()
Print, emphasized 'good', the given 'txt' message
def fitted(self, fid=0): """Test if enough Levenberg-Marquardt loops have been done. It returns True if no improvement possible. :param fid: the id of the sub-fitter (numerical) """ self._checkid(fid) return not (self._fitids[fid]["fit"] > 0 or self....
Test if enough Levenberg-Marquardt loops have been done. It returns True if no improvement possible. :param fid: the id of the sub-fitter (numerical)
def update_policy(self,defaultHeaders): """ rewrite update policy so that additional pins are added and not overwritten """ if self.inputs is not None: for k,v in defaultHeaders.items(): if k not in self.inputs: self.inputs[k] = v if k == 'pins': self.inputs[k] = self.inputs[k] + defaultHeaders...
rewrite update policy so that additional pins are added and not overwritten
def copyh5(inh5, outh5): """Recursively copy all hdf5 data from one group to another Data from links is copied. Parameters ---------- inh5: str, h5py.File, or h5py.Group The input hdf5 data. This can be either a file name or an hdf5 object. outh5: str, h5py.File, h5py.Group, or...
Recursively copy all hdf5 data from one group to another Data from links is copied. Parameters ---------- inh5: str, h5py.File, or h5py.Group The input hdf5 data. This can be either a file name or an hdf5 object. outh5: str, h5py.File, h5py.Group, or None The output hdf5 da...
def issue_type_by_name(self, name): """ :param name: Name of the issue type :type name: str :rtype: IssueType """ issue_types = self.issue_types() try: issue_type = [it for it in issue_types if it.name == name][0] except IndexError: ...
:param name: Name of the issue type :type name: str :rtype: IssueType
def add_waveform(self, waveform): """ Add a waveform to the plot. :param waveform: the waveform to be added :type waveform: :class:`~aeneas.plotter.PlotWaveform` :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform` """ ...
Add a waveform to the plot. :param waveform: the waveform to be added :type waveform: :class:`~aeneas.plotter.PlotWaveform` :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`
def get_value(self, key): """Extract a value for a given key.""" for title in _TITLES.get(key, ()) + (key,): try: value = [entry['lastMeasurement']['value'] for entry in self.data['sensors'] if entry['title'] == title][0] return value ...
Extract a value for a given key.
def tip_zscores(a): """ Calculates the "target identification from profiles" (TIP) zscores from Cheng et al. 2001, Bioinformatics 27(23):3221-3227. :param a: NumPy array, where each row is the signal for a feature. """ weighted = a * a.mean(axis=0) scores = weighted.sum(axis=1) zscores ...
Calculates the "target identification from profiles" (TIP) zscores from Cheng et al. 2001, Bioinformatics 27(23):3221-3227. :param a: NumPy array, where each row is the signal for a feature.
def mbar_W_nk(u_kn, N_k, f_k): """Calculate the weight matrix. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of sampl...
Calculate the weight matrix. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samples in each state f_k : np.ndarray,...
def current_line_num(self): '''Get current line number as an integer (1-based) Translated from PyFrame_GetLineNumber and PyCode_Addr2Line See Objects/lnotab_notes.txt ''' if self.is_optimized_out(): return None f_trace = self.field('f_trace') if long...
Get current line number as an integer (1-based) Translated from PyFrame_GetLineNumber and PyCode_Addr2Line See Objects/lnotab_notes.txt
def run_object_query(client, base_object_query, start_record, limit_to, verbose=False): """inline method to take advantage of retry""" if verbose: print("[start: %d limit: %d]" % (start_record, limit_to)) start = datetime.datetime.now() result = client.execute_object_query( ...
inline method to take advantage of retry
def _raise_missing_antenna_errors(ant_uvw, max_err): """ Raises an informative error for missing antenna """ # Find antenna uvw coordinates where any UVW component was nan # nan + real == nan problems = np.nonzero(np.add.reduce(np.isnan(ant_uvw), axis=2)) problem_str = [] for c, a in zip(*prob...
Raises an informative error for missing antenna
def time_logger(name): """This logs the time usage of a code block""" start_time = time.time() yield end_time = time.time() total_time = end_time - start_time logging.info("%s; time: %ss", name, total_time)
This logs the time usage of a code block
def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Defaults to ...
Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Defaults to ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Defaults to ``None``. Existing auxiliary states...
def add_to_configs(self, configs): """Add one or more measurement configurations to the stored configurations Parameters ---------- configs: list or numpy.ndarray list or array of configurations Returns ------- configs: Kx4 numpy.ndarray ...
Add one or more measurement configurations to the stored configurations Parameters ---------- configs: list or numpy.ndarray list or array of configurations Returns ------- configs: Kx4 numpy.ndarray array holding all configurations of th...
def weight_statistics(self): """ Extract a statistical summary of edge weights present in the graph. :return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' """ all_weights = [d.get('weight', None) for u, v, d ...
Extract a statistical summary of edge weights present in the graph. :return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev'
def purge_module(self, module_name): """ A module has been removed e.g. a module that had an error. We need to find any containers and remove the module from them. """ containers = self.config["py3_config"][".module_groups"] containers_to_update = set() if module_...
A module has been removed e.g. a module that had an error. We need to find any containers and remove the module from them.
def generate(self, z_mu=None): """ Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. """ if z_mu is None: z_mu = np.random....
Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space.
def choi_matrix(pauli_tm, basis): """ Compute the Choi matrix for a quantum process from its Pauli Transfer Matrix. This agrees with the definition in `Chow et al. <https://doi.org/10.1103/PhysRevLett.109.060501>`_ except for a different overall normalization. Our normalization agrees with that...
Compute the Choi matrix for a quantum process from its Pauli Transfer Matrix. This agrees with the definition in `Chow et al. <https://doi.org/10.1103/PhysRevLett.109.060501>`_ except for a different overall normalization. Our normalization agrees with that of qutip. :param numpy.ndarray pauli_tm:...
def validate(self, data): """ Validated data using defined regex. :param data: data to be validated :return: return validated data. """ e = self._error try: if self._pattern.search(data): return data else: r...
Validated data using defined regex. :param data: data to be validated :return: return validated data.
def get_dataframe_from_data(data): """ Parameters ---------- data : string or pandas dataframe. If string, data should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row per available alternative for e...
Parameters ---------- data : string or pandas dataframe. If string, data should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row per available alternative for each observation. If pandas dataframe, t...
def _onArgument(self, name, annotation): """Memorizes a function argument""" self.objectsStack[-1].arguments.append(Argument(name, annotation))
Memorizes a function argument
def update_state(self, slots: Union[List[Tuple[str, Any]], Dict[str, Any]]) -> 'Tracker': """ Updates dialogue state with new ``slots``, calculates features. Returns: Tracker: .""" pass
Updates dialogue state with new ``slots``, calculates features. Returns: Tracker: .
def set_data(self, data=None, **kwargs): """Set the line data Parameters ---------- data : array-like The data. **kwargs : dict Keywoard arguments to pass to MarkerVisual and LineVisal. """ if data is None: pos = None e...
Set the line data Parameters ---------- data : array-like The data. **kwargs : dict Keywoard arguments to pass to MarkerVisual and LineVisal.
def _read(self, command, future): """Invoked when a command is executed to read and parse its results. It will loop on the IOLoop until the response is complete and then set the value of the response in the execution future. :param command: The command that was being executed :t...
Invoked when a command is executed to read and parse its results. It will loop on the IOLoop until the response is complete and then set the value of the response in the execution future. :param command: The command that was being executed :type command: tredis.client.Command :p...
def _try_assign_utc_time(self, raw_time, time_base): """Try to assign a UTC time to this reading.""" # Check if the raw time is encoded UTC since y2k or just uptime if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)): y2k_offset = self.raw_time ^ (1 << 31) ...
Try to assign a UTC time to this reading.
def set_obs_angle(self, theta_rad): """Set the observer angle relative to the field. **Call signature** *theta_rad* The angle between the ray path and the local magnetic field, in radians. Returns *self* for convenience in chaining. """ sel...
Set the observer angle relative to the field. **Call signature** *theta_rad* The angle between the ray path and the local magnetic field, in radians. Returns *self* for convenience in chaining.
def _get_last_worker_died(self): """Return the last died worker information or None""" for service_id in list(self._running_services.keys()): # We copy the list to clean the orignal one processes = list(self._running_services[service_id].items()) for process, worker_i...
Return the last died worker information or None
def match_date(self, value, strict=False): """if value is a date""" value = stringify(value) try: parse(value) except Exception: self.shout('Value %r is not a valid date', strict, value)
if value is a date
def get_symlink_luid(): """ Get the LUID for the SeCreateSymbolicLinkPrivilege """ symlink_luid = privilege.LUID() res = privilege.LookupPrivilegeValue( None, "SeCreateSymbolicLinkPrivilege", symlink_luid) if not res > 0: raise RuntimeError("Couldn't lookup privilege value") return symlink_luid
Get the LUID for the SeCreateSymbolicLinkPrivilege
def safe_type(self, data, tree): """ Make sure that the incoming data complies with the class type we are expecting it to be. In this case, classes that inherit from this base class expect data to be of type ``list``. """ if not isinstance(data, list): name = ...
Make sure that the incoming data complies with the class type we are expecting it to be. In this case, classes that inherit from this base class expect data to be of type ``list``.
def lstlti(x, n, array): """ Given a number x and an array of non-decreasing int, find the index of the largest array element less than x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlti_c.html :param x: Value to search against :type x: int :param n: Number elements in array...
Given a number x and an array of non-decreasing int, find the index of the largest array element less than x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlti_c.html :param x: Value to search against :type x: int :param n: Number elements in array :type n: int :param array: A...
def runningMedian(seq, M): """ Purpose: Find the median for the points in a sliding window (odd number in size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a running median (in a sliding window) is t...
Purpose: Find the median for the points in a sliding window (odd number in size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a running median (in a sliding window) is to be calculated M -- numbe...
def update_checkplot_objectinfo(cpf, fast_mode=False, findercmap='gray_r', finderconvolve=None, deredden_object=True, custom_bandpasses=None, ...
This updates a checkplot objectinfo dict. Useful in cases where a previous round of GAIA/finderchart/external catalog acquisition failed. This will preserve the following keys in the checkplot if they exist:: comments varinfo objectinfo.objecttags Parameters ---------- ...
def extract_links(bs4): """Extracting links from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of links """ unique_links = list(set([anchor['href'] for anchor in bs4.select('a[href]') if anchor.has_attr('href')])) # remove irrelevant link unique_links = [link for l...
Extracting links from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of links
def filter_none(list_of_points): """ :param list_of_points: :return: list_of_points with None's removed """ remove_elementnone = filter(lambda p: p is not None, list_of_points) remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone) return list(remove_sublistnon...
:param list_of_points: :return: list_of_points with None's removed
def formatmany(self, sql, many_params): """ Formats the SQL query to use ordinal parameters instead of named parameters. *sql* (|string|) is the SQL query. *many_params* (|iterable|) contains each *params* to format. - *params* (|dict|) maps each named parameter (|string|) to value (|object|). If |se...
Formats the SQL query to use ordinal parameters instead of named parameters. *sql* (|string|) is the SQL query. *many_params* (|iterable|) contains each *params* to format. - *params* (|dict|) maps each named parameter (|string|) to value (|object|). If |self.named| is "numeric", then *params* can be ...
def register_hooks(self, field): """Register a field on its target hooks.""" for hook, subhooks in field.register_hooks(): self.hooks[hook].append(field) self.subhooks[hook] |= set(subhooks)
Register a field on its target hooks.
def pick_up_tip(self, location=None, presses=None, increment=None): """ Pick up a tip for the Pipette to run liquid-handling commands with Notes ----- A tip can be manually set by passing a `location`. If no location is passed, the Pipette will pick up the next available...
Pick up a tip for the Pipette to run liquid-handling commands with Notes ----- A tip can be manually set by passing a `location`. If no location is passed, the Pipette will pick up the next available tip in it's `tip_racks` list (see :any:`Pipette`) Parameters -...
def bulk_csv_import_mongo(csvfile, database_name, collection_name, delete_collection_before_import=False): """return a response_dict with a list of search results""" """method can be insert or update""" l = [] response_dict = {} try: mongodb_client_url = getattr(s...
return a response_dict with a list of search results
def resolve_variable(var_name, var_def, provided_variable, blueprint_name): """Resolve a provided variable value against the variable definition. Args: var_name (str): The name of the defined variable on a blueprint. var_def (dict): A dictionary representing the defined variables at...
Resolve a provided variable value against the variable definition. Args: var_name (str): The name of the defined variable on a blueprint. var_def (dict): A dictionary representing the defined variables attributes. provided_variable (:class:`stacker.variables.Variable`): The vari...
def extract(self, feature, remove_subfeatures=False): '''Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extr...
Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence aside from the ...
def run(self, module, options): """ Run the operator. :param module: The target module path. :type module: ``str`` :param options: Any runtime options. :type options: ``dict`` :return: The operator results. :rtype: ``dict`` """ logger....
Run the operator. :param module: The target module path. :type module: ``str`` :param options: Any runtime options. :type options: ``dict`` :return: The operator results. :rtype: ``dict``
def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): """ Subclassed from omdict._bin_update_items() to make update() and updateall() process lists of values as multiple values. <replacements and <leftovers> are modified directly, al...
Subclassed from omdict._bin_update_items() to make update() and updateall() process lists of values as multiple values. <replacements and <leftovers> are modified directly, ala pass by reference.
def set_row(self, index, values): """ Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing """ if self._sort: exists,...
Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing
def _rename(self): """ Called during a PUT request where the action specifies a rename operation. Returns resource URI of the renamed file. """ newname = self.action['newname'] try: newpath = self.fs.rename(self.fp,newname) except OSError: ...
Called during a PUT request where the action specifies a rename operation. Returns resource URI of the renamed file.
def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop. """ if self.attacks_data_initialized: return # init data from datastore self.submissions.init_fro...
Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop.
def sorted_for_ner(crf_classes): """ Return labels sorted in a default order suitable for NER tasks: >>> sorted_for_ner(['B-ORG', 'B-PER', 'O', 'I-PER']) ['O', 'B-ORG', 'B-PER', 'I-PER'] """ def key(cls): if len(cls) > 2 and cls[1] == '-': # group names like B-ORG and I-ORG ...
Return labels sorted in a default order suitable for NER tasks: >>> sorted_for_ner(['B-ORG', 'B-PER', 'O', 'I-PER']) ['O', 'B-ORG', 'B-PER', 'I-PER']
def save(self): """Save the changes to the instance and any related objects.""" # first call save with commit=False for all Forms for form in self._forms: if isinstance(form, BaseForm): form.save(commit=False) # call save on the instance self.instanc...
Save the changes to the instance and any related objects.
def get_credentials(username=None, password=None, netrc=None, use_keyring=False): """ Return valid username, password tuple. Raises CredentialsError if username or password is missing. """ if netrc: path = None if netrc is True else netrc return authenticate_through_netrc(path) ...
Return valid username, password tuple. Raises CredentialsError if username or password is missing.
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string URI that is used to instantiate the class, such as '201802040nwe'. """ if self._away_points is None and self._home_points is Non...
Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string URI that is used to instantiate the class, such as '201802040nwe'.
def get_layout(self, page): """ Get PDFMiner Layout object for given page object or page number. """ if type(page) == int: page = self.get_page(page) self.interpreter.process_page(page) layout = self.device.get_result() layout = self._add_annots(layout, page.ann...
Get PDFMiner Layout object for given page object or page number.
def set(self, key, value, expire=0, noreply=None): """ The memcached "set" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cach...
The memcached "set" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional boo...
def get(cls, uni_char): """Return the general category code (as Unicode string) for the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode return unicod(unicodedata.category(uni_char))
Return the general category code (as Unicode string) for the given Unicode character
def request_get_variable_json(self, py_db, request, thread_id): ''' :param VariablesRequest request: ''' py_db.post_method_as_internal_command( thread_id, internal_get_variable_json, request)
:param VariablesRequest request:
def list_functions(*args, **kwargs): # pylint: disable=unused-argument ''' List the functions for all modules. Optionally, specify a module or modules from which to list. CLI Example: .. code-block:: bash salt '*' sys.list_functions salt '*' sys.list_functions sys salt '*...
List the functions for all modules. Optionally, specify a module or modules from which to list. CLI Example: .. code-block:: bash salt '*' sys.list_functions salt '*' sys.list_functions sys salt '*' sys.list_functions sys user Function names can be specified as globs. .....
def get_access_token(self, code=None, **params): """ Return the memoized access token or go out and fetch one. """ if self._access_token is None: if code is None: raise ValueError(_('Invalid code.')) self.access_token_dict = self._get_...
Return the memoized access token or go out and fetch one.
def get_recurrence(self, config): ''' Calculates the recurrence model for the given settings as an instance of the openquake.hmtk.models.IncrementalMFD :param dict config: Configuration settings of the magnitude frequency distribution. ''' model = MFD_MAP[con...
Calculates the recurrence model for the given settings as an instance of the openquake.hmtk.models.IncrementalMFD :param dict config: Configuration settings of the magnitude frequency distribution.
def _GetContainingRange(self, partition_key): """Gets the containing range based on the partition key. """ for keyrange in self.partition_map.keys(): if keyrange.Contains(partition_key): return keyrange return None
Gets the containing range based on the partition key.
def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True): """This function convert an UTM coordinate into Latitude and Longitude Parameters ---------- easting: int Easting value of UTM coordinate northing: int Northing valu...
This function convert an UTM coordinate into Latitude and Longitude Parameters ---------- easting: int Easting value of UTM coordinate northing: int Northing value of UTM coordinate zone number: int Zone Number is represented with global map...
def normalize_pdf(mu, pofmu): """ Takes a function pofmu defined at rate sample values mu and normalizes it to be a suitable pdf. Both mu and pofmu must be arrays or lists of the same length. """ if min(pofmu) < 0: raise ValueError("Probabilities cannot be negative, don't ask me to " ...
Takes a function pofmu defined at rate sample values mu and normalizes it to be a suitable pdf. Both mu and pofmu must be arrays or lists of the same length.
def create_ui(self): ''' .. versionchanged:: 0.20 Debounce window expose and resize handlers to improve responsiveness. .. versionchanged:: X.X.X Call debounced `_on_expose_event` handler on _leading_ edge to make UI update more responsive when, e...
.. versionchanged:: 0.20 Debounce window expose and resize handlers to improve responsiveness. .. versionchanged:: X.X.X Call debounced `_on_expose_event` handler on _leading_ edge to make UI update more responsive when, e.g., changing window focus. ...
def split_namespace(clarkName): """Return (namespace, localname) tuple for a property name in Clark Notation. Namespace defaults to ''. Example: '{DAV:}foo' -> ('DAV:', 'foo') 'bar' -> ('', 'bar') """ if clarkName.startswith("{") and "}" in clarkName: ns, localname = clarkName.spl...
Return (namespace, localname) tuple for a property name in Clark Notation. Namespace defaults to ''. Example: '{DAV:}foo' -> ('DAV:', 'foo') 'bar' -> ('', 'bar')
def merge(self, other): """ Merges the two values """ other = self.coerce(other) if list_diff(self.domain, other.domain) != []: raise Exception("Incomparable orderings. Different domains") if self.is_equal(other): # pick among dependencies ...
Merges the two values
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: ...
sets the final key to be used currently
def unpin_chat_message(self, *args, **kwargs): """See :func:`unpin_chat_message`""" return unpin_chat_message(*args, **self._merge_overrides(**kwargs)).run()
See :func:`unpin_chat_message`
def parse_bitcode(bitcode, context=None): """ Create Module from a LLVM *bitcode* (a bytes object). """ if context is None: context = get_global_context() buf = c_char_p(bitcode) bufsize = len(bitcode) with ffi.OutputString() as errmsg: mod = ModuleRef(ffi.lib.LLVMPY_ParseBit...
Create Module from a LLVM *bitcode* (a bytes object).
def unsubscribe(self): """Unsubscribes this subscriber from the associated list.""" body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
Unsubscribes this subscriber from the associated list.
def add(self, tipo_opcao, nome_opcao): """Inserts a new Option Pool and returns its identifier. :param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-] :param nome_opcao_txt: Name Option. String with a maximum of 50 characters and respect [a-zA-Z\_-] :re...
Inserts a new Option Pool and returns its identifier. :param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-] :param nome_opcao_txt: Name Option. String with a maximum of 50 characters and respect [a-zA-Z\_-] :return: Following dictionary: :: ...
def write_short(self, number): """ Writes a short integer to the underlying output file as a 2-byte value. """ buf = pack(self.byte_order + "h", number) self.write(buf)
Writes a short integer to the underlying output file as a 2-byte value.
def find_ctrlpts_surface(t_u, t_v, surf, **kwargs): """ Finds the control points involved in the evaluation of the surface point defined by the input parameter pair. This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller. :param t_u: parameter on t...
Finds the control points involved in the evaluation of the surface point defined by the input parameter pair. This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller. :param t_u: parameter on the u-direction :type t_u: float :param t_v: paramete...
def format_npm_command_for_logging(command): """Convert npm command list to string for display to user.""" if platform.system().lower() == 'windows': if command[0] == 'npx.cmd' and command[1] == '-c': return "npx.cmd -c \"%s\"" % " ".join(command[2:]) return " ".join(command) # S...
Convert npm command list to string for display to user.
def update_unit(self, unit_id, unit_dict): """ Updates an unit :param unit_id: the unit id :param unit_dict: dict :return: dict """ return self._create_put_request(resource=UNITS, billomat_id=unit_id, send_data=unit_dict)
Updates an unit :param unit_id: the unit id :param unit_dict: dict :return: dict
def scopusRecordParser(record, header = None): """The parser [ScopusRecords](../classes/ScopusRecord.html#metaknowledge.scopus.ScopusRecord) use. This takes a line from [scopusParser()](#metaknowledge.scopus.scopusHandlers.scopusParser) and parses it as a part of the creation of a `ScopusRecord`. **Note** this...
The parser [ScopusRecords](../classes/ScopusRecord.html#metaknowledge.scopus.ScopusRecord) use. This takes a line from [scopusParser()](#metaknowledge.scopus.scopusHandlers.scopusParser) and parses it as a part of the creation of a `ScopusRecord`. **Note** this is for csv files downloaded from scopus _not_ the tex...
def run(self, host='localhost', port=1234): """ Launch the server. Will run forever accepting connections until interrupted. Parameters: * host: The host to listen on * port: The port to listen on """ # Setup loop loop = asyncio.get_event_loop() ...
Launch the server. Will run forever accepting connections until interrupted. Parameters: * host: The host to listen on * port: The port to listen on
def has_delete_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overriden by the user in subclasses. In such case it should ...
Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overriden by the user in subclasses. In such case it should return True if the given request has permission to delete the `o...