code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def load(source, **kwargs): """Deserialize and load a model. Example: end_model = EndModel.load("my_end_model.pkl") end_model.score(...) """ with open(source, "rb") as f: return torch.load(f, **kwargs)
Deserialize and load a model. Example: end_model = EndModel.load("my_end_model.pkl") end_model.score(...)
def set_parent(self, key_name, new_parent): """Sets the parent of the key.""" self.unbake() kf = self.dct[key_name] kf['parent'] = new_parent self.bake()
Sets the parent of the key.
def solve(self, hash160_lookup, tx_in_idx, hash_type=None, **kwargs): """ Sign a standard transaction. hash160_lookup: An object with a get method that accepts a hash160 and returns the corresponding (secret exponent, public_pair, is_compressed) tuple or None ...
Sign a standard transaction. hash160_lookup: An object with a get method that accepts a hash160 and returns the corresponding (secret exponent, public_pair, is_compressed) tuple or None if it's unknown (in which case the script will obviously not be signed). A sta...
def per_installer_data(self): """ Return download data by installer name and version. :return: dict of cache data; keys are datetime objects, values are dict of installer name/version (str) to count (int). :rtype: dict """ ret = {} for cache_date in sel...
Return download data by installer name and version. :return: dict of cache data; keys are datetime objects, values are dict of installer name/version (str) to count (int). :rtype: dict
def collaborators(self, *roles): """ Returns a list of :py:class:`.User` who are collaborators on this project. Zero or more role arguments can be passed as strings to narrow down the results. If any roles are given, users who possess at least one of the given roles are ...
Returns a list of :py:class:`.User` who are collaborators on this project. Zero or more role arguments can be passed as strings to narrow down the results. If any roles are given, users who possess at least one of the given roles are returned. Examples:: all_collab...
def dump(obj, fp, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=Fals...
Serialize ``obj`` as an Ion-formatted stream to ``fp`` (a file-like object), using the following conversion table:: +-------------------+-------------------+ | Python | Ion | |-------------------+-------------------| | None | null.null | ...
def _load_entries(self): """Check for availability of lemmatizer for French.""" rel_path = os.path.join('~','cltk_data', 'french', 'text','french_data_cltk' ,'entries.py') path = os.path.expanduser(r...
Check for availability of lemmatizer for French.
def _registerUnitInImpl(self, uName, u): """ :attention: unit has to be parametrized before it is registered (some components can change interface by parametrization) """ self._registerUnit(uName, u) u._loadDeclarations() self._lazyLoaded.extend(u._toRtl(self....
:attention: unit has to be parametrized before it is registered (some components can change interface by parametrization)
def predict_dataset(self, x, **kwargs): """Generic dataset prediction function. Runs the score independently on all pairs. Args: x (pandas.DataFrame): a CEPC format Dataframe. kwargs (dict): additional arguments for the algorithms Returns: pandas.Da...
Generic dataset prediction function. Runs the score independently on all pairs. Args: x (pandas.DataFrame): a CEPC format Dataframe. kwargs (dict): additional arguments for the algorithms Returns: pandas.DataFrame: a Dataframe with the predictions.
def notice(self, client, message): """send a notice to client""" if client and message: messages = utils.split_message(message, self.config.max_length) for msg in messages: client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)
send a notice to client
def get_chunks(self,chunk_type): """ Returns the chunks for a certain type @type chunk_type: string @param chunk_type: type of the chunk @rtype: list @return: the chunks for that type """ for nonter,this_type in self.label_for_nonter.items(): i...
Returns the chunks for a certain type @type chunk_type: string @param chunk_type: type of the chunk @rtype: list @return: the chunks for that type
def _compose_custom_getters(getter_a, getter_b): """Compose two custom getters. Example use: tf.get_variable_scope().set_custom_getter( compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter)) This composes getters in the same way as creating a new variable scope with the new_getter, b...
Compose two custom getters. Example use: tf.get_variable_scope().set_custom_getter( compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter)) This composes getters in the same way as creating a new variable scope with the new_getter, but it does not actually create a new variable scope. ...
def createdb(args): """ cldf createdb <DATASET> <SQLITE_DB_PATH> Load CLDF dataset <DATASET> into a SQLite DB, where <DATASET> may be the path to - a CLDF metadata file - a CLDF core data file """ if len(args.args) < 2: raise ParserError('not enough arguments') ds = _get_dataset...
cldf createdb <DATASET> <SQLITE_DB_PATH> Load CLDF dataset <DATASET> into a SQLite DB, where <DATASET> may be the path to - a CLDF metadata file - a CLDF core data file
def _remove_debug_only(self): """Iterate through each handler removing the invalid dictConfig key of debug_only. """ LOGGER.debug('Removing debug only from handlers') for handler in self.config[self.HANDLERS]: if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]...
Iterate through each handler removing the invalid dictConfig key of debug_only.
def get_body(self): """Get the body of the email message""" if self.is_multipart(): # get the plain text version only text_parts = [part for part in typed_subpart_iterator(self, 'text', ...
Get the body of the email message
def _find_pkg_info(self): """ Find information about the installed package from pkg_resources. :returns: information from pkg_resources about ``self.package_name`` :rtype: dict """ dist = pkg_resources.require(self.package_name)[0] self._pkg_resources_locations =...
Find information about the installed package from pkg_resources. :returns: information from pkg_resources about ``self.package_name`` :rtype: dict
def from_http_json(operation, api_request, result_type, **kwargs): """Create an operation future using a HTTP/JSON client. This interacts with the long-running operations `service`_ (specific to a given API) via `HTTP/JSON`_. .. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\ ...
Create an operation future using a HTTP/JSON client. This interacts with the long-running operations `service`_ (specific to a given API) via `HTTP/JSON`_. .. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\ v1beta1/operations#Operation Args: operation (dict): Operatio...
def create_big_thumbnail(self, token, bitstream_id, item_id, width=575): """ Create a big thumbnail for the given bitstream with the given width. It is used as the main image of the given item and shown in the item view page. :param token: A valid token for the user in question....
Create a big thumbnail for the given bitstream with the given width. It is used as the main image of the given item and shown in the item view page. :param token: A valid token for the user in question. :type token: string :param bitstream_id: The bitstream from which to create ...
def _set_stats_data(self, test_id, metrics): """ Get summary stats data from each metric and set it in the _Analysis object specified by test_id to make it available for retrieval :return: currently always returns CONSTANTS.OK. Maybe enhanced in future to return additional status """ for metric ...
Get summary stats data from each metric and set it in the _Analysis object specified by test_id to make it available for retrieval :return: currently always returns CONSTANTS.OK. Maybe enhanced in future to return additional status
def _other_to_lon(func): """Wrapper for casting Longitude operator arguments to Longitude""" def func_other_to_lon(obj, other): return func(obj, _maybe_cast_to_lon(other)) return func_other_to_lon
Wrapper for casting Longitude operator arguments to Longitude
def _uri2path(self, uri): ''' Convert uri to absolute filepath Parameters ---------- uri : string URI of python module to return path for Returns ------- path : None or string Returns None if there is no valid path for this URI ...
Convert uri to absolute filepath Parameters ---------- uri : string URI of python module to return path for Returns ------- path : None or string Returns None if there is no valid path for this URI Otherwise returns absolute file syst...
def match_trailer(self, tokens, item): """Matches typedefs and as patterns.""" internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens) match, trailers = tokens[0], tokens[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i],...
Matches typedefs and as patterns.
def construct(self): """Lazy init. Returns ------- self : Dataset Constructed Dataset object. """ if self.handle is None: if self.reference is not None: if self.used_indices is None: # create valid ...
Lazy init. Returns ------- self : Dataset Constructed Dataset object.
def coordination_geometry_symmetry_measures_separation_plane(self, coordination_geometry, separation_plane_algo, testing=Fals...
Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ... :param coordination_geometry: The coordination geometry to be investigated :return: The sy...
def sample(self, input_sample, num_samples, num_params, k_choices, num_groups=None): """Computes the optimum k_choices of trajectories from the input_sample. Arguments --------- input_sample : numpy.ndarray num_samples : int The number of sampl...
Computes the optimum k_choices of trajectories from the input_sample. Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int ...
def watch_thread(self): '''watch for settings changes from child''' from mp_settings import MPSetting while True: setting = self.child_pipe.recv() if not isinstance(setting, MPSetting): break try: self.settings.set(setting.name,...
watch for settings changes from child
def thread_stopped(self): """ If original task is :class:`.WStoppableTask` object, then stop it :return: None """ task = self.task() if isinstance(task, WStoppableTask) is True: task.stop()
If original task is :class:`.WStoppableTask` object, then stop it :return: None
def __cancel(self, subscription_id, **kwargs): """Call documentation: `/subscription/cancel <https://www.wepay.com/developer/reference/subscription#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``...
Call documentation: `/subscription/cancel <https://www.wepay.com/developer/reference/subscription#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` ...
def gdal_nodata_mask(pcl, pcsl, tirs_arr): """ Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style uint8 mask """ tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0) return ((~(pcl | pcsl | tirs_mask)) * 2...
Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style uint8 mask
def _load_region(self, acct_id, region_name, path): """load config from a single per-region subdirectory of an account""" lim_path = os.path.join(path, 'limit_overrides.json') thresh_path = os.path.join(path, 'threshold_overrides.json') res = {'limit_overrides': {}, 'threshold_overrides'...
load config from a single per-region subdirectory of an account
def run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, blotter): """Run a ...
Run a backtest for the given algorithm.
def check_or_confirm_overwrite(file_name): """ Returns True if OK to proceed, False otherwise """ try: with open(file_name) as fd: header = next(fd) if header.find(':sedge:') == -1: okay = ask_overwrite(file_name) if okay: ...
Returns True if OK to proceed, False otherwise
def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels): """ Sample some boxes from all proposals for training. #fg is guaranteed to be > 0, because ground truth boxes will be added as proposals. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, ...
Sample some boxes from all proposals for training. #fg is guaranteed to be > 0, because ground truth boxes will be added as proposals. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, int32 Returns: A BoxProposals instance. sampled_b...
def hincrby(self, key, field, increment): """ Increments the number stored at `field` in the hash stored at `key`. If `key` does not exist, a new key holding a hash is created. If `field` does not exist the value is set to ``0`` before the operation is performed. The range of ...
Increments the number stored at `field` in the hash stored at `key`. If `key` does not exist, a new key holding a hash is created. If `field` does not exist the value is set to ``0`` before the operation is performed. The range of values supported is limited to 64-bit signed integers....
def expand(self, id): """ Expand a concept or collection to all it's narrower concepts. If the id passed belongs to a :class:`skosprovider.skos.Concept`, the id of the concept itself should be include in the return value. :param str id: A concept or collection id. :retur...
Expand a concept or collection to all it's narrower concepts. If the id passed belongs to a :class:`skosprovider.skos.Concept`, the id of the concept itself should be include in the return value. :param str id: A concept or collection id. :returns: A :class:`lst` of id's. Return...
def get_system_python_library(): """ FIXME; hacky way of finding python library. Not cross platform yet. """ import os import utool as ut from os.path import basename, realpath pyname = basename(realpath(sys.executable)) ld_library_path = os.environ['LD_LIBRARY_PATH'] libdirs = [x fo...
FIXME; hacky way of finding python library. Not cross platform yet.
def visualize_saliency_with_losses(input_tensor, losses, seed_input, wrt_tensor=None, grad_modifier='absolute', keepdims=False): """Generates an attention heatmap over the `seed_input` by using positive gradients of `input_tensor` with respect to weighted `losses`. This function is intended for advanced us...
Generates an attention heatmap over the `seed_input` by using positive gradients of `input_tensor` with respect to weighted `losses`. This function is intended for advanced use cases where a custom loss is desired. For common use cases, refer to `visualize_class_saliency` or `visualize_regression_saliency`...
def close_thread(self): """ Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None """ if self.__thread is not None and self.__thread.is_alive() is True: raise WThreadJoiningTimeoutError('Thread is still alive. Thread name: %s' % self.__thread.name) ...
Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None
def mapToPixel(mX, mY, geoTransform): """Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) """ mX = np.asarray(mX) mY = np.asarray(mY) if geoTran...
Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
def encode(binary): """Encode (gzip) binary data.""" encoded = io.BytesIO() gzip_file = dict(mode='wb', fileobj=encoded, compresslevel=LEVEL) with gzip.GzipFile(**gzip_file) as file_: file_.write(binary) encoded.seek(0) return encoded.read()
Encode (gzip) binary data.
def sonos_uri_from_id(self, item_id): """Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9J...
Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9JE`` Returns: str: A URI of t...
def _expose_all_eligible_locations(match_query, location_types, eligible_locations): """Return a MATCH query where all eligible locations are valid as query start locations.""" eligible_location_types = dict() new_match_traversals = [] for current_traversal in match_query.match_traversals: new_...
Return a MATCH query where all eligible locations are valid as query start locations.
def set_centralized_assembled_values(self, a): """Set assembled matrix values on processor 0.""" if self.myid != 0: return assert a.size == self.id.nz self._refs.update(a=a) self.id.a = self.cast_array(a)
Set assembled matrix values on processor 0.
def create(session, course_name): """ Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of On...
Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of OnDemandCourseMaterialItems @rtype: OnDemandCour...
def rotate_slaves(self): "Round-robin slave balancer" slaves = self.sentinel_manager.discover_slaves(self.service_name) if slaves: if self.slave_rr_counter is None: self.slave_rr_counter = random.randint(0, len(slaves) - 1) for _ in xrange(len(slaves)): ...
Round-robin slave balancer
def environment_exists(self, name=None, prefix=None, abspath=True, log=True): """Check if an environment exists by 'name' or by 'prefix'. If query is by 'name' only the default conda environments directory is searched. """ if log: logger.de...
Check if an environment exists by 'name' or by 'prefix'. If query is by 'name' only the default conda environments directory is searched.
def _is_extra_source(asset, field, map): """ Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup. """ # If we have an extra source with a column called "price", only look # at it if it's on something like p...
Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup.
def _clean_longitudinal_data(cls, data, null=None): """ Private function. Make sure we have what we need to make a striplog. """ # Rename 'depth' or 'MD' if ('top' not in data.keys()): data['top'] = data.pop('depth', data.pop('MD', None)) # Sort everything ...
Private function. Make sure we have what we need to make a striplog.
def lower_ir(ir_blocks, query_metadata_table, type_equivalence_hints=None): """Lower the IR into an IR form that can be represented in Gremlin queries. Args: ir_blocks: list of IR blocks to lower into Gremlin-compatible form query_metadata_table: QueryMetadataTable object containing all metadat...
Lower the IR into an IR form that can be represented in Gremlin queries. Args: ir_blocks: list of IR blocks to lower into Gremlin-compatible form query_metadata_table: QueryMetadataTable object containing all metadata collected during query processing, including locati...
def run(self): """ Queues all services to be polled for metrics. Should be run via beat. """ services = Service.objects.all() for service in services: service_metric_sync.apply_async( kwargs={"service_id": str(service.id)}) key = "service...
Queues all services to be polled for metrics. Should be run via beat.
def hexagonal(a: float, c: float): """ Convenience constructor for a hexagonal lattice. Args: a (float): *a* lattice parameter of the hexagonal cell. c (float): *c* lattice parameter of the hexagonal cell. Returns: Hexagonal lattice of dimensions a x...
Convenience constructor for a hexagonal lattice. Args: a (float): *a* lattice parameter of the hexagonal cell. c (float): *c* lattice parameter of the hexagonal cell. Returns: Hexagonal lattice of dimensions a x a x c.
def load(self, source: Union[str, BinaryIO, "Model"]=None, cache_dir: str=None, backend: StorageBackend=None, lazy=False) -> "Model": """ Build a new Model instance. :param source: UUID, file system path, file object or an URL; None means auto. :param cache_dir: The directo...
Build a new Model instance. :param source: UUID, file system path, file object or an URL; None means auto. :param cache_dir: The directory where to store the downloaded model. :param backend: Remote storage backend to use if ``source`` is a UUID or a URL. :param lazy: Do not really load...
def decrypt_batch_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt...
Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt items :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig` :param callable read_method: Method that reads from the table ...
def getTempFilename(dir=None, shared=False, suffix=""): '''return a temporary filename. The file is created and the caller needs to delete the temporary file once it is not used any more. Arguments --------- dir : string Directory of the temporary file and if not given is set to the ...
return a temporary filename. The file is created and the caller needs to delete the temporary file once it is not used any more. Arguments --------- dir : string Directory of the temporary file and if not given is set to the default temporary location in the global configuration di...
def delete_one(self, *args, **kwargs): """ Run the pymongo delete_one command against the default database and collection and return the deleted IDs. """ result = self.collection.delete_one(*args, **kwargs) return result.raw_result
Run the pymongo delete_one command against the default database and collection and return the deleted IDs.
def pip_command(self, command, *args): """ Runs a pip command """ try: from pip._internal import main as pip_main except ImportError: from pip import main as pip_main args = [command] + list(args) if self.verbosity == 0: args.i...
Runs a pip command
def get_external_commands(self): """Send a HTTP request to the satellite (GET /_external_commands) to get the external commands from the satellite. :return: External Command list on success, [] on failure :rtype: list """ res = self.con.get('_external_commands', wait=Fal...
Send a HTTP request to the satellite (GET /_external_commands) to get the external commands from the satellite. :return: External Command list on success, [] on failure :rtype: list
def get_host_post_state(self): """Get the current state of system POST. Retrieves current state of system POST. :returns: POST state of the server. The valida states are:- null, Unknown, Reset, PowerOff, InPost, InPostDiscoveryComplete and FinishedPost. ...
Get the current state of system POST. Retrieves current state of system POST. :returns: POST state of the server. The valida states are:- null, Unknown, Reset, PowerOff, InPost, InPostDiscoveryComplete and FinishedPost. :raises: IloError, on an error from iL...
def all_contents(self): """Iterates over all subviews from collections at this view from *all* sources. If the object for this view in any source is not iterable, then a ConfigTypeError is raised. This method is intended to be used when the view indicates a list; this method will...
Iterates over all subviews from collections at this view from *all* sources. If the object for this view in any source is not iterable, then a ConfigTypeError is raised. This method is intended to be used when the view indicates a list; this method will concatenate the contents of the li...
def count(self, q): """ Shorthand for counting the results of a specific query. ## Arguments * `q` (str): The query to count. This will be executed as: `"SELECT COUNT(*) %s" % q`. ## Returns * `count` (int): The resulting count. """ q = "SEL...
Shorthand for counting the results of a specific query. ## Arguments * `q` (str): The query to count. This will be executed as: `"SELECT COUNT(*) %s" % q`. ## Returns * `count` (int): The resulting count.
def install_repo(self, repo, location=''): """todo: Docstring for install_repo :param repo: arg description :type repo: type description :return: :rtype: """ dst = location or settings.upkg_destdir # make sure the destination dir exists. if not o...
todo: Docstring for install_repo :param repo: arg description :type repo: type description :return: :rtype:
def handle_request(self, req, validate=True): ''' handle a jsonrpc request req - request as jsonrpc-dict validate - validate the request? (default: True) returns jsonrpc-dict with result or error ''' #result that will be filled and returned res = {'json...
handle a jsonrpc request req - request as jsonrpc-dict validate - validate the request? (default: True) returns jsonrpc-dict with result or error
def restart(self): """ restart all child processes """ BackgroundProcess.objects.filter(pk=self.process_id).update( last_update=now(), message='restarting..') timeout = time() + 60 # wait max 60 seconds self.kill_processes(signal.SIGTERM) ...
restart all child processes
def _write_row_into_ods(ods, sheet_no, row_no, row): """ Write row with translations to ods file into specified sheet and row_no. """ ods.content.getSheet(sheet_no) for j, col in enumerate(row): cell = ods.content.getCell(j, row_no+1) cell.stringValue(_escape_apostrophe(col)) ...
Write row with translations to ods file into specified sheet and row_no.
def _notnull(expr): """ Return a sequence or scalar according to the input indicating if the values are not null. :param expr: sequence or scalar :return: sequence or scalar """ if isinstance(expr, SequenceExpr): return NotNull(_input=expr, _data_type=types.boolean) elif isinstance...
Return a sequence or scalar according to the input indicating if the values are not null. :param expr: sequence or scalar :return: sequence or scalar
def coordinate_filter(self, query, mongo_query): """ Adds genomic coordinated-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: ...
Adds genomic coordinated-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: mongo_query(dict): returned object contains coord...
def minify_css(css): """Little css minifier""" # Inspired by slimmer by Peter Bengtsson remove_next_comment = 1 for css_comment in css_comments.findall(css): if css_comment[-3:] == '\*/': remove_next_comment = 0 continue if remove_next_comment: css = c...
Little css minifier
def flush_events(self): """Flush events from the cloud node.""" response = self._send_data('DELETE', 'admin', 'flush-events', {}) if response['success']: msg = "Events flushed" else: msg = "Flushing of events failed" output = {'message': msg} ret...
Flush events from the cloud node.
def scalc_vgp_df(vgp_df, anti=0, rev=0, cutoff=180., kappa=0, n=0, spin=0, v=0, boot=0, mm97=0, nb=1000): """ Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997) Parameters ____...
Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997) Parameters _________ df : Pandas Dataframe with columns REQUIRED: vgp_lat : VGP latitude ONLY REQUIRED f...
def on_remove_cols(self, event): """ enter 'remove columns' mode """ # open the help message self.toggle_help(event=None, mode='open') # first unselect any selected cols/cells self.remove_cols_mode = True self.grid.ClearSelection() self.remove_cols...
enter 'remove columns' mode
def add_face_from_stream( self, large_face_list_id, image, user_data=None, target_face=None, custom_headers=None, raw=False, callback=None, **operation_config): """Add a face to a large face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFace...
Add a face to a large face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. :param large_face_list_id: Id referencing a particular large face list. :type lar...
def generate_user(mode=None, pk=None): """Return a false user for standalone mode""" user = None if mode == 'log' or pk == "-1": user = DUser(pk=-1, username='Logged', first_name='Logged', last_name='Hector', email='logeedin@plugit-standalone.ebuio') user.gravatar = 'https://www.gravatar.c...
Return a false user for standalone mode
def plot_monthly_returns_heatmap(returns, ax=None, **kwargs): """ Plots a heatmap of returns by month. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, optional ...
Plots a heatmap of returns by month. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, optional Axes upon which to plot. **kwargs, optional Passed to ...
def get_gyration_tensor(elements, coordinates): """ Return the gyration tensor of a molecule. The gyration tensor should be invariant to the molecule's position. The known formulas for the gyration tensor have the correction for the centre of mass of the molecule, therefore, the coordinates are fir...
Return the gyration tensor of a molecule. The gyration tensor should be invariant to the molecule's position. The known formulas for the gyration tensor have the correction for the centre of mass of the molecule, therefore, the coordinates are first corrected for the centre of mass and essentially shif...
def _getExtensionKVArgs(self, aliases=None): """Get the extension arguments for the key/value pairs contained in this message. @param aliases: An alias mapping. Set to None if you don't care about the aliases for this request. """ if aliases is None: alia...
Get the extension arguments for the key/value pairs contained in this message. @param aliases: An alias mapping. Set to None if you don't care about the aliases for this request.
def _cor_compile(rule, var, val, result_class, key, compilation_list): """ Actual compilation worker method. """ compilation = compilation_list.get(key, None) if compilation: if isinstance(val, ListRule): result = [] for itemv in val.va...
Actual compilation worker method.
def flush(self): """Flush the underlying hdf5 file""" if self.parent != (): self.parent.flush() if self.hdf5: # is open self.hdf5.flush()
Flush the underlying hdf5 file
def splini(xa, ya, y2a, n, x, y): ''' /* INTEGRATE CUBIC SPLINE FUNCTION FROM XA(1) TO X * XA,YA: ARRAYS OF TABULATED FUNCTION IN ASCENDING ORDER BY X * Y2A: ARRAY OF SECOND DERIVATIVES * N: SIZE OF ARRAYS XA,YA,Y2A * X: ABSCISSA ENDPOINT FOR INTEGRATION * Y: OUTPUT VALUE */...
/* INTEGRATE CUBIC SPLINE FUNCTION FROM XA(1) TO X * XA,YA: ARRAYS OF TABULATED FUNCTION IN ASCENDING ORDER BY X * Y2A: ARRAY OF SECOND DERIVATIVES * N: SIZE OF ARRAYS XA,YA,Y2A * X: ABSCISSA ENDPOINT FOR INTEGRATION * Y: OUTPUT VALUE */
def query(self, SQL, params='', fmt='array', fetch='all', unpack=False, export='', \ verbose=False, use_converters=True): """ Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. ...
Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. For example, to extract the ra and dec of all entries in SOURCES in astropy.Table format one can write: data = db.query('SELECT ra, dec FROM sou...
def unindex_layer(self, layer_id, use_cache=False): """ Remove the index for a layer in the search backend. If cache is set, append it to the list of removed layers, if it isn't send the transaction right away. """ from hypermap.aggregator.models import Layer layer = Layer.objects.get(id=layer_...
Remove the index for a layer in the search backend. If cache is set, append it to the list of removed layers, if it isn't send the transaction right away.
def dump(self): """Dump all commands in this object to a string. Returns: str: An encoded list of commands separated by \n characters suitable for saving to a file. """ out = [] out.append(self.filetype) out.append("Format: {}".format(self.v...
Dump all commands in this object to a string. Returns: str: An encoded list of commands separated by \n characters suitable for saving to a file.
def tohdf5(input_files, output_file, n_events, conv_times_to_jte, **kwargs): """Convert Any file to HDF5 file""" if len(input_files) > 1: cprint( "Preparing to convert {} files to HDF5.".format(len(input_files)) ) from km3pipe import Pipeline # noqa from km3pipe.io import...
Convert Any file to HDF5 file
def cookie_length(self, domain): '''Return approximate length of all cookie key-values for a domain.''' cookies = self.cookie_jar._cookies if domain not in cookies: return 0 length = 0 for path in cookies[domain]: for name in cookies[domain][path]: ...
Return approximate length of all cookie key-values for a domain.
def discriminator(self, imgs): """ return a (b, 1) logits""" nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .BatchNorm('bn1') ...
return a (b, 1) logits
def repository(self, owner, repository): """Returns a Repository object for the specified combination of owner and repository :param str owner: (required) :param str repository: (required) :returns: :class:`Repository <github3.repos.Repository>` """ json = None ...
Returns a Repository object for the specified combination of owner and repository :param str owner: (required) :param str repository: (required) :returns: :class:`Repository <github3.repos.Repository>`
def forward_word_end_extend_selection(self, e): # u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word_end_extend_selection(self.argument_reset) self.finalize()
u"""Move forward to the end of the next word. Words are composed of letters and digits.
def cli(yamlfile, format, dir, classes, img, noimages): """ Generate markdown documentation of a biolink model """ MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)
Generate markdown documentation of a biolink model
def _build_protobuf(self): """Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf object for the current state of the iterator. """ pb = _pb_from_query(self._qu...
Build a query protobuf. Relies on the current state of the iterator. :rtype: :class:`.query_pb2.Query` :returns: The query protobuf object for the current state of the iterator.
def output_command(info, image_info, pretty=False): '''output as docker-run command format''' sep = pretty and ' \\\n ' or ' ' short_options = '' options = [] container = info['Name'][1:] conf = info['Config'] hconf = info['HostConfig'] options.append("--name={name}".format(name=c...
output as docker-run command format
def np_dtype_to_point_format(dtype, unpacked=False): """ Tries to find a matching point format id for the input numpy dtype To match, the input dtype has to be 100% equal to a point format dtype so all names & dimensions types must match Parameters: ---------- dtype : numpy.dtype The in...
Tries to find a matching point format id for the input numpy dtype To match, the input dtype has to be 100% equal to a point format dtype so all names & dimensions types must match Parameters: ---------- dtype : numpy.dtype The input dtype unpacked : bool, optional [description]...
def cases(store, case_query, limit=100): """Preprocess case objects. Add the necessary information to display the 'cases' view Args: store(adapter.MongoAdapter) case_query(pymongo.Cursor) limit(int): Maximum number of cases to display Returns: data(dict): includes the ...
Preprocess case objects. Add the necessary information to display the 'cases' view Args: store(adapter.MongoAdapter) case_query(pymongo.Cursor) limit(int): Maximum number of cases to display Returns: data(dict): includes the cases, how many there are and the limit.
def _createJobStateFile(self): """ Create the job state file for the current job and fill in the required values. :return: Path to the job state file :rtype: str """ jobStateFile = os.path.join(self.localTempDir, '.jobState') jobState = {'jobPID': os.getp...
Create the job state file for the current job and fill in the required values. :return: Path to the job state file :rtype: str
def block_hash(self, block_number=None, force_recent=True): """ Calculates a block's hash :param block_number: the block number for which to calculate the hash, defaulting to the most recent block :param force_recent: if True (the default) return zero for any block that is in the future ...
Calculates a block's hash :param block_number: the block number for which to calculate the hash, defaulting to the most recent block :param force_recent: if True (the default) return zero for any block that is in the future or older than 256 blocks :return: the block hash
def parseSingleAttr(self, attrValue): """Parse a single CSS attribute source string, and returns the built CSS expression. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseAttributes """ results = self.parseAttributes(temp=attrValue) if 'temp...
Parse a single CSS attribute source string, and returns the built CSS expression. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseAttributes
def delete_instance_if_removed(self, port): """Enqueue instance delete if it's no longer in the db""" instance_type = self.get_instance_type(port) if not instance_type: return if not db_lib.instance_provisioned(port['device_id']): i_res = MechResource(port['device...
Enqueue instance delete if it's no longer in the db
def regex_validation_sealer(fields, defaults, RegexType=type(re.compile(""))): """ Example sealer that just does regex-based validation. """ required = set(fields) - set(defaults) if required: raise TypeError( "regex_validation_sealer doesn't support required arguments. Fields th...
Example sealer that just does regex-based validation.
def add(self): """Add authenticator to an account. The account's phone number will receive a SMS code required for :meth:`finalize`. :raises: :class:`SteamAuthenticatorError` """ if not self.has_phone_number(): raise SteamAuthenticatorError("Account doesn't have a ve...
Add authenticator to an account. The account's phone number will receive a SMS code required for :meth:`finalize`. :raises: :class:`SteamAuthenticatorError`
def _romanize(word: str) -> str: """ :param str word: Thai word to be romanized, should have already been tokenized. :return: Spells out how the Thai word should be pronounced. """ if not isinstance(word, str) or not word: return "" word = _replace_vowels(_normalize(word)) res = _RE...
:param str word: Thai word to be romanized, should have already been tokenized. :return: Spells out how the Thai word should be pronounced.
async def create( cls, boot_source, os, release, *, arches=None, subarches=None, labels=None): """Create a new `BootSourceSelection`.""" if not isinstance(boot_source, BootSource): raise TypeError( "boot_source must be a BootSource, not %s" ...
Create a new `BootSourceSelection`.
def rename(df, **kwargs): """Renames columns, where keyword argument values are the current names of columns and keys are the new names. Args: df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe. Kwargs: **kwargs: key:value pairs where keys are new names for columns and ...
Renames columns, where keyword argument values are the current names of columns and keys are the new names. Args: df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe. Kwargs: **kwargs: key:value pairs where keys are new names for columns and values are current names...