code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
print('pynYNAB CSV import')
args = self.parser.parse_args()
verify_common_args(args)
verify_csvimport(args.schema, args.accountname)
client = clientfromkwargs(**args)
delta = do_csvimport(args, client)
client.push(expected_delta=delta) | def command(self) | Manually import a CSV into a nYNAB budget | 13.079678 | 11.176918 | 1.17024 |
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) | def command(self) | Manually import an OFX into a nYNAB budget | 15.010623 | 11.324001 | 1.325558 |
@event.listens_for(col_attr, "init_scalar", retval=True, propagate=True)
def init_scalar(target, value, dict_):
if default.is_callable:
# the callable of ColumnDefault always accepts a context argument
value = default.arg(None)
elif default.is_scalar:
v... | def default_listener(col_attr, default) | Establish a default-setting listener. | 7.084238 | 7.116814 | 0.995423 |
if os.path.exists(self.git_dir + os.sep + '.coverage'):
try:
with open(self.git_dir + os.sep + '.coverage', 'r') as f:
blob = f.read()
blob = blob.split('!')[2]
json.loads(blob)
return True
... | def has_coverage(self) | Returns a boolean for is a parseable .coverage file can be found in the repository
:return: bool | 3.180589 | 2.797918 | 1.13677 |
if not self.has_coverage():
return DataFrame(columns=['filename', 'lines_covered', 'total_lines', 'coverage'])
with open(self.git_dir + os.sep + '.coverage', 'r') as f:
blob = f.read()
blob = blob.split('!')[2]
cov = json.loads(blob)
ds... | def coverage(self) | If there is a .coverage file available, this will attempt to form a DataFrame with that information in it, which
will contain the columns:
* filename
* lines_covered
* total_lines
* coverage
If it can't be found or parsed, an empty DataFrame of that form will be ret... | 2.690665 | 2.384635 | 1.128334 |
max_diff_in_minutes = grouping_window * 60.0
first_commit_addition_in_minutes = single_commit_hours * 60.0
# First get the commit history
ch = self.commit_history(branch=branch, limit=limit, days=days, ignore_globs=ignore_globs,
include_globs=i... | def hours_estimate(self, branch='master', grouping_window=0.5, single_commit_hours=0.5, limit=None, days=None,
committer=True, ignore_globs=None, include_globs=None) | inspired by: https://github.com/kimmobrunfeldt/git-hours/blob/8aaeee237cb9d9028e7a2592a25ad8468b1f45e4/index.js#L114-L143
Iterates through the commit history of repo to estimate the time commitement of each author or committer over
the course of time indicated by limit/extensions/days/etc.
:pa... | 2.85678 | 2.892735 | 0.987571 |
# setup the dataset of commits
if limit is None:
if days is None:
ds = [[
x.author.name,
x.committer.name,
x.committed_date,
x.message,
... | def file_change_history(self, branch='master', limit=None, days=None, ignore_globs=None, include_globs=None) | Returns a DataFrame of all file changes (via the commit history) for the specified branch. This is similar to
the commit history DataFrame, but is one row per file edit rather than one row per commit (which may encapsulate
many file changes). Included in the DataFrame will be the columns:
* d... | 2.073111 | 2.0707 | 1.001164 |
if include_globs is None or include_globs == []:
include_globs = ['*']
out = {}
for key in files.keys():
# count up the number of patterns in the ignore globs list that match
if ignore_globs is not None:
count_exclude = sum([1 if fnm... | def __check_extension(files, ignore_globs=None, include_globs=None) | Internal method to filter a list of file changes by extension and ignore_dirs.
:param files:
:param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir)
:param include_globs: a list of globs to include (if none, includes all).
:return: dict | 2.574832 | 2.588376 | 0.994768 |
blames = []
file_names = [x for x in self.repo.git.log(pretty='format:', name_only=True, diff_filter='A').split('\n') if
x.strip() != '']
for file in self.__check_extension({x: x for x in file_names}, ignore_globs=ignore_globs,
... | def blame(self, rev='HEAD', committer=True, by='repository', ignore_globs=None, include_globs=None) | Returns the blame from the current HEAD of the repository as a DataFrame. The DataFrame is grouped by committer
name, so it will be the sum of all contributions to the repository by each committer. As with the commit history
method, extensions and ignore_dirs parameters can be passed to exclude certain... | 1.958047 | 1.875683 | 1.043911 |
if limit is None and skip is None and num_datapoints is not None:
limit = sum(1 for _ in self.repo.iter_commits())
skip = int(float(limit) / num_datapoints)
else:
if limit is None:
limit = sys.maxsize
elif skip is not None:
... | def revs(self, branch='master', limit=None, skip=None, num_datapoints=None) | Returns a dataframe of all revision tags and their timestamps. It will have the columns:
* date
* rev
:param branch: (optional, default 'master') the branch to work in
:param limit: (optional, default None), the maximum number of revisions to return, None for no limit
:param ... | 2.522348 | 2.459629 | 1.0255 |
revs = self.revs(branch=branch, limit=limit, skip=skip, num_datapoints=num_datapoints)
# get the commit history to stub out committers (hacky and slow)
if sys.version_info.major == 2:
committers = set([x.committer.name for x in self.repo.iter_commits(branch, max_count=sys.... | def cumulative_blame(self, branch='master', limit=None, skip=None, num_datapoints=None, committer=True,
ignore_globs=None, include_globs=None) | Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines
blamed to each committer at each timestamp as data.
:param branch: (optional, default 'master') the branch to work in
:param limit: (optional, default None), the maximum number of re... | 2.727797 | 2.718709 | 1.003343 |
if not _has_joblib:
raise ImportError('''Must have joblib installed to use parallel_cumulative_blame(), please use
cumulative_blame() instead.''')
revs = self.revs(branch=branch, limit=limit, skip=skip, num_datapoints=num_datapoints)
if self.verbose:
... | def parallel_cumulative_blame(self, branch='master', limit=None, skip=None, num_datapoints=None, committer=True,
workers=1, ignore_globs=None, include_globs=None) | Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines
blamed to each committer at each timestamp as data.
:param branch: (optional, default 'master') the branch to work in
:param limit: (optional, default None), the maximum number of re... | 2.95186 | 2.937966 | 1.004729 |
# first pull the local branches
local_branches = self.repo.branches
data = [[x.name, True] for x in list(local_branches)]
# then the remotes
remote_branches = self.repo.git.branch(all=True).split('\n')
if sys.version_info.major == 2:
remote_branches... | def branches(self) | Returns a data frame of all branches in origin. The DataFrame will have the columns:
* repository
* branch
* local
:returns: DataFrame | 2.997706 | 2.676821 | 1.119875 |
tags = self.repo.tags
df = DataFrame([x.name for x in list(tags)], columns=['tag'])
df['repository'] = self._repo_name()
return df | def tags(self) | Returns a data frame of all tags in origin. The DataFrame will have the columns:
* repository
* tag
:returns: DataFrame | 7.501885 | 6.196218 | 1.21072 |
if self._git_repo_name is not None:
return self._git_repo_name
else:
reponame = self.repo.git_dir.split(os.sep)[-2]
if reponame.strip() == '':
return 'unknown_repo'
return reponame | def _repo_name(self) | Returns the name of the repository, using the local directory name.
:returns: str | 3.598982 | 3.261718 | 1.103401 |
if by == 'file':
raise NotImplementedError('File-wise bus factor')
blame = self.blame(include_globs=include_globs, ignore_globs=ignore_globs, by=by)
blame = blame.sort_values(by=['loc'], ascending=False)
total = blame['loc'].sum()
cumulative = 0
tc... | def bus_factor(self, by='repository', ignore_globs=None, include_globs=None) | An experimental heuristic for truck factor of a repository calculated by the current distribution of blame in
the repository's primary branch. The factor is the fewest number of contributors whose contributions make up at
least 50% of the codebase's LOC
:param ignore_globs: (optional, default=... | 3.775956 | 3.349783 | 1.127224 |
try:
if committer:
cm = 'committer'
else:
cm = 'author'
blame = self.repo.blame(rev, os.path.join(self.git_dir, filename))
blame = DataFrame([[x[0].committer.name, len(x[1])] for x in blame], columns=[cm, 'loc']).groupby(c... | def file_owner(self, rev, filename, committer=True) | Returns the owner (by majority blame) of a given file in a given rev. Returns the committers' name.
:param rev:
:param filename:
:param committer: | 3.510996 | 3.496473 | 1.004154 |
# first get the blame
blame = self.blame(
include_globs=include_globs,
ignore_globs=ignore_globs,
rev=rev,
committer=committer,
by='file'
)
blame = blame.reset_index(level=1)
blame = blame.reset_index(level=1)
... | def file_detail(self, include_globs=None, ignore_globs=None, rev='HEAD', committer=True) | Returns a table of all current files in the repos, with some high level information about each file (total LOC,
file owner, extension, most recent edit date, etc.).
:param ignore_globs: (optional, default=None) a list of globs to ignore, default none excludes nothing
:param include_globs: (opti... | 3.097328 | 2.802406 | 1.105239 |
ch = self.commit_history(
branch=branch,
limit=limit,
days=days,
ignore_globs=ignore_globs,
include_globs=include_globs
)
# add in the date fields
ch['day_of_week'] = ch.index.map(lambda x: x.weekday())
ch['ho... | def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None,
include_globs=None) | Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
* insertions
* deletions
* net
:param branch: the branch to return commits for
:param limit: (optional, default... | 2.204406 | 1.976966 | 1.115045 |
if not HAS_MPL:
raise ImportError('Must have matplotlib installed to use the plotting functions')
# find how many plots we are making
if by is not None:
unique_vals = set(df[by].values.tolist())
else:
unique_vals = ['foo']
for idx, val in enumerate(unique_vals):
... | def plot_punchcard(df, metric='lines', title='punchcard', by=None) | Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return: | 2.250847 | 2.247844 | 1.001336 |
return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8") | def _decode(self, obj, context) | Get the python representation of the obj | 7.77183 | 6.827575 | 1.1383 |
kwargs = {}
if model_field.null or model_field.blank:
kwargs['required'] = False
if model_field.null:
kwargs['allow_null'] = True
if model_field.blank and (issubclass(model_field.__class__, models.CharField) or
... | def build_standard_field(self, field_name, model_field) | Creates a default instance of a basic non-relational field. | 2.56186 | 2.54514 | 1.006569 |
model = self.Meta.model
meta = self.Meta.model._meta
original_virtual_fields = list(meta.virtual_fields) # copy
if hasattr(model, '_hstore_virtual_fields'):
# remove hstore virtual fields from meta
for field in model._hstore_virtual_fields.values():
... | def update(self, instance, validated_data) | temporarily remove hstore virtual fields otherwise DRF considers them many2many | 2.606759 | 2.180697 | 1.195379 |
"simulated data"
t0 = time.time()
lt = time.localtime(t0)
tmin, tsec = lt[4],lt[5]
u = np.random.random()
v = np.random.random()
x = np.sin( (u + tsec)/3.0) + tmin/30. + v/5.0
return t0, x | def next_data() | simulated data | 5.486574 | 5.241573 | 1.046742 |
if style is not None:
self.conf.style = style
self.axes.cla()
conf = self.conf
conf.log_scale = False
conf.rot, conf.flip_ud, conf.flip_lr = False, False, False
conf.highlight_areas = []
if 1 in data.shape:
data = data.squeeze()
... | def display(self, data, x=None, y=None, xlabel=None, ylabel=None,
style=None, nlevels=None, levels=None, contour_labels=None,
store_data=True, col=0, unzoom=True, auto_contrast=False,
contrast_level=0, **kws) | generic display, using imshow (default) or contour | 2.383246 | 2.379309 | 1.001655 |
if 1 in data.shape:
data = data.squeeze()
if self.conf.contrast_level is not None:
clevels = [self.conf.contrast_level, 100.0-self.conf.contrast_level]
imin, imax = np.percentile(data, clevels)
data = np.clip((data - imin)/(imax - imin + 1.e-8), 0... | def update_image(self, data) | update image on panel, as quickly as possible | 2.986337 | 2.8692 | 1.040826 |
patch = mask * np.ones(mask.shape) * 0.9
cmap = self.conf.cmap[col]
area = self.axes.contour(patch, cmap=cmap, levels=[0, 1])
self.conf.highlight_areas.append(area)
col = None
if hasattr(cmap, '_lut'):
rgb = [int(i*240)^255 for i in cmap._lut[0][:3]]... | def add_highlight_area(self, mask, label=None, col=0) | add a highlighted area -- outline an arbitrarily shape --
as if drawn from a Lasso event.
This takes a mask, which should be a boolean array of the
same shape as the image. | 3.733272 | 3.856892 | 0.967948 |
if axes is None:
axes = self.axes
xmin, xmax, ymin, ymax = self.data_range
if len(self.conf.zoom_lims) >1:
zlims = self.conf.zoom_lims[-1]
if axes in zlims:
xmin, xmax, ymin, ymax = zlims[axes]
xmin = max(self.data_range[0], ... | def set_viewlimits(self, axes=None) | update xy limits of a plot | 2.124783 | 2.124465 | 1.00015 |
figsize = (1.0*self.size[0]/self.dpi, 1.0*self.size[1]/self.dpi)
self.fig = Figure(figsize, dpi=self.dpi)
self.axes = self.fig.add_axes([0.0, 0.0, 1.0, 1.0])
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
self.fig.set_facecolor('#FFFFFD')
self.conf.axes... | def BuildPanel(self) | builds basic GUI panel and popup menu | 2.52683 | 2.543231 | 0.993551 |
if len(shape) == 2:
ny, nx = shape
elif len(shape) == 3:
ny, nx, nchan = shape
inds = []
for iy in range(ny):
inds.extend([(ix, iy) for ix in range(nx)])
self.conf.indices = np.array(inds) | def calc_indices(self, shape) | calculates and stores the set of indices
ix=[0, nx-1], iy=[0, ny-1] for data of shape (nx, ny) | 3.119076 | 2.9579 | 1.05449 |
lims = None
if len(self.conf.zoom_lims) > 1:
lims = self.conf.zoom_lims.pop()
ax = self.axes
if lims is None: # auto scale
self.conf.zoom_lims = [None]
xmin, xmax, ymin, ymax = self.data_range
lims = {self.axes: [xmin, xmax, ymin, ... | def unzoom(self, event=None, set_bounds=True) | zoom out 1 level, or to full data range | 4.119521 | 3.939725 | 1.045637 |
if self.zoom_ini is None:
return
ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini
try:
dx = abs(ini_x - event.x)
dy = abs(ini_y - event.y)
except:
dx, dy = 0, 0
t0 = time.time()
self.rbbox = None
self.zoom_ini ... | def zoom_leftup(self, event=None) | leftup event handler for zoom mode in images | 2.719896 | 2.695593 | 1.009016 |
directories = util.to_absolute_paths(directories)
if not self.recursive:
return self._remove_blacklisted(directories)
recursive_dirs = set()
for dir_ in directories:
walk_iter = os.walk(dir_, followlinks=True)
walk_iter = [w[0] for w in walk... | def collect_directories(self, directories) | Collects all the directories into a `set` object.
If `self.recursive` is set to `True` this method will iterate through
and return all of the directories and the subdirectories found from
`directories` that are not blacklisted.
if `self.recursive` is set to `False` this will return all... | 2.740459 | 2.583451 | 1.060774 |
directories = util.to_absolute_paths(directories)
if except_blacklisted:
directories = self._remove_blacklisted(directories)
self.plugin_directories.update(directories) | def add_directories(self, directories, except_blacklisted=True) | Adds `directories` to the set of plugin directories.
`directories` may be either a single object or a iterable.
`directories` can be relative paths, but will be converted into
absolute paths based on the current working directory.
if `except_blacklisted` is `True` all `directories` in... | 4.676288 | 4.555826 | 1.026441 |
directories = util.to_absolute_paths(directories)
if except_blacklisted:
directories = self._remove_blacklisted(directories)
self.plugin_directories = directories | def set_directories(self, directories, except_blacklisted=True) | Sets the plugin directories to `directories`. This will delete
the previous state stored in `self.plugin_directories` in favor
of the `directories` passed in.
`directories` may be either a single object or an iterable.
`directories` can contain relative paths but will be
conver... | 4.935633 | 4.633593 | 1.065185 |
directories = util.to_absolute_paths(directories)
self.plugin_directories = util.remove_from_set(self.plugin_directories,
directories) | def remove_directories(self, directories) | Removes any `directories` from the set of plugin directories.
`directories` may be a single object or an iterable.
Recommend passing in all paths as absolute, but the method will
attemmpt to convert all paths to absolute if they are not already
based on the current working directory. | 5.790123 | 5.166687 | 1.120665 |
absolute_paths = util.to_absolute_paths(directories)
self.blacklisted_directories.update(absolute_paths)
if remove_from_stored_directories:
plug_dirs = self.plugin_directories
plug_dirs = util.remove_from_set(plug_dirs,
... | def add_blacklisted_directories(self,
directories,
remove_from_stored_directories=True) | Adds `directories` to be blacklisted. Blacklisted directories will not
be returned or searched recursively when calling the
`collect_directories` method.
`directories` may be a single instance or an iterable. Recommend
passing in absolute paths, but method will try to convert to absolut... | 3.717519 | 3.524242 | 1.054842 |
absolute_paths = util.to_absolute_paths(directories)
self.blacklisted_directories = absolute_paths
if remove_from_stored_directories:
plug_dirs = self.plugin_directories
plug_dirs = util.remove_from_set(plug_dirs,
dire... | def set_blacklisted_directories(self,
directories,
remove_from_stored_directories=True) | Sets the `directories` to be blacklisted. Blacklisted directories will
not be returned or searched recursively when calling
`collect_directories`.
This will replace the previously stored set of blacklisted
paths.
`directories` may be a single instance or an iterable. Recommend
... | 4.11665 | 4.065273 | 1.012638 |
directories = util.to_absolute_paths(directories)
black_dirs = self.blacklisted_directories
black_dirs = util.remove_from_set(black_dirs, directories) | def remove_blacklisted_directories(self, directories) | Attempts to remove the `directories` from the set of blacklisted
directories. If a particular directory is not found in the set of
blacklisted, method will continue on silently.
`directories` may be a single instance or an iterable. Recommend
passing in absolute paths. Method will try t... | 4.728167 | 4.410632 | 1.071993 |
directories = util.to_absolute_paths(directories)
directories = util.remove_from_set(directories,
self.blacklisted_directories)
return directories | def _remove_blacklisted(self, directories) | Attempts to remove the blacklisted directories from `directories`
and then returns whatever is left in the set.
Called from the `collect_directories` method. | 5.993104 | 7.200323 | 0.832338 |
return self.frame.plot(x,y,**kw) | def plot(self, x, y, **kw) | plot x, y values (erasing old plot),
for method options see PlotPanel.plot. | 7.77322 | 6.706584 | 1.159043 |
return self.frame.oplot(x,y,**kw) | def oplot(self, x, y, **kw) | overplot x, y values (on top of old plot),
for method options see PlotPanel.oplot | 7.368006 | 6.571909 | 1.121136 |
with TIFFfile(filename) as tif:
return tif.asarray(*args, **kwargs) | def imread(filename, *args, **kwargs) | Return image data from TIFF file as numpy array.
The first image series is returned if no arguments are provided.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
Defines which series of pages to return as arra... | 4.507054 | 8.81873 | 0.511077 |
return numpy.fromfile(fd, byte_order+dtype[-1], count).tostring() | def read_bytes(fd, byte_order, dtype, count) | Read tag data from file and return as byte string. | 6.959547 | 6.82627 | 1.019524 |
return numpy.fromfile(fd, byte_order+dtype[-1], count) | def read_numpy(fd, byte_order, dtype, count) | Read tag data from file and return as numpy array. | 5.749956 | 6.489963 | 0.885977 |
fd.seek(12, 1)
return {'version': struct.unpack(byte_order+'H', fd.read(2))[0]} | def read_nih_image_header(fd, byte_order, dtype, count) | Read NIH_IMAGE_HEADER tag from file and return as dictionary. | 3.812001 | 3.502614 | 1.08833 |
return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0] | def read_mm_header(fd, byte_order, dtype, count) | Read MM_HEADER tag from file and return as numpy.rec.array. | 6.847585 | 4.821499 | 1.420219 |
t = fd.read(8*count)
t = struct.unpack('%s%iI' % (byte_order, 2*count), t)
return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2])
if k in MM_TAG_IDS) | def read_mm_uic1(fd, byte_order, dtype, count) | Read MM_UIC1 tag from file and return as dictionary. | 3.683747 | 3.319294 | 1.109798 |
result = {'number_planes': count}
values = numpy.fromfile(fd, byte_order+'I', 6*count)
result['z_distance'] = values[0::6] // values[1::6]
#result['date_created'] = tuple(values[2::6])
#result['time_created'] = tuple(values[3::6])
#result['date_modified'] = tuple(values[4::6])
#result['... | def read_mm_uic2(fd, byte_order, dtype, count) | Read MM_UIC2 tag from file and return as dictionary. | 3.198548 | 3.159801 | 1.012262 |
t = numpy.fromfile(fd, byte_order+'I', 2*count)
return {'wavelengths': t[0::2] // t[1::2]} | def read_mm_uic3(fd, byte_order, dtype, count) | Read MM_UIC3 tag from file and return as dictionary. | 6.365402 | 5.982269 | 1.064045 |
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1,
byteorder=byte_order)[0]
{50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation
return result | def read_cz_lsm_info(fd, byte_order, dtype, count) | Read CS_LSM_INFO tag from file and return as numpy.rec.array. | 9.074122 | 8.3843 | 1.082275 |
size, count = struct.unpack(byte_order+'II', fd.read(8))
if size != (8 + 8 * count):
raise ValueError("lsm_time_stamps block is too short")
return struct.unpack(('%s%dd' % (byte_order, count)),
fd.read(8*count)) | def read_cz_lsm_time_stamps(fd, byte_order) | Read LSM time stamps from file and return as list. | 3.598161 | 3.562568 | 1.009991 |
count = struct.unpack(byte_order+'II', fd.read(8))[1]
events = []
while count > 0:
esize, etime, etype = struct.unpack(byte_order+'IdI', fd.read(16))
etext = stripnull(fd.read(esize - 16))
events.append((etime, etype, etext))
count -= 1
return events | def read_cz_lsm_event_list(fd, byte_order) | Read LSM events from file and return as list of (time, type, text). | 2.925612 | 2.668513 | 1.096346 |
block = Record()
blocks = [block]
unpack = struct.unpack
if 0x10000000 != struct.unpack(byte_order+"I", fd.read(4))[0]:
raise ValueError("not a lsm_scan_info structure")
fd.read(8)
while True:
entry, dtype, size = unpack(byte_order+"III", fd.read(12))
if dtype == 2:
... | def read_cz_lsm_scan_info(fd, byte_order) | Read LSM scan information from file and return as Record. | 2.396833 | 2.366096 | 1.012991 |
def decorate(func, module_function=module_function, warn=warn):
sys.path.append(os.path.dirname(__file__))
try:
module, function = module_function.split('.')
func, oldfunc = getattr(__import__(module), function), func
globals()['__old_' + func.__name__] = old... | def _replace_by(module_function, warn=False) | Try replace decorated function by module.function. | 3.25436 | 3.202051 | 1.016336 |
func = ord if sys.version[0] == '2' else lambda x: x
result = []
i = 0
try:
while True:
n = func(encoded[i]) + 1
i += 1
if n < 129:
result.extend(encoded[i:i+n])
i += n
elif n > 129:
result.exten... | def decodepackbits(encoded) | Decompress PackBits encoded byte string.
PackBits is a simple byte-oriented run-length compression scheme. | 2.440811 | 2.534333 | 0.963098 |
unpack = struct.unpack
if sys.version[0] == '2':
newtable = [chr(i) for i in range(256)]
else:
newtable = [bytes([i]) for i in range(256)]
newtable.extend((0, 0))
def next_code():
start = bitcount // 8
s = encoded[start:start+4]
try:
... | def decodelzw(encoded) | Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string).
The strip must begin with a CLEAR code and end with an EOI code.
This is an implementation of the LZW decoding algorithm described in (1).
It is not compatible with old style LZW compressed files like quad-lzw.tif. | 2.997443 | 2.869767 | 1.04449 |
if itemsize == 1: # bitarray
data = numpy.fromstring(data, '|B')
data = numpy.unpackbits(data)
if runlen % 8:
data = data.reshape(-1, runlen+(8-runlen%8))
data = data[:, :runlen].reshape(-1)
return data.astype(dtype)
dtype = numpy.dtype(dtype)
i... | def unpackints(data, dtype, itemsize, runlen=0) | Decompress byte string to array of integers of any bit size <= 32.
Parameters
----------
data : byte str
Data to decompress.
dtype : numpy.dtype or str
A numpy boolean or integer type.
itemsize : int
Number of bits per integer.
runlen : int
Number of consecutive ... | 2.918385 | 2.949418 | 0.989478 |
o = TIFF_ORIENTATIONS.get(orientation, orientation)
if o == 'top_left':
return image
elif o == 'top_right':
return image[..., ::-1, :]
elif o == 'bottom_left':
return image[..., ::-1, :, :]
elif o == 'bottom_right':
return image[..., ::-1, ::-1, :]
elif o == ... | def reorient(image, orientation) | Return reoriented view of image array.
Parameters
----------
image : numpy array
Non-squeezed output of asarray() functions.
Axes -3 and -2 must be image length and width respectively.
orientation : int or str
One of TIFF_ORIENTATIONS keys or values. | 1.572616 | 1.545121 | 1.017795 |
i = string.find(b'\x00')
return string if (i < 0) else string[:i] | def stripnull(string) | Return string truncated at first null character. | 3.765472 | 3.29518 | 1.142721 |
return epoch + datetime.timedelta(n) | def datetime_from_timestamp(n, epoch=datetime.datetime.fromordinal(693594)) | Return datetime object from timestamp in Excel serial format.
Examples
--------
>>> datetime_from_timestamp(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982) | 5.605204 | 43.017445 | 0.130301 |
if not hasattr(self, 'tiffs'):
return
for tif in self._tiffs.values():
if tif._fd:
tif._fd.close()
tif._fd = None | def close(self) | Close open file handle(s). | 4.845447 | 4.201188 | 1.153352 |
self._fd.seek(0)
try:
self.byte_order = {b'II': '<', b'MM': '>'}[self._fd.read(2)]
except KeyError:
raise ValueError("not a valid TIFF file")
version = struct.unpack(self.byte_order+'H', self._fd.read(2))[0]
if version == 43: # BigTiff
... | def _fromfile(self) | Read TIFF header and all page records from file. | 2.481455 | 2.364985 | 1.049248 |
if self.is_ome:
series = self._omeseries()
elif self.is_fluoview:
dims = {b'X': 'X', b'Y': 'Y', b'Z': 'Z', b'T': 'T',
b'WAVELENGTH': 'C', b'TIME': 'T', b'XY': 'R',
b'EVENT': 'V', b'EXPOSURE': 'L'}
mmhd = list(reversed(s... | def series(self) | Return series of TIFFpage with compatible shape and properties. | 2.997931 | 2.912021 | 1.029502 |
if key is None and series is None:
series = 0
if series is not None:
pages = self.series[series].pages
else:
pages = self.pages
if key is None:
pass
elif isinstance(key, int):
pages = [pages[key]]
elif ... | def asarray(self, key=None, series=None) | Return image data of multiple TIFF pages as numpy array.
By default the first image series is returned.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
Defines which series of pages... | 2.913619 | 2.771291 | 1.051358 |
root = ElementTree.XML(self.pages[0].tags['image_description'].value)
uuid = root.attrib.get('UUID', None)
self._tiffs = {uuid: self}
modulo = {}
result = []
for element in root:
if element.tag.endswith('BinaryOnly'):
warnings.warn("no... | def _omeseries(self) | Return image series in OME-TIFF files. | 3.107044 | 3.068272 | 1.012637 |
fd = self.parent._fd
byte_order = self.parent.byte_order
offset_size = self.parent.offset_size
fmt = {4: 'I', 8: 'Q'}[offset_size]
offset = struct.unpack(byte_order + fmt, fd.read(offset_size))[0]
if not offset:
raise StopIteration()
# read ... | def _fromfile(self) | Read TIFF IFD structure and its tags from file.
File cursor must be at storage position of IFD offset and is left at
offset to next IFD.
Raises StopIteration if offset (first bytes read) is 0. | 3.369628 | 3.183861 | 1.058347 |
self.code = int(code)
self.name = name if name else str(code)
self.dtype = TIFF_DATA_TYPES[dtype]
self.count = int(count)
self.value = value | def _fromdata(self, code, dtype, count, value, name=None) | Initialize instance from arguments. | 3.07996 | 2.807364 | 1.0971 |
fd = parent._fd
byte_order = parent.byte_order
self._offset = fd.tell()
self.value_offset = self._offset + parent.offset_size + 4
fmt, size = {4: ('HHI4s', 12), 8: ('HHQ8s', 20)}[parent.offset_size]
data = fd.read(size)
code, dtype = struct.unpack(byte_... | def _fromfile(self, parent) | Read tag structure from open file. Advance file cursor. | 2.87667 | 2.812588 | 1.022784 |
if self.panel is not None:
self.panel.set_xylims(limits, axes=axes) | def set_xylims(self, limits, axes=None) | overwrite data for trace t | 3.585309 | 3.533975 | 1.014526 |
if self.panel is not None:
self.panel.unzoom_all(event=event) | def unzoom_all(self,event=None) | zoom out full data range | 4.077588 | 3.723606 | 1.095064 |
if self.panel is not None: self.panel.unzoom(event=event) | def unzoom(self,event=None) | zoom out 1 level, or to full data range | 5.830085 | 5.474485 | 1.064956 |
"set plot xlabel"
if self.panel is not None: self.panel.set_xlabel(s)
self.panel.canvas.draw() | def set_xlabel(self,s) | set plot xlabel | 5.639371 | 5.095529 | 1.106729 |
"set plot xlabel"
if self.panel is not None: self.panel.set_ylabel(s)
self.panel.canvas.draw() | def set_ylabel(self,s) | set plot xlabel | 6.305453 | 5.126356 | 1.230007 |
if self.panel is not None:
self.panel.save_figure(event=event,
transparent=transparent, dpi=dpi) | def save_figure(self,event=None, transparent=False, dpi=600) | save figure image to file | 3.349942 | 3.497078 | 0.957926 |
panel = self.get_panel(panel)
panel.plot(x, y, **kws)
if xlabel is not None:
self.xlabel = xlabel
if self.xlabel is not None:
self.panel_bot.set_xlabel(self.xlabel) | def plot(self, x, y, panel='top', xlabel=None, **kws) | plot after clearing current plot | 2.731621 | 2.630722 | 1.038354 |
for p in (self.panel, self.panel_bot):
p.conf.zoom_lims = []
p.conf.unzoom(full=True) | def unzoom_all(self, event=None) | zoom out full data range | 11.109932 | 9.761417 | 1.138147 |
panel = self.get_panel(panel)
panel.conf.unzoom(event=event)
self.panel.set_viewlimits() | def unzoom(self, event=None, panel='top') | zoom out 1 level, or to full data range | 6.762112 | 6.37516 | 1.060697 |
panel = self.get_panel(panel)
panel.update_line(t, x, y, **kws) | def update_line(self, t, x, y, panel='top', **kws) | overwrite data for trace t | 2.559055 | 2.804573 | 0.912458 |
panel = self.get_panel(panel)
# print("Stacked set_xylims ", panel, self.panel)
panel.set_xylims(lims, axes=axes, **kws) | def set_xylims(self, lims, axes=None, panel='top', **kws) | set xy limits | 4.970145 | 4.813651 | 1.03251 |
"set plot title"
panel = self.get_panel(panel)
panel.set_title(s) | def set_title(self,s, panel='top') | set plot title | 5.388371 | 5.247485 | 1.026848 |
"set plot xlabel"
panel = self.get_panel(panel)
panel.set_ylabel(s) | def set_ylabel(self,s, panel='top') | set plot xlabel | 6.571478 | 4.919309 | 1.335854 |
panel = self.get_panel(panel)
panel.save_figure(event=event) | def save_figure(self, event=None, panel='top') | save figure image to file | 4.2555 | 3.941828 | 1.079575 |
"toggle grid on top/bottom panels"
if show is None:
show = not self.panel.conf.show_grid
for p in (self.panel, self.panel_bot):
p.conf.enable_grid(show) | def toggle_grid(self, event=None, show=None) | toggle grid on top/bottom panels | 6.634803 | 4.965875 | 1.336079 |
bconf = self.panel_bot.conf
if item == 'grid':
bconf.set_gridcolor(color)
elif item == 'bg':
bconf.set_bgcolor(color)
elif item == 'frame':
bconf.set_framecolor(color)
elif item == 'text':
bconf.set_textcolor(color)
... | def onThemeColor(self, color, item) | pass theme colors to bottom panel | 3.521984 | 3.228372 | 1.090948 |
bconf = self.panel_bot.conf
l, t, r, b = bconf.margins
bconf.set_margins(left=left, top=t, right=right, bottom=b)
bconf.canvas.draw() | def onMargins(self, left=0.1, top=0.1, right=0.1, bottom=0.1) | pass left/right margins on to bottom panel | 4.78116 | 4.38864 | 1.08944 |
this_panel = self.get_panel(panel)
xmin, xmax, ymin, ymax = this_panel.conf.set_viewlimits()[0]
# print("Set ViewLimits ", xmin, xmax, ymin, ymax)
# make top/bottom panel follow xlimits
if this_panel == self.panel:
other = self.panel_bot
for _ax ... | def set_viewlimits(self, panel='top') | update xy limits of a plot, as used with .update_line() | 5.669295 | 5.434509 | 1.043203 |
fmt = '%1.5g'
ax = self.panel_bot.axes.yaxis
ticks = ax.get_major_locator()()
dtick = ticks[1] - ticks[0]
if dtick > 29999:
fmt = '%1.5g'
elif dtick > 1.99:
fmt = '%1.0f'
elif dtick > 0.099:
fmt = '%1.1f'
e... | def bot_yformatter(self, val, type='') | custom formatter for FuncFormatter() and bottom panel | 2.284236 | 2.23592 | 1.021609 |
names = util.return_set(names)
self.entry_point_names.update(names) | def add_entry_points(self, names) | adds `names` to the internal collection of entry points to track
`names` can be a single object or an iterable but
must be a string or iterable of strings. | 7.633477 | 8.546822 | 0.893136 |
names = util.return_set(names)
self.entry_point_names = names | def set_entry_points(self, names) | sets the internal collection of entry points to be
equal to `names`
`names` can be a single object or an iterable but
must be a string or iterable of strings. | 9.185574 | 11.917596 | 0.770757 |
names = util.return_set(names)
util.remove_from_set(self.entry_point_names,
names) | def remove_entry_points(self, names) | removes `names` from the set of entry points to track.
`names` can be a single object or an iterable. | 7.890122 | 9.289958 | 0.849317 |
if entry_points is None:
entry_points = self.entry_point_names
else:
entry_points = util.return_set(entry_points)
plugins = []
plugin_names = []
for name in entry_points:
for entry_point in pkg_resources.iter_entry_points(name):
... | def collect_plugins(self,
entry_points=None,
verify_requirements=False,
return_dict=False) | collects the plugins from the `entry_points`. If `entry_points` is not
explicitly defined, this method will pull from the internal state
defined using the add/set entry points methods.
`entry_points` can be a single object or an iterable, but must be
either a string or an iterable of st... | 2.158904 | 2.212287 | 0.97587 |
s = "%s " % txt
out = []
i = 0
while i < len(s)-1:
if s[i] == '\\' and s[i+1] in ('n', 't'):
if s[i+1] == 'n':
out.append('\n')
elif s[i+1] == 't':
out.append('\t')
i += 1
elif s[i] == '$':
j = s[i+1:].f... | def clean_texmath(txt) | clean tex math string, preserving control sequences
(incluing \n, so also '\nu') inside $ $, while allowing
\n and \t to be meaningful in the text string | 2.123535 | 2.015802 | 1.053444 |
abspath = os.path.abspath
paths = return_set(paths)
absolute_paths = {abspath(x) for x in paths}
return absolute_paths | def to_absolute_paths(paths) | helper method to change `paths` to absolute paths.
Returns a `set` object
`paths` can be either a single object or iterable | 5.191133 | 5.655297 | 0.917924 |
if line:
markercolor = self.markercolor
if markercolor is None: markercolor=self.color
# self.set_markeredgecolor(markercolor, line=line)
# self.set_markerfacecolor(markercolor, line=line)
self.set_label(self.label, line=line)
sel... | def update(self, line=None) | set a matplotlib Line2D to have the current properties | 2.249419 | 2.031442 | 1.107302 |
while n >= len(self.traces):
self.traces.append(LineProperties())
line = self.traces[n]
label = "trace %i" % (n+1)
line.label = label
line.drawstyle = 'default'
if zorder is None:
zorder = 5 * (n+1)
line.zorder = zorder
... | def _init_trace(self, n, color, style,
linewidth=2.5, zorder=None, marker=None, markersize=6) | used for building set of traces | 2.312428 | 2.387605 | 0.968513 |
" re draw labels (title, x, y labels)"
n = self.labelfont.get_size()
self.titlefont.set_size(n+1)
# print(" plot relabel ", delay_draw)
rcParams['xtick.labelsize'] = rcParams['ytick.labelsize'] = n
rcParams['xtick.color'] = rcParams['ytick.color'] = self.textcolor
... | def relabel(self, xlabel=None, ylabel=None,
y2label=None, title=None, delay_draw=False) | re draw labels (title, x, y labels) | 2.280769 | 2.170769 | 1.050673 |
"set margins"
self.margins = (left, top, right, bottom)
if self.panel is not None:
self.panel.gridspec.update(left=left, top=1-top,
right=1-right, bottom=bottom)
for ax in self.canvas.figure.get_axes():
ax.update_params()
... | def set_margins(self, left=0.1, top=0.1, right=0.1, bottom=0.1,
delay_draw=False) | set margins | 2.799864 | 2.851192 | 0.981997 |
self.gridcolor = color
for ax in self.canvas.figure.get_axes():
for i in ax.get_xgridlines()+ax.get_ygridlines():
i.set_color(color)
i.set_zorder(-1)
if callable(self.theme_color_callback):
self.theme_color_callback(color, 'grid') | def set_gridcolor(self, color) | set color for grid | 3.169874 | 3.091215 | 1.025446 |
self.bgcolor = color
for ax in self.canvas.figure.get_axes():
if matplotlib.__version__ < '2.0':
ax.set_axis_bgcolor(color)
else:
ax.set_facecolor(color)
if callable(self.theme_color_callback):
self.theme_color_callback... | def set_bgcolor(self, color) | set color for background of plot | 3.262974 | 3.068192 | 1.063484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.