INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Drops any existing work tables as returned by: meth: ~giraffez. load. TeradataBulkLoad. tables. | def cleanup(self):
"""
Drops any existing work tables, as returned by
:meth:`~giraffez.load.TeradataBulkLoad.tables`.
:raises `giraffez.TeradataPTError`: if a Teradata error ocurred
"""
threads = []
for i, table in enumerate(filter(lambda x: self.mload.exists(x),... |
Finishes the load job. Called automatically when the connection closes. | def finish(self):
"""
Finishes the load job. Called automatically when the connection closes.
:return: The exit code returned when applying rows to the table
"""
if self.finished:
return self.exit_code
checkpoint_status = self.checkpoint()
self.exit_c... |
Load from a file into the target table handling each step of the load process. | def from_file(self, filename, table=None, delimiter='|', null='NULL',
panic=True, quotechar='"', parse_dates=False):
"""
Load from a file into the target table, handling each step of the
load process.
Can load from text files, and properly formatted giraffez archive
... |
Load a single row into the target table. | def put(self, items, panic=True):
"""
Load a single row into the target table.
:param list items: A list of values in the row corresponding to the
fields specified by :code:`self.columns`
:param bool panic: If :code:`True`, when an error is encountered it will be
... |
Attempt release of target mload table. | def release(self):
"""
Attempt release of target mload table.
:raises `giraffez.errors.GiraffeError`: if table was not set by
the constructor, the :code:`TeradataBulkLoad.table`, or
:meth:`~giraffez.load.TeradataBulkLoad.from_file`.
"""
if self.table is N... |
The names of the work tables used for loading. | def tables(self):
"""
The names of the work tables used for loading.
:return: A list of four tables, each the name of the target table
with the added suffixes, "_wt", "_log", "_e1", and "_e2"
:raises `giraffez.errors.GiraffeError`: if table was not set by
the con... |
Monkey - patch compiler to allow for removal of default compiler flags. | def fix_compile(remove_flags):
"""
Monkey-patch compiler to allow for removal of default compiler flags.
"""
import distutils.ccompiler
def _fix_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
... |
Attempts to find the Teradata install directory with the defaults for a given platform. Should always return None when the defaults are not present and the TERADATA_HOME environment variable wasn t explicitly set to the correct install location. | def find_teradata_home():
"""
Attempts to find the Teradata install directory with the defaults
for a given platform. Should always return `None` when the defaults
are not present and the TERADATA_HOME environment variable wasn't
explicitly set to the correct install location.
"""
if platfo... |
Retrieve the decrypted value of a key in a giraffez configuration file. | def get(self, key):
"""
Retrieve the decrypted value of a key in a giraffez
configuration file.
:param str key: The key used to lookup the encrypted value
"""
if not key.startswith("secure.") and not key.startswith("connections."):
key = "secure.{0}".format(k... |
Set a decrypted value by key in a giraffez configuration file. | def set(self, key, value):
"""
Set a decrypted value by key in a giraffez configuration file.
:param str key: The key used to lookup the encrypted value
:param value: Value to set at the given key, can be any value that is
YAML serializeable.
"""
if not key.s... |
Display results in table format | def do_table(self, line):
"""Display results in table format"""
if len(line) > 0:
if line.strip().lower() == "on":
log.write("Table ON")
self.table_output = True
return
elif line.strip().lower() == "off":
log.write("... |
Sets the current encoder output to Python dict and returns the cursor. This makes it possible to set the output encoding and iterate over the results: | def to_dict(self):
"""
Sets the current encoder output to Python `dict` and returns
the cursor. This makes it possible to set the output encoding
and iterate over the results:
.. code-block:: python
with giraffez.Cmd() as cmd:
for row in cmd.execute... |
Set the current encoder output to: class: giraffez. Row objects and returns the cursor. This is the default value so it is not necessary to select this unless the encoder settings have been changed already. | def to_list(self):
"""
Set the current encoder output to :class:`giraffez.Row` objects
and returns the cursor. This is the default value so it is not
necessary to select this unless the encoder settings have been
changed already.
"""
self.conn.set_encoding(ROW_EN... |
Execute commands using CLIv2. | def execute(self, command, coerce_floats=True, parse_dates=False, header=False, sanitize=True,
silent=False, panic=None, multi_statement=False, prepare_only=False):
"""
Execute commands using CLIv2.
:param str command: The SQL command to be executed
:param bool coerce_float... |
Check that object ( table or view ): code: object_name exists by executing a: code: show table object_name query followed by a: code: show view object_name query if: code: object_name is not a table. | def exists(self, object_name, silent=False):
"""
Check that object (table or view) :code:`object_name` exists, by executing a :code:`show table object_name` query,
followed by a :code:`show view object_name` query if :code:`object_name` is not a table.
:param str object_name: The name ... |
Return the column information for: code: table_name by executing a: code: select top 1 * from table_name query. | def fetch_columns(self, table_name, silent=False):
"""
Return the column information for :code:`table_name` by executing a :code:`select top 1 * from table_name` query.
:param str table_name: The fully-qualified name of the table to retrieve schema for
:param bool silent: Silence consol... |
Load a text file into the specified: code: table_name or Insert Python: code: list rows into the specified: code: table_name | def insert(self, table_name, rows, fields=None, delimiter=None, null='NULL', parse_dates=False, quotechar='"'):
"""
Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination ... |
Return a: code: dict of connections from the configuration settings. | def connections(self):
"""
Return a :code:`dict` of connections from the configuration settings.
:raises `giraffez.errors.ConfigurationError`: if connections are not present
"""
if "connections" not in self.settings:
raise ConfigurationError("Could not retrieve conne... |
Retrieve a connection by the given: code: dsn or the default connection. | def get_connection(self, dsn=None):
"""
Retrieve a connection by the given :code:`dsn`, or the default connection.
:param str dsn: The name of the connection to retrieve. Defaults to :code:`None`,
which retrieves the default connection.
:return: A dict of connection settings... |
Retrieve a value from the configuration based on its key. The key may be nested. | def get_value(self, key, default={}, nested=True, decrypt=True):
"""
Retrieve a value from the configuration based on its key. The key
may be nested.
:param str key: A path to the value, with nested levels joined by '.'
:param default: Value to return if the key does not exist (... |
Return the contents of the configuration as a: code: dict. Depending on the structure of the YAML settings the return value may contain nested: code: dict objects. | def list_value(self, decrypt=False):
"""
Return the contents of the configuration as a :code:`dict`. Depending on
the structure of the YAML settings, the return value may contain nested
:code:`dict` objects.
:param bool decrypt: If :code:`True`, decrypt the contents before retur... |
A class method to lock a connection ( given by: code: dsn ) in the specified configuration file. Automatically opens the file and writes to it before closing. | def lock_connection(cls, conf, dsn, key=None):
"""
A class method to lock a connection (given by :code:`dsn`) in the specified
configuration file. Automatically opens the file and writes to it before
closing.
:param str conf: The configuration file to modify
:param str d... |
Set a value within the configuration based on its key. The key may be nested any nested levels that do not exist prior to the final segment of the key path will be created. * Note *: In order to write changes to the file ensure that: meth: ~giraffez. config. Config. write is called prior to exit. | def set_value(self, key, value):
"""
Set a value within the configuration based on its key. The key
may be nested, any nested levels that do not exist prior to the final
segment of the key path will be created.
*Note*: In order to write changes to the file, ensure that
:m... |
A class method to unlock a connection ( given by: code: dsn ) in the specified configuration file. Automatically opens the file and writes to it before closing. | def unlock_connection(cls, conf, dsn, key=None):
"""
A class method to unlock a connection (given by :code:`dsn`) in the specified
configuration file. Automatically opens the file and writes to it before
closing.
:param str conf: The configuration file to modify
:param s... |
Remove a value at the given key -- and any nested values -- from the configuration. * Note *: In order to write changes to the file ensure that: meth: ~giraffez. config. Config. write is called prior to exit. | def unset_value(self, key):
"""
Remove a value at the given key -- and any nested values --
from the configuration.
*Note*: In order to write changes to the file, ensure that
:meth:`~giraffez.config.Config.write` is called prior to exit.
:param str key: A path to the val... |
Save the current configuration to its file ( as given by: code: self. _config_file ). Optionally settings may be passed in to override the current settings before writing. Returns: code: None if the file could not be written to either due to permissions or if the: class: ~giraffez. config. Config object has the: code: ... | def write(self, settings=None):
"""
Save the current configuration to its file (as given by :code:`self._config_file`).
Optionally, settings may be passed in to override the current settings before
writing. Returns :code:`None` if the file could not be written to, either due to
p... |
A class method to write a default configuration file structure to a file. Note that the contents of the file will be overwritten if it already exists. | def write_default(self, conf=None):
"""
A class method to write a default configuration file structure to a file.
Note that the contents of the file will be overwritten if it already exists.
:param str conf: The name of the file to write to. Defaults to :code:`None`, for ~/.girafferc
... |
Retrieve a column from the list with name value: code: column_name | def get(self, column_name):
"""
Retrieve a column from the list with name value :code:`column_name`
:param str column_name: The name of the column to get
:return: :class:`~giraffez.types.Column` with the specified name, or :code:`None` if it does not exist.
"""
column_na... |
Set the names of columns to be used when iterating through the list retrieving names etc. | def set_filter(self, names=None):
"""
Set the names of columns to be used when iterating through the list,
retrieving names, etc.
:param list names: A list of names to be used, or :code:`None` for all
"""
_names = []
if names:
for name in names:
... |
Serializes the columns into the giraffez archive header binary format:: | def serialize(self):
"""
Serializes the columns into the giraffez archive header
binary format::
0 1 2
+------+------+------+------+------+------+------+------+
| Header | Header Data |
| Length | ... |
Deserializes giraffez Archive header. See: meth: ~giraffez. types. Columns. serialize for more information. | def deserialize(cls, data):
"""
Deserializes giraffez Archive header. See
:meth:`~giraffez.types.Columns.serialize` for more information.
:param str data: data in giraffez Archive format, to be deserialized
:return: :class:`~giraffez.types.Columns` object decoded from data
... |
Represents the contents of the row as a: code: dict with the column names as keys and the row s fields as values. | def items(self):
"""
Represents the contents of the row as a :code:`dict` with the column
names as keys, and the row's fields as values.
:rtype: dict
"""
return {k.name: v for k, v in zip(self.columns, self)} |
Set the query to be run and initiate the connection with Teradata. Only necessary if the query/ table name was not specified as an argument to the constructor of the instance. | def query(self, query):
"""
Set the query to be run and initiate the connection with Teradata.
Only necessary if the query/table name was not specified as an argument
to the constructor of the instance.
:param str query: Valid SQL query to be executed
"""
if quer... |
Writes export archive files in the Giraffez archive format. This takes a giraffez. io. Writer and writes archive chunks to file until all rows for a given statement have been exhausted. | def to_archive(self, writer):
"""
Writes export archive files in the Giraffez archive format.
This takes a `giraffez.io.Writer` and writes archive chunks to
file until all rows for a given statement have been exhausted.
.. code-block:: python
with giraffez.BulkExpor... |
Sets the current encoder output to Python str and returns a row iterator. | def to_str(self, delimiter='|', null='NULL'):
"""
Sets the current encoder output to Python `str` and returns
a row iterator.
:param str null: The string representation of null values
:param str delimiter: The string delimiting values in the output
string
:r... |
Convert string with optional k M G T multiplier to float | def float_with_multiplier(string):
"""Convert string with optional k, M, G, T multiplier to float"""
match = re_float_with_multiplier.search(string)
if not match or not match.group('num'):
raise ValueError('String "{}" is not numeric!'.format(string))
num = float(match.group('num'))
multi =... |
Convert string with gains of individual amplification elements to dict | def specific_gains(string):
"""Convert string with gains of individual amplification elements to dict"""
if not string:
return {}
gains = {}
for gain in string.split(','):
amp_name, value = gain.split('=')
gains[amp_name.strip()] = float(value.strip())
return gains |
Convert string with SoapySDR device settings to dict | def device_settings(string):
"""Convert string with SoapySDR device settings to dict"""
if not string:
return {}
settings = {}
for setting in string.split(','):
setting_name, value = setting.split('=')
settings[setting_name.strip()] = value.strip()
return settings |
Wrap text to terminal width with default indentation | def wrap(text, indent=' '):
"""Wrap text to terminal width with default indentation"""
wrapper = textwrap.TextWrapper(
width=int(os.environ.get('COLUMNS', 80)),
initial_indent=indent,
subsequent_indent=indent
)
return '\n'.join(wrapper.wrap(text)) |
Returns detected SoapySDR devices | def detect_devices(soapy_args=''):
"""Returns detected SoapySDR devices"""
devices = simplesoapy.detect_devices(soapy_args, as_string=True)
text = []
text.append('Detected SoapySDR devices:')
if devices:
for i, d in enumerate(devices):
text.append(' {}'.format(d))
else:
... |
Returns info about selected SoapySDR device | def device_info(soapy_args=''):
"""Returns info about selected SoapySDR device"""
text = []
try:
device = simplesoapy.SoapyDevice(soapy_args)
text.append('Selected device: {}'.format(device.hardware))
text.append(' Available RX channels:')
text.append(' {}'.format(', '.jo... |
Setup command line parser | def setup_argument_parser():
"""Setup command line parser"""
# Fix help formatter width
if 'COLUMNS' not in os.environ:
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
parser = argparse.ArgumentParser(
prog='soapy_power',
formatter_class=argparse.RawDescriptionHe... |
Set center frequency and clear averaged PSD data | def set_center_freq(self, center_freq):
"""Set center frequency and clear averaged PSD data"""
psd_state = {
'repeats': 0,
'freq_array': self._base_freq_array + self._lnb_lo + center_freq,
'pwr_array': None,
'update_lock': threading.Lock(),
'fu... |
Return freqs and averaged PSD for given center frequency | def result(self, psd_state):
"""Return freqs and averaged PSD for given center frequency"""
freq_array = numpy.fft.fftshift(psd_state['freq_array'])
pwr_array = numpy.fft.fftshift(psd_state['pwr_array'])
if self._crop_factor:
crop_bins_half = round((self._crop_factor * self.... |
Wait for all PSD threads to finish and return result | def wait_for_result(self, psd_state):
"""Wait for all PSD threads to finish and return result"""
if len(psd_state['futures']) > 1:
concurrent.futures.wait(psd_state['futures'])
elif psd_state['futures']:
psd_state['futures'][0].result()
return self.result(psd_stat... |
Compute PSD from samples and update average for given center frequency | def update(self, psd_state, samples_array):
"""Compute PSD from samples and update average for given center frequency"""
freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins,
window=self._fft_window, noverl... |
Compute PSD from samples and update average for given center frequency ( asynchronously in another thread ) | def update_async(self, psd_state, samples_array):
"""Compute PSD from samples and update average for given center frequency (asynchronously in another thread)"""
future = self._executor.submit(self.update, psd_state, samples_array)
future.add_done_callback(self._release_future_memory)
ps... |
Write PSD of one frequncy hop ( asynchronously in another thread ) | def write_async(self, psd_data_or_future, time_start, time_stop, samples):
"""Write PSD of one frequncy hop (asynchronously in another thread)"""
return self._executor.submit(self.write, psd_data_or_future, time_start, time_stop, samples) |
Read data from file - like object | def read(self, f):
"""Read data from file-like object"""
magic = f.read(len(self.magic))
if not magic:
return None
if magic != self.magic:
raise ValueError('Magic bytes not found! Read data: {}'.format(magic))
header = self.header._make(
self.... |
Write data to file - like object | def write(self, f, time_start, time_stop, start, stop, step, samples, pwr_array):
"""Write data to file-like object"""
f.write(self.magic)
f.write(self.header_struct.pack(
self.version, time_start, time_stop, start, stop, step, samples, pwr_array.nbytes
))
#pwr_array.... |
Write PSD of one frequency hop | def write(self, psd_data_or_future, time_start, time_stop, samples):
"""Write PSD of one frequency hop"""
try:
# Wait for result of future
f_array, pwr_array = psd_data_or_future.result()
except AttributeError:
f_array, pwr_array = psd_data_or_future
... |
Write PSD of one frequency hop | def write(self, psd_data_or_future, time_start, time_stop, samples):
"""Write PSD of one frequency hop"""
try:
# Wait for result of future
f_array, pwr_array = psd_data_or_future.result()
except AttributeError:
f_array, pwr_array = psd_data_or_future
... |
Write PSD of one frequency hop | def write(self, psd_data_or_future, time_start, time_stop, samples):
"""Write PSD of one frequency hop"""
try:
# Wait for result of future
f_array, pwr_array = psd_data_or_future.result()
except AttributeError:
f_array, pwr_array = psd_data_or_future
... |
Submits a callable to be executed with the given arguments. | def submit(self, fn, *args, **kwargs):
"""Submits a callable to be executed with the given arguments.
Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached.
"""
future = super().submit(fn, *args, **kwargs)
work_queue_size = self._work_queue.qsize()
... |
Return nearest number of FFT bins ( even or power of two ) | def nearest_bins(self, bins, even=False, pow2=False):
"""Return nearest number of FFT bins (even or power of two)"""
if pow2:
bins_log2 = math.log(bins, 2)
if bins_log2 % 1 != 0:
bins = 2**math.ceil(bins_log2)
logger.warning('number of FFT bins sho... |
Return nearest overlap/ crop factor based on number of bins | def nearest_overlap(self, overlap, bins):
"""Return nearest overlap/crop factor based on number of bins"""
bins_overlap = overlap * bins
if bins_overlap % 2 != 0:
bins_overlap = math.ceil(bins_overlap / 2) * 2
overlap = bins_overlap / bins
logger.warning('numb... |
Convert integration time to number of repeats | def time_to_repeats(self, bins, integration_time):
"""Convert integration time to number of repeats"""
return math.ceil((self.device.sample_rate * integration_time) / bins) |
Returns list of frequencies for frequency hopping | def freq_plan(self, min_freq, max_freq, bins, overlap=0, quiet=False):
"""Returns list of frequencies for frequency hopping"""
bin_size = self.bins_to_bin_size(bins)
bins_crop = round((1 - overlap) * bins)
sample_rate_crop = (1 - overlap) * self.device.sample_rate
freq_range = m... |
Create buffer for reading samples | def create_buffer(self, bins, repeats, base_buffer_size, max_buffer_size=0):
"""Create buffer for reading samples"""
samples = bins * repeats
buffer_repeats = 1
buffer_size = math.ceil(samples / base_buffer_size) * base_buffer_size
if not max_buffer_size:
# Max buffe... |
Prepare samples buffer and start streaming samples from device | def setup(self, bins, repeats, base_buffer_size=0, max_buffer_size=0, fft_window='hann',
fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None,
lnb_lo=0, tune_delay=0, reset_stream=False, max_threads=0, max_queue_size=0):
"""Prepare samples buffer and start st... |
Stop streaming samples from device and delete samples buffer | def stop(self):
"""Stop streaming samples from device and delete samples buffer"""
if not self.device.is_streaming:
return
self.device.stop_stream()
self._writer.close()
self._bins = None
self._repeats = None
self._base_buffer_size = None
sel... |
Tune to specified center frequency and compute Power Spectral Density | def psd(self, freq):
"""Tune to specified center frequency and compute Power Spectral Density"""
if not self.device.is_streaming:
raise RuntimeError('Streaming is not initialized, you must run setup() first!')
# Tune to new frequency in main thread
logger.debug(' Frequency ... |
Sweep spectrum using frequency hopping | def sweep(self, min_freq, max_freq, bins, repeats, runs=0, time_limit=0, overlap=0,
fft_window='hann', fft_overlap=0.5, crop=False, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0,
tune_delay=0, reset_stream=False, base_buffer_size=0, max_buffer_size=0, max_threads=0, max_queue_size=... |
close () | def close(self):
"""close()
Disconnects the object from the bus.
"""
os.close(self._fd)
self._fd = -1
self._addr = -1
self._pec = 0 |
open ( bus ) | def open(self, bus):
"""open(bus)
Connects the object to the specified SMBus.
"""
bus = int(bus)
path = "/dev/i2c-%d" % (bus,)
if len(path) >= MAXPATH:
raise OverflowError("Bus number is invalid.")
try:
self._fd = os.open(path, os.O_RD... |
private helper method | def _set_addr(self, addr):
"""private helper method"""
if self._addr != addr:
ioctl(self._fd, SMBUS.I2C_SLAVE, addr)
self._addr = addr |
write_quick ( addr ) | def write_quick(self, addr):
"""write_quick(addr)
Perform SMBus Quick transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_quick(self._fd, SMBUS.I2C_SMBUS_WRITE) != 0:
raise IOError(ffi.errno) |
read_byte ( addr ) - > result | def read_byte(self, addr):
"""read_byte(addr) -> result
Perform SMBus Read Byte transaction.
"""
self._set_addr(addr)
result = SMBUS.i2c_smbus_read_byte(self._fd)
if result == -1:
raise IOError(ffi.errno)
return result |
write_byte ( addr val ) | def write_byte(self, addr, val):
"""write_byte(addr, val)
Perform SMBus Write Byte transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_byte(self._fd, ffi.cast("__u8", val)) == -1:
raise IOError(ffi.errno) |
read_byte_data ( addr cmd ) - > result | def read_byte_data(self, addr, cmd):
"""read_byte_data(addr, cmd) -> result
Perform SMBus Read Byte Data transaction.
"""
self._set_addr(addr)
res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast("__u8", cmd))
if res == -1:
raise IOError(ffi.errno)
... |
write_byte_data ( addr cmd val ) | def write_byte_data(self, addr, cmd, val):
"""write_byte_data(addr, cmd, val)
Perform SMBus Write Byte Data transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_byte_data(self._fd,
ffi.cast("__u8", cmd),
... |
read_word_data ( addr cmd ) - > result | def read_word_data(self, addr, cmd):
"""read_word_data(addr, cmd) -> result
Perform SMBus Read Word Data transaction.
"""
self._set_addr(addr)
result = SMBUS.i2c_smbus_read_word_data(self._fd, ffi.cast("__u8", cmd))
if result == -1:
raise IOError(ffi.errno)
... |
write_word_data ( addr cmd val ) | def write_word_data(self, addr, cmd, val):
"""write_word_data(addr, cmd, val)
Perform SMBus Write Word Data transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_word_data(self._fd,
ffi.cast("__u8", cmd),
... |
process_call ( addr cmd val ) | def process_call(self, addr, cmd, val):
"""process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = False on the SMBus in... |
read_block_data ( addr cmd ) - > results | def read_block_data(self, addr, cmd):
"""read_block_data(addr, cmd) -> results
Perform SMBus Read Block Data transaction.
"""
# XXX untested, the raspberry pi i2c driver does not support this
# command
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")... |
write_block_data ( addr cmd vals ) | def write_block_data(self, addr, cmd, vals):
"""write_block_data(addr, cmd, vals)
Perform SMBus Write Block Data transaction.
"""
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")
list_to_smbus_data(data, vals)
if SMBUS.i2c_smbus_access(self._fd,
... |
block_process_call ( addr cmd vals ) - > results | def block_process_call(self, addr, cmd, vals):
"""block_process_call(addr, cmd, vals) -> results
Perform SMBus Block Process Call transaction.
"""
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")
list_to_smbus_data(data, vals)
if SMBUS.i2c_smbus_acce... |
read_i2c_block_data ( addr cmd len = 32 ) - > results | def read_i2c_block_data(self, addr, cmd, len=32):
"""read_i2c_block_data(addr, cmd, len=32) -> results
Perform I2C Block Read transaction.
"""
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")
data.block[0] = len
if len == 32:
arg = SMBUS.... |
True if Packet Error Codes ( PEC ) are enabled | def pec(self, value):
"""True if Packet Error Codes (PEC) are enabled"""
pec = bool(value)
if pec != self._pec:
if ioctl(self._fd, SMBUS.I2C_PEC, pec):
raise IOError(ffi.errno)
self._pec = pec |
Forcing to run cmake | def run_cmake(arg=""):
"""
Forcing to run cmake
"""
if ds.find_executable('cmake') is None:
print "CMake is required to build zql"
print "Please install cmake version >= 2.8 and re-run setup"
sys.exit(-1)
print "Configuring zql build with CMake.... "
cmake_args = arg
... |
Return the starting datetime: number of units before now. | def start(cls, now, number, **options):
"""
Return the starting datetime: ``number`` of units before ``now``.
"""
return (cls.mask(now, **options) -
timedelta(**{cls.__name__.lower(): number - 1})) |
Return a set of datetimes after filtering datetimes. | def filter(cls, datetimes, number, now=None, **options):
"""Return a set of datetimes, after filtering ``datetimes``.
The result will be the ``datetimes`` which are ``number`` of
units before ``now``, until ``now``, with approximately one
unit between each of them. The first datetime f... |
Return a datetime with the same value as dt to a resolution of days. | def mask(cls, dt, **options):
"""
Return a datetime with the same value as ``dt``, to a
resolution of days.
"""
return dt.replace(hour=0, minute=0, second=0, microsecond=0) |
Return the starting datetime: number of weeks before now. | def start(cls, now, number, firstweekday=calendar.SATURDAY, **options):
"""
Return the starting datetime: ``number`` of weeks before ``now``.
``firstweekday`` determines when the week starts. It defaults
to Saturday.
"""
week = cls.mask(now, firstweekday=firstweekday, **... |
Return a datetime with the same value as dt to a resolution of weeks. | def mask(cls, dt, firstweekday=calendar.SATURDAY, **options):
"""
Return a datetime with the same value as ``dt``, to a
resolution of weeks.
``firstweekday`` determines when the week starts. It defaults
to Saturday.
"""
correction = (dt.weekday() - firstweekday) ... |
Return the starting datetime: number of months before now. | def start(cls, now, number, **options):
"""
Return the starting datetime: ``number`` of months before ``now``.
"""
year = now.year
month = now.month - number + 1
# Handle negative months
if month < 0:
year = year + (month // cls.MONTHS_IN_YEAR)
... |
Return the starting datetime: number of years before now. | def start(cls, now, number, **options):
"""
Return the starting datetime: ``number`` of years before ``now``.
"""
return cls.mask(now).replace(year=(now.year - number + 1)) |
Return a set of datetimes that should be kept out of datetimes. | def to_keep(datetimes,
years=0, months=0, weeks=0, days=0,
hours=0, minutes=0, seconds=0,
firstweekday=SATURDAY, now=None):
"""
Return a set of datetimes that should be kept, out of ``datetimes``.
Keeps up to ``years``, ``months``, ``weeks``, ``days``,
``hours``, ``m... |
Return a set of datetimes that should be deleted out of datetimes. | def to_delete(datetimes,
years=0, months=0, weeks=0, days=0,
hours=0, minutes=0, seconds=0,
firstweekday=SATURDAY, now=None):
"""
Return a set of datetimes that should be deleted, out of ``datetimes``.
See ``to_keep`` for a description of arguments.
"""
dat... |
Return a set of dates that should be kept out of dates. | def dates_to_keep(dates,
years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY,
now=None):
"""
Return a set of dates that should be kept, out of ``dates``.
See ``to_keep`` for a description of arguments.
"""
datetimes = to_keep((datetime.combine(d, time()) fo... |
Return a set of date that should be deleted out of dates. | def dates_to_delete(dates,
years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY,
now=None):
"""
Return a set of date that should be deleted, out of ``dates``.
See ``to_keep`` for a description of arguments.
"""
dates = set(dates)
return dates - dates... |
Returns an SPI control byte. | def _get_spi_control_byte(self, read_write_cmd):
"""Returns an SPI control byte.
The MCP23S17 is a slave SPI device. The slave address contains
four fixed bits and three user-defined hardware address bits
(if enabled via IOCON.HAEN) (pins A2, A1 and A0) with the
read/write bit f... |
Returns the bit specified from the address. | def read_bit(self, bit_num, address):
"""Returns the bit specified from the address.
:param bit_num: The bit number to read from.
:type bit_num: int
:param address: The address to read from.
:type address: int
:returns: int -- the bit value from the address
"""
... |
Writes the value given to the bit in the address specified. | def write_bit(self, value, bit_num, address):
"""Writes the value given to the bit in the address specified.
:param value: The value to write.
:type value: int
:param bit_num: The bit number to write to.
:type bit_num: int
:param address: The address to write to.
... |
Returns the lowest bit num from a given bit pattern. Returns None if no bits set. | def get_bit_num(bit_pattern):
"""Returns the lowest bit num from a given bit pattern. Returns None if no
bits set.
:param bit_pattern: The bit pattern.
:type bit_pattern: int
:returns: int -- the bit number
:returns: None -- no bits set
>>> pifacecommon.core.get_bit_num(0)
None
>>>... |
Waits for a port event. When a port event occurs it is placed onto the event queue. | def watch_port_events(port, chip, pin_function_maps, event_queue,
return_after_kbdint=False):
"""Waits for a port event. When a port event occurs it is placed onto the
event queue.
:param port: The port we are waiting for interrupts on (GPIOA/GPIOB).
:type port: int
:param chi... |
Waits for events on the event queue and calls the registered functions. | def handle_events(
function_maps, event_queue, event_matches_function_map,
terminate_signal):
"""Waits for events on the event queue and calls the registered functions.
:param function_maps: A list of classes that have inheritted from
:class:`FunctionMap`\ s describing what to do with e... |
Bring the interrupt pin on the GPIO into Linux userspace. | def bring_gpio_interrupt_into_userspace(): # activate gpio interrupt
"""Bring the interrupt pin on the GPIO into Linux userspace."""
try:
# is it already there?
with open(GPIO_INTERRUPT_DEVICE_VALUE):
return
except IOError:
# no, bring it into userspace
with open... |
Set the interrupt edge on the userspace GPIO pin. | def set_gpio_interrupt_edge(edge='falling'):
"""Set the interrupt edge on the userspace GPIO pin.
:param edge: The interrupt edge ('none', 'falling', 'rising').
:type edge: string
"""
# we're only interested in the falling edge (1 -> 0)
start_time = time.time()
time_limit = start_time + FIL... |
Wait until a file exists. | def wait_until_file_exists(filename):
"""Wait until a file exists.
:param filename: The name of the file to wait for.
:type filename: string
"""
start_time = time.time()
time_limit = start_time + FILE_IO_TIMEOUT
while time.time() < time_limit:
try:
with open(filename):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.