text stringlengths 81 112k |
|---|
Invoke the `UpdateItem`_ function.
Edits an existing item's attributes, or adds a new item to the table
if it does not already exist. You can put, delete, or add attribute
values. You can also perform a conditional update on an existing item
(insert a new attribute name-value pair if it... |
A `Query`_ operation uses the primary key of a table or a secondary
index to directly access items from that table or index.
:param str table_name: The name of the table containing the requested
items.
:param bool consistent_read: Determines the read consistency model: If
... |
The `Scan`_ operation returns one or more items and item attributes
by accessing every item in a table or a secondary index.
If the total number of scanned items exceeds the maximum data set size
limit of 1 MB, the scan stops and results are returned to the user as a
``LastEvaluatedKey`... |
Execute a DynamoDB action with the given parameters. The method will
retry requests that failed due to OS level errors or when being
throttled by DynamoDB.
:param str action: DynamoDB action to invoke
:param dict parameters: parameters to send into the action
:rtype: tornado.con... |
Assign a method to invoke when a request has encountered an
unrecoverable error in an action execution.
:param method callback: The method to invoke
def set_error_callback(self, callback):
"""Assign a method to invoke when a request has encountered an
unrecoverable error in an action e... |
Assign a method to invoke when a request has completed gathering
measurements.
:param method callback: The method to invoke
def set_instrumentation_callback(self, callback):
"""Assign a method to invoke when a request has completed gathering
measurements.
:param method callbac... |
Invoke a DynamoDB action
:param str action: DynamoDB action to invoke
:param dict parameters: parameters to send into the action
:param int attempt: Which attempt number this is
:param list measurements: A list for accumulating request measurements
:rtype: tornado.concurrent.Fut... |
Invoked when the HTTP request to the DynamoDB has returned and
is responsible for setting the future result or exception based upon
the HTTP response provided.
:param str action: The action that was taken
:param str table: The table name the action was made against
:param int at... |
Process the raw AWS response, returning either the mapped exception
or deserialized response.
:param tornado.concurrent.Future response: The request future
:rtype: dict or list
:raises: sprockets_dynamodb.exceptions.DynamoDBException
def _process_response(response):
"""Process... |
Write and obj in bdb.
:param obj: value to be written in bdb.
:param resource_id: id to make possible read and search for an resource.
:return: id of the transaction
def write(self, obj, resource_id=None):
"""Write and obj in bdb.
:param obj: value to be written in bdb.
... |
Read and obj in bdb using the tx_id.
:param resource_id: id of the transaction to be read.
:return: value with the data, transaction id and transaction.
def _get(self, tx_id):
"""Read and obj in bdb using the tx_id.
:param resource_id: id of the transaction to be read.
:return... |
Update and obj in bdb using the tx_id.
:param metadata: new metadata for the transaction.
:param tx_id: id of the transaction to be updated.
:return: id of the transaction.
def _update(self, metadata, tx_id, resource_id):
"""Update and obj in bdb using the tx_id.
:param metada... |
List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions.
def list(self, search_from=None, search_to=None, limit=None):
"""List all ... |
List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions.
def _list(self):
"""List all the objects saved in the namespace.
:para... |
Query to bdb namespace.
:param query_string: query in string format.
:return: list of transactions that match with the query.
def query(self, search_model: QueryModel):
"""Query to bdb namespace.
:param query_string: query in string format.
:return: list of transactions that m... |
Delete a transaction. Read documentation about CRAB model in https://blog.bigchaindb.com/crab-create-retrieve-append-burn-b9f6d111f460.
:param tx_id: transaction id
:return:
def _delete(self, tx_id):
"""Delete a transaction. Read documentation about CRAB model in https://blog.bigchaindb.com/cr... |
Return the tx_id of the first transaction.
:param tx_id: Transaction id to start the recursive search.
:return Transaction id parent.
def get_asset_id(self, tx_id):
"""Return the tx_id of the first transaction.
:param tx_id: Transaction id to start the recursive search.
:retur... |
write ENVI header files
Parameters
----------
data: str or dict
the file or dictionary to get the info from
filename: str
the HDR file to write
Returns
-------
def hdr(data, filename):
"""
write ENVI header files
Parameters
----------
data: str or dict
... |
read a HDR file into a dictionary
http://gis.stackexchange.com/questions/48618/how-to-read-write-envi-metadata-using-gdal
Returns
-------
dict
the hdr file metadata attributes
def __hdr2dict(self):
"""
read a HDR file into a dictionary
http://gis.stac... |
write object to an ENVI header file
def write(self, filename='same'):
"""
write object to an ENVI header file
"""
if filename == 'same':
filename = self.filename
if not filename.endswith('.hdr'):
filename += '.hdr'
with open(filename, 'w') as out:... |
Setup of maximum speed
def MaxSpeed(self, speed):
' Setup of maximum speed '
spi.SPI_write_byte(self.CS, 0x07) # Max Speed setup
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed) |
Go to Zero position
def GoZero(self, speed):
' Go to Zero position '
self.ReleaseSW()
spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed)
while self.IsBusy():
pass
... |
Move some distance units from current position
def Move(self, units):
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write_byte(self.CS, 0x40... |
Report given status bit
def ReadStatusBit(self, bit):
' Report given status bit '
spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS)
spi.SPI_write_byte(self.CS, 0x00)
data0 = spi.SPI_read_byte() # 1st byte
spi.SPI_write_byte(self.CS, 0x00)
da... |
Writes a data to a SPI device selected by chipselect bit.
def SPI_write_byte(self, chip_select, data):
'Writes a data to a SPI device selected by chipselect bit. '
self.bus.write_byte_data(self.address, chip_select, data) |
Writes data to SPI device selected by chipselect bit.
def SPI_write(self, chip_select, data):
'Writes data to SPI device selected by chipselect bit. '
dat = list(data)
dat.insert(0, chip_select)
return self.bus.write_i2c_block(self.address, dat); |
Configure SPI interface parameters.
def SPI_config(self,config):
'Configure SPI interface parameters.'
self.bus.write_byte_data(self.address, 0xF0, config)
return self.bus.read_byte_data(self.address, 0xF0) |
Reads logic state on GPIO enabled slave-selects pins.
def GPIO_read(self):
'Reads logic state on GPIO enabled slave-selects pins.'
self.bus.write_byte_data(self.address, 0xF5, 0x0f)
status = self.bus.read_byte(self.address)
bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status... |
Enable or disable slave-select pins as gpio.
def GPIO_config(self, gpio_enable, gpio_config):
'Enable or disable slave-select pins as gpio.'
self.bus.write_byte_data(self.address, 0xF6, gpio_enable)
self.bus.write_byte_data(self.address, 0xF7, gpio_config)
return |
Returns sensors I2C address.
def get_address(self):
"""
Returns sensors I2C address.
"""
LOGGER.debug("Reading RPS01A sensor's address.",)
return self.bus.read_byte_data(self.address, self.address_reg) |
Returns programmed zero position in OTP memory.
def get_zero_position(self):
"""
Returns programmed zero position in OTP memory.
"""
LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB)
MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB)
D... |
Returns sensor's Automatic Gain Control actual value.
0 - Represents high magtetic field
0xFF - Represents low magnetic field
def get_agc_value(self):
"""
Returns sensor's Automatic Gain Control actual value.
0 - Represents high magtetic field
0xFF... |
Reads diagnostic data from the sensor.
OCF (Offset Compensation Finished) - logic high indicates the finished Offset Compensation Algorithm. After power up the flag remains always to logic high.
COF (Cordic Overflow) - logic high indicates an out of range error in the CORDIC part. When this bit is set,... |
Retuns measured angle in degrees in range 0-360.
def get_angle(self, verify = False):
"""
Retuns measured angle in degrees in range 0-360.
"""
LSB = self.bus.read_byte_data(self.address, self.angle_LSB)
MSB = self.bus.read_byte_data(self.address, self.angle_MSB)
DATA = (... |
Annotating BED file based on reference features annotations.
def main(input_bed, output_file, output_features=False, genome=None,
only_canonical=False, short=False, extended=False, high_confidence=False,
ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False... |
% of Full Charge
def StateOfCharge(self):
""" % of Full Charge """
return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) |
Get cells chemistry
def Chemistry(self):
''' Get cells chemistry '''
length = self.bus.read_byte_data(self.address, 0x79)
chem = []
for n in range(length):
chem.append(self.bus.read_byte_data(self.address, 0x7A + n))
return chem |
r"""(slow) 2D reconstruction with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,z)`
by a dielectric object with refractive index
:math:`n(x,z)`.
This function implements the solution... |
r"""2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,z)`
by a dielectric object with refractive index
:math:`n(x,z)`.
This method implements the 2D backpropagati... |
triangles.
Colors:
- http://paletton.com/#uid=70l150klllletuehUpNoMgTsdcs shade 2
def color(x, y):
"""triangles.
Colors:
- http://paletton.com/#uid=70l150klllletuehUpNoMgTsdcs shade 2
"""
if (x-4) > (y-4) and -(y-4) <= (x-4):
# right
return "#CDB95B"
elif (x-4) > (y-4... |
Reads data from desired register only once.
def single_read(self, register):
'''
Reads data from desired register only once.
'''
comm_reg = (0b00010 << 3) + register
if register == self.AD7730_STATUS_REG:
bytes_num = 1
elif register == self.AD7730_... |
RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet
STDY - Steady Bit. This bit is updated when the filter writes a result to the Data... |
def setMode(self
,mode = self.AD7730_IDLE_MODE
,polarity = self.AD7730_UNIPOLAR_MODE
,den = self.AD7730_IODISABLE_MODE
,iovalue = 0b00
,data_lenght = self.AD7730_24bitDATA_MODE
,reference = self.AD77... |
get N random headers from a fastq file without reading the
whole thing into memory
modified from: http://www.biostars.org/p/6544/
def downsample(work_dir, sample_name, fastq_left_fpath, fastq_right_fpath, downsample_to, num_pairs=None):
""" get N random headers from a fastq file without reading the
who... |
The physical value RH given above corresponds to the
relative humidity above liquid water according to World
Meteorological Organization (WMO)
def get_hum(self, raw = False):
"""
The physical value RH given above corresponds to the
relative humidity above liquid water according ... |
4.12 Checksum Calculation from an unsigned short input
def _calculate_checksum(value):
"""4.12 Checksum Calculation from an unsigned short input"""
# CRC
polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001
crc = 0xFF
# calculates 8-Bit checksum with given polynomial
... |
Run when button is pressed.
def run(self):
"""Run when button is pressed."""
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:... |
Decorator for action handlers.
The action name is inferred from the function name.
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded.
def on(f):
"""Decorator for action handlers.
The action name is inferred from the function name.
... |
Decorator for action handlers.
:param str action: explicit action name
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded.
def on_action(action):
"""Decorator for action handlers.
:param str action: explicit action name
This also ... |
Initialize datastores for this analysis instance.
This creates instances of :class:`.Datastore` at ``data`` and
``class_data`` with the datastore domains being the current id
and the class name of this analysis respectively.
Overwrite this method to use other datastore backends.
def i... |
Emit a signal to the frontend.
:param str signal: name of the signal
:param message: message to send
:returns: return value from frontend emit function
:rtype: tornado.concurrent.Future
def emit(self, signal, message='__nomessagetoken__'):
"""Emit a signal to the frontend.
... |
Set value at position i and return a Future.
:rtype: tornado.concurrent.Future
def set(self, i, value):
"""Set value at position i and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(i))
if i in self.data an... |
Set a value at key and return a Future.
:rtype: tornado.concurrent.Future
def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and se... |
Update.
def update(self, new_data):
"""Update."""
for k, v in new_data.items():
self[k] = v
return self |
Trigger all callbacks that were set with on_change().
def trigger_all_change_callbacks(self):
"""Trigger all callbacks that were set with on_change()."""
return [
ret
for key in DatastoreLegacy.store[self.domain].keys()
for ret in self.trigger_change_callbacks(key)
... |
Set value at key and return a Future
:rtype: tornado.concurrent.Future
def set(self, key, value):
"""Set value at key and return a Future
:rtype: tornado.concurrent.Future
"""
return DatastoreLegacy.store[self.domain].set(key, value) |
Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
def init(self, key_value_pairs):
"""Initialize datastore.
Only sets values for keys that are no... |
Close and delete instance.
def close(self):
"""Close and delete instance."""
# remove callbacks
DatastoreLegacy.datastores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and \
not DatastoreLegacy.datastores[self.domai... |
Recursively add the current index (with respect to a repeated section) in all
data dictionaries.
def AddIndex(node, index=None):
"""
Recursively add the current index (with respect to a repeated section) in all
data dictionaries.
"""
if isinstance(node, list):
for i, item in enumerate(node):
AddI... |
Renerate documentation when it changes.
def watch():
"""Renerate documentation when it changes."""
# Start with a clean build
sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG
handler = ShellCommandTrick(
shell_command='sphinx-build -b html docs docs/_build/html',
patt... |
Generate html and dirhtml output.
def gen(skipdirhtml=False):
"""Generate html and dirhtml output."""
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_buil... |
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice p... |
set up the vertical profile plot
Returns
-------
def __init_vertical_plot(self):
"""
set up the vertical profile plot
Returns
-------
"""
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cl... |
respond to mouse clicks in the plot.
This function responds to clicks on the first (horizontal slice) plot and updates the vertical profile and
slice plots
Parameters
----------
event: matplotlib.backend_bases.MouseEvent
the click event object containing image coordi... |
Returns a *function* suitable for passing as the more_formatters argument
to Template.
NOTE: In Java, this would be implemented using the 'Composite' pattern. A
*list* of formatter lookup function behaves the same as a *single* formatter
lookup funcion.
Note the distinction between formatter *lookup* funct... |
Use Python % format strings as template format specifiers.
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None |
Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too.
def Plural(format_str):
"""Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than o... |
Returns all CDS merged, used:
- for TargQC general reports CDS coverage statistics for WGS
- for Seq2C CNV calling when no capture BED available
def get_merged_cds(genome):
"""
Returns all CDS merged, used:
- for TargQC general reports CDS coverage statistics for WGS
- for Seq2C CNV calling whe... |
:param relative_path: relative path of the file inside the repository
:param genome: genome name. Can contain chromosome name after comma, like hg19-chr20,
in case of BED, the returning BedTool will be with added filter.
:return: BedTools object if it's a BED file, or filepath
def _get(relat... |
Run the provided command, logging details and checking for errors.
def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
stdout_tx=True, reuse=False, env_vars=None):
"""Run the provided command, logging details and checking for errors.
"""
if output_fpath and reu... |
fixing java.lang.Double.parseDouble error on entries like "6,082.49"
def _correct_qualimap_genome_results(samples):
""" fixing java.lang.Double.parseDouble error on entries like "6,082.49"
"""
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = Fals... |
replacing Qualimap insert size histogram with Picard one.
def _correct_qualimap_insert_size_histogram(work_dir, samples):
""" replacing Qualimap insert size histogram with Picard one.
"""
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport'... |
Normalize the length of a vector to one
def norm_vec(vector):
"""Normalize the length of a vector to one"""
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) |
Rotate all points of a list, such that `axis==[0,1,0]`
This is accomplished by rotating in the x-z-plane by phi into the
y-z-plane, then rotation in the y-z-plane by theta up to [0,1,0],
and finally rotating back in the x-z-plane by -phi.
Parameters
----------
points: list-like with elements o... |
Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for the correct 3D orientation
of the backpropagated projection... |
Compute rotation matrix to go from [0,0,1] to `point`,
while taking into account the tilted axis of rotation.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for the ... |
For a given tilt of the rotational axis `tilted_axis`, compute
the points on a unit sphere that correspond to the distribution
`angles` along the great circle about this axis.
Parameters
----------
angles: 1d ndarray
The angles that will be distributed on the great circle.
tilted_axis: ... |
r"""3D backpropagation with a tilted axis of rotation
Three-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,y,z)`
by a dielectric object with refractive index
:math:`n(x,y,z)`.
This method implements the 3D backpropagati... |
Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
returns: ['A','B']
AA.BB.foo.txt
CC.foo.... |
Executes an process in the analysis with the given message.
It also handles the start and stop signals in case a process_id
is given.
def run_process(self, analysis, action_name, message='__nomessagetoken__'):
"""Executes an process in the analysis with the given message.
It also hand... |
Check git to avoid overwriting user changes.
def check_git_unchanged(filename, yes=False):
"""Check git to avoid overwriting user changes."""
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
retur... |
Check if there are 'changes to be committed' in the index.
def check_staged(filename=None):
"""Check if there are 'changes to be committed' in the index."""
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
... |
Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to trigger.
:param message: Message.
:param callback:
A... |
Download `url` to `dest`
def dl_file(url, dest, chunk_size=6553):
"""Download `url` to `dest`"""
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data... |
Extract an lzma file and return the temporary file name
def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpna... |
Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full p... |
Load example data
def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) |
Load example sinogram data from a .tar.lzma file
def load_tar_lzma_data(tlfile):
"""Load example sinogram data from a .tar.lzma file"""
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
... |
Load example sinogram data from a .zip file
def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None):
"""Load example sinogram data from a .zip file"""
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(arc.open(f_sin... |
r"""2D Fourier mapping with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,z)`
by a dielectric object with refractive index
:math:`n(x,z)`.
This function implements the solution by in... |
Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:... |
Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. This also memoizes the output file... |
Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
def chdir(new_dir):
"""Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
"""
... |
Check if a file exists, is non-empty and is more recent than cmp_fname.
def file_uptodate(fname, cmp_fname):
"""Check if a file exists, is non-empty and is more recent than cmp_fname.
"""
try:
return (file_exists(fname) and file_exists(cmp_fname) and
getmtime(fname) >= getmtime(cmp_... |
Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message.
def save_diskspace(fname, reason, config):
"""Overwrite a file in place with a short message to save disk.
This keeps files as a... |
Create relative symlinks and handle associated biological index files.
def symlink_plus(orig, new):
"""Create relative symlinks and handle associated biological index files.
"""
for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]:
if os.path.exists(orig + ext) and not os.path.lexists(new + ext):
... |
Use a predicate to partition entries into false entries and true entries
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
try:
return itertools... |
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
e... |
returns the path to an executable or None if it can't be found
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
... |
Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing.
def expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.