_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263900 | ABFplot.figure_protocol | validation | def figure_protocol(self):
"""plot the current sweep protocol."""
self.log.debug("creating overlayed protocols plot")
self.figure()
plt.plot(self.abf.protoX,self.abf.protoY,color='r')
self.marginX=0
self.decorate(protocol=True) | python | {
"resource": ""
} |
q263901 | ABFplot.figure_protocols | validation | def figure_protocols(self):
"""plot the protocol of all sweeps."""
self.log.debug("creating overlayed protocols plot")
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
plt.plot(self.abf.protoX,self.abf.protoY,color='r')
self.marg... | python | {
"resource": ""
} |
q263902 | clampfit_rename | validation | def clampfit_rename(path,char):
"""
Given ABFs and TIFs formatted long style, rename each of them to prefix their number with a different number.
Example: 2017_10_11_0011.abf
Becomes: 2017_10_11_?011.abf
where ? can be any character.
"""
assert len(char)==1 and type(char)==str, "replacement... | python | {
"resource": ""
} |
q263903 | filesByExtension | validation | def filesByExtension(fnames):
"""given a list of files, return a dict organized by extension."""
byExt={"abf":[],"jpg":[],"tif":[]} # prime it with empties
for fname in fnames:
ext = os.path.splitext(fname)[1].replace(".",'').lower()
if not ext in byExt.keys():
byExt[ext]=[]
... | python | {
"resource": ""
} |
q263904 | filesByCell | validation | def filesByCell(fnames,cells):
"""given files and cells, return a dict of files grouped by cell."""
byCell={}
fnames=smartSort(fnames)
days = list(set([elem[:5] for elem in fnames if elem.endswith(".abf")])) # so pythonic!
for day in smartSort(days):
parent=None
for i,fname in enumer... | python | {
"resource": ""
} |
q263905 | ABFindex.folderScan | validation | def folderScan(self,abfFolder=None):
"""populate class properties relating to files in the folder."""
if abfFolder is None and 'abfFolder' in dir(self):
abfFolder=self.abfFolder
else:
self.abfFolder=abfFolder
self.abfFolder=os.path.abspath(self.abfFolder)
... | python | {
"resource": ""
} |
q263906 | ABFindex.html_index | validation | def html_index(self,launch=False,showChildren=False):
"""
generate list of cells with links. keep this simple.
automatically generates splash page and regnerates frames.
"""
self.makePics() # ensure all pics are converted
# generate menu
html='<a href="index_splas... | python | {
"resource": ""
} |
q263907 | ABFindex.html_singleAll | validation | def html_singleAll(self,template="basic"):
"""generate a data view for every ABF in the project folder."""
for fname in smartSort(self.cells):
if template=="fixed":
self.html_single_fixed(fname)
else:
self.html_single_basic(fname) | python | {
"resource": ""
} |
q263908 | proto_01_01_HP010 | validation | def proto_01_01_HP010(abf=exampleABF):
"""hyperpolarization step. Use to calculate tau and stuff."""
swhlab.memtest.memtest(abf) #knows how to do IC memtest
swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did
swhlab.plot.save(abf,tag="tau") | python | {
"resource": ""
} |
q263909 | proto_01_12_steps025 | validation | def proto_01_12_steps025(abf=exampleABF):
"""IC steps. Use to determine gain function."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_'+feature)
... | python | {
"resource": ""
} |
q263910 | proto_01_13_steps025dual | validation | def proto_01_13_steps025dual(abf=exampleABF):
"""IC steps. See how hyperpol. step affects things."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_... | python | {
"resource": ""
} |
q263911 | proto_02_01_MT70 | validation | def proto_02_01_MT70(abf=exampleABF):
"""repeated membrane tests."""
standard_overlayWithAverage(abf)
swhlab.memtest.memtest(abf)
swhlab.memtest.checkSweep(abf)
swhlab.plot.save(abf,tag='check',resize=False) | python | {
"resource": ""
} |
q263912 | proto_02_03_IVfast | validation | def proto_02_03_IVfast(abf=exampleABF):
"""fast sweeps, 1 step per sweep, for clean IV without fast currents."""
av1,sd1=swhlab.plot.IV(abf,.6,.9,True)
swhlab.plot.save(abf,tag='iv1')
Xs=abf.clampValues(.6) #generate IV clamp values
abf.saveThing([Xs,av1],'iv') | python | {
"resource": ""
} |
q263913 | proto_04_01_MTmon70s2 | validation | def proto_04_01_MTmon70s2(abf=exampleABF):
"""repeated membrane tests, likely with drug added. Maybe IPSCs."""
standard_inspect(abf)
swhlab.memtest.memtest(abf)
swhlab.memtest.checkSweep(abf)
swhlab.plot.save(abf,tag='check',resize=False)
swhlab.memtest.plot_standard4(abf)
swhlab.plot.save(a... | python | {
"resource": ""
} |
q263914 | proto_VC_50_MT_IV | validation | def proto_VC_50_MT_IV(abf=exampleABF):
"""combination of membrane test and IV steps."""
swhlab.memtest.memtest(abf) #do membrane test on every sweep
swhlab.memtest.checkSweep(abf) #see all MT values
swhlab.plot.save(abf,tag='02-check',resize=False)
av1,sd1=swhlab.plot.IV(abf,1.2,1.4,True,'b')
s... | python | {
"resource": ""
} |
q263915 | indexImages | validation | def indexImages(folder,fname="index.html"):
"""OBSOLETE WAY TO INDEX A FOLDER.""" #TODO: REMOVE
html="<html><body>"
for item in glob.glob(folder+"/*.*"):
if item.split(".")[-1] in ['jpg','png']:
html+="<h3>%s</h3>"%os.path.basename(item)
html+='<img src="%s">'%os.path.basenam... | python | {
"resource": ""
} |
q263916 | BaseActivatableModel.save | validation | def save(self, *args, **kwargs):
"""
A custom save method that handles figuring out when something is activated or deactivated.
"""
current_activable_value = getattr(self, self.ACTIVATABLE_FIELD_NAME)
is_active_changed = self.id is None or self.__original_activatable_value != cur... | python | {
"resource": ""
} |
q263917 | BaseActivatableModel.delete | validation | def delete(self, force=False, **kwargs):
"""
It is impossible to delete an activatable model unless force is True. This function instead sets it to inactive.
"""
if force:
return super(BaseActivatableModel, self).delete(**kwargs)
else:
setattr(self, self.A... | python | {
"resource": ""
} |
q263918 | Command.show | validation | def show(self, args, file_handle=None, **kwargs):
"Write to file_handle if supplied, othewise print output"
full_string = ''
info = {'root_directory': '<root_directory>',
'batch_name': '<batch_name>',
'batch_tag': '<batch_tag>',
... | python | {
"resource": ""
} |
q263919 | Launcher.get_root_directory | validation | def get_root_directory(self, timestamp=None):
"""
A helper method that supplies the root directory name given a
timestamp.
"""
if timestamp is None: timestamp = self.timestamp
if self.timestamp_format is not None:
root_name = (time.strftime(self.timestamp_for... | python | {
"resource": ""
} |
q263920 | Launcher._append_log | validation | def _append_log(self, specs):
"""
The log contains the tids and corresponding specifications
used during launch with the specifications in JSON format.
"""
self._spec_log += specs # This should be removed
log_path = os.path.join(self.root_directory, ("%s.log" % self.batch... | python | {
"resource": ""
} |
q263921 | Launcher._record_info | validation | def _record_info(self, setup_info=None):
"""
All launchers should call this method to write the info file
at the end of the launch. The .info file is saved given
setup_info supplied by _setup_launch into the
root_directory. When called without setup_info, the existing
inf... | python | {
"resource": ""
} |
q263922 | Launcher._launch_process_group | validation | def _launch_process_group(self, process_commands, streams_path):
"""
Launches processes defined by process_commands, but only
executes max_concurrency processes at a time; if a process
completes and there are still outstanding processes to be
executed, the next processes are run ... | python | {
"resource": ""
} |
q263923 | Launcher.summary | validation | def summary(self):
"""
A succinct summary of the Launcher configuration. Unlike the
repr, a summary does not have to be complete but must supply
key information relevant to the user.
"""
print("Type: %s" % self.__class__.__name__)
print("Batch Name: %r" % self.ba... | python | {
"resource": ""
} |
q263924 | QLauncher._qsub_collate_and_launch | validation | def _qsub_collate_and_launch(self, output_dir, error_dir, job_names):
"""
The method that actually runs qsub to invoke the python
process with the necessary commands to trigger the next
collation step and next block of jobs.
"""
job_name = "%s_%s_collate_%d" % (self.batc... | python | {
"resource": ""
} |
q263925 | QLauncher._qsub_block | validation | def _qsub_block(self, output_dir, error_dir, tid_specs):
"""
This method handles static argument specifiers and cases where
the dynamic specifiers cannot be queued before the arguments
are known.
"""
processes = []
job_names = []
for (tid, spec) in tid_sp... | python | {
"resource": ""
} |
q263926 | ScriptLauncher._launch_process_group | validation | def _launch_process_group(self, process_commands, streams_path):
"""
Aggregates all process_commands and the designated output files into a
list, and outputs it as JSON, after which the wrapper script is called.
"""
processes = []
for cmd, tid in process_commands:
... | python | {
"resource": ""
} |
q263927 | review_and_launch.cross_check_launchers | validation | def cross_check_launchers(self, launchers):
"""
Performs consistency checks across all the launchers.
"""
if len(launchers) == 0: raise Exception('Empty launcher list')
timestamps = [launcher.timestamp for launcher in launchers]
if not all(timestamps[0] == tstamp for tst... | python | {
"resource": ""
} |
q263928 | review_and_launch._launch_all | validation | def _launch_all(self, launchers):
"""
Launches all available launchers.
"""
for launcher in launchers:
print("== Launching %s ==" % launcher.batch_name)
launcher()
return True | python | {
"resource": ""
} |
q263929 | review_and_launch._review_all | validation | def _review_all(self, launchers):
"""
Runs the review process for all the launchers.
"""
# Run review of launch args if necessary
if self.launch_args is not None:
proceed = self.review_args(self.launch_args,
show_repr=True,
... | python | {
"resource": ""
} |
q263930 | review_and_launch.input_options | validation | def input_options(self, options, prompt='Select option', default=None):
"""
Helper to prompt the user for input on the commandline.
"""
check_options = [x.lower() for x in options]
while True:
response = input('%s [%s]: ' % (prompt, ', '.join(options))).lower()
... | python | {
"resource": ""
} |
q263931 | FileType.save | validation | def save(self, filename, metadata={}, **data):
"""
The implementation in the base class simply checks there is no
clash between the metadata and data keys.
"""
intersection = set(metadata.keys()) & set(data.keys())
if intersection:
msg = 'Key(s) overlap betwe... | python | {
"resource": ""
} |
q263932 | FileType._savepath | validation | def _savepath(self, filename):
"""
Returns the full path for saving the file, adding an extension
and making the filename unique as necessary.
"""
(basename, ext) = os.path.splitext(filename)
basename = basename if (ext in self.extensions) else filename
ext = ext ... | python | {
"resource": ""
} |
q263933 | FileType.file_supported | validation | def file_supported(cls, filename):
"""
Returns a boolean indicating whether the filename has an
appropriate extension for this class.
"""
if not isinstance(filename, str):
return False
(_, ext) = os.path.splitext(filename)
if ext not in cls.extensions:... | python | {
"resource": ""
} |
q263934 | ImageFile.save | validation | def save(self, filename, imdata, **data):
"""
Data may be either a PIL Image object or a Numpy array.
"""
if isinstance(imdata, numpy.ndarray):
imdata = Image.fromarray(numpy.uint8(imdata))
elif isinstance(imdata, Image.Image):
imdata.save(self._savepath(f... | python | {
"resource": ""
} |
q263935 | fileModifiedTimestamp | validation | def fileModifiedTimestamp(fname):
"""return "YYYY-MM-DD" when the file was modified."""
modifiedTime=os.path.getmtime(fname)
stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))
return stamp | python | {
"resource": ""
} |
q263936 | loadResults | validation | def loadResults(resultsFile):
"""returns a dict of active folders with days as keys."""
with open(resultsFile) as f:
raw=f.read().split("\n")
foldersByDay={}
for line in raw:
folder=line.split('"')[1]+"\\"
line=[]+line.split('"')[2].split(", ")
for day in line[1:]... | python | {
"resource": ""
} |
q263937 | ndist | validation | def ndist(data,Xs):
"""
given some data and a list of X posistions, return the normal
distribution curve as a Y point at each of those Xs.
"""
sigma=np.sqrt(np.var(data))
center=np.average(data)
curve=mlab.normpdf(Xs,center,sigma)
curve*=len(data)*HIST_RESOLUTION
return curve | python | {
"resource": ""
} |
q263938 | ABF.abfinfo | validation | def abfinfo(self,printToo=False,returnDict=False):
"""show basic info about ABF class variables."""
info="\n### ABF INFO ###\n"
d={}
for thingName in sorted(dir(self)):
if thingName in ['cm','evIs','colormap','dataX','dataY',
'protoX','protoY']:
... | python | {
"resource": ""
} |
q263939 | ABF.headerHTML | validation | def headerHTML(self,fname=None):
"""read the ABF header and save it HTML formatted."""
if fname is None:
fname = self.fname.replace(".abf","_header.html")
html="<html><body><code>"
html+="<h2>abfinfo() for %s.abf</h2>"%self.ID
html+=self.abfinfo().replace("<","<").... | python | {
"resource": ""
} |
q263940 | ABF.generate_colormap | validation | def generate_colormap(self,colormap=None,reverse=False):
"""use 1 colormap for the whole abf. You can change it!."""
if colormap is None:
colormap = pylab.cm.Dark2
self.cm=colormap
self.colormap=[]
for i in range(self.sweeps): #TODO: make this the only colormap
... | python | {
"resource": ""
} |
q263941 | ABF.get_data_around | validation | def get_data_around(self,timePoints,thisSweep=False,padding=0.02,msDeriv=0):
"""
return self.dataY around a time point. All units are seconds.
if thisSweep==False, the time point is considered to be experiment time
and an appropriate sweep may be selected. i.e., with 10 second
... | python | {
"resource": ""
} |
q263942 | ABF.filter_gaussian | validation | def filter_gaussian(self,sigmaMs=100,applyFiltered=False,applyBaseline=False):
"""RETURNS filtered trace. Desn't filter it in place."""
if sigmaMs==0:
return self.dataY
filtered=cm.filter_gaussian(self.dataY,sigmaMs)
if applyBaseline:
self.dataY=self.dataY-filtere... | python | {
"resource": ""
} |
q263943 | validate_activatable_models | validation | def validate_activatable_models():
"""
Raises a ValidationError for any ActivatableModel that has ForeignKeys or OneToOneFields that will
cause cascading deletions to occur. This function also raises a ValidationError if the activatable
model has not defined a Boolean field with the field name defined b... | python | {
"resource": ""
} |
q263944 | to_table | validation | def to_table(args, vdims=[]):
"Helper function to convet an Args object to a HoloViews Table"
if not Table:
return "HoloViews Table not available"
kdims = [dim for dim in args.constant_keys + args.varying_keys
if dim not in vdims]
items = [tuple([spec[k] for k in kdims+vdims])
... | python | {
"resource": ""
} |
q263945 | PrettyPrinted.pprint_args | validation | def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):
"""
Method to define the positional arguments and keyword order
for pretty printing.
"""
if infix_operator and not (len(pos_args)==2 and keyword_args==[]):
raise Exception('Infix form... | python | {
"resource": ""
} |
q263946 | Arguments.spec_formatter | validation | def spec_formatter(cls, spec):
" Formats the elements of an argument set appropriately"
return type(spec)((k, str(v)) for (k,v) in spec.items()) | python | {
"resource": ""
} |
q263947 | Arguments._collect_by_key | validation | def _collect_by_key(self,specs):
"""
Returns a dictionary like object with the lists of values
collapsed by their respective key. Useful to find varying vs
constant keys and to find how fast keys vary.
"""
# Collect (key, value) tuples as list of lists, flatten with chain... | python | {
"resource": ""
} |
q263948 | Arguments.summary | validation | def summary(self):
"""
A succinct summary of the argument specifier. Unlike the repr,
a summary does not have to be complete but must supply the
most relevant information about the object to the user.
"""
print("Items: %s" % len(self))
varying_keys = ', '.join('%r... | python | {
"resource": ""
} |
q263949 | Args._build_specs | validation | def _build_specs(self, specs, kwargs, fp_precision):
"""
Returns the specs, the remaining kwargs and whether or not the
constructor was called with kwarg or explicit specs.
"""
if specs is None:
overrides = param.ParamOverrides(self, kwargs,
... | python | {
"resource": ""
} |
q263950 | Args.show | validation | def show(self, exclude=[]):
"""
Convenience method to inspect the available argument values in
human-readable format. The ordering of keys is determined by
how quickly they vary.
The exclude list allows specific keys to be excluded for
readability (e.g. to hide long, abs... | python | {
"resource": ""
} |
q263951 | Args.lexsort | validation | def lexsort(self, *order):
"""
The lexical sort order is specified by a list of string
arguments. Each string is a key name prefixed by '+' or '-'
for ascending and descending sort respectively. If the key is
not found in the operand's set of varying keys, it is ignored.
... | python | {
"resource": ""
} |
q263952 | Range.linspace | validation | def linspace(self, start, stop, n):
""" Simple replacement for numpy linspace"""
if n == 1: return [start]
L = [0.0] * n
nm1 = n - 1
nm1inv = 1.0 / nm1
for i in range(n):
L[i] = nm1inv * (start*(nm1 - i) + stop*i)
return L | python | {
"resource": ""
} |
q263953 | Log.extract_log | validation | def extract_log(log_path, dict_type=dict):
"""
Parses the log file generated by a launcher and returns
dictionary with tid keys and specification values.
Ordering can be maintained by setting dict_type to the
appropriate constructor (i.e. OrderedDict). Keys are converted
... | python | {
"resource": ""
} |
q263954 | Log.write_log | validation | def write_log(log_path, data, allow_append=True):
"""
Writes the supplied specifications to the log path. The data
may be supplied as either as a an Args or as a list of
dictionaries.
By default, specifications will be appropriately appended to
an existing log file. This... | python | {
"resource": ""
} |
q263955 | FilePattern.directory | validation | def directory(cls, directory, root=None, extension=None, **kwargs):
"""
Load all the files in a given directory selecting only files
with the given extension if specified. The given kwargs are
passed through to the normal constructor.
"""
root = os.getcwd() if root is Non... | python | {
"resource": ""
} |
q263956 | FilePattern.fields | validation | def fields(self):
"""
Return the fields specified in the pattern using Python's
formatting mini-language.
"""
parse = list(string.Formatter().parse(self.pattern))
return [f for f in zip(*parse)[1] if f is not None] | python | {
"resource": ""
} |
q263957 | FilePattern._load_expansion | validation | def _load_expansion(self, key, root, pattern):
"""
Loads the files that match the given pattern.
"""
path_pattern = os.path.join(root, pattern)
expanded_paths = self._expand_pattern(path_pattern)
specs=[]
for (path, tags) in expanded_paths:
filelist =... | python | {
"resource": ""
} |
q263958 | FilePattern._expand_pattern | validation | def _expand_pattern(self, pattern):
"""
From the pattern decomposition, finds the absolute paths
matching the pattern.
"""
(globpattern, regexp, fields, types) = self._decompose_pattern(pattern)
filelist = glob.glob(globpattern)
expansion = []
for fname i... | python | {
"resource": ""
} |
q263959 | FileInfo.from_pattern | validation | def from_pattern(cls, pattern, filetype=None, key='filename', root=None, ignore=[]):
"""
Convenience method to directly chain a pattern processed by
FilePattern into a FileInfo instance.
Note that if a default filetype has been set on FileInfo, the
filetype argument may be omitt... | python | {
"resource": ""
} |
q263960 | FileInfo.load_table | validation | def load_table(self, table):
"""
Load the file contents into the supplied Table using the
specified key and filetype. The input table should have the
filenames as values which will be replaced by the loaded
data. If data_key is specified, this key will be used to index
th... | python | {
"resource": ""
} |
q263961 | FileInfo.load_dframe | validation | def load_dframe(self, dframe):
"""
Load the file contents into the supplied dataframe using the
specified key and filetype.
"""
filename_series = dframe[self.key]
loaded_data = filename_series.map(self.filetype.data)
keys = [list(el.keys()) for el in loaded_data.v... | python | {
"resource": ""
} |
q263962 | FileInfo._info | validation | def _info(self, source, key, filetype, ignore):
"""
Generates the union of the source.specs and the metadata
dictionary loaded by the filetype object.
"""
specs, mdata = [], {}
mdata_clashes = set()
for spec in source.specs:
if key not in spec:
... | python | {
"resource": ""
} |
q263963 | EventIterator._push | validation | async def _push(self, *args, **kwargs):
"""Push new data into the buffer. Resume looping if paused."""
self._data.append((args, kwargs))
if self._future is not None:
future, self._future = self._future, None
future.set_result(True) | python | {
"resource": ""
} |
q263964 | figureStimulus | validation | def figureStimulus(abf,sweeps=[0]):
"""
Create a plot of one area of interest of a single sweep.
"""
stimuli=[2.31250, 2.35270]
for sweep in sweeps:
abf.setsweep(sweep)
for stimulus in stimuli:
S1=int(abf.pointsPerSec*stimulus)
S2=int(abf.pointsPerSec*(stimul... | python | {
"resource": ""
} |
q263965 | doStuff | validation | def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,
launch=True):
"""Inelegant for now, but lets you manually analyze every ABF in a folder."""
IN=INDEX(ABFfolder)
if analyze:
IN.analyzeAll()
if convert:
IN.convertImages() | python | {
"resource": ""
} |
q263966 | analyzeSingle | validation | def analyzeSingle(abfFname):
"""Reanalyze data for a single ABF. Also remakes child and parent html."""
assert os.path.exists(abfFname) and abfFname.endswith(".abf")
ABFfolder,ABFfname=os.path.split(abfFname)
abfID=os.path.splitext(ABFfname)[0]
IN=INDEX(ABFfolder)
IN.analyzeABF(abfID)
IN.sca... | python | {
"resource": ""
} |
q263967 | INDEX.scan | validation | def scan(self):
"""
scan folder1 and folder2 into files1 and files2.
since we are on windows, simplify things by making them all lowercase.
this WILL cause problems on 'nix operating systems.If this is the case,
just run a script to rename every file to all lowercase.
"""... | python | {
"resource": ""
} |
q263968 | INDEX.convertImages | validation | def convertImages(self):
"""
run this to turn all folder1 TIFs and JPGs into folder2 data.
TIFs will be treated as micrographs and converted to JPG with enhanced
contrast. JPGs will simply be copied over.
"""
# copy over JPGs (and such)
exts=['.jpg','.png']
... | python | {
"resource": ""
} |
q263969 | INDEX.analyzeAll | validation | def analyzeAll(self):
"""analyze every unanalyzed ABF in the folder."""
searchableData=str(self.files2)
self.log.debug("considering analysis for %d ABFs",len(self.IDs))
for ID in self.IDs:
if not ID+"_" in searchableData:
self.log.debug("%s needs analysis",ID)... | python | {
"resource": ""
} |
q263970 | INDEX.htmlFor | validation | def htmlFor(self,fname):
"""return appropriate HTML determined by file extension."""
if os.path.splitext(fname)[1].lower() in ['.jpg','.png']:
html='<a href="%s"><img src="%s"></a>'%(fname,fname)
if "_tif_" in fname:
html=html.replace('<img ','<img class="datapic ... | python | {
"resource": ""
} |
q263971 | INDEX.html_single_basic | validation | def html_single_basic(self,abfID,launch=False,overwrite=False):
"""
generate a generic flat file html for an ABF parent. You could give
this a single ABF ID, its parent ID, or a list of ABF IDs.
If a child ABF is given, the parent will automatically be used.
"""
if type(a... | python | {
"resource": ""
} |
q263972 | INDEX.html_single_plot | validation | def html_single_plot(self,abfID,launch=False,overwrite=False):
"""create ID_plot.html of just intrinsic properties."""
if type(abfID) is str:
abfID=[abfID]
for thisABFid in cm.abfSort(abfID):
parentID=cm.parent(self.groups,thisABFid)
saveAs=os.path.abspath("%s... | python | {
"resource": ""
} |
q263973 | convolve | validation | def convolve(signal,kernel):
"""
This applies a kernel to a signal through convolution and returns the result.
Some magic is done at the edges so the result doesn't apprach zero:
1. extend the signal's edges with len(kernel)/2 duplicated values
2. perform the convolution ('same' mode)
... | python | {
"resource": ""
} |
q263974 | timeit | validation | def timeit(timer=None):
"""simple timer. returns a time object, or a string."""
if timer is None:
return time.time()
else:
took=time.time()-timer
if took<1:
return "%.02f ms"%(took*1000.0)
elif took<60:
return "%.02f s"%(took)
else:
... | python | {
"resource": ""
} |
q263975 | list_move_to_front | validation | def list_move_to_front(l,value='other'):
"""if the value is in the list, move it to the front and return it."""
l=list(l)
if value in l:
l.remove(value)
l.insert(0,value)
return l | python | {
"resource": ""
} |
q263976 | list_move_to_back | validation | def list_move_to_back(l,value='other'):
"""if the value is in the list, move it to the back and return it."""
l=list(l)
if value in l:
l.remove(value)
l.append(value)
return l | python | {
"resource": ""
} |
q263977 | list_order_by | validation | def list_order_by(l,firstItems):
"""given a list and a list of items to be first, return the list in the
same order except that it begins with each of the first items."""
l=list(l)
for item in firstItems[::-1]: #backwards
if item in l:
l.remove(item)
l.insert(0,item)
... | python | {
"resource": ""
} |
q263978 | abfSort | validation | def abfSort(IDs):
"""
given a list of goofy ABF names, return it sorted intelligently.
This places things like 16o01001 after 16901001.
"""
IDs=list(IDs)
monO=[]
monN=[]
monD=[]
good=[]
for ID in IDs:
if ID is None:
continue
if 'o' in ID:
m... | python | {
"resource": ""
} |
q263979 | abfGroupFiles | validation | def abfGroupFiles(groups,folder):
"""
when given a dictionary where every key contains a list of IDs, replace
the keys with the list of files matching those IDs. This is how you get a
list of files belonging to each child for each parent.
"""
assert os.path.exists(folder)
files=os.listdir(fo... | python | {
"resource": ""
} |
q263980 | parent | validation | def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # ... | python | {
"resource": ""
} |
q263981 | userFolder | validation | def userFolder():
"""return the semi-temporary user folder"""
#path=os.path.abspath(tempfile.gettempdir()+"/swhlab/")
#don't use tempdir! it will get deleted easily.
path=os.path.expanduser("~")+"/.swhlab/" # works on windows or linux
# for me, path=r"C:\Users\swharden\.swhlab"
if not os.path.ex... | python | {
"resource": ""
} |
q263982 | _try_catch_coro | validation | async def _try_catch_coro(emitter, event, listener, coro):
"""Coroutine wrapper to catch errors after async scheduling.
Args:
emitter (EventEmitter): The event emitter that is attempting to
call a listener.
event (str): The event that triggered the emitter.
listener (async d... | python | {
"resource": ""
} |
q263983 | EventEmitter._check_limit | validation | def _check_limit(self, event):
"""Check if the listener limit is hit and warn if needed."""
if self.count(event) > self.max_listeners:
warnings.warn(
'Too many listeners for event {}'.format(event),
ResourceWarning,
) | python | {
"resource": ""
} |
q263984 | EventEmitter.add_listener | validation | def add_listener(self, event, listener):
"""Bind a listener to a particular event.
Args:
event (str): The name of the event to listen for. This may be any
string value.
listener (def or async def): The callback to execute when the event
fires. Thi... | python | {
"resource": ""
} |
q263985 | EventEmitter.once | validation | def once(self, event, listener):
"""Add a listener that is only called once."""
self.emit('new_listener', event, listener)
self._once[event].append(listener)
self._check_limit(event)
return self | python | {
"resource": ""
} |
q263986 | EventEmitter.remove_listener | validation | def remove_listener(self, event, listener):
"""Remove a listener from the emitter.
Args:
event (str): The event name on which the listener is bound.
listener: A reference to the same object given to add_listener.
Returns:
bool: True if a listener was removed... | python | {
"resource": ""
} |
q263987 | EventEmitter._dispatch_coroutine | validation | def _dispatch_coroutine(self, event, listener, *args, **kwargs):
"""Schedule a coroutine for execution.
Args:
event (str): The name of the event that triggered this call.
listener (async def): The async def that needs to be executed.
*args: Any number of positional a... | python | {
"resource": ""
} |
q263988 | EventEmitter._dispatch_function | validation | def _dispatch_function(self, event, listener, *args, **kwargs):
"""Execute a sync function.
Args:
event (str): The name of the event that triggered this call.
listener (def): The def that needs to be executed.
*args: Any number of positional arguments.
**... | python | {
"resource": ""
} |
q263989 | EventEmitter._dispatch | validation | def _dispatch(self, event, listener, *args, **kwargs):
"""Dispatch an event to a listener.
Args:
event (str): The name of the event that triggered this call.
listener (def or async def): The listener to trigger.
*args: Any number of positional arguments.
... | python | {
"resource": ""
} |
q263990 | EventEmitter.emit | validation | def emit(self, event, *args, **kwargs):
"""Call each listener for the event with the given arguments.
Args:
event (str): The event to trigger listeners on.
*args: Any number of positional arguments.
**kwargs: Any number of keyword arguments.
This method pass... | python | {
"resource": ""
} |
q263991 | EventEmitter.count | validation | def count(self, event):
"""Get the number of listeners for the event.
Args:
event (str): The event for which to count all listeners.
The resulting count is a combination of listeners added using
'on'/'add_listener' and 'once'.
"""
return len(self._listeners[... | python | {
"resource": ""
} |
q263992 | genPNGs | validation | def genPNGs(folder,files=None):
"""Convert each TIF to PNG. Return filenames of new PNGs."""
if files is None:
files=glob.glob(folder+"/*.*")
new=[]
for fname in files:
ext=os.path.basename(fname).split(".")[-1].lower()
if ext in ['tif','tiff']:
if not os.path.exists(... | python | {
"resource": ""
} |
q263993 | htmlABF | validation | def htmlABF(ID,group,d,folder,overwrite=False):
"""given an ID and the dict of files, generate a static html for that abf."""
fname=folder+"/swhlab4/%s_index.html"%ID
if overwrite is False and os.path.exists(fname):
return
html=TEMPLATES['abf']
html=html.replace("~ID~",ID)
html=html.repl... | python | {
"resource": ""
} |
q263994 | genIndex | validation | def genIndex(folder,forceIDs=[]):
"""expects a folder of ABFs."""
if not os.path.exists(folder+"/swhlab4/"):
print(" !! cannot index if no /swhlab4/")
return
timestart=cm.timethis()
files=glob.glob(folder+"/*.*") #ABF folder
files.extend(glob.glob(folder+"/swhlab4/*.*"))
print(" ... | python | {
"resource": ""
} |
q263995 | plotAllSweeps | validation | def plotAllSweeps(abfFile):
"""simple example how to load an ABF file and plot every sweep."""
r = io.AxonIO(filename=abfFile)
bl = r.read_block(lazy=False, cascade=True)
print(abfFile+"\nplotting %d sweeps..."%len(bl.segments))
plt.figure(figsize=(12,10))
plt.title(abfFile)
for sweep i... | python | {
"resource": ""
} |
q263996 | plot_shaded_data | validation | def plot_shaded_data(X,Y,variances,varianceX):
"""plot X and Y data, then shade its background by variance."""
plt.plot(X,Y,color='k',lw=2)
nChunks=int(len(Y)/CHUNK_POINTS)
for i in range(0,100,PERCENT_STEP):
varLimitLow=np.percentile(variances,i)
varLimitHigh=np.percentile(variances,i+P... | python | {
"resource": ""
} |
q263997 | show_variances | validation | def show_variances(Y,variances,varianceX,logScale=False):
"""create some fancy graphs to show color-coded variances."""
plt.figure(1,figsize=(10,7))
plt.figure(2,figsize=(10,7))
varSorted=sorted(variances)
plt.figure(1)
plt.subplot(211)
plt.grid()
plt.title("chronological varia... | python | {
"resource": ""
} |
q263998 | AP.ensureDetection | validation | def ensureDetection(self):
"""
run this before analysis. Checks if event detection occured.
If not, runs AP detection on all sweeps.
"""
if self.APs==False:
self.log.debug("analysis attempted before event detection...")
self.detect() | python | {
"resource": ""
} |
q263999 | AP.detect | validation | def detect(self):
"""runs AP detection on every sweep."""
self.log.info("initializing AP detection on all sweeps...")
t1=cm.timeit()
for sweep in range(self.abf.sweeps):
self.detectSweep(sweep)
self.log.info("AP analysis of %d sweeps found %d APs (completed in %s)",
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.