sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def writeOutput(self, filename, samples, srcFs, targetFs): """ Resamples the signal to the targetFs and writes it to filename. :param filename: the filename. :param signal: the signal to resample. :param targetFs: the target fs. :return: None """ import li...
Resamples the signal to the targetFs and writes it to filename. :param filename: the filename. :param signal: the signal to resample. :param targetFs: the target fs. :return: None
entailment
def delete(self, name): """ Deletes the named entry. :param name: the entry. :return: the deleted entry. """ i, entry = next(((i, x) for i, x in enumerate(self._uploadCache) if x['name'] == name), (None, None)) if entry is not None: logger.info("Deleti...
Deletes the named entry. :param name: the entry. :return: the deleted entry.
entailment
def eparOptionFactory(master, statusBar, param, defaultParam, doScroll, fieldWidths, plugIn=None, editedCallbackObj=None, helpCallbackObj=None, mainGuiObj=None, defaultsVerb="Default", bg=None, indent=False, fl...
Return EparOption item of appropriate type for the parameter param
entailment
def extraBindingsForSelectableText(self): """ Collect in 1 place the bindings needed for watchTextSelection() """ # See notes in watchTextSelection self.entry.bind('<FocusIn>', self.watchTextSelection, "+") self.entry.bind('<ButtonRelease-1>', self.watchTextSelection, "+") self.e...
Collect in 1 place the bindings needed for watchTextSelection()
entailment
def focusOut(self, event=None): """Clear selection (if text is selected in this widget)""" # do nothing if this isn't a text-enabled widget if not self.isSelectable: return if self.entryCheck(event) is None: # Entry value is OK # Save the last selectio...
Clear selection (if text is selected in this widget)
entailment
def watchTextSelection(self, event=None): """ Callback used to see if there is a new text selection. In certain cases we manually add the text to the clipboard (though on most platforms the correct behavior happens automatically). """ # Note that this isn't perfect - it is a key click be...
Callback used to see if there is a new text selection. In certain cases we manually add the text to the clipboard (though on most platforms the correct behavior happens automatically).
entailment
def focusIn(self, event=None): """Select all text (if applicable) on taking focus""" try: # doScroll returns false if the call was ignored because the # last call also came from this widget. That avoids unwanted # scrolls and text selection when the focus moves in an...
Select all text (if applicable) on taking focus
entailment
def widgetEdited(self, event=None, val=None, action='entry', skipDups=True): """ A general method for firing any applicable triggers when a value has been set. This is meant to be easily callable from any part of this class (or its subclasses), so that it can be called as so...
A general method for firing any applicable triggers when a value has been set. This is meant to be easily callable from any part of this class (or its subclasses), so that it can be called as soon as need be (immed. on click?). This is smart enough to be called multiple...
entailment
def popupChoices(self, event=None): """Popup right-click menu of special parameter operations Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled instance attributes to determine which items are available. """ # don't bother if all items are disabled if N...
Popup right-click menu of special parameter operations Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled instance attributes to determine which items are available.
entailment
def fileBrowser(self): """Invoke a tkinter file dialog""" if capable.OF_TKFD_IN_EPAR: fname = askopenfilename(parent=self.entry, title="Select File") else: from . import filedlg self.fd = filedlg.PersistLoadFileDialog(self.entry, "...
Invoke a tkinter file dialog
entailment
def dirBrowser(self): """Invoke a tkinter directory dialog""" if capable.OF_TKFD_IN_EPAR: fname = askdirectory(parent=self.entry, title="Select Directory") else: raise NotImplementedError('Fix popupChoices() logic.') if not fname: return # canceled ...
Invoke a tkinter directory dialog
entailment
def forceValue(self, newVal, noteEdited=False): """Force-set a parameter entry to the given value""" if newVal is None: newVal = "" self.choice.set(newVal) if noteEdited: self.widgetEdited(val=newVal, skipDups=False)
Force-set a parameter entry to the given value
entailment
def unlearnValue(self): """Unlearn a parameter value by setting it back to its default""" defaultValue = self.defaultParamInfo.get(field = "p_filename", native = 0, prompt = 0) self.choice.set(defaultValue)
Unlearn a parameter value by setting it back to its default
entailment
def setActiveState(self, active): """ Use this to enable or disable (grey out) a parameter. """ st = DISABLED if active: st = NORMAL self.entry.configure(state=st) self.inputLabel.configure(state=st) self.promptLabel.configure(state=st)
Use this to enable or disable (grey out) a parameter.
entailment
def flagThisPar(self, currentVal, force): """ If this par's value is different from the default value, it is here that we flag it somehow as such. This basic version simply makes the surrounding text red (or returns it to normal). May be overridden. Leave force at False if you want to a...
If this par's value is different from the default value, it is here that we flag it somehow as such. This basic version simply makes the surrounding text red (or returns it to normal). May be overridden. Leave force at False if you want to allow this mehtod to make smart time-saving dec...
entailment
def keypress(self, event): """Allow keys typed in widget to select items""" try: self.choice.set(self.shortcuts[event.keysym]) except KeyError: # key not found (probably a bug, since we intend to catch # only events from shortcut keys, but ignore it anyway) ...
Allow keys typed in widget to select items
entailment
def postcmd(self): """Make sure proper entry is activated when menu is posted""" value = self.choice.get() try: index = self.paramInfo.choice.index(value) self.entry.menu.activate(index) except ValueError: # initial null value may not be in list ...
Make sure proper entry is activated when menu is posted
entailment
def convertToNative(self, aVal): """ Convert to native bool; interpret certain strings. """ if aVal is None: return None if isinstance(aVal, bool): return aVal # otherwise interpret strings return str(aVal).lower() in ('1','on','yes','true')
Convert to native bool; interpret certain strings.
entailment
def toggle(self, event=None): """Toggle value between Yes and No""" if self.choice.get() == "yes": self.rbno.select() else: self.rbyes.select() self.widgetEdited()
Toggle value between Yes and No
entailment
def entryCheck(self, event = None, repair = True): """ Ensure any INDEF entry is uppercase, before base class behavior """ valupr = self.choice.get().upper() if valupr.strip() == 'INDEF': self.choice.set(valupr) return EparOption.entryCheck(self, event, repair = repair)
Ensure any INDEF entry is uppercase, before base class behavior
entailment
def xyinterp(x,y,xval): """ :Purpose: Interpolates y based on the given xval. x and y are a pair of independent/dependent variable arrays that must be the same length. The x array must also be sorted. xval is a user-specified value. This routine looks up xval in the x array and uses that ...
:Purpose: Interpolates y based on the given xval. x and y are a pair of independent/dependent variable arrays that must be the same length. The x array must also be sorted. xval is a user-specified value. This routine looks up xval in the x array and uses that information to properly interpolate th...
entailment
def _setSampleSizeBytes(self): """ updates the current record of the packet size per sample and the relationship between this and the fifo reads. """ self.sampleSizeBytes = self.getPacketSize() if self.sampleSizeBytes > 0: self.maxBytesPerFifoRead = (32 // self.sampl...
updates the current record of the packet size per sample and the relationship between this and the fifo reads.
entailment
def getPacketSize(self): """ the current packet size. :return: the current packet size based on the enabled registers. """ size = 0 if self.isAccelerometerEnabled(): size += 6 if self.isGyroEnabled(): size += 6 if self.isTemperature...
the current packet size. :return: the current packet size based on the enabled registers.
entailment
def initialiseDevice(self): """ performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return: """ logger.debug("Initialising device") self.getInterruptStatus() self.setAccelerometerSensitivity(se...
performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return:
entailment
def enableAccelerometer(self): """ Specifies the device should write acceleration values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling acceleration sensor") self.fifoSensorMask |= self.enableAccelerometerMask self._acc...
Specifies the device should write acceleration values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def disableAccelerometer(self): """ Specifies the device should NOT write acceleration values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling acceleration sensor") self.fifoSensorMask &= ~self.enableAccelerometerMask ...
Specifies the device should NOT write acceleration values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def enableGyro(self): """ Specifies the device should write gyro values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling gyro sensor") self.fifoSensorMask |= self.enableGyroMask self._gyroEnabled = True self._set...
Specifies the device should write gyro values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def disableGyro(self): """ Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling gyro sensor") self.fifoSensorMask &= ~self.enableGyroMask self._gyroEnabled = False s...
Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def enableTemperature(self): """ Specifies the device should write temperature values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling temperature sensor") self.fifoSensorMask |= self.enableTemperatureMask self._setSampl...
Specifies the device should write temperature values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def disableTemperature(self): """ Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling temperature sensor") self.fifoSensorMask &= ~self.enableTemperatureMask self._s...
Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called. :return:
entailment
def setGyroSensitivity(self, value): """ Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the self tests) :param value: the target sensitivity. """ try: self.i2c_io.write(self.MPU6050_ADDRESS, se...
Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the self tests) :param value: the target sensitivity.
entailment
def setAccelerometerSensitivity(self, value): """ Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if the value provided is not valid. :param value: the target sensitivity. """ # note that this implicitly disables t...
Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if the value provided is not valid. :param value: the target sensitivity.
entailment
def setSampleRate(self, targetSampleRate): """ Sets the internal sample rate of the MPU-6050, this requires writing a value to the device to set the sample rate as Gyroscope Output Rate / (1 + SMPLRT_DIV) where the gryoscope outputs at 8kHz and the peak sampling rate is 1kHz. The target...
Sets the internal sample rate of the MPU-6050, this requires writing a value to the device to set the sample rate as Gyroscope Output Rate / (1 + SMPLRT_DIV) where the gryoscope outputs at 8kHz and the peak sampling rate is 1kHz. The target sample rate is therefore capped at 1kHz. :param target...
entailment
def resetFifo(self): """ Resets the FIFO by first disabling the FIFO then sending a FIFO_RESET and then re-enabling the FIFO. :return: """ logger.debug("Resetting FIFO") self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL, 0b00000000) pass se...
Resets the FIFO by first disabling the FIFO then sending a FIFO_RESET and then re-enabling the FIFO. :return:
entailment
def enableFifo(self): """ Enables the FIFO, resets it and then sets which values should be written to the FIFO. :return: """ logger.debug("Enabling FIFO") self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_EN, 0) self.resetFifo() self.i2c_io.writ...
Enables the FIFO, resets it and then sets which values should be written to the FIFO. :return:
entailment
def getFifoCount(self): """ gets the amount of data available on the FIFO right now. :return: the number of bytes available on the FIFO which will be proportional to the number of samples available based on the values the device is configured to sample. """ bytes = self.i...
gets the amount of data available on the FIFO right now. :return: the number of bytes available on the FIFO which will be proportional to the number of samples available based on the values the device is configured to sample.
entailment
def getDataFromFIFO(self, bytesToRead): """ reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there is new data available (to avoid reading duplicate data). :param bytesToRead: the number of bytes to read. :return: the byte...
reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there is new data available (to avoid reading duplicate data). :param bytesToRead: the number of bytes to read. :return: the bytes read.
entailment
def provideData(self): """ reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read from the device itself. :return: a list of data where each item is a single sample of data converted into real values and stored as a dict. ...
reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read from the device itself. :return: a list of data where each item is a single sample of data converted into real values and stored as a dict.
entailment
def unpackSample(self, rawData): """ unpacks a single sample of data (where sample length is based on the currently enabled sensors). :param rawData: the data to convert :return: a converted data set. """ length = len(rawData) # TODO error if not multiple of 2 ...
unpacks a single sample of data (where sample length is based on the currently enabled sensors). :param rawData: the data to convert :return: a converted data set.
entailment
def wrap(text, width, *args, **kwargs): """ Like :func:`textwrap.wrap` but preserves existing newlines which :func:`textwrap.wrap` does not otherwise handle well. See Also -------- :func:`textwrap.wrap` """ return sum([textwrap.wrap(line, width, *args, **kwargs) if line...
Like :func:`textwrap.wrap` but preserves existing newlines which :func:`textwrap.wrap` does not otherwise handle well. See Also -------- :func:`textwrap.wrap`
entailment
def textbox(text, width=78, boxchar='#', indent=0): """ Outputs line-wrapped text wrapped in a box drawn with a repeated (usually ASCII) character. For example: >>> print(textbox('Text to wrap', width=16)) ################ # # # Text to wrap # # ...
Outputs line-wrapped text wrapped in a box drawn with a repeated (usually ASCII) character. For example: >>> print(textbox('Text to wrap', width=16)) ################ # # # Text to wrap # # # ################ Parameters -------...
entailment
def main(): """Entrypoint function.""" parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', help='Hydro Quebec username') parser.add_argument('-p', '--password', help='Password') parser.add_argument('-j', '--json', action='store_t...
Entrypoint function.
entailment
def easter(year): '''Calculate western easter''' # formula taken from http://aa.usno.navy.mil/faq/docs/easter.html c = trunc(year / 100) n = year - 19 * trunc(year / 19) k = trunc((c - 17) / 25) i = c - trunc(c / 4) - trunc((c - k) / 3) + (19 * n) + 15 i = i - 30 * trunc(i / 30) i = i ...
Calculate western easter
entailment
def independence_day(year, observed=None): '''July 4th''' day = 4 if observed: if calendar.weekday(year, JUL, 4) == SAT: day = 3 if calendar.weekday(year, JUL, 4) == SUN: day = 5 return (year, JUL, day)
July 4th
entailment
def columbus_day(year, country='usa'): '''in USA: 2nd Monday in Oct Elsewhere: Oct 12''' if country == 'usa': return nth_day_of_month(2, MON, OCT, year) else: return (year, OCT, 12)
in USA: 2nd Monday in Oct Elsewhere: Oct 12
entailment
def thanksgiving(year, country='usa'): '''USA: last Thurs. of November, Canada: 2nd Mon. of October''' if country == 'usa': if year in [1940, 1941]: return nth_day_of_month(3, THU, NOV, year) elif year == 1939: return nth_day_of_month(4, THU, NOV, year) else: ...
USA: last Thurs. of November, Canada: 2nd Mon. of October
entailment
def linefit(x, y, weights=None): """ Parameters ---------- y: 1D numpy array The data to be fitted x: 1D numpy array The x values of the y array. x and y must have the same shape. weights: 1D numpy array, must have the same shape as x and y weight values E...
Parameters ---------- y: 1D numpy array The data to be fitted x: 1D numpy array The x values of the y array. x and y must have the same shape. weights: 1D numpy array, must have the same shape as x and y weight values Examples -------- >>> import numpy as N...
entailment
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Analysing ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE) ...
Analyses the measurement with the given parameters :param measurementId: :return:
entailment
def _applyTargetState(targetState, md, httpclient): """ compares the current device state against the targetStateProvider and issues updates as necessary to ensure the device is at that state. :param md: :param targetState: the target state. :param httpclient: the http client :return: ...
compares the current device state against the targetStateProvider and issues updates as necessary to ensure the device is at that state. :param md: :param targetState: the target state. :param httpclient: the http client :return:
entailment
def updateDeviceState(self, device): """ Updates the target state on the specified device. :param targetState: the target state to reach. :param device: the device to update. :return: """ # this is only threadsafe because the targetstate is effectively immutable, ...
Updates the target state on the specified device. :param targetState: the target state to reach. :param device: the device to update. :return:
entailment
def updateTargetState(self, newState): """ Updates the system target state and propagates that to all devices. :param newState: :return: """ self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state) for device in self.deviceContr...
Updates the system target state and propagates that to all devices. :param newState: :return:
entailment
def convert(input, width=132, output=None, keep=False): """Input ASCII trailer file "input" will be read. The contents will then be written out to a FITS file in the same format as used by 'stwfits' from IRAF. Parameters =========== input : str Filename of input ASCII trailer file ...
Input ASCII trailer file "input" will be read. The contents will then be written out to a FITS file in the same format as used by 'stwfits' from IRAF. Parameters =========== input : str Filename of input ASCII trailer file width : int Number of characters wide to use for defin...
entailment
def flatten_errors(cfg, res, levels=None, results=None): """ An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. ...
An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. (This is a recursive function, so you shouldn't use the ``levels`` or...
entailment
def get_extra_values(conf, _prepend=()): """ Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a list of tuples where each tuple represents either an extra section, or an extra value. The tuples contain two values, a tuple represent...
Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a list of tuples where each tuple represents either an extra section, or an extra value. The tuples contain two values, a tuple representing the section the value is in and the name of t...
entailment
def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ # switch off interpolation before we try and fetch anything ! save_interp = self.section.main.interpolation self.section.m...
Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found.
entailment
def pop(self, key, default=MISSING): """ 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' """ try: val = self[key] except KeyError: if default is...
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised'
entailment
def popitem(self): """Pops the first (key,val)""" sequence = (self.scalars + self.sections) if not sequence: raise KeyError(": 'popitem(): dictionary is empty'") key = sequence[0] val = self[key] del self[key] return key, val
Pops the first (key,val)
entailment
def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] ...
A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected
entailment
def items(self): """D.items() -> list of D's (key, value) pairs, as 2-tuples""" return list(zip((self.scalars + self.sections), list(self.values())))
D.items() -> list of D's (key, value) pairs, as 2-tuples
entailment
def dict(self): """ Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() # doctest: +SKIP >>> n == a # doctest: +SKIP 1 ...
Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() # doctest: +SKIP >>> n == a # doctest: +SKIP 1 >>> n is a # doctest: +SKIP ...
entailment
def merge(self, indict): """ A recursive update - useful for merging config files. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ...
A recursive update - useful for merging config files. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ... [section1] ... option1 =...
entailment
def rename(self, oldkey, newkey): """ Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments. """ if oldkey in self.scal...
Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments.
entailment
def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs): """ Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=...
Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you...
entailment
def as_bool(self, key): """ Accepts a key as input. The corresponding value must be a string or the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to retain compatibility with Python 2.2. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ...
Accepts a key as input. The corresponding value must be a string or the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to retain compatibility with Python 2.2. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ``True``. If the string is one ...
entailment
def as_list(self, key): """ A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1]...
A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1] >>> a.as_list('a') [1]
entailment
def restore_default(self, key): """ Restore (and return) default value for the specified key. This method will only work for a ConfigObj that was created with a configspec and has been validated. If there is no default value for this key, ``KeyError`` is raised. """ ...
Restore (and return) default value for the specified key. This method will only work for a ConfigObj that was created with a configspec and has been validated. If there is no default value for this key, ``KeyError`` is raised.
entailment
def restore_defaults(self): """ Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created with a configspec and has been validated. It doesn't delete or modify entries without default values. ""...
Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created with a configspec and has been validated. It doesn't delete or modify entries without default values.
entailment
def _handle_bom(self, infile): """ Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding ...
Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.) If an enc...
entailment
def _decode(self, infile, encoding): """ Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. """ if isinstance(infile, string_types): # can't be unicode # NOTE: Could raise a ``UnicodeDecodeError`` ...
Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list.
entailment
def _decode_element(self, line): """Decode element to unicode if necessary.""" if not self.encoding: return line if isinstance(line, str) and self.default_encoding: return line.decode(self.default_encoding) return line
Decode element to unicode if necessary.
entailment
def _parse(self, infile): """Actually parse the config file.""" temp_list_values = self.list_values if self.unrepr: self.list_values = False comment_list = [] done_start = False this_section = self maxline = len(infile) - 1 cur_index = -1 ...
Actually parse the config file.
entailment
def _match_depth(self, sect, depth): """ Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section. Return a reference to the right section, or raise a SyntaxError. """ while depth < sect.depth:...
Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section. Return a reference to the right section, or raise a SyntaxError.
entailment
def _handle_error(self, text, ErrorClass, infile, cur_index): """ Handle an error according to the error settings. Either raise the error or store it. The error will have occured at ``cur_index`` """ line = infile[cur_index] cur_index += 1 message = text ...
Handle an error according to the error settings. Either raise the error or store it. The error will have occured at ``cur_index``
entailment
def _unquote(self, value): """Return an unquoted version of a value""" if not value: # should only happen during parsing of lists raise SyntaxError if (value[0] == value[-1]) and (value[0] in ('"', "'")): value = value[1:-1] return value
Return an unquoted version of a value
entailment
def _quote(self, value, multiline=True): """ Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. ...
Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. * Recursively quote members of a list and return a comma join...
entailment
def _handle_value(self, value): """ Given a value string, unquote, remove comment, handle lists. (including empty and single member lists) """ if self._inspec: # Parsing a configspec so don't handle comments return (value, '') # do we look for list...
Given a value string, unquote, remove comment, handle lists. (including empty and single member lists)
entailment
def _multiline(self, value, infile, cur_index, maxline): """Extract the value, where we are in a multiline situation.""" quot = value[:3] newvalue = value[3:] single_line = self._triple_quote[quot][0] multi_line = self._triple_quote[quot][1] mat = single_line.match(value)...
Extract the value, where we are in a multiline situation.
entailment
def _handle_configspec(self, configspec): """Parse the configspec.""" # FIXME: Should we check that the configspec was created with the # correct settings ? (i.e. ``list_values=False``) if not isinstance(configspec, ConfigObj): try: configspec = ConfigO...
Parse the configspec.
entailment
def _set_configspec(self, section, copy): """ Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ """ configspec = section.configspec many = configspec.get('__many__') if isinstance(many, dict): ...
Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__
entailment
def _write_line(self, indent_string, entry, this_entry, comment): """Write an individual line, for the write method""" # NOTE: the calls to self._quote here handles non-StringType values. if not self.unrepr: val = self._decode_element(self._quote(this_entry)) else: ...
Write an individual line, for the write method
entailment
def _write_marker(self, indent_string, depth, entry, comment): """Write a section marker line""" return '%s%s%s%s%s' % (indent_string, self._a_to_u('[' * depth), self._quote(self._decode_element(entry), multiline=False), ...
Write a section marker line
entailment
def _handle_comment(self, comment): """Deal with a comment.""" if not comment: return '' start = self.indent_type if not comment.startswith('#'): start += self._a_to_u(' # ') return (start + comment)
Deal with a comment.
entailment
def write(self, outfile=None, section=None): """ Write the current ConfigObj as a file tekNico: FIXME: use StringIO instead of real files >>> filename = a.filename # doctest: +SKIP >>> a.filename = 'test.ini' # doctest: +SKIP >>> a.write() # doctest: +SKIP ...
Write the current ConfigObj as a file tekNico: FIXME: use StringIO instead of real files >>> filename = a.filename # doctest: +SKIP >>> a.filename = 'test.ini' # doctest: +SKIP >>> a.write() # doctest: +SKIP >>> a.filename = filename # doctest: +SKIP >>> a == Con...
entailment
def validate(self, validator, preserve_errors=False, copy=False, section=None): """ Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(...
Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(validator) (Normally having previously passed in the configspec when the ConfigObj was created - you...
entailment
def reset(self): """Clear ConfigObj instance and restore to 'freshly created' state.""" self.clear() self._initialise() # FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload) # requires an empty dictionary self.configspec = None # ...
Clear ConfigObj instance and restore to 'freshly created' state.
entailment
def reload(self): """ Reload a ConfigObj from file. This method raises a ``ReloadError`` if the ConfigObj doesn't have a filename attribute pointing to a file. """ if not isinstance(self.filename, string_types): raise ReloadError() filename = self.fi...
Reload a ConfigObj from file. This method raises a ``ReloadError`` if the ConfigObj doesn't have a filename attribute pointing to a file.
entailment
def check(self, check, member, missing=False): """A dummy check method, always returns the value unchanged.""" if missing: raise self.baseErrorClass() return member
A dummy check method, always returns the value unchanged.
entailment
def _processCommandLineArgs(): """ Get the command line arguments Parameters: NONE Returns: files list of file specifications to be converted outputFileNames list of output file specifications (one per input file) ...
Get the command line arguments Parameters: NONE Returns: files list of file specifications to be converted outputFileNames list of output file specifications (one per input file) Default: a list of None value...
entailment
def _verify(waiveredHdul): """ Verify that the input HDUList is for a waivered FITS file. Parameters: waiveredHdul HDUList object to be verified Returns: None Exceptions: ValueError Input HDUList is not for a waivered FITS file """ if len...
Verify that the input HDUList is for a waivered FITS file. Parameters: waiveredHdul HDUList object to be verified Returns: None Exceptions: ValueError Input HDUList is not for a waivered FITS file
entailment
def toMultiExtensionFits(waiveredObject, multiExtensionFileName=None, forceFileOutput=False, verbose=False): """ Convert the input waivered FITS object to a multi-extension FITS HDUList object. Generate an output multi-exten...
Convert the input waivered FITS object to a multi-extension FITS HDUList object. Generate an output multi-extension FITS file if requested. Parameters: waiveredObject input object representing a waivered FITS file; either a astroyp.io.fits.HDUList object, ...
entailment
def convertwaiveredfits(waiveredObject, outputFileName=None, forceFileOutput=False, convertTo='multiExtension', verbose=False): """ Convert the input waivered FITS object to various formats. The default ...
Convert the input waivered FITS object to various formats. The default conversion format is multi-extension FITS. Generate an output file in the desired format if requested. Parameters: waiveredObject input object representing a waivered FITS file; either...
entailment
def to_jd(year, month, day): '''Determine Julian day from Persian date''' if year >= 0: y = 474 else: y = 473 epbase = year - y epyear = 474 + (epbase % 2820) if month <= 7: m = (month - 1) * 31 else: m = (month - 1) * 30 + 6 return day + m + trunc(((ep...
Determine Julian day from Persian date
entailment
def from_jd(jd): '''Calculate Persian date from Julian day''' jd = trunc(jd) + 0.5 depoch = jd - to_jd(475, 1, 1) cycle = trunc(depoch / 1029983) cyear = (depoch % 1029983) if cyear == 1029982: ycycle = 2820 else: aux1 = trunc(cyear / 366) aux2 = cyear % 366 ...
Calculate Persian date from Julian day
entailment
def setup_global_logging(): """ Initializes capture of stdout/stderr, Python warnings, and exceptions; redirecting them to the loggers for the modules from which they originated. """ global global_logging_started if not PY3K: sys.exc_clear() if global_logging_started: retu...
Initializes capture of stdout/stderr, Python warnings, and exceptions; redirecting them to the loggers for the modules from which they originated.
entailment
def teardown_global_logging(): """Disable global logging of stdio, warnings, and exceptions.""" global global_logging_started if not global_logging_started: return stdout_logger = logging.getLogger(__name__ + '.stdout') stderr_logger = logging.getLogger(__name__ + '.stderr') if sys.std...
Disable global logging of stdio, warnings, and exceptions.
entailment
def create_logger(name, format='%(levelname)s: %(message)s', datefmt=None, stream=None, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate=True): """ Do basic configuration for the logging system. Similar to logging.basicConfig but the logger ``nam...
Do basic configuration for the logging system. Similar to logging.basicConfig but the logger ``name`` is configurable and both a file output and a stream output can be created. Returns a logger object. The default behaviour is to create a logger called ``name`` with a null handled, and to use the "%(le...
entailment
def set_stream(self, stream): """ Set the stream that this logger is meant to replace. Usually this will be either `sys.stdout` or `sys.stderr`, but can be any object with `write()` and `flush()` methods, as supported by `logging.StreamHandler`. """ for handler ...
Set the stream that this logger is meant to replace. Usually this will be either `sys.stdout` or `sys.stderr`, but can be any object with `write()` and `flush()` methods, as supported by `logging.StreamHandler`.
entailment
def write(self, message): """ Buffers each message until a newline is reached. Each complete line is then published to the logging system through ``self.log()``. """ self.__thread_local_ctx.write_count += 1 try: if self.__thread_local_ctx.write_count > 1: ...
Buffers each message until a newline is reached. Each complete line is then published to the logging system through ``self.log()``.
entailment
def find_actual_caller(self): """ Returns the full-qualified module name, full pathname, line number, and function in which `StreamTeeLogger.write()` was called. For example, if this instance is used to replace `sys.stdout`, this will return the location of any print statement. ...
Returns the full-qualified module name, full pathname, line number, and function in which `StreamTeeLogger.write()` was called. For example, if this instance is used to replace `sys.stdout`, this will return the location of any print statement.
entailment
def load(fp): ''' Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a XPORT document) to a Python object. ''' reader = reading.Reader(fp) keys = reader.fields columns = {k: [] for k in keys} for row in reader: for key, value in zip(keys, row): c...
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a XPORT document) to a Python object.
entailment