INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Completes the measurement session.: param deviceId: the device id.: param measurementId: the measurement id.: return: true if it was completed.
def completeMeasurement(self, measurementId, deviceId): """ Completes the measurement session. :param deviceId: the device id. :param measurementId: the measurement id. :return: true if it was completed. """ am, handler = self.getDataHandler(measurementId, deviceI...
Fails the measurement session.: param deviceName: the device name.: param measurementId: the measurement name.: param failureReason: why it failed.: return: true if it was completed.
def failMeasurement(self, measurementId, deviceName, failureReason=None): """ Fails the measurement session. :param deviceName: the device name. :param measurementId: the measurement name. :param failureReason: why it failed. :return: true if it was completed. """...
Deletes the named measurement from the completed measurement store if it exists.: param measurementId:: return: String: error messages Integer: count of measurements deleted
def _deleteCompletedMeasurement(self, measurementId): """ Deletes the named measurement from the completed measurement store if it exists. :param measurementId: :return: String: error messages Integer: count of measurements deleted """ message, cou...
Reloads the completed measurements from the backing store.
def reloadCompletedMeasurements(self): """ Reloads the completed measurements from the backing store. """ from pathlib import Path reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()] logger.info('Reloaded ' + str(len(reloaded)) + ' ...
Gets all available measurements.: param measurementStatus return only the measurements in the given state.: return:
def getMeasurements(self, measurementStatus=None): """ Gets all available measurements. :param measurementStatus return only the measurements in the given state. :return: """ if measurementStatus is None: return self.activeMeasurements + self.completeMeasureme...
Gets the measurement with the given id.: param measurementId: the id.: param measurementStatus: the status of the requested measurement.: return: the matching measurement or none if it doesn t exist.
def getMeasurement(self, measurementId, measurementStatus=None): """ Gets the measurement with the given id. :param measurementId: the id. :param measurementStatus: the status of the requested measurement. :return: the matching measurement or none if it doesn't exist. """...
Writes the measurement metadata to disk on completion.: param activeMeasurement: the measurement that has completed.: returns the persisted metadata.
def store(self, measurement): """ Writes the measurement metadata to disk on completion. :param activeMeasurement: the measurement that has completed. :returns the persisted metadata. """ os.makedirs(self._getPathToMeasurementMetaDir(measurement.idAsPath), exist_ok=True) ...
Loads a CompletedMeasurement from the path. á: param path: the path at which the data is found.: return: the measurement
def load(self, path): """ Loads a CompletedMeasurement from the path.á :param path: the path at which the data is found. :return: the measurement """ meta = self._loadMetaFromJson(path) return CompleteMeasurement(meta, self.dataDir) if meta is not None else None
Reads the json meta into memory.: return: the meta.
def _loadMetaFromJson(self, path): """ Reads the json meta into memory. :return: the meta. """ try: with (path / 'metadata.json').open() as infile: return json.load(infile) except FileNotFoundError: logger.error('Metadata does not e...
Edits the specified measurement with the provided data.: param measurementId: the measurement id.: param data: the data to update.: return: true if the measurement was edited
def editMeasurement(self, measurementId, data): """ Edits the specified measurement with the provided data. :param measurementId: the measurement id. :param data: the data to update. :return: true if the measurement was edited """ oldMeasurement = self.getMeasur...
Copies the data file to a new file in the tmp dir filtering it according to newStart and newEnd and adjusting the times as appropriate so it starts from 0.: param dataFile: the input file.: param newStart: the new start time.: param newEnd: the new end time.: param newDataDir: the tmp dir to write to.: return: the devi...
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir): """ Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting the times as appropriate so it starts from 0. :param dataFile: the input file. :param newStart: the n...
- Converts waiver fits sciece and data quality files to MEF format - Converts GEIS science and data quality files to MEF format - Checks for stis association tables and splits them into single imsets - Removes files with EXPTIME = 0 and the corresponding ivm files - Removes files with NGOODPIX == 0 ( to exclude saturat...
def checkFiles(filelist,ivmlist = None): """ - Converts waiver fits sciece and data quality files to MEF format - Converts GEIS science and data quality files to MEF format - Checks for stis association tables and splits them into single imsets - Removes files with EXPTIME=0 and the corresponding iv...
This code will check whether or not files are GEIS or WAIVER FITS and convert them to MEF if found. It also keeps the IVMLIST consistent with the input filelist in the case that some inputs get dropped during the check/ conversion.
def checkFITSFormat(filelist, ivmlist=None): """ This code will check whether or not files are GEIS or WAIVER FITS and convert them to MEF if found. It also keeps the IVMLIST consistent with the input filelist, in the case that some inputs get dropped during the check/conversion. """ if ivml...
Removes files with EXPTIME == 0 from filelist.
def check_exptime(filelist): """ Removes files with EXPTIME==0 from filelist. """ toclose = False removed_files = [] for f in filelist: if isinstance(f, str): f = fits.open(f) toclose = True try: exptime = f[0].header['EXPTIME'] except...
Only for ACS WFC3 and STIS check NGOODPIX If all pixels are bad on all chips exclude this image from further processing. Similar checks requiring comparing driz_sep_bits against WFPC2 c1f. fits arrays and NICMOS DQ arrays will need to be done separately ( and later ).
def checkNGOODPIX(filelist): """ Only for ACS, WFC3 and STIS, check NGOODPIX If all pixels are 'bad' on all chips, exclude this image from further processing. Similar checks requiring comparing 'driz_sep_bits' against WFPC2 c1f.fits arrays and NICMOS DQ arrays will need to be done separately...
Input: A stis multiextension file Output: Number of stis science extensions in input
def stisObsCount(input): """ Input: A stis multiextension file Output: Number of stis science extensions in input """ count = 0 toclose = False if isinstance(input, str): input = fits.open(input) toclose = True for ext in input: if 'extname' in ext.header: ...
Split a STIS association file into multiple imset MEF files.
def splitStis(stisfile, sci_count): """ Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Returns ------- names: list a list with the name...
Several kw which are usually in the primary header are in the extension header for STIS. They are copied to the primary header for convenience. List if kw: DATE - OBS EXPEND EXPSTART EXPTIME
def stisExt2PrimKw(stisfiles): """ Several kw which are usually in the primary header are in the extension header for STIS. They are copied to the primary header for convenience. List if kw: 'DATE-OBS', 'EXPEND', 'EXPSTART', 'EXPTIME' """ kw_list = ['DATE-OBS', 'EXPE...
Checks if a file is in WAIVER of GEIS format and converts it to MEF
def convert2fits(sci_ivm): """ Checks if a file is in WAIVER of GEIS format and converts it to MEF """ removed_files = [] translated_names = [] newivmlist = [] for file in sci_ivm: #find out what the input is # if science file is not found on disk, add it to removed_files fo...
Converts a GEIS science file and its corresponding data quality file ( if present ) to MEF format Writes out both files to disk. Returns the new name of the science image.
def waiver2mef(sciname, newname=None, convert_dq=True, writefits=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ if isinstance(sciname, fits.HDUList): ...
Converts a GEIS science file and its corresponding data quality file ( if present ) to MEF format Writes out both files to disk. Returns the new name of the science image.
def geis2mef(sciname, convert_dq=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ clobber = True mode = 'update' memmap = True # Input was speci...
Retrieve journals attribute for this very Issue
def journals(self): """ Retrieve journals attribute for this very Issue """ try: target = self._item_path json_data = self._redmine.get(target % str(self.id), parms={'include': 'journals'}) data = self._redmine...
Save all changes back to Redmine with optional notes.
def save(self, notes=None): '''Save all changes back to Redmine with optional notes.''' # Capture the notes if given if notes: self._changes['notes'] = notes # Call the base-class save function super(Issue, self).save()
Save all changes and set to the given new_status
def set_status(self, new_status, notes=None): '''Save all changes and set to the given new_status''' self.status_id = new_status try: self.status['id'] = self.status_id # We don't have the id to name mapping, so blank the name self.status['name'] = None ...
Save all changes and resolve this issue
def resolve(self, notes=None): '''Save all changes and resolve this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes)
Save all changes and close this issue
def close(self, notes=None): '''Save all changes and close this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_CLOSED, notes=notes)
Return an object derived from the given json data.
def _objectify(self, json_data=None, data={}): '''Return an object derived from the given json data.''' if json_data: # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which...
Create a new item with the provided dict information at the given page_name. Returns the new item.
def new(self, page_name, **dict): ''' Create a new item with the provided dict information at the given page_name. Returns the new item. As of version 2.2 of Redmine, this doesn't seem to function. ''' self._item_new_path = '/projects/%s/wiki/%s.json' % \ (s...
Set up this object based on the capabilities of the known versions of Redmine
def _set_version(self, version): ''' Set up this object based on the capabilities of the known versions of Redmine ''' # Store the version we are evaluating self.version = version or None # To evaluate the version capabilities, # assume the best-case if no...
extracts a new TargetState object from the specified configuration: param targetStateConfig: the config dict.: param existingTargetState: the existing state: return:
def loadTargetState(targetStateConfig, existingTargetState=None): """ extracts a new TargetState object from the specified configuration :param targetStateConfig: the config dict. :param existingTargetState: the existing state :return: """ from analyser.common.targetstatecontroller import Ta...
Converts input bit flags to a single integer value ( bitmask ) or None.
def interpret_bit_flags(bit_flags, flip_bits=None): """ Converts input bit flags to a single integer value (bitmask) or `None`. When input is a list of flags (either a Python list of integer flags or a sting of comma- or '+'-separated list of flags), the returned bitmask is obtained by summing inpu...
bitfield_to_boolean_mask ( bitfield ignore_flags = None flip_bits = None \ good_mask_value = True dtype = numpy. bool \ _ ) Converts an array of bit fields to a boolean ( or integer ) mask array according to a bitmask constructed from the supplied bit flags ( see ignore_flags parameter ).
def bitfield_to_boolean_mask(bitfield, ignore_flags=0, flip_bits=None, good_mask_value=True, dtype=np.bool_): """ bitfield_to_boolean_mask(bitfield, ignore_flags=None, flip_bits=None, \ good_mask_value=True, dtype=numpy.bool\_) Converts an array of bit fields to a boolean (or in...
Converts input bits value from string to a single integer value or None. If a comma - or + - separated set of values are provided they are summed.
def interpret_bits_value(val): """ Converts input bits value from string to a single integer value or None. If a comma- or '+'-separated set of values are provided, they are summed. .. note:: In order to flip the bits of the final result (after summation), for input of `str` type, prepe...
bitmask2mask ( bitmask ignore_bits good_mask_value = 1 dtype = numpy. bool \ _ ) Interprets an array of bit flags and converts it to a binary mask array. This function is particularly useful to convert data quality arrays to binary masks.
def bitmask2mask(bitmask, ignore_bits, good_mask_value=1, dtype=np.bool_): """ bitmask2mask(bitmask, ignore_bits, good_mask_value=1, dtype=numpy.bool\_) Interprets an array of bit flags and converts it to a "binary" mask array. This function is particularly useful to convert data quality arrays to b...
Format data to get a readable output.
def output_text(account, all_data, show_hourly=False): """Format data to get a readable output.""" print(""" ################################# # Hydro Quebec data for account # # {} #################################""".format(account)) for contract, data in all_data.items(): data['contract'] = contr...
Print data using influxDB format.
def output_influx(data): """Print data using influxDB format.""" for contract in data: # Pop yesterdays data yesterday_data = data[contract]['yesterday_hourly_consumption'] del data[contract]['yesterday_hourly_consumption'] # Print general data out = "pyhydroquebec,cont...
Convenience function. Returns one of ( x11 aqua ) in answer to the question of whether this is an X11 - linked Python/ tkinter or a natively built ( framework Aqua ) one. This is only for OSX. This relies on the assumption that on OSX PyObjC is installed in the Framework builds of Python. If it doesn t find PyObjC this...
def which_darwin_linkage(force_otool_check=False): """ Convenience function. Returns one of ('x11', 'aqua') in answer to the question of whether this is an X11-linked Python/tkinter, or a natively built (framework, Aqua) one. This is only for OSX. This relies on the assumption that on OSX, PyObjC is i...
Convenience function to return owner of/ dev/ console. If raises is True this raises an exception on any error. If not it returns any error string as the owner name. If owner is self and if mask_if_self returns <self >.
def get_dc_owner(raises, mask_if_self): """ Convenience function to return owner of /dev/console. If raises is True, this raises an exception on any error. If not, it returns any error string as the owner name. If owner is self, and if mask_if_self, returns "<self>".""" try: from pwd import ...
Determine Julian day from Bahai date
def to_jd(year, month, day): '''Determine Julian day from Bahai date''' gy = year - 1 + EPOCH_GREGORIAN_YEAR if month != 20: m = 0 else: if isleap(gy + 1): m = -14 else: m = -15 return gregorian.to_jd(gy, 3, 20) + (19 * (month - 1)) + m + day
Calculate Bahai date from Julian day
def from_jd(jd): '''Calculate Bahai date from Julian day''' jd = trunc(jd) + 0.5 g = gregorian.from_jd(jd) gy = g[0] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian.to_jd(gy, 3, 20): x = 1 else: x = 0 # verify this next line... bys = gy - (bstarty + (((gregorian....
Determine Julian day from Mayan long count
def to_jd(baktun, katun, tun, uinal, kin): '''Determine Julian day from Mayan long count''' return EPOCH + (baktun * 144000) + (katun * 7200) + (tun * 360) + (uinal * 20) + kin
Calculate Mayan long count from Julian day
def from_jd(jd): '''Calculate Mayan long count from Julian day''' d = jd - EPOCH baktun = trunc(d / 144000) d = (d % 144000) katun = trunc(d / 7200) d = (d % 7200) tun = trunc(d / 360) d = (d % 360) uinal = trunc(d / 20) kin = int((d % 20)) return (baktun, katun, tun, uinal,...
Determine Mayan Haab month and day from Julian day
def to_haab(jd): '''Determine Mayan Haab "month" and day from Julian day''' # Number of days since the start of the long count lcount = trunc(jd) + 0.5 - EPOCH # Long Count begins 348 days after the start of the cycle day = (lcount + 348) % 365 count = day % 20 month = trunc(day / 20) ...
Determine Mayan Tzolkin month and day from Julian day
def to_tzolkin(jd): '''Determine Mayan Tzolkin "month" and day from Julian day''' lcount = trunc(jd) + 0.5 - EPOCH day = amod(lcount + 4, 13) name = amod(lcount + 20, 20) return int(day), TZOLKIN_NAMES[int(name) - 1]
Return the count of the given haab in the cycle. e. g. 0 Pop == 1 5 Wayeb == 365
def _haab_count(day, month): '''Return the count of the given haab in the cycle. e.g. 0 Pop == 1, 5 Wayeb' == 365''' if day < 0 or day > 19: raise IndexError("Invalid day number") try: i = HAAB_MONTHS.index(month) except ValueError: raise ValueError("'{0}' is not a valid Haab' m...
For a given tzolkin name/ number combination return a generator that gives cycle starting with the input
def tzolkin_generator(number=None, name=None): '''For a given tzolkin name/number combination, return a generator that gives cycle, starting with the input''' # By default, it will start at the beginning number = number or 13 name = name or "Ajaw" if number > 13: raise ValueError("Inva...
Generate long counts starting with input
def longcount_generator(baktun, katun, tun, uinal, kin): '''Generate long counts, starting with input''' j = to_jd(baktun, katun, tun, uinal, kin) while True: yield from_jd(j) j = j + 1
For a given haab month and a julian day count find the next start of that month on or after the JDC
def next_haab(month, jd): '''For a given haab month and a julian day count, find the next start of that month on or after the JDC''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") hday, hmonth = to_haab(jd) if hmonth == month: days = 1 - hday else: cou...
For a given tzolk in day and a julian day count find the next occurrance of that tzolk in after the date
def next_tzolkin(tzolkin, jd): '''For a given tzolk'in day, and a julian day count, find the next occurrance of that tzolk'in after the date''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") count1 = _tzolkin_count(*to_tzolkin(jd)) count2 = _tzolkin_count(*tzolkin) add...
For a given haab - tzolk in combination and a Julian day count find the next occurrance of the combination after the date
def next_tzolkin_haab(tzolkin, haab, jd): '''For a given haab-tzolk'in combination, and a Julian day count, find the next occurrance of the combination after the date''' # get H & T of input jd, and their place in the 18,980 day cycle haabcount = _haab_count(*to_haab(jd)) haab_desired_count = _haab_coun...
For a given long count return a calender of the current haab month divided into tzolkin weeks
def haab_monthcalendar(baktun=None, katun=None, tun=None, uinal=None, kin=None, jdc=None): '''For a given long count, return a calender of the current haab month, divided into tzolkin "weeks"''' if not jdc: jdc = to_jd(baktun, katun, tun, uinal, kin) haab_number, haab_month = to_haab(jdc) first...
Update the data in this object.
def _update_data(self, data={}): '''Update the data in this object.''' # Store the changes to prevent this update from affecting it pending_changes = self._changes or {} try: del self._changes except: pass # Map custom fields into our custom fiel...
Remaps a given changed field from tag to tag_id.
def _remap_tag_to_tag_id(cls, tag, new_data): '''Remaps a given changed field from tag to tag_id.''' try: value = new_data[tag] except: # If tag wasn't changed, just return return tag_id = tag + '_id' try: # Remap the ID change to ...
Add an item manager to this object.
def _add_item_manager(self, key, item_class, **paths): ''' Add an item manager to this object. ''' updated_paths = {} for path_type, path_value in paths.iteritems(): updated_paths[path_type] = path_value.format(**self.__dict__) manager = Redmine_Items_Manager...
Save all changes on this item ( if any ) back to Redmine.
def save(self): '''Save all changes on this item (if any) back to Redmine.''' self._check_custom_fields() if not self._changes: return None for tag in self._remap_to_id: self._remap_tag_to_tag_id(tag, self._changes) # Check for custom handlers for tags ...
Refresh this item from data on the server. Will save any unsaved data first.
def refresh(self): '''Refresh this item from data on the server. Will save any unsaved data first.''' if not self._item_path: raise AttributeError('refresh is not available for %s' % self._type) if not self.id: raise RedmineError('%s did not come from the Redmine...
Get all changed values.
def _get_changes(self): '''Get all changed values.''' result = dict( (f['id'], f.get('value','')) for f in self._data if f.get('changed', False) ) self._clear_changes return result
Return a query interator with ( id object ) pairs.
def iteritems(self, **options): '''Return a query interator with (id, object) pairs.''' iter = self.query(**options) while True: obj = iter.next() yield (obj.id, obj)
Return an object derived from the given json data.
def _objectify(self, json_data=None, data={}): '''Return an object derived from the given json data.''' if json_data: # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which...
Create a new item with the provided dict information. Returns the new item.
def new(self, **dict): '''Create a new item with the provided dict information. Returns the new item.''' if not self._item_new_path: raise AttributeError('new is not available for %s' % self._item_name) # Remap various tag to tag_id for tag in self._object._remap_to_id: ...
Get a single item with the given ID
def get(self, id, **options): '''Get a single item with the given ID''' if not self._item_path: raise AttributeError('get is not available for %s' % self._item_name) target = self._item_path % id json_data = self._redmine.get(target, **options) data = self._redmine.un...
Update a given item with the passed data.
def update(self, id, **dict): '''Update a given item with the passed data.''' if not self._item_path: raise AttributeError('update is not available for %s' % self._item_name) target = (self._update_path or self._item_path) % id payload = json.dumps({self._item_type:dict}) ...
Delete a single item with the given ID
def delete(self, id): '''Delete a single item with the given ID''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) return None
Return an iterator for the given items.
def query(self, **options): '''Return an iterator for the given items.''' if not self._query_path: raise AttributeError('query is not available for %s' % self._item_name) last_item = 0 offset = 0 current_item = None limit = options.get('limit', 25) opt...
Create the authentication object with the given credentials.
def _setup_authentication(self, username, password): '''Create the authentication object with the given credentials.''' ## BUG WORKAROUND if self.version < 1.1: # Version 1.0 had a bug when using the key parameter. # Later versions have the opposite bug (a key in the use...
Opens a page from the server with optional XML. Returns a response file - like object
def open_raw(self, page, parms=None, payload=None, HTTPrequest=None, payload_type='application/json' ): '''Opens a page from the server with optional XML. Returns a response file-like object''' if not parms: parms={} # if we're using a key, but it's not going in the header, add it ...
Opens a page from the server with optional content. Returns the string response.
def open(self, page, parms=None, payload=None, HTTPrequest=None ): '''Opens a page from the server with optional content. Returns the string response.''' response = self.open_raw( page, parms, payload, HTTPrequest ) return response.read()
Posts a string payload to the server - used to make new Redmine items. Returns an JSON string or error.
def post(self, page, payload, parms=None ): '''Posts a string payload to the server - used to make new Redmine items. Returns an JSON string or error.''' if self.readonlytest: print 'Redmine read only test: Pretending to create: ' + page return payload else: ...
Puts an XML object on the server - used to update Redmine items. Returns nothing useful.
def put(self, page, payload, parms=None ): '''Puts an XML object on the server - used to update Redmine items. Returns nothing useful.''' if self.readonlytest: print 'Redmine read only test: Pretending to update: ' + page else: return self.open( page, parms, payload, HTT...
Deletes a given object on the server - used to remove items from Redmine. Use carefully!
def delete(self, page ): '''Deletes a given object on the server - used to remove items from Redmine. Use carefully!''' if self.readonlytest: print 'Redmine read only test: Pretending to delete: ' + page else: return self.open( page, HTTPrequest=self.DELETE_Request )
Decodes a json string and unwraps any type it finds within.
def unwrap_json(self, type, json_data): '''Decodes a json string, and unwraps any 'type' it finds within.''' # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which likely contains an error message ins...
Finds and stores a reference to all Redmine_Item subclasses for later use.
def find_all_item_classes(self): '''Finds and stores a reference to all Redmine_Item subclasses for later use.''' # This is a circular import, but performed after the class is defined and an object is instatiated. # We do this in order to get references to any objects definitions in the redmine....
Returns the updated cached version of the given dict
def check_cache(self, type, data, obj=None): '''Returns the updated cached version of the given dict''' try: id = data['id'] except: # Not an identifiable item #print 'don\'t know this item %r:%r' % (type, data) return data # If obj was pa...
Return a Point instance as the displacement of two points.
def substract(self, pt): """Return a Point instance as the displacement of two points.""" if isinstance(pt, Point): return Point(pt.x - self.x, pt.y - self.y, pt.z - self.z) else: raise TypeError
Return a Point instance from a given list
def from_list(cls, l): """Return a Point instance from a given list""" if len(l) == 3: x, y, z = map(float, l) return cls(x, y, z) elif len(l) == 2: x, y = map(float, l) return cls(x, y) else: raise AttributeError
Return a Vector as the product of the vector and a real number.
def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()])
Return magnitude of the vector.
def magnitude(self): """Return magnitude of the vector.""" return math.sqrt( reduce(lambda x, y: x + y, [x ** 2 for x in self.to_list()]) )
Return a Vector instance as the vector sum of two vectors.
def sum(self, vector): """Return a Vector instance as the vector sum of two vectors.""" return self.from_list( [x + vector.vector[i] for i, x in self.to_list()] )
Return the dot product of two vectors.
def dot(self, vector, theta=None): """Return the dot product of two vectors. If theta is given then the dot product is computed as v1*v1 = |v1||v2|cos(theta). Argument theta is measured in degrees. """ if theta is not None: return (self.magnitude() * vector.m...
Return a Vector instance as the cross product of two vectors
def cross(self, vector): """Return a Vector instance as the cross product of two vectors""" return Vector((self.y * vector.z - self.z * vector.y), (self.z * vector.x - self.x * vector.z), (self.x * vector.y - self.y * vector.x))
Return a Vector instance of the unit vector
def unit(self): """Return a Vector instance of the unit vector""" return Vector( (self.x / self.magnitude()), (self.y / self.magnitude()), (self.z / self.magnitude()) )
Return the angle between two vectors in degrees.
def angle(self, vector): """Return the angle between two vectors in degrees.""" return math.degrees( math.acos( self.dot(vector) / (self.magnitude() * vector.magnitude()) ) )
Return True if vectors are non - parallel.
def non_parallel(self, vector): """Return True if vectors are non-parallel. Non-parallel vectors are vectors which are neither parallel nor perpendicular to each other. """ if (self.is_parallel(vector) is not True and self.is_perpendicular(vector) is not True): ...
Returns the rotated vector. Assumes angle is in radians
def rotate(self, angle, axis=(0, 0, 1)): """Returns the rotated vector. Assumes angle is in radians""" if not all(isinstance(a, int) for a in axis): raise ValueError x, y, z = self.x, self.y, self.z # Z axis rotation if(axis[2]): x = (self.x * math.cos(an...
Return a Vector instance from two given points.
def from_points(cls, point1, point2): """Return a Vector instance from two given points.""" if isinstance(point1, Point) and isinstance(point2, Point): displacement = point1.substract(point2) return cls(displacement.x, displacement.y, displacement.z) raise TypeError
Returns a Vector instance from spherical coordinates
def spherical(cls, mag, theta, phi=0): '''Returns a Vector instance from spherical coordinates''' return cls( mag * math.sin(phi) * math.cos(theta), # X mag * math.sin(phi) * math.sin(theta), # Y mag * math.cos(phi) # Z )
Returns a Vector instance from cylindircal coordinates
def cylindrical(cls, mag, theta, z=0): '''Returns a Vector instance from cylindircal coordinates''' return cls( mag * math.cos(theta), # X mag * math.sin(theta), # Y z # Z )
Modulus function which returns numerator if modulus is zero
def amod(a, b): '''Modulus function which returns numerator if modulus is zero''' modded = int(a % b) return b if modded is 0 else modded
Determine the Julian date for the next or previous weekday
def search_weekday(weekday, jd, direction, offset): '''Determine the Julian date for the next or previous weekday''' return weekday_before(weekday, jd + (direction * offset))
Return ( year month day ) tuple that represents nth weekday of month in year. If n == 0 returns last weekday of month. Weekdays: Monday = 0
def nth_day_of_month(n, weekday, month, year): """ Return (year, month, day) tuple that represents nth weekday of month in year. If n==0, returns last weekday of month. Weekdays: Monday=0 """ if not (0 <= n <= 5): raise IndexError("Nth day of month must be 0-5. Received: {}".format(n)) ...
Returns a list of filenames based on the type of IRAF input.
def irafglob(inlist, atfile=None): """ Returns a list of filenames based on the type of IRAF input. Handles lists, wild-card characters, and at-files. For special at-files, use the atfile keyword to process them. This function is recursive, so IRAF lists can also contain at-files and wild-card ch...
Return binary format of packet.
def pack(self): """Return binary format of packet. The returned string is the binary format of the packet with stuffing and framing applied. It is ready to be sent to the GPS. """ # Possible structs for packet ID. # try: structs_ = ...
Instantiate Packet from binary string.
def unpack(cls, rawpacket): """Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. `rawpacket` must already have framing (DLE...DLE/ETX) removed and byte stuffing reversed. """ structs_ = g...
Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLIPBOARD.
def ch_handler(offset=0, length=-1, **kw): """ Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLIPBOARD. """ global _lastSel offset = int(offset) length = int(length) if length < 0: length = len(_lastSel) return _lastSel[offs...
Put the given string into the given clipboard.
def put(text, cbname): """ Put the given string into the given clipboard. """ global _lastSel _checkTkInit() if cbname == 'CLIPBOARD': _theRoot.clipboard_clear() if text: # for clipboard_append, kwds can be -displayof, -format, or -type _theRoot.clipboard_append(t...
Get the contents of the given clipboard.
def get(cbname): """ Get the contents of the given clipboard. """ _checkTkInit() if cbname == 'PRIMARY': try: return _theRoot.selection_get(selection='PRIMARY') except: return None if cbname == 'CLIPBOARD': try: return _theRoot.selection_get(se...
Creates a measurement deviceCfg from the input configuration.: param: deviceCfg: the deviceCfg cfg.: param: handlers: the loaded handlers.: return: the constructed deviceCfg.
def createDevice(self, deviceCfg): """ Creates a measurement deviceCfg from the input configuration. :param: deviceCfg: the deviceCfg cfg. :param: handlers: the loaded handlers. :return: the constructed deviceCfg. """ ioCfg = deviceCfg['io'] type = deviceC...
Loads the recordingDevices specified in the configuration.: param: handlers the loaded handlers.: return: the constructed recordingDevices in a dict keyed by name.
def _loadRecordingDevices(self): """ Loads the recordingDevices specified in the configuration. :param: handlers the loaded handlers. :return: the constructed recordingDevices in a dict keyed by name. """ return {device.name: device for device in [self.cre...
Creates a data handler from the input configuration.: param handler: the handler cfg.: return: the constructed handler.
def createHandler(self, handler): """ Creates a data handler from the input configuration. :param handler: the handler cfg. :return: the constructed handler. """ target = handler['target'] if handler['type'] == 'log': self.logger.warning("Initialising ...
creates a dictionary of named handler instances: return: the dictionary
def _loadHandlers(self): """ creates a dictionary of named handler instances :return: the dictionary """ return {handler.name: handler for handler in map(self.createHandler, self.config['handlers'])}