text
stringlengths
81
112k
Fill X with NaN values if necessary, construct the n_samples x n_samples distance matrix and set the self-distance of each row to infinity. Returns contents of X laid out in row-major, the distance matrix, and an "effective infinity" which is larger than any entry of the distance matrix. def knn_initi...
Fill in the given incomplete matrix using k-nearest neighbor imputation. This version assumes that most of the time the same neighbors will be used so first performs the weighted average of a row's k-nearest neighbors and checks afterward whether it was valid (due to possible missing values). Has been...
We can't really compute distances over incomplete data since rows are missing different numbers of entries. The next best thing is the mean squared difference between two vectors (a normalized distance), which gets computed only over the columns that two vectors have in common. If two vectors have no fe...
Reference implementation of normalized all-pairs distance, used for testing the more efficient implementation above for equivalence. def all_pairs_normalized_distances_reference(X): """ Reference implementation of normalized all-pairs distance, used for testing the more efficient implementation above f...
Fill in the given incomplete matrix using k-nearest neighbor imputation. This version is a simpler algorithm meant primarily for testing but surprisingly it's faster for many (but not all) dataset sizes, particularly when most of the columns are missing in any given row. The crucial bottleneck is the c...
Reference implementation of kNN imputation logic. def knn_impute_reference( X, missing_mask, k, verbose=False, print_interval=100): """ Reference implementation of kNN imputation logic. """ n_rows, n_cols = X.shape X_result, D, effective_infinity = \ ...
Returns all active users, e.g. not logged and non-expired session. def active(self, registered_only=True): "Returns all active users, e.g. not logged and non-expired session." visitors = self.filter( expiry_time__gt=timezone.now(), end_time=None ) if registered_o...
Returns a dictionary of visits including: * total visits * unique visits * return ratio * pages per visit (if pageviews are enabled) * time on site for all users, registered users and guests. def stats(self, start_date, end_date, registered_only=Fal...
Returns a dictionary of pageviews including: * total pageviews for all users, registered users and guests. def stats(self, start_date=None, end_date=None, registered_only=False): """Returns a dictionary of pageviews including: * total pageviews for all users, registe...
Counts, aggregations and more! def dashboard(request): "Counts, aggregations and more!" end_time = now() start_time = end_time - timedelta(days=7) defaults = {'start': start_time, 'end': end_time} form = DashboardForm(data=request.GET or defaults) if form.is_valid(): start_time = form....
Attempt to retrieve MaxMind GeoIP data based on visitor's IP. def geoip_data(self): """Attempt to retrieve MaxMind GeoIP data based on visitor's IP.""" if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None ...
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if ...
Jade iteration supports "for 'value' [, key]?" iteration only. PyJade has implicitly supported value unpacking instead, without the list indexes. Trying to not break existing code, the following rules are applied: 1. If the object is a mapping type, return it as-is, and assume the caller has...
Calls an arbitrary method on an object. def do_evaluate(parser, token): '''Calls an arbitrary method on an object.''' code = token.contents firstspace = code.find(' ') if firstspace >= 0: code = code[firstspace+1:] return Evaluator(code)
Calls an arbitrary method on an object. def do_set(parser, token): '''Calls an arbitrary method on an object.''' code = token.contents firstspace = code.find(' ') if firstspace >= 0: code = code[firstspace+1:] return Setter(code)
Evaluates the code in the page and returns the result def render(self, context): '''Evaluates the code in the page and returns the result''' modules = { 'pyjade': __import__('pyjade') } context['false'] = False context['true'] = True try: return six.text_type(eval('pyjade.runtime....
Evaluates the code in the page and returns the result def render(self, context): '''Evaluates the code in the page and returns the result''' modules = { } context['false'] = False context['true'] = True new_ctx = eval('dict(%s)'%self.code,modules,context) context.update(new_ctx) return ...
returns the filepath of the sprite *relative to SPRITE_CACHE* def sprite_filepath_build(sprite_type, sprite_id, **kwargs): """returns the filepath of the sprite *relative to SPRITE_CACHE*""" options = parse_sprite_options(sprite_type, **kwargs) filename = '.'.join([str(sprite_id), SPRITE_EXT]) filepa...
Takes an object and returns a corresponding API class. The names and values of the data will match exactly with those found in the online docs at https://pokeapi.co/docsv2/ . In some cases, the data may be of a standard type, such as an integer or string. For those cases, the input value is simply retu...
Function to collect reference data and connect it to the instance as attributes. Internal function, does not usually need to be called by the user, as it is called automatically when an attribute is requested. :return None def _load(self): """Function to collect reference d...
Create a leaf directory and all intermediate ones in a safe way. A wrapper to os.makedirs() that handles existing leaf directories while avoiding os.path.exists() race conditions. :param path: relative or absolute directory tree to create :param mode: directory permissions in octal :return: The ne...
Get the default cache location. Adheres to the XDG Base Directory specification, as described in https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html :return: the default cache directory absolute path def get_default_cache(): """Get the default cache location. Adheres to the X...
Simple function to change the cache location. `new_path` can be an absolute or relative path. If the directory does not exist yet, this function will create it. If None it will set the cache to the default cache directory. If you are going to change the cache directory, this function should be cal...
Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun_or_snap: the lun, snap, or a member snap of cg snap :param skip_hlu_0: whether to skip hlu 0 :return: the hlu number def attach(self, lun_or_snap, skip_hlu_0=False): ""...
Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lun_or_snap` is attached, otherwise False. def has_hlu(self,...
Gets the host lun of a lun, lun snap, cg snap or a member snap of cg snap. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: the host lun object. def get_host_lun(self,...
Gets the hlu number of a lun, lun snap, cg snap or a member snap of cg snap. :param resource: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: the hlu number. def get_hlu(self, resource, ...
Primarily for puppet-unity use. Update the iSCSI and FC initiators if needed. def update_initiators(self, iqns=None, wwns=None): """Primarily for puppet-unity use. Update the iSCSI and FC initiators if needed. """ # First get current iqns iqns = set(iqns) if iqns else ...
Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>...
Load NASA CDAWeb CDF files. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str...
Routine to download NASA CDAWeb CDF data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- supported_tags : dict dict of dicts. Keys are supported tag names for download. Value is a dict with 'd...
Returns an instance of :class:`HttpError` or subclass based on response. :param response: instance of `requests.Response` class :param method: HTTP method used for request :param url: URL used for request def from_response(response, method, url): """Returns an instance of :class:`HttpError` or subclas...
Create pool based on RaidGroupParameter. :param name: pool name :param raid_groups: a list of *RaidGroupParameter* :param description: pool description :param alert_threshold: Threshold at which the system will generate alerts about the free space in the pool, specified a...
Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports. def get_file_port(self): """Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports. """ eths = self.get_ethernet_port(bond=False)...
Configures a remote system for remote replication. :param management_address: the management IP address of the remote system. :param local_username: administrative username of local system. :param local_password: administrative password of local system. :param remote_usernam...
Creates a replication interface. :param sp: `UnityStorageProcessor` object. Storage processor on which the replication interface is running. :param ip_port: `UnityIpPort` object. Physical port or link aggregation on the storage processor on which the interface is running. ...
geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one point it is [[glat,glon]]). ...
Restores a snapshot. :param res_id: the LUN number of primary LUN or snapshot mount point to be restored. :param backup_snap: the name of a backup snapshot to be created before restoring. def restore(self, res_id, backup_snap=None): """ Restores a snapshot. ...
Return a Pandas Series of every file for chosen SuperMAG data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (default='') sat_id : (string or NoneType) ...
Load the SuperMAG files Parameters ----------- fnames : (list) List of filenames tag : (str or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (default='') sat_id : (str or NoneType) ...
Load data from a comma separated SuperMAG file Parameters ------------ fname : (str) CSV SuperMAG file name tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). Returns -------- data...
Load data from a self-documenting ASCII SuperMAG file Parameters ------------ fname : (str) ASCII SuperMAG filename tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). Returns -------- ...
Update SuperMAG metadata Parameters ----------- col_name : (str) Data column name Returns -------- col_dict : (dict) Dictionary of strings detailing the units and long-form name of the data def update_smag_metadata(col_name): """Update SuperMAG metadata Parameters ...
Format the list of baseline information from the loaded files into a cohesive, informative string Parameters ------------ baseline_list : (list) List of strings specifying the baseline information for each SuperMAG file Returns --------- base_string : (str) Single s...
Routine to download SuperMAG data Parameters ----------- date_array : np.array Array of datetime objects tag : string String denoting the type of file to load, accepted values are 'indices', 'all', 'stations', and '' (for only magnetometer data) sat_id : string Not u...
Load the SuperMAG files Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data file_fmt : str String denoting file type (ascii or csv) tag : string String denoting the type of file to load, accepted values are...
Append data from multiple files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data tag : string String denoting the type of file to load, accepted values are 'indices', 'all', 'station...
Append data from multiple csv files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data Returns ------- out_string : string String with all data, ready for output to a file def append...
Adds custom calculations to orbit simulation. This routine is run once, and only once, upon instantiation. Adds quasi-dipole coordiantes, velocity calculation in ECEF coords, adds the attitude vectors of spacecraft assuming x is ram pointing and z is generally nadir, adds ionospheric parameters fro...
Returns data and metadata in the format required by pysat. Finds position of satellite in both ECI and ECEF co-ordinates. Routine is directly called by pysat and not the user. Parameters ---------- fnames : list-like collection File name that contains date in its name. ...
Produce a fake list of files spanning a year def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a fake list of files spanning a year""" index = pds.date_range(pysat.datetime(2017,12,1), pysat.datetime(2018,12,1)) # file list is effectively just the date in string forma...
Add attitude vectors for spacecraft assuming ram pointing. Presumes spacecraft is pointed along the velocity vector (x), z is generally nadir pointing (positive towards Earth), and y completes the right handed system (generally southward). Notes ----- Expects velocity and positi...
Calculates spacecraft velocity in ECEF frame. Presumes that the spacecraft velocity in ECEF is in the input instrument object as position_ecef_*. Uses a symmetric difference to calculate the velocity thus endpoints will be set to NaN. Routine should be run using pysat data padding feature to c...
Uses Apexpy package to add quasi-dipole coordinates to instrument object. The Quasi-Dipole coordinate system includes both the tilt and offset of the geomagnetic field to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. This system is ...
Uses AACGMV2 package to add AACGM coordinates to instrument object. The Altitude Adjusted Corrected Geomagnetic Coordinates library is used to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. Example ------- # function added...
Uses IRI (International Reference Ionosphere) model to simulate an ionosphere. Uses pyglow module to run IRI. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_i...
Uses HWM (Horizontal Wind Model) model to obtain neutral wind details. Uses pyglow module to run HWM. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_hwm_winds...
Uses International Geomagnetic Reference Field (IGRF) model to obtain geomagnetic field values. Uses pyglow module to run IGRF. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call ins...
Uses MSIS model to obtain thermospheric values. Uses pyglow module to run MSIS. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_msis, 'modify', glat_label='cus...
Express input vector using s/c attitude directions x - ram pointing y - generally southward z - generally nadir Parameters ---------- x_label : string Label used to get ECEF-X component of vector to be projected y_label : string Label used to get ECEF-Y component of...
Return scatterplot of data_label(s) as functions of labelx,y over a season. Parameters ---------- labelx : string data product for x-axis labely : string data product for y-axis data_label : string, array-like of strings data product(s) to be scatter plotted datalim : ...
Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG def enable_log(level=logging.DEBUG): """Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG """ logger = loggin...
Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary data type (ascii) is loaded. (default=None) sat_id : (string or None...
Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. def load_files(files, tag=None, sat_id=None, altitude_bin=None): '''Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. ''' output = ...
round the number to the multiple of 60 Say a random value is represented by: 60 * n + r n is an integer and r is an integer between 0 and 60. if r < 30, the result is 60 * n. otherwise, the result is 60 * (n + 1) The use of this function is that the counter refreshment on VNX is always 1 minut...
calculate the utilization delta_busy = curr.busy - prev.busy delta_idle = curr.idle - prev.idle utilization = delta_busy / (delta_busy + delta_idle) :param prev: previous resource :param curr: current resource :param counters: list of two, busy ticks and idle ticks :return: value, NaN if i...
calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param curr: current resource :param counters: the counter to do delta and per second, one only :return: value, NaN if invalid. def delta_ps(prev, curr, counters): """ calculate the...
calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: prev resource, not used :param curr: current resource :param counters: two stats, bandwidth in MB and throughput count :return: value, NaN if invalid def io_size_kb(prev, curr, co...
Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary data type (ascii) is loaded. (default='') sat_id : (string or NoneTy...
Load CHAMP STAR files Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str or NoneType) satellite id or None (default=None) Returns --------- data : (pandas.DataFrame) Objec...
Assign all external science instrument methods to Instrument object. def _assign_funcs(self, by_name=False, inst_module=None): """Assign all external science instrument methods to Instrument object. """ import importlib # set defaults self._list_rtn = self._pass_func ...
Load data for an instrument on given date or fid, dependng upon input. Parameters ------------ date : (dt.datetime.date object or NoneType) file date fid : (int or NoneType) filename index value Returns -------- data : (pds.DataFrame) ...
Load the next days data (or file) without incrementing the date. Repeated calls will not advance date/file and will produce the same data Uses info stored in object to either increment the date, or the file. Looks for self._load_by_date flag. def _load_next(self): """Load the ...
Load the next days data (or file) without decrementing the date. Repeated calls will not decrement date/file and will produce the same data Uses info stored in object to either decrement the date, or the file. Looks for self._load_by_date flag. def _load_prev(self): ""...
Load instrument data into Instrument object .data. Parameters ---------- yr : integer year for desired data doy : integer day of year date : datetime object date to load fname : 'string' filename to be loaded verify...
Download data for given Instrument object from start to stop. Parameters ---------- start : pandas.datetime start date to download data stop : pandas.datetime stop date to download data freq : string Stepsize between dates for season, ...
Manually iterate through the data loaded in Instrument object. Bounds of iteration and iteration type (day/file) are set by `bounds` attribute. Note ---- If there were no previous calls to load then the first day(default)/file will be loaded. def next...
Determines the two-character type code for a given variable type Parameters ---------- coltype : type or np.dtype The type of the variable Returns ------- str The variable type code for the given type def _get_var_type_code(self, coltype): ...
Support file writing by determiniing data type and other options Parameters ---------- data : pandas object Data to be written file_format : basestring String indicating netCDF3 or netCDF4 Returns ------- data_flag, datetime_flag, old_for...
Filter metadata properties to be consistent with netCDF4. Notes ----- removed forced to True if coltype consistent with a string type Parameters ---------- mdata_dict : dict Dictionary equivalent to Meta object info coltype : type ...
Translates the metadate contained in an object into a dictionary suitable for export. Parameters ---------- meta_to_translate : Meta The metadata object to translate Returns ------- dict A dictionary of the metadata for each variable of a...
Stores loaded data into a netCDF4 file. Parameters ---------- fname : string full path to save instrument object to base_instrument : pysat.Instrument used as a comparison, only attributes that are present with self and not on base_instrument ...
Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number ---------- ---------- 0 12 1 23 ``` ALU stands for array LUN number hlu stands for host LUN number :param input_...
Convert following input to disk indices Sample input: ``` Disks: Bus 0 Enclosure 0 Disk 9 Bus 1 Enclosure 0 Disk 12 Bus 1 Enclosure 0 Disk 9 Bus 0 Enclosure 0 Disk 4 Bus 0 Enclosure 0 Disk 7 ``` :param value: disk list :return: disk indices in list def to_disk_indices(val...
convert a url to a host (ip or domain) :param url: url string :returns: host: domain name or ipv4/v6 address :rtype: str :raises: ValueError: given an illegal url that without a ip or domain name def url_to_host(url): """convert a url to a host (ip or domain) :param url: url string :retur...
parse host address to get domain name or ipv4/v6 address, cidr prefix and net mask code string if given a subnet address :param addr: :type addr: str :return: parsed domain name/ipv4 address/ipv6 address, cidr prefix if there is, net mask code string if there is :rtype: (s...
ipv4 cidr prefix to net mask :param prefix: cidr prefix , rang in (0, 32) :type prefix: int :return: dot separated ipv4 net mask code, eg: 255.255.255.0 :rtype: str def ipv4_prefix_to_mask(prefix): """ ipv4 cidr prefix to net mask :param prefix: cidr prefix , rang in (0, 32) :type pre...
ipv6 cidr prefix to net mask :param prefix: cidr prefix, rang in (0, 128) :type prefix: int :return: comma separated ipv6 net mask code, eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000 :rtype: str def ipv6_prefix_to_mask(prefix): """ ipv6 cidr prefix to net mask :param prefix: ci...
expand the LUN to a new size :param new_size: new size in bytes. :return: the old size def expand(self, new_size): """ expand the LUN to a new size :param new_size: new size in bytes. :return: the old size """ ret = self.size_total resp = self.modify(si...
Primarily for puppet-unity use. Update the hosts for the lun if needed. :param host_names: specify the new hosts which access the LUN. def update_hosts(self, host_names): """Primarily for puppet-unity use. Update the hosts for the lun if needed. :param host_names: specify t...
Creates a replication session with a existing lun as destination. :param dst_lun_id: destination lun id. :param max_time_out_of_sync: maximum time to wait before syncing the source and destination. Value `-1` means the automatic sync is not performed. `0` means it is a sync repl...
Creates a replication session with destination lun provisioning. :param max_time_out_of_sync: maximum time to wait before syncing the source and destination. Value `-1` means the automatic sync is not performed. `0` means it is a sync replication. :param dst_pool_id: id of pool ...
Returns the link aggregation object or the ethernet port object. def get_physical_port(self): """Returns the link aggregation object or the ethernet port object.""" obj = None if self.is_link_aggregation(): obj = UnityLinkAggregation.get(self._cli, self.get_id()) else: ...
Constructs an embeded object of `UnityResourceConfig`. :param pool_id: storage pool of the resource. :param is_thin_enabled: is thin type or not. :param is_deduplication_enabled: is deduplication enabled or not. :param is_compression_enabled: is in-line compression (ILC) enabled or ...
Creates a replication session. :param cli: the rest cli. :param src_resource_id: id of the replication source, could be lun/fs/cg. :param dst_resource_id: id of the replication destination. :param max_time_out_of_sync: maximum time to wait before syncing the sour...
Create a replication session along with destination resource provisioning. :param cli: the rest cli. :param src_resource_id: id of the replication source, could be lun/fs/cg. :param dst_resource_config: `UnityResourceConfig` object. The user chosen config for des...
Modifies properties of a replication session. :param max_time_out_of_sync: same as the one in `create` method. :param name: same as the one in `create` method. :param hourly_snap_replication_policy: same as the one in `create` method. :param daily_snap_replication_policy: sa...
Resumes a replication session. This can be applied on replication session when it's operational status is reported as Failed over, or Paused. :param force_full_copy: needed when replication session goes out of sync due to a fault. True - replicate all data. ...
Fails over a replication session. :param sync: True - sync the source and destination resources before failing over the asynchronous replication session or keep them in sync after failing over the synchronous replication session. False - don't sync. :param force: Tru...
Fails back a replication session. This can be applied on a replication session that is failed over. Fail back will synchronize the changes done to original destination back to original source site and will restore the original direction of session. :param force_full_copy: indic...