text stringlengths 81 112k |
|---|
Send a message to a recipient
Args:
target (string, class, instance, function or builtin):
The object to weave.
aspects (:py:obj:`aspectlib.Aspect`, function decorator or list of):
The aspects to apply to the object.
subclasses (bool):
If ``True``, subcla... |
Low-level weaver for instances.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
def weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options):
"""
Low-level weaver for instances.
.. warning:: You should not use th... |
Low-level weaver for "whole module weaving".
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options):
"""
Low-level weaver for "whole module weaving".
.. warning::... |
Low-level weaver for classes.
.. warning:: You should not use this directly.
def weave_class(klass, aspect, methods=NORMAL_METHODS, subclasses=True, lazy=False,
owner=None, name=None, aliases=True, bases=True, bag=BrokenBag):
"""
Low-level weaver for classes.
.. warning:: You should n... |
Low-level attribute patcher.
:param module module: Object to patch.
:param str name: Attribute to patch
:param replacement: The replacement value.
:param original: The original value (in case the object beeing patched uses descriptors or is plain weird).
:param bool aliases: If ``True`` patch all t... |
Low-level patcher for one function from a specified module.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options):
"""
Low-level patcher for one function from a specifi... |
Strip leading DLE and trailing DLE/ETX from packet.
:param packet: TSIP packet with leading DLE and trailing DLE/ETX.
:type packet: Binary string.
:return: TSIP packet with leading DLE and trailing DLE/ETX removed.
:raise: ``ValueError`` if `packet` does not start with DLE and end in DLE/ETX.
def unfr... |
Add byte stuffing to TSIP packet.
:param packet: TSIP packet with byte stuffing. The packet must already
have been stripped or `ValueError` will be raised.
:type packet: Binary string.
:return: Packet with byte stuffing.
def stuff(packet):
"""
Add byte stuffing to TSIP packet.
:param pa... |
Remove byte stuffing from a TSIP packet.
:param packet: TSIP packet with byte stuffing. The packet must already
have been stripped or `ValueError` will be raised.
:type packet: Binary string.
:return: Packet without byte stuffing.
def unstuff(packet):
"""
Remove byte stuffing from a TSIP p... |
Parse out filename from any specified extensions.
Returns rootname and string version of extension name.
Modified from 'pydrizzle.fileutil' to allow this
module to be independent of PyDrizzle/MultiDrizzle.
def parseFilename(filename):
"""
Parse out filename from any specified exten... |
Returns the shape of the data array associated with this file.
def _shape(self):
""" Returns the shape of the data array associated with this file."""
hdu = self.open()
_shape = hdu.shape
if not self.inmemory:
self.close()
del hdu
return _shape |
Returns the data array associated with this file/extenstion.
def _data(self):
""" Returns the data array associated with this file/extenstion."""
hdu = self.open()
_data = hdu.data.copy()
if not self.inmemory:
self.close()
del hdu
return _data |
Returns the shape of the data array associated with this file.
def type(self):
""" Returns the shape of the data array associated with this file."""
hdu = self.open()
_type = hdu.data.dtype.name
if not self.inmemory:
self.close()
del hdu
return _type |
Opens the file for subsequent access.
def open(self):
""" Opens the file for subsequent access. """
if self.handle is None:
self.handle = fits.open(self.fname, mode='readonly')
if self.extn:
if len(self.extn) == 1:
hdu = self.handle[self.extn[0]]
... |
Tests if the given times overlap with this measurement.
:param targetStartTime: the target start time.
:param duration: the duration
:return: true if the given times overlap with this measurement.
def overlapsWith(self, targetStartTime, duration):
"""
Tests if the given times ov... |
Updates the current device status.
:param deviceName: the device name.
:param state: the state.
:param reason: the reason for the change.
:return:
def updateDeviceStatus(self, deviceName, state, reason=None):
"""
Updates the current device status.
:param deviceNa... |
For a device that is recording, updates the last timestamp so we now when we last received data.
:param deviceId: the device id.
:param dataCount: the no of items of data recorded in this batch.
:return:
def stillRecording(self, deviceId, dataCount):
"""
For a device that is rec... |
loads the recording into memory and returns it as a Signal
:return:
def inflate(self):
"""
loads the recording into memory and returns it as a Signal
:return:
"""
if self.measurementParameters['accelerometerEnabled']:
if len(self.data) == 0:
l... |
Checks the state of each measurement and verifies their state, if an active measurement is now complete then
passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts.
:return:
def _sweep(self):
"""
Checks the state of each measurement... |
Schedules a new measurement with the given name.
:param name:
:param duration:
:param startTime:
:param description:
:return: a tuple
boolean: measurement was scheduled if true
message: description, generally only used as an error code
def schedule(self, ... |
verifies that this measurement does not clash with an already scheduled measurement.
:param startTime: the start time.
:param duration: the duration.
:return: true if the measurement is allowed.
def _clashes(self, startTime, duration):
"""
verifies that this measurement does not... |
Starts the measurement for the device.
:param deviceId: the device that is starting.
:param measurementId: the measurement that is started.
:return: true if it started (i.e. device and measurement exists).
def startMeasurement(self, measurementId, deviceId):
"""
Starts the measu... |
finds the handler.
:param measurementId: the measurement
:param deviceId: the device.
:return: active measurement and handler
def getDataHandler(self, measurementId, deviceId):
"""
finds the handler.
:param measurementId: the measurement
:param deviceId: the devi... |
Passes the data to the handler.
:param deviceId: the device the data comes from.
:param measurementId: the measurement id.
:param data: the data.
:return: true if the data was handled.
def recordData(self, measurementId, deviceId, data):
"""
Passes the data to the handle... |
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.
... |
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 ... |
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 f... |
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(... |
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.
... |
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 m... |
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 measuremen... |
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
... |
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 Fil... |
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 ... |
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: ... |
- 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 ex... |
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 che... |
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:
e... |
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... |
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... |
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 names of the new flt files.
def splitStis(stisfile,... |
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 prim... |
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
... |
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
... |
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)... |
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={'includ... |
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 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 ... |
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:
... |
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.
def new(self, page_name, **dict):
'''
Create a new item with the provided dict information
at the given page_name. R... |
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 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 configurat... |
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 input flags.
.. note::
In order to flip the bits of the... |
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).
This function is partic... |
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, prepend '~' to the input string. '~' must
... |
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.
Parameters
----------
bitmask : numpy.ndarray
An arra... |
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.it... |
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 dat... |
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 does... |
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 owne... |
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) +... |
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...
... |
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 % ... |
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
... |
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(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 be... |
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.")
... |
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... |
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 inpu... |
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:
... |
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 c... |
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'
... |
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__)
... |
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... |
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)
... |
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:
... |
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)
#... |
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, **opt... |
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
paylo... |
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)
retur... |
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
lim... |
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.
... |
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:
... |
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 )
... |
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 'Re... |
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: Pretendin... |
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: ' + p... |
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, ... |
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 d... |
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, ... |
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)
el... |
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()]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.