def Func(arg_0, arg_1):
        """Execute update subcommand."""
        if arg_1.name is not None:
            arg_0.print_workspace(arg_1.name)
        elif arg_1.all is not None:
            arg_0.print_all()


def Func(arg_0, arg_1, arg_2):
        """Print repository update."""
        arg_3 = Color()
        arg_0.logger.info(arg_3.colored(
            "=> [%s] %s" % (arg_1, arg_2), "green"))
        try:
            arg_4 = Repository(arg_2)
            arg_4.update()
        except RepositoryError as e:
            arg_0.logger.error(e)
            pass
        print("\n")


def Func(arg_0, arg_1, arg_2=None):
        """Execute command with os.popen and return output."""
        arg_3 = logging.getLogger(__name__)

        arg_0.check_executable()
        arg_3.debug("Executing command `%s` (cwd: %s)" % (arg_1, arg_2))
        arg_4 = subprocess.Popen(
            arg_1,
            shell=True,
            cwd=arg_2,
            arg_5=subprocess.PIPE,
            arg_6=subprocess.PIPE
        )
        arg_5, arg_6 = arg_4.communicate()
        arg_7 = arg_4.wait()

        if arg_5:
            arg_3.info(arg_5.decode("utf-8"))

        if arg_6:
            if arg_7 != 0:
                arg_3.error(arg_6.decode("utf-8"))
            else:
                arg_3.info(arg_6.decode("utf-8"))

        return arg_4


def Func(arg_0):
    """
    Import a png file into a numpy array.

    Arguments:
        png_filename (str): A string filename of a png datafile

    Returns:
        A numpy array with data from the png file
    """
    # Expand filename to be absolute
    arg_0 = os.path.expanduser(arg_0)

    try:
        arg_1 = Image.open(arg_0)
    except Exception as e:
        raise ValueError("Could not Func file {0} for conversion."
                         .format(arg_0))
        raise

    return numpy.array(arg_1)


def Func(arg_0, arg_1):
    """
    Export a numpy array to a png file.

    Arguments:
        filename (str): A filename to which to Func the png data
        numpy_data (numpy.ndarray OR str): The numpy array to Func to png.
            OR a string: If a string is provded, it should be a binary png str

    Returns:
        str. The expanded filename that now holds the png data

    Raises:
        ValueError: If the Func fails; for instance if the binary string data
            cannot be coerced into a png, or perhaps your numpy.ndarray is
            ill-formed?
    """
    # Expand filename to be absolute
    arg_2 = os.path.expanduser(arg_0)

    if type(arg_1) is str:
        arg_3 = open(arg_2, "wb")
        arg_3.write(arg_1)
        arg_3.close()
        return arg_2

    try:
        if arg_1.dtype.name != 'uint8':
            arg_4 = 'I'
            arg_5 = Image.fromarray(arg_1, mode=arg_4)
        else:
            arg_5 = Image.fromarray(arg_1)
        arg_5.Func(arg_2)
    except Exception as e:
        raise ValueError("Could not Func png file {0}.".format(arg_2))
    return arg_2


def Func(arg_0):
    """provide all stats on the first AP."""
    arg_1=""
    for arg_2 in range(arg_0.sweeps):
        for arg_3 in arg_0.APs[arg_2]:
            for arg_4 in sorted(arg_3.keys()):
                if arg_4[-1] is "I" or arg_4[-2:] in ["I1","I2"]:
                    continue
                arg_1+="%s = %s\n"%(arg_4,arg_3[arg_4])
            return arg_1


def Func(arg_0, arg_1):
        """Print workspace status."""
        arg_2 = find_path(arg_1, arg_0.config)

        if len(arg_2) == 0:
            arg_0.logger.error("No matches for `%s`" % arg_1)
            return False

        for arg_1, arg_3 in arg_2.items():
            arg_0.print_status(arg_1, arg_3)


def Func(arg_0, arg_1, arg_2):
        """Print repository status."""
        arg_3 = Color()
        arg_0.logger.info(arg_3.colored(
            "=> [%s] %s" % (arg_1, arg_2), "green"))
        try:
            arg_4 = Repository(arg_2)
            arg_4.status()
        except RepositoryError as e:
            arg_0.logger.error(e)
            pass
        print("\n")


def Func(arg_0):
    """easy way to plot a Func function."""
    arg_1=np.nan_to_num(swhlab.ap.getAvgBySweep(arg_0,'freq'))
    arg_2=arg_0.clampValues(arg_0.dataX[int(arg_0.protoSeqX[1]+.01)])
    swhlab.plot.new(arg_0,title="Func function",xlabel="command current (pA)",
                    ylabel="average inst. freq. (Hz)")
    pylab.plot(arg_2,arg_1,'.-',ms=20,alpha=.5,color='b')
    pylab.axhline(0,alpha=.5,lw=2,color='r',ls="--")
    pylab.margins(.1,.1)


def Func(arg_0,arg_1=False):
    """draw vertical lines at comment points. Defaults to seconds."""
    if not len(arg_0.commentTimes):
        return
    for arg_2 in range(len(arg_0.commentTimes)):
        arg_3,arg_4 = arg_0.commentTimes[arg_2],arg_0.commentTags[arg_2]
        if arg_1:
            arg_3=arg_3/60
        pylab.axvline(arg_3,lw=1,color='r',ls="--",alpha=.5)
        arg_5,arg_6,arg_7,arg_8=pylab.axis()
        arg_8=arg_8-abs(arg_8-arg_7)*.02
        pylab.text(arg_3,arg_8,arg_4,size=8,color='r',rotation='vertical',
                   ha='right',va='top',weight='bold',alpha=.5)
        if arg_1:
            pylab.xlabel("minutes")
        else:
            pylab.xlabel("seconds")


def Func(arg_0):
    """stamp the bottom with file info."""
    arg_1="SWHLab %s "%str(swhlab.VERSION)
    arg_1+="ID:%s "%arg_0.ID
    arg_1+="CH:%d "%arg_0.channel
    arg_1+="PROTOCOL:%s "%arg_0.protoComment
    arg_1+="COMMAND: %d%s "%(arg_0.holding,arg_0.units)
    arg_1+="GENERATED:%s "%'{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
    pylab.Func(arg_1,(.001,.001),xycoords='figure fraction',ha='left',
                   va='bottom',color='#999999',family='monospace',size=8,
                   weight='bold')
    if arg_0.nADC>1:
        arg_1="Ch %d/%d"%(arg_0.channel+1,arg_0.nADC)
        pylab.Func(arg_1,(.01,.99),xycoords='figure fraction',ha='left',
                       va='top',color='#FF0000',family='monospace',size=12,
                       weight='bold')


def Func(arg_0,arg_1=False,arg_2=None,arg_3=None,arg_4=None):
    """
    makes a Func matplotlib figure with default dims and DPI.
    Also labels it with pA or mV depending on ABF.
    """
    if len(pylab.get_fignums()) and arg_1==False:
        #print("adding to existing figure")
        return
    pylab.figure(figsize=(8,6))
    pylab.grid(alpha=.5)
    pylab.title(arg_0.ID)
    pylab.ylabel(arg_0.units)
    pylab.xlabel("seconds")
    if arg_3:
        pylab.xlabel(arg_3)
    if arg_4:
        pylab.ylabel(arg_4)
    if arg_2:
        pylab.title(arg_2)
    annotate(arg_0)


def Func(arg_0):
    """
    Import a TIFF file into a numpy array.

    Arguments:
        tiff_filename:  A string filename of a TIFF datafile

    Returns:
        A numpy array with data from the TIFF file
    """
    # Expand filename to be absolute
    arg_0 = os.path.expanduser(arg_0)

    try:
        arg_1 = tiff.imread(arg_0)
    except Exception as e:
        raise ValueError("Could not Func file {0} for conversion."
                         .format(arg_0))
        raise

    return numpy.array(arg_1)


def Func(arg_0):
        """
        When dynamic, not all argument values may be available.
        """
        arg_1 = arg_0.copy()
        arg_2 = [el for el in enumerate(arg_1)]
        for (arg_3, arg_4) in arg_2:
            if len(arg_2) > 1: print("Group %d" % arg_3)
            arg_5 = arg_0.constant_keys + arg_0.varying_keys
            # Ordered nicely by varying_keys definition.
            arg_6 = [', '.join(['%s=%s' % (k, s[k]) for k in arg_5]) for s in arg_4]
            print('\n'.join(['%d: %s' % (arg_7,arg_8) for (arg_7,arg_8) in enumerate(arg_6)]))

        print('Remaining arguments not available for %s' % arg_0.__class__.__name__)


def Func(arg_0):
        """
        Summarizes the trace of values used to update the DynamicArgs
        and the arguments subsequently returned. May be used to
        implement the summary method.
        """
        for (arg_1, (arg_2, arg_3)) in enumerate(arg_0.trace):
            if arg_3 is StopIteration:
                arg_4 = "Terminated"
            else:
                arg_5 = ','.join('{' + ','.join('%s=%r' % (k,v)
                         for (k,v) in arg.items()) + '}' for arg in arg_3)
                arg_4 = ("exploring arguments [%s]" % arg_5 )

            if arg_1 == 0: print("Step %d: Initially %s." % (arg_1, arg_4))
            else:      print("Step %d: %s after receiving input(s) %s." % (arg_1, arg_4.capitalize(), arg_2))


def Func(arg_0, arg_1):
        """
        Takes as input a list or tuple of two elements. First the
        value returned by incrementing by 'stepsize' followed by the
        value returned after a 'stepsize' decrement.
        """
        arg_0._steps_complete += 1
        if arg_0._steps_complete == arg_0.max_steps:
            arg_0._termination_info = (False, arg_0._best_val, arg_0._arg)
            return StopIteration

        arg_3, arg_4 = arg_1
        arg_5 = min(arg_3, arg_4, arg_0._best_val)
        if arg_5 == arg_0._best_val:
            arg_0._termination_info = (True, arg_5, arg_0._arg)
            return StopIteration

        arg_0._arg += arg_0.stepsize if (arg_4 > arg_3) else -arg_0.stepsize
        arg_0._best_val= arg_5
        return [{arg_0.key:arg_0._arg+arg_0.stepsize},
                {arg_0.key:arg_0._arg-arg_0.stepsize}]


def Func(arg_0=False,arg_1=True,arg_2=None):
    """given a filename or ABF object, try to Func it."""
    if arg_0 and os.path.exists(arg_0.replace(".abf",".rst")):
        print("SKIPPING DUE TO RST FILE")
        return
    arg_3.plotting.core.IMAGE_SAVE=arg_1
    if arg_2 is None:
        if cm.isIpython():
            arg_3.plotting.core.IMAGE_SHOW=True
        else:
            arg_3.plotting.core.IMAGE_SHOW=False
    #swhlab.plotting.core.IMAGE_SHOW=show
    arg_8=ABF(arg_0) # ensure it's a class
    print(">>>>> PROTOCOL >>>>>",arg_8.protocomment)
    arg_9="proto_unknown"
    if "proto_"+arg_8.protocomment in globals():
        arg_9="proto_"+arg_8.protocomment
    arg_8.log.debug("running %s()"%(arg_9))
    plt.close('all') # get ready
    globals()[arg_9](arg_8) # run that function
    try:
        globals()[arg_9](arg_8) # run that function
    except:
        arg_8.log.error("EXCEPTION DURING PROTOCOL FUNCTION")
        arg_8.log.error(sys.exc_info()[0])
        return "ERROR"
    plt.close('all') # clean up
    return "SUCCESS"


def Func():
    """Get version from package resources."""
    arg_0 = pkg_resources.Requirement.parse("yoda")
    arg_1 = pkg_resources.get_provider(arg_0)
    return arg_1.version


def Func(arg_0,arg_1="",arg_2="plot",arg_3=False,arg_4=True):
    """
    frame the current matplotlib plot with ABF info, and optionally save it.
    Note that this is entirely independent of the ABFplot class object.
    if saveImage is False, show it instead.

    Datatype should be:
        * plot
        * experiment
    """
    print("closeWhenDone",arg_4)
    plt.tight_layout()
    plt.subplots_adjust(top=.93,bottom =.07)
    plt.annotate(arg_1,(.01,.99),xycoords='figure fraction',ha='left',va='top',family='monospace',size=10,alpha=.5)
    arg_5="%s [%s]"%(arg_0.ID,arg_0.protocomment)
    plt.annotate(arg_5,(.01,.01),xycoords='figure fraction',ha='left',va='bottom',family='monospace',size=10,alpha=.5)
    arg_6=arg_1.lower().replace(" ",'_')+".jpg"
    arg_6=arg_2+"_"+arg_6
    plt.tight_layout()
    if IMAGE_SAVE:
        arg_0.log.info("saving [%s]",arg_6)
        try:
            if arg_3:
                arg_7=os.path.abspath(arg_3)
            else:
                arg_7=os.path.abspath(arg_0.outPre+arg_6)
            if not os.path.exists(arg_0.outFolder):
                os.mkdir(arg_0.outFolder)
            plt.savefig(arg_7)
        except Exception as E:
            arg_0.log.error("saving [%s] failed! 'pip install pillow'?",arg_6)
            print(E)
    if IMAGE_SHOW==True:
        if arg_4==False:
            print("NOT SHOWING (because closeWhenDone==True and showing would mess things up)")
        else:
            arg_0.log.info("showing [%s]",arg_6)
            plt.show()
    if arg_4:
        print("closing figure")
        plt.close('all')


def Func(arg_0,arg_1=False):
        """make sure a Func is ready."""
        if plt._pylab_helpers.Gcf.get_num_fig_managers()>0 and arg_1 is False:
            arg_0.log.debug("Func already seen, not creating one.")
            return

        if arg_0.subplot:
            arg_0.log.debug("subplot mode enabled, not creating new Func")
        else:
            arg_0.log.debug("creating new Func")
            plt.Func(figsize=(arg_0.Func_width,arg_0.Func_height))


def Func(arg_0,arg_1="misc",arg_2=True,arg_3=False):
        """Func the existing figure. does not close it."""
        if arg_3 is False:
            arg_4=arg_0.abf.outPre+"plot_"+arg_1+".jpg"
        else:
            arg_4=arg_1
        if not os.path.exists(os.path.dirname(arg_4)):
            os.mkdir(os.path.dirname(arg_4))
        plt.Funcfig(arg_4)
        arg_0.log.info("Funcd [%s]",os.path.basename(arg_4))
        if arg_2:
            plt.close()


def Func(arg_0, arg_1=0, arg_2=0):
        """plot every sweep of an ABF file."""
        arg_0.log.debug("creating overlayed sweeps plot")
        arg_0.figure()
        for arg_3 in range(arg_0.abf.sweeps):
            arg_0.abf.setsweep(arg_3)
            arg_0.setColorBySweep()
            plt.plot(arg_0.abf.sweepX2+arg_3*arg_1,
                     arg_0.abf.sweepY+arg_3*arg_2,
                     **arg_0.kwargs)
        if arg_1:
            arg_0.marginX=.05
        arg_0.decorate()


def Func(arg_0):
        """plot the current sweep protocol."""
        arg_0.log.debug("creating overlayed protocols plot")
        arg_0.figure()
        plt.plot(arg_0.abf.protoX,arg_0.abf.protoY,color='r')
        arg_0.marginX=0
        arg_0.decorate(protocol=True)


def Func(arg_0):
        """plot the protocol of all sweeps."""
        arg_0.log.debug("creating overlayed protocols plot")
        arg_0.figure()
        for arg_1 in range(arg_0.abf.sweeps):
            arg_0.abf.setsweep(arg_1)
            plt.plot(arg_0.abf.protoX,arg_0.abf.protoY,color='r')
        arg_0.marginX=0
        arg_0.decorate(protocol=True)


def Func(arg_0, arg_1, arg_2):
    '''Same as mix_and_match, but using the @option decorator.'''
    # Use the @option decorator when you need more control over the
    # command line options.
    arg_3 = '%s, %s' % (arg_1, arg_0)
    if arg_2:
        print '%s!' % arg_3.upper()
    else:
        print '%s.' % arg_3


def Func(arg_0,arg_1):
    """
    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(arg_1)==1 and type(arg_1)==str, "replacement character must be a single character"
    assert os.path.exists(arg_0), "path doesn't exist"
    arg_2 = sorted(os.listdir(arg_0))
    arg_2 = [x for x in arg_2 if len(x)>18 and x[4]+x[7]+x[10]=='___']
    for arg_3 in arg_2:
        arg_4 = list(arg_3)
        arg_4[11]=arg_1
        arg_4="".join(arg_4)

        if arg_3==arg_4:
            print(arg_3, "==", arg_4)
        else:
            print(arg_3, "->", arg_4)
#            fname=os.path.join(path,fname)
#            fname2=os.path.join(path,fname2)
#            if not os.path.exists(fname2):
#                os.rename(fname,fname2)
    return


def Func(arg_0, arg_1):
        """
        Returns info regarding a particular dataset.

        Arugments:
            name (str): Dataset name

        Returns:
            dict: Dataset information
        """
        arg_2 = arg_0.url() + "/resource/dataset/{}".format(arg_1)
        arg_3 = arg_0.remote_utils.get_url(arg_2)

        if arg_3.status_code is not 200:
            raise RemoteDataNotFoundError('Could not find {}'.format(arg_3.text))
        else:
            return arg_3.json()


def Func(arg_0, arg_1):
        """
        Lists datasets in resources. Setting 'get_global_public' to 'True'
        will retrieve all public datasets in cloud. 'False' will get user's
        public datasets.

        Arguments:
            get_global_public (bool): True if user wants all public datasets in
                                      cloud. False if user wants only their
                                      public datasets.

        Returns:
            dict: Returns datasets in JSON format

        """
        arg_2 = ""
        if arg_1:
            arg_2 = "public"
        arg_3 = arg_0.url() + "/resource/{}dataset/".format(arg_2)
        arg_4 = arg_0.remote_utils.get_url(arg_3)

        if arg_4.status_code is not 200:
            raise RemoteDataNotFoundError('Could not find {}'.format(arg_4.text))
        else:
            return arg_4.json()


def Func(arg_0, arg_1):
        """Show specific workspace."""
        if not arg_0.workspace.exists(arg_1):
            raise ValueError("Workspace `%s` doesn't exists." % arg_1)

        arg_2 = Color()
        arg_3 = arg_0.workspace.list()

        arg_0.logger.info("<== %s workspace ==>" % arg_2.colored(arg_1, "green"))
        arg_0.logger.info("\tPath: %s" % arg_3[arg_1]["path"])
        arg_0.logger.info("\tNumber of repositories: %s"
                         % arg_2.colored(
                             len(arg_3[arg_1]["repositories"]),
                             "yellow"))

        arg_4 = arg_2.colored("Repositories", "blue")
        arg_5 = arg_2.colored("Path", "blue")
        arg_6 = PrettyTable(
            [arg_4, arg_5, arg_2.colored("+", "blue")])
        arg_6.align[arg_4] = "l"
        arg_6.align[arg_5] = "l"

        for arg_8 in arg_3[arg_1]["repositories"]:
            arg_9 = "%s/%s" % (arg_1, arg_8)
            arg_10 = find_path(arg_9, arg_0.config)[arg_9]
            try:
                arg_11 = Repository(arg_10)
                arg_12 = arg_11.get_scm()
            except RepositoryAdapterNotFound:
                arg_12 = None
            arg_6.add_row(
                [arg_2.colored(arg_8, "cyan"), arg_10, arg_12])

        arg_0.logger.info(arg_6)


def Func(arg_0):
        """Show details for all workspaces."""
        for arg_1 in arg_0.workspace.list().keys():
            arg_0.show_workspace(arg_1)
            print("\n\n")


def Func(arg_0, arg_1=''):
        """
        Get the base URL of the Remote.

        Arguments:
            None
        Returns:
            `str` base URL
        """
        if not arg_1.startswith('/'):
            arg_1 = "/" + arg_1
        return arg_0.protocol + "://" + arg_0.hostname + arg_1


def Func(arg_0,arg_1):
    """given files and cells, return a dict of files grouped by cell."""
    arg_2={}
    arg_0=smartSort(arg_0)
    arg_3 = list(set([elem[:5] for elem in arg_0 if elem.endswith(".abf")])) # so pythonic!
    for arg_4 in smartSort(arg_3):
        arg_5=None
        for arg_6,arg_7 in enumerate([elem for elem in arg_0 if elem.startswith(arg_4) and elem.endswith(".abf")]):
            arg_8=os.path.splitext(arg_7)[0]
            if len([arg_9 for arg_9 in arg_0 if arg_9.startswith(arg_8)])-1:
                arg_5=arg_8
            if not arg_5 in arg_2:
                arg_2[arg_5]=[]
            arg_2[arg_5]=arg_2[arg_5]+[arg_7]
    return arg_2


def Func(arg_0,arg_1=None):
        """populate class properties relating to files in the folder."""
        if arg_1 is None and 'abfFolder' in dir(arg_0):
            arg_1=arg_0.abfFolder
        else:
            arg_0.abfFolder=arg_1
        arg_0.abfFolder=os.path.abspath(arg_0.abfFolder)
        arg_0.log.info("scanning [%s]",arg_0.abfFolder)
        if not os.path.exists(arg_0.abfFolder):
            arg_0.log.error("path doesn't exist: [%s]",arg_1)
            return
        arg_0.abfFolder2=os.path.abspath(arg_0.abfFolder+"/swhlab/")
        if not os.path.exists(arg_0.abfFolder2):
            arg_0.log.error("./swhlab/ doesn't exist. creating it...")
            os.mkdir(arg_0.abfFolder2)
        arg_0.fnames=os.listdir(arg_0.abfFolder)
        arg_0.fnames2=os.listdir(arg_0.abfFolder2)
        arg_0.log.debug("./ has %d files",len(arg_0.fnames))
        arg_0.log.debug("./swhlab/ has %d files",len(arg_0.fnames2))
        arg_0.fnamesByExt = filesByExtension(arg_0.fnames)
        if not "abf" in arg_0.fnamesByExt.keys():
            arg_0.log.error("no ABF files found")
        arg_0.log.debug("found %d ABFs",len(arg_0.fnamesByExt["abf"]))

        arg_0.cells=findCells(arg_0.fnames) # list of cells by their ID
        arg_0.log.debug("found %d cells"%len(arg_0.cells))

        arg_0.fnamesByCell = filesByCell(arg_0.fnames,arg_0.cells) # only ABFs
        arg_0.log.debug("grouped cells by number of source files: %s"%\
            str([len(arg_0.fnamesByCell[arg_8]) for arg_8 in arg_0.fnamesByCell]))


def Func(arg_0,arg_1=False,arg_2=False):
        """
        generate list of cells with links. keep this simple.
        automatically generates splash page and regnerates frames.
        """
        arg_0.makePics() # ensure all pics are converted
        # generate menu
        arg_3='./%s/
'%os.path.basename(arg_0.abfFolder)
        for arg_4 in smartSort(arg_0.fnamesByCell.keys()):
            arg_5=''
            if arg_4+".html" in arg_0.fnames2:
                arg_5='href="%s.html" target="content"'%arg_4
            arg_3+=('%s
'%(arg_5,arg_4)) # show the parent ABF (ID)
            if arg_2:
                for arg_6 in arg_0.fnamesByCell[arg_4]:
                    arg_7=os.path.splitext(arg_6)[0]
                    arg_8=[x for x in arg_0.fnames2 if x.startswith(arg_7) and not x.endswith(".html")]
                    arg_3+='%s'%arg_7 # show the child ABF
                    if len(arg_8):
                        arg_3+=' (%s)'%len(arg_8) # show number of supporting files
                    arg_3+='
'
                arg_3+="
"
        style.save(arg_3,arg_0.abfFolder2+"/index_menu.html")
        arg_0.Func_splash() # make splash page
        style.frames(arg_0.abfFolder2+"/index.html",arg_1=arg_1)


def Func(arg_0,arg_1="basic"):
        """generate a data view for every ABF in the project folder."""
        for arg_2 in smartSort(arg_0.cells):
            if arg_1=="fixed":
                arg_0.html_single_fixed(arg_2)
            else:
                arg_0.html_single_basic(arg_2)


def Func(arg_0=arg_1):
    """IC steps. See how hyperpol. step affects things."""
    swhlab.ap.detect(arg_0)
    standard_groupingForInj(arg_0,200)

    for arg_2 in ['freq','downslope']:
        swhlab.ap.plot_values(arg_0,arg_2,continuous=False) #plot AP info
        swhlab.plot.save(arg_0,tag='A_'+arg_2)

    arg_3=swhlab.ap.getAvgBySweep(arg_0,'freq',None,1)
    arg_4=swhlab.ap.getAvgBySweep(arg_0,'freq',1,None)
    arg_3=np.nan_to_num(arg_3)
    arg_4=np.nan_to_num(arg_4)
    arg_5=arg_0.clampValues(arg_0.dataX[int(arg_0.protoSeqX[1]+.01)])
    swhlab.plot.new(arg_0,title="gain function",xlabel="command current (pA)",
                    ylabel="average inst. freq. (Hz)")
    pylab.plot(arg_5,arg_3,'.-',ms=20,alpha=.5,label="step 1",color='b')
    pylab.plot(arg_5,arg_4,'.-',ms=20,alpha=.5,label="step 2",color='r')
    pylab.legend(loc='upper left')
    pylab.axis([arg_5[0],arg_5[-1],None,None])
    swhlab.plot.save(arg_0,tag='gain')


def Func(arg_0=arg_1):
    """repeated membrane tests."""
    standard_overlayWithAverage(arg_0)
    swhlab.memtest.memtest(arg_0)
    swhlab.memtest.checkSweep(arg_0)
    swhlab.plot.save(arg_0,tag='check',resize=False)


def Func(arg_0=arg_1):
    """fast sweeps, 1 step per sweep, for clean IV without fast currents."""
    arg_2,arg_3=swhlab.plot.IV(arg_0,.6,.9,True)
    swhlab.plot.save(arg_0,tag='iv1')
    arg_4=arg_0.clampValues(.6) #generate IV clamp values
    arg_0.saveThing([arg_4,arg_2],'iv')


def Func(arg_0=arg_1):
    """combination of membrane test and IV steps."""
    swhlab.memtest.memtest(arg_0) #do membrane test on every sweep
    swhlab.memtest.checkSweep(arg_0) #see all MT values
    swhlab.plot.save(arg_0,tag='02-check',resize=False)

    arg_2,arg_3=swhlab.plot.IV(arg_0,1.2,1.4,True,'b')
    swhlab.plot.save(arg_0,tag='iv')
    arg_4=arg_0.clampValues(1.2) #generate IV clamp values
    arg_0.saveThing([arg_4,arg_2],'01_iv')


def Func(arg_0,arg_1="index.html"):
    """OBSOLETE WAY TO INDEX A FOLDER.""" #TODO: REMOVE
    arg_2=""
    for arg_3 in glob.glob(arg_0+"/*.*"):
        if arg_3.split(".")[-1] in ['jpg','png']:
            arg_2+="
%s
"%os.path.basename(arg_3)
            arg_2+=''%os.path.basename(arg_3)
            arg_2+='
'*10
    arg_2+=""
    arg_4=open(arg_0+"/"+arg_1,'w')
    arg_4.write(arg_2)
    arg_4.close
    print("indexed:")
    print("  ",os.path.abspath(arg_0+"/"+arg_1))
    return


def Func(arg_0, *arg_1, **arg_2):
        """
        A custom Func method that handles figuring out when something is activated or deactivated.
        """
        arg_3 = getattr(arg_0, arg_0.ACTIVATABLE_FIELD_NAME)
        arg_4 = arg_0.id is None or arg_0.__original_activatable_value != arg_3
        arg_0.__original_activatable_value = arg_3

        arg_6 = super(BaseActivatableModel, arg_0).Func(*arg_1, **arg_2)

        # Emit the signals for when the is_active flag is changed
        if arg_4:
            model_activations_changed.send(arg_0.__class__, instance_ids=[arg_0.id], is_active=arg_3)
        if arg_0.activatable_field_updated:
            model_activations_updated.send(arg_0.__class__, instance_ids=[arg_0.id], is_active=arg_3)

        return arg_6


def Func(arg_0, arg_1=False, **arg_2):
        """
        It is impossible to Func an activatable model unless force is True. This function instead sets it to inactive.
        """
        if arg_1:
            return super(BaseActivatableModel, arg_0).Func(**arg_2)
        else:
            setattr(arg_0, arg_0.ACTIVATABLE_FIELD_NAME, False)
            return arg_0.save(update_fields=[arg_0.ACTIVATABLE_FIELD_NAME])


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        "Write to file_handle if supplied, othewise print output"
        arg_4 = ''
        arg_5 = {'root_directory':     '<root_directory>',
                'batch_name':         '<batch_name>',
                'batch_tag':          '<batch_tag>',
                'batch_description':  '<batch_description>',
                'launcher':        '<launcher>',
                'timestamp_format':   '<timestamp_format>',
                'timestamp':          tuple(time.localtime()),
                'varying_keys':       arg_1.varying_keys,
                'constant_keys':      arg_1.constant_keys,
                'constant_items':     arg_1.constant_items}

        arg_6 = [ subprocess.list2cmdline(
                [el for el in arg_0(arg_0._formatter(s),'<tid>',arg_5)])
                        for s in arg_1.specs]

        arg_7 = ['%d: %s\n' % (i, qcmds) for (i,qcmds)
                     in enumerate(arg_6)]
        arg_4 += ''.join(arg_7)
        if arg_2:
            arg_2.write(arg_4)
            arg_2.flush()
        else:
            print(arg_4)


def Func(arg_0, arg_1=None):
        """
        A helper method that supplies the root directory name given a
        timestamp.
        """
        if arg_1 is None: arg_1 = arg_0.timestamp
        if arg_0.timestamp_format is not None:
            arg_2 =  (time.strftime(arg_0.timestamp_format, arg_1)
                          + '-' + arg_0.batch_name)
        else:
            arg_2 = arg_0.batch_name

        arg_3 = os.path.join(arg_0.output_directory,
                                *(arg_0.subdir+[arg_2]))
        return os.path.abspath(arg_3)


def Func(arg_0, arg_1):
        """
        The log contains the tids and corresponding specifications
        used during launch with the specifications in JSON format.
        """
        arg_0._spec_log += arg_1 # This should be removed
        arg_2 = os.path.join(arg_0.root_directory, ("%s.log" % arg_0.batch_name))
        core.Log.write_log(arg_2, [arg_4 for (arg_3, arg_4) in arg_1], allow_append=True)


def Func(arg_0, arg_1=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
        info file is updated with the end-time.
        """
        arg_2 = os.path.join(arg_0.root_directory, ('%s.info' % arg_0.batch_name))

        if arg_1 is None:
            try:
                with open(arg_2, 'r') as info_file:
                    arg_1 = json.load(info_file)
            except:
                arg_1 = {}

            arg_1.update({'end_time' : tuple(time.localtime())})
        else:
            arg_1.update({
                'end_time' : None,
                'metadata' : arg_0.metadata
                })

        with open(arg_2, 'w') as info_file:
            json.dump(arg_1, info_file, sort_keys=True, indent=4)


def Func(arg_0, arg_1, arg_2):
        """
        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 until max_concurrency is
        reached again.
        """
        arg_3 = {}
        def check_complete_processes(arg_4=False):
            """
            Returns True if a process completed, False otherwise.
            Optionally allows waiting for better performance (avoids
            sleep-poll cycle if possible).
            """
            arg_5 = False
            # list creates copy of keys, as dict is modified in loop
            for arg_6 in list(arg_3):
                if arg_4: arg_6.wait()
                if arg_6.poll() is not None:
                    # process is done, free up slot
                    arg_0.debug("Process %d exited with code %d."
                               % (arg_3[arg_6]['tid'], arg_6.poll()))
                    arg_3[arg_6]['stdout'].close()
                    arg_3[arg_6]['stderr'].close()
                    del arg_3[arg_6]
                    arg_5 = True
            return arg_5

        for arg_7, arg_8 in arg_1:
            arg_0.debug("Starting process %d..." % arg_8)
            arg_9 = time.strftime('%H%M%S')
            arg_10 = "%s_%s_tid_%d" % (arg_0.batch_name, arg_9, arg_8)
            arg_11 = open(os.path.join(arg_2, "%s.o.%d"
                                              % (arg_10, arg_8)), "wb")
            arg_12 = open(os.path.join(arg_2, "%s.e.%d"
                                              % (arg_10, arg_8)), "wb")
            arg_6 = subprocess.Popen(arg_7, stdout=arg_11, stderr=arg_12)
            arg_3[arg_6] = { 'tid' : arg_8,
                                'stdout' : arg_11,
                                'stderr' : arg_12 }

            if arg_0.max_concurrency:
                # max_concurrency reached, wait until more slots available
                while len(arg_3) >= arg_0.max_concurrency:
                    if not check_complete_processes(len(arg_3)==1):
                        time.sleep(0.1)

        # Wait for all processes to complete
        while len(arg_3) > 0:
            if not check_complete_processes(True):
                time.sleep(0.1)


def Func(arg_0):
        """
        A succinct Func of the Launcher configuration.  Unlike the
        repr, a Func does not have to be complete but must supply
        key information relevant to the user.
        """
        print("Type: %s" % arg_0.__class__.__name__)
        print("Batch Name: %r" % arg_0.batch_name)
        if arg_0.tag:
            print("Tag: %s" % arg_0.tag)
        print("Root directory: %r" % arg_0.get_root_directory())
        print("Maximum concurrency: %s" % arg_0.max_concurrency)
        if arg_0.description:
            print("Description: %s" % arg_0.description)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        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.
        """

        arg_4 = "%s_%s_collate_%d" % (arg_0.batch_name,
                                         arg_0.job_timestamp,
                                         arg_0.collate_count)

        arg_5 = [("-e",arg_2), ('-N',arg_4), ("-o",arg_1),
                     ('-hold_jid',','.join(arg_3))]

        arg_6 =["import os, pickle, lancet",
                      ("pickle_path = os.path.join(%r, 'qlauncher.pkl')"
                       % arg_0.root_directory),
                      "launcher = pickle.load(open(pickle_path,'rb'))",
                      "launcher.collate_and_launch()"]

        arg_7 = [arg_0.command.executable,
                    '-c', ';'.join(arg_6)]
        arg_8 = arg_0._qsub_args(arg_5, arg_7)

        arg_9 = subprocess.Popen(arg_8, arg_10=subprocess.PIPE)
        (arg_10, arg_11) = arg_9.communicate()

        arg_0.debug(arg_10)
        if arg_9.poll() != 0:
            raise EnvironmentError("qsub command exit with code: %d" % arg_9.poll())

        arg_0.collate_count += 1
        arg_0.message("Invoked qsub for next batch.")
        return arg_4


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        This method handles static argument specifiers and cases where
        the dynamic specifiers cannot be queued before the arguments
        are known.
        """
        arg_4 = []
        arg_5 = []

        for (arg_6, arg_7) in arg_3:
            arg_8 = "%s_%s_tid_%d" % (arg_0.batch_name, arg_0.job_timestamp, arg_6)
            arg_5.append(arg_8)
            arg_9 = arg_0.command(
                    arg_0.command._formatter(arg_7),
                    arg_6, arg_0._launchinfo)

            arg_10 = arg_0._qsub_args([("-e",arg_2), ('-N',arg_8), ("-o",arg_1)],
                                        arg_9)
            arg_11 = subprocess.Popen(arg_10, arg_12=subprocess.PIPE)
            (arg_12, arg_13) = arg_11.communicate()

            arg_0.debug(arg_12)
            if arg_11.poll() != 0:
                raise EnvironmentError("qsub command exit with code: %d" % arg_11.poll())

            arg_4.append(arg_11)

        arg_0.message("Invoked qsub for %d commands" % len(arg_4))
        if (arg_0.reduction_fn is not None) or arg_0.dynamic:
            arg_0._qsub_collate_and_launch(arg_1, arg_2, arg_5)


def Func(arg_0, arg_1, arg_2):
        """
        Aggregates all process_commands and the designated output files into a
        list, and outputs it as JSON, after which the wrapper script is called.
        """
        arg_3 = []
        for arg_4, arg_5 in arg_1:
            arg_6 = time.strftime('%H%M%S')
            arg_7 = "%s_%s_tid_%d" % (arg_0.batch_name, arg_6, arg_5)
            arg_8 = os.path.join(arg_2, "%s.o.%d" % (arg_7, arg_5))
            arg_9 = os.path.join(arg_2, "%s.e.%d" % (arg_7, arg_5))
            arg_10 = { 'tid' : arg_5,
                        'cmd' : arg_4,
                        'stdout' : arg_8,
                        'stderr' : arg_9 }
            arg_3.append(arg_10)

        # To make the JSON filename unique per group, we use the last tid in
        # this group.
        arg_11 = os.path.join(arg_0.root_directory, arg_0.json_name % (arg_5))
        with open(arg_11, 'w') as json_file:
            json.dump(arg_3, json_file, sort_keys=True, indent=4)

        arg_12 = subprocess.Popen([arg_0.script_path, arg_11, arg_0.batch_name,
                              str(len(arg_3)), str(arg_0.max_concurrency)])
        if arg_12.wait() != 0:
            raise EnvironmentError("Script command exit with code: %d" % arg_12.poll())


def Func(arg_0, arg_1):
        """
        Performs consistency checks across all the launchers.
        """
        if len(arg_1) == 0: raise Exception('Empty launcher list')
        arg_2 = [arg_5.timestamp for arg_5 in arg_1]

        if not all(arg_2[0] == arg_3 for arg_3 in arg_2):
            raise Exception("Launcher timestamps not all equal. "
                            "Consider setting timestamp explicitly.")

        arg_4 = []
        for arg_5 in arg_1:
            arg_6 = arg_5.command
            arg_7 = arg_5.args
            arg_6.verify(arg_7)
            arg_8 = arg_5.get_root_directory()
            if os.path.isdir(arg_8):
                raise Exception("Root directory already exists: %r" % arg_8)
            if arg_8 in arg_4:
                raise Exception("Each launcher requires a unique root directory")
            arg_4.append(arg_8)


def Func(arg_0, arg_1):
        """
        Launches all available launchers.
        """
        for arg_2 in arg_1:
            print("== Launching  %s ==" % arg_2.batch_name)
            arg_2()
        return True


def Func(arg_0, arg_1, arg_2='Select option', arg_3=None):
        """
        Helper to prompt the user for input on the commandline.
        """
        arg_4 = [x.lower() for x in arg_1]
        while True:
            arg_5 = input('%s [%s]: ' % (arg_2, ', '.join(arg_1))).lower()
            if arg_5 in arg_4: return arg_5.strip()
            elif arg_5 == '' and arg_3 is not None:
                return arg_3.lower().strip()


def Func(arg_0, arg_1,  arg_2={}, **arg_3):
        """
        The implementation in the base class simply checks there is no
        clash between the metadata and data keys.
        """
        arg_4 = set(arg_2.keys()) & set(arg_3.keys())
        if arg_4:
            arg_5 = 'Key(s) overlap between data and metadata: %s'
            raise Exception(arg_5  % ','.join(arg_4))


def Func(arg_0, arg_1):
        """
        Returns the full path for saving the file, adding an extension
        and making the filename unique as necessary.
        """
        (arg_2, arg_3) = os.path.splitext(arg_1)
        arg_2 = arg_2 if (arg_3 in arg_0.extensions) else arg_1
        arg_3 = arg_3 if (arg_3 in arg_0.extensions) else arg_0.extensions[0]
        arg_4 = os.path.abspath(os.path.join(arg_0.directory,
                                                 '%s%s' % (arg_2, arg_3)))
        return (tempfile.mkstemp(arg_3, arg_2 + "_", arg_0.directory)[1]
                if arg_0.hash_suffix else arg_4)


def Func(arg_0, arg_1):
        """
        Returns a boolean indicating whether the filename has an
        appropriate extension for this class.
        """
        if not isinstance(arg_1, str):
            return False
        (arg_2, arg_3) = os.path.splitext(arg_1)
        if arg_3 not in arg_0.extensions:
            return False
        else:
            return True


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Data may be either a PIL Image object or a Numpy array.
        """
        if isinstance(arg_2, numpy.ndarray):
            arg_2 = Image.fromarray(numpy.uint8(arg_2))
        elif isinstance(arg_2, Image.Image):
            arg_2.Func(arg_0._Funcpath(arg_1))


def Func(arg_0):
    """return "YYYY-MM-DD" when the file was modified."""
    arg_1=os.path.getmtime(arg_0)
    arg_2=time.strftime('%Y-%m-%d', time.localtime(arg_1))
    return arg_2


def Func(arg_0):
    """returns a dict of active folders with days as keys."""
    with open(arg_0) as f:
        arg_1=f.read().split("\n")
    arg_2={}
    for arg_3 in arg_1:
        arg_4=arg_3.split('"')[1]+"\\"
        arg_3=[]+arg_3.split('"')[2].split(", ")
        for arg_5 in arg_3[1:]:
            if not arg_5 in arg_2:
                arg_2[arg_5]=[]
            arg_2[arg_5]=arg_2[arg_5]+[arg_4]
    arg_6=len(arg_2)
    arg_7=sorted(arg_2.keys())[0]
    arg_8=sorted(arg_2.keys())[-1]
    arg_7=datetime.datetime.strptime(arg_7, "%Y-%m-%d" )
    arg_8=datetime.datetime.strptime(arg_8, "%Y-%m-%d" )
    arg_9 = (arg_8 - arg_7).days + 1
    arg_10=0
    for arg_11 in range(arg_9):
        arg_5=arg_7+datetime.timedelta(days=arg_11)
        arg_12=datetime.datetime.strftime(arg_5, "%Y-%m-%d" )
        if not arg_12 in arg_2:
            arg_2[arg_12]=[]
            arg_10+=1
    arg_13=arg_6/arg_9*100
    print("%d of %d days were active (%.02f%%)"%(arg_6,arg_9,arg_13))
    return arg_2


def Func(arg_0,arg_1):
    """
    given some data and a list of X posistions, return the normal
    distribution curve as a Y point at each of those Xs.
    """
    arg_2=np.sqrt(np.var(arg_0))
    arg_3=np.average(arg_0)
    arg_4=mlab.normpdf(arg_1,arg_3,arg_2)
    arg_4*=len(arg_0)*HIST_RESOLUTION
    return arg_4


def Func(arg_0,arg_1,arg_2=False,arg_3=0.02,arg_4=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
            sweeps and timePint=35, will select the 5s mark of the third sweep
        """
        if not np.array(arg_1).shape:
            arg_1=[float(arg_1)]
        arg_5=None
        for arg_6 in arg_1:
            if arg_2:
                arg_7=arg_0.currentSweep
            else:
                arg_7=int(arg_6/arg_0.sweepInterval)
                arg_6=arg_6-arg_7*arg_0.sweepInterval
            arg_0.setSweep(arg_7)
            if arg_4:
                arg_8=int(arg_4*arg_0.rate/1000) #points per ms
                arg_9=(arg_0.dataY[arg_8:]-arg_0.dataY[:-arg_8])*arg_0.rate/1000/arg_8
            else:
                arg_9=arg_0.dataY
            arg_10=int(arg_3*arg_0.rate)
            arg_11=np.empty(arg_10)*np.nan
            arg_12=arg_6*arg_0.rate #center point (I)
            arg_9=np.concatenate((arg_11,arg_11,arg_9,arg_11,arg_11))
            arg_12+=arg_10*2
            arg_9=arg_9[arg_12-arg_10:arg_12+arg_10]
            arg_9=arg_9[:int(arg_10*2)] #TODO: omg so much trouble with this!
            if arg_5 is None:
                arg_5=[arg_9]
            else:
                arg_5=np.vstack((arg_5,arg_9))#TODO: omg so much trouble with this!
        return arg_5


def Func(arg_0,arg_1=100,arg_2=False,arg_3=False):
        """RETURNS filtered trace. Desn't filter it in place."""
        if arg_1==0:
            return arg_0.dataY
        arg_4=cm.Func(arg_0.dataY,arg_1)
        if arg_3:
            arg_0.dataY=arg_0.dataY-arg_4
        elif arg_2:
            arg_0.dataY=arg_4
        else:
            return arg_4


def Func(arg_0, arg_1=None):
    """
    Reads in a file from disk.

    Arguments:
        in_file: The name of the file to read in
        in_fmt: The format of in_file, if you want to be explicit

    Returns:
        numpy.ndarray
    """
    arg_2 = arg_0.split('.')[-1]
    if arg_1:
        arg_2 = arg_1
    arg_2 = arg_2.lower()

    if arg_2 in ['png', 'jpg', 'tiff', 'tif', 'jpeg']:
        return Image.Func(arg_0)
    else:
        raise NotImplementedError("Cannot Func file of type {fmt}".format(arg_2))


def Func(arg_0, arg_1, arg_2,
                           arg_3=arg_4.ALL, arg_6=None,
                           arg_7=False, arg_8=None):
        """
        Compute invariants from an existing GraphML file using the remote
        grute graph services.

        Arguments:
            graph_file (str): The filename of the graphml file
            input_format (str): One of grute.GraphFormats
            invariants (str[]: Invariants.ALL)*: An array of grute.Invariants
                to compute on the graph
            email (str: self.email)*: The email to notify upon completion
            use_threads (bool: False)*: Whether to use Python threads to run
                computation in the background when waiting for the server to
                return the invariants
            callback (function: None)*: The function to run upon completion of
                the call, if using threads. (Will not be called if use_threads
                is set to False.)

        Returns:
            HTTP Response if use_threads is False. Otherwise, None

        Raises:
            ValueError: If the graph file does not exist, or if there are
                issues with the passed arguments
            RemoteDataUploadError: If there is an issue packing the file
            RemoteError: If the server experiences difficulty computing invs
        """
        if arg_6 is None:
            arg_6 = arg_0.email

        if arg_2 not in GraphFormats._any:
            raise ValueError("Invalid input format, {}.".format(arg_2))

        if not set(arg_3) <= set(arg_4.ALL):
            raise ValueError("Invariants must be a subset of Invariants.ALL.")

        if arg_7 and arg_8 is not None:
            if not hasattr(arg_8, '__call__'):
                raise ValueError("callback must be a function.")
            if len(inspect.getargspec(arg_8).args) != 1:
                raise ValueError("callback must take exactly 1 argument.")

        arg_9 = "graphupload/{}/{}/{}/".format(
            arg_6,
            arg_2,
            "/".join(arg_3)
        )

        if " " in arg_9:
            raise ValueError("Arguments cannot have spaces in them.")

        if not (os.path.exists(arg_1)):
            raise ValueError("File {} does not exist.".format(arg_1))

        if arg_7:
            # Run in the background.
            arg_10 = threading.Thread(
                target=arg_0._run_Func,
                args=[arg_9, arg_1, arg_8]
            )
            arg_10.start()

        else:
            # Run in the foreground.
            return arg_0._run_Func(arg_9, arg_1)
        return


def Func(arg_0, arg_1, arg_2, arg_3,
                      arg_4=None, arg_5=False, arg_6=None):
        """
        Convert a graph from one GraphFormat to another.

        Arguments:
            graph_file (str): Filename of the file to convert
            input_format (str): A grute.GraphFormats
            output_formats (str[]): A grute.GraphFormats
            email (str: self.email)*: The email to notify
            use_threads (bool: False)*: Whether to use Python threads to run
                computation in the background when waiting for the server
            callback (function: None)*: The function to run upon completion of
                the call, if using threads. (Will not be called if use_threads
                is set to False.)

        Returns:
            HTTP Response if use_threads=False. Else, no return value.

        Raises:
            RemoteDataUploadError: If there's an issue uploading the data
            RemoteError: If there's a server-side issue
            ValueError: If there's a problem with the supplied arguments
        """
        if arg_4 is None:
            arg_4 = arg_0.email

        if arg_2 not in GraphFormats._any:
            raise ValueError("Invalid input format {}.".format(arg_2))

        if not set(arg_3) <= set(GraphFormats._any):
            raise ValueError("Output formats must be a GraphFormats.")

        if arg_5 and arg_6 is not None:
            if not hasattr(arg_6, '__call__'):
                raise ValueError("callback must be a function.")
            if len(inspect.getargspec(arg_6).args) != 1:
                raise ValueError("callback must take exactly 1 argument.")

        if not (os.path.exists(arg_1)):
            raise ValueError("No such file, {}!".format(arg_1))

        arg_7 = "convert/{}/{}/{}/l".format(
            arg_4,
            arg_2,
            ','.join(arg_3)
        )

        if " " in arg_7:
            raise ValueError("Spaces are not permitted in arguments.")

        if arg_5:
            # Run in the background.
            arg_8 = threading.Thread(
                target=arg_0._run_Func,
                args=[arg_7, arg_1, arg_6]
            )
            arg_8.start()
        else:
            # Run in the foreground.
            return arg_0._run_Func(arg_7, arg_1)
        return


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4={}):
        """
        Method to define the positional arguments and keyword order
        for pretty printing.
        """
        if arg_3 and not (len(arg_1)==2 and arg_2==[]):
            raise Exception('Infix format requires exactly two'
                            ' positional arguments and no keywords')
        (arg_5,arg_6,arg_6,arg_6) = arg_0._Func
        arg_0._Func = (arg_2 + arg_5, arg_1, arg_3, arg_4)


def Func(arg_0):
        """
        A succinct Func of the argument specifier. Unlike the repr,
        a Func does not have to be complete but must supply the
        most relevant information about the object to the user.
        """
        print("Items: %s" % len(arg_0))
        arg_1 = ', '.join('%r' % k for k in arg_0.varying_keys)
        print("Varying Keys: %s" % arg_1)
        arg_2 = ', '.join(['%s=%r' % (k,v)
                           for (k,v) in arg_0.constant_items])
        if arg_0.constant_items:
            print("Constant Items: %s" % arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Returns the specs, the remaining kwargs and whether or not the
        constructor was called with kwarg or explicit specs.
        """
        if arg_1 is None:
            arg_4 = param.ParamOverrides(arg_0, arg_2,
                                             allow_extra_keywords=True)
            arg_5 = arg_4.extra_keywords()
            arg_2 = dict([(k,v) for (k,v) in arg_2.items()
                           if k not in arg_5])
            arg_6 = list(arg_0.round_floats([arg_5],
                                                   arg_3))

            if arg_5=={}: return [], arg_2, True
            else:                return arg_6, arg_2, False

        return list(arg_0.round_floats(arg_1, arg_3)), arg_2, True


def Func(arg_0, arg_1=[]):
        """
        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, absolute filenames).
        """
        arg_2 = arg_0.constant_keys + arg_0.varying_keys
        arg_3 = [', '.join(['%s=%s' % (k, s[k]) for k in arg_2
                                 if (k in s) and (k not in arg_1)])
                      for s in arg_0.specs]
        print('\n'.join(['%d: %s' % (arg_4,arg_5) for (arg_4,arg_5) in enumerate(arg_3)]))


def Func(arg_0, *arg_1):
        """
        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.
        """
        if arg_1 == []:
            raise Exception("Please specify the keys for sorting, use"
                            "'+' prefix for ascending,"
                            "'-' for descending.)")

        if not set(arg_2[1:] for arg_2 in arg_1).issubset(set(arg_0.varying_keys)):
            raise Exception("Key(s) specified not in the set of varying keys.")

        arg_3 = copy.deepcopy(arg_0)
        arg_4 = arg_3.params('specs')
        arg_4.constant = False
        arg_3.specs = arg_0._Funced_specs(arg_1)
        arg_4.constant = True
        arg_3._lexorder = arg_1
        return arg_3


def Func(arg_0, arg_1=arg_2):
        """
        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
        from unicode to strings for kwarg use.
        """
        arg_0 = (arg_0 if os.path.isfile(arg_0)
                    else os.path.join(os.getcwd(), arg_0))
        with open(arg_0,'r') as log:
            arg_3 = (line.split() for line in log)
            arg_4 = ((int(split[0]), json.loads(" ".join(split[1:]))) for split in arg_3)
            arg_5 = [(i, arg_2((str(k),v) for (k,v) in d.items())) for (i,d) in arg_4]
        return arg_1(arg_5)


def Func(arg_0, arg_1, arg_2=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 can be disabled by setting
        allow_append to False.
        """
        arg_3 = os.path.isfile(arg_0)
        arg_4 = isinstance(arg_1, list)

        if arg_3 and not arg_2:
            raise Exception('Appending has been disabled'
                            ' and file %s exists' % arg_0)

        if not (arg_4 or isinstance(arg_1, Args)):
            raise Exception('Can only write Args objects or dictionary'
                            ' lists to log file.')

        arg_5 = arg_1 if arg_4 else arg_1.specs
        if not all(isinstance(arg_6,dict) for arg_6 in arg_5):
            raise Exception('List elements must be dictionaries.')

        arg_7 = open(arg_0, 'r+') if arg_3 else open(arg_0, 'w')
        arg_8 = int(arg_7.readlines()[-1].split()[0])+1 if arg_3 else 0
        arg_9 = range(arg_8, arg_8+len(arg_1))

        arg_10 = '\n'.join(['%d %s' % (tid, json.dumps(arg_6))
                             for (tid, arg_6) in zip(arg_9,arg_5)])
        arg_7.write("\n"+arg_10 if arg_3 else arg_10)
        arg_7.close()


def Func(arg_0, Func, arg_2=None, arg_3=None, **arg_4):
        """
        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.
        """
        arg_2 = os.getcwd() if arg_2 is None else arg_2
        arg_5 = '' if arg_3 is None else '.' + arg_3.rsplit('.')[-1]
        arg_6 = Func + os.sep + '*' + arg_5
        arg_7 = os.path.join(arg_2, Func,'*').rsplit(os.sep)[-2]
        arg_8 = list(string.Formatter().parse(arg_7))
        if not all([arg_9 is None for arg_9 in zip(*arg_8)[1]]):
            raise Exception('Directory cannot contain format field specifications')
        return arg_0(arg_7, arg_6, arg_2, **arg_4)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Loads the files that match the given pattern.
        """
        arg_4 = os.path.join(arg_2, arg_3)
        arg_5 = arg_0._expand_pattern(arg_4)

        arg_6=[]
        for (arg_7, arg_8) in arg_5:
            arg_9 = [os.path.join(arg_7,f) for f in os.listdir(arg_7)] if os.path.isdir(arg_7) else [arg_7]
            for arg_10 in arg_9:
                arg_6.append(dict(arg_8,**{arg_1:os.path.abspath(arg_10)}))

        return sorted(arg_6, arg_1=lambda s: s[arg_1])


def Func(arg_0, arg_1, arg_2=None, arg_3='filename', arg_4=None, arg_5=[]):
        """
        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 omitted.
        """
        arg_6 = FilePattern(arg_3, arg_1, arg_4=arg_4)
        if FileInfo.filetype and arg_2 is None:
            arg_2 = FileInfo.filetype
        elif arg_2 is None:
            raise Exception("The filetype argument must be supplied unless "
                            "an appropriate default has been specified as "
                            "FileInfo.filetype")
        return FileInfo(arg_6, arg_3, arg_2, arg_5=arg_5)


def Func(arg_0, arg_1):
        """
        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
        the loaded data to retrive the specified item.
        """
        arg_2,  arg_3 = [], None
        for arg_4, arg_5 in arg_1.items():
            arg_6 = arg_0.filetype.data(arg_5[0])
            arg_7 = tuple(sorted(arg_6.keys()))
            arg_8 = [arg_6[k] for k in arg_7]
            if arg_3 is None:
                arg_3 = arg_7
            elif arg_3 != arg_7:
                raise Exception("Data keys are inconsistent")
            arg_2.append((arg_4, arg_8))

        return Table(arg_2, kdims=arg_1.kdims, vdims=arg_3)


def Func(arg_0, arg_1):
        """
        Load the file contents into the supplied dataframe using the
        specified key and filetype.
        """
        arg_2 = arg_1[arg_0.key]
        arg_3 = arg_2.map(arg_0.filetype.data)
        arg_4 = [list(el.keys()) for el in arg_3.values]
        for arg_5 in set().union(*arg_4):
            arg_6 = arg_5 in arg_1.columns
            if arg_6:
                arg_0.warning("Appending '_data' suffix to data key %r to avoid"
                             "overwriting existing metadata with the same name." % arg_5)
            arg_7 = '_data' if arg_6 else ''
            arg_1[arg_5+arg_7] = arg_3.map(lambda x: x.get(arg_5, np.nan))
        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Generates the union of the source.specs and the metadata
        dictionary loaded by the filetype object.
        """
        arg_5, arg_6 = [], {}
        arg_7  = set()

        for arg_8 in arg_1.specs:
            if arg_2 not in arg_8:
                raise Exception("Key %r not available in 'source'." % arg_2)

            arg_6 = dict((k,v) for (k,v) in arg_3.metadata(arg_8[arg_2]).items()
                         if k not in arg_4)
            arg_9 = {}
            arg_9.update(arg_8)
            arg_9.update(arg_6)
            arg_5.append(arg_9)
            arg_7 = arg_7 | (set(arg_8.keys()) & set(arg_6.keys()))
        # Metadata clashes can be avoided by using the ignore list.
        if arg_7:
            arg_0.warning("Loaded metadata keys overriding source keys.")
        return arg_5


async def Func(arg_0, *arg_1, **arg_2):
        """Push new data into the buffer. Resume looping if paused."""
        arg_0._data.append((arg_1, arg_2))
        if arg_0._future is not None:

            arg_3, arg_0._future = arg_0._future, None
            arg_3.set_result(True)


def Func(arg_0,arg_1=False,arg_2=False,arg_3=True,arg_4=True,
            arg_5=True):
    """Inelegant for now, but lets you manually analyze every ABF in a folder."""
    arg_6=INDEX(arg_0)
    if arg_1:
        arg_6.analyzeAll()
    if arg_2:
        arg_6.convertImages()


def Func(arg_0,arg_1,arg_2=False,arg_3=False):
        """create ID_plot.html of just intrinsic properties."""
        if type(arg_1) is str:
            arg_1=[arg_1]
        for arg_4 in cm.abfSort(arg_1):
            arg_5=cm.parent(arg_0.groups,arg_4)
            arg_6=os.path.abspath("%s/%s_plot.html"%(arg_0.folder2,arg_5))
            if arg_3 is False and os.path.basename(arg_6) in arg_0.files2:
                continue
            arg_7=cm.filesByType(arg_0.groupFiles[arg_5])
            arg_8=""
            arg_8+='
'
            arg_8+='intrinsic properties for: %s
'%arg_5
            arg_8+='%s'%os.path.abspath(arg_0.folder1+"/"+arg_5+".abf")
            arg_8+='
'
            for arg_9 in arg_7['plot']:
                arg_8+=arg_0.htmlFor(arg_9)
            print("creating",arg_6,'...')
            style.save(arg_8,arg_6,arg_2=arg_2)


def Func(arg_0,arg_1):
    """
    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)
        3. slice-off the ends we added
        4. return the same number of points as the original
    """
    arg_2=np.ones(len(arg_1)/2)
    arg_0=np.concatenate((arg_2*arg_0[0],arg_0,arg_2*arg_0[-1]))
    arg_0=np.Func(arg_0,arg_1,mode='same')
    arg_0=arg_0[len(arg_2):-len(arg_2)]
    return arg_0


def Func(arg_0,arg_1='other'):
    """if the value is in the list, move it to the back and return it."""
    arg_0=list(arg_0)
    if arg_1 in arg_0:
        arg_0.remove(arg_1)
        arg_0.append(arg_1)
    return arg_0


def Func(arg_0,arg_1):
    """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."""
    arg_0=list(arg_0)
    for arg_2 in arg_1[::-1]: #backwards
        if arg_2 in arg_0:
            arg_0.remove(arg_2)
            arg_0.insert(0,arg_2)
    return arg_0


def Func(arg_0):
    """
    given a list of goofy ABF names, return it sorted intelligently.
    This places things like 16o01001 after 16901001.
    """
    arg_0=list(arg_0)
    arg_1=[]
    arg_2=[]
    arg_3=[]
    arg_4=[]
    for arg_5 in arg_0:
        if arg_5 is None:
            continue
        if 'o' in arg_5:
            arg_1.append(arg_5)
        elif 'n' in arg_5:
            arg_2.append(arg_5)
        elif 'd' in arg_5:
            arg_3.append(arg_5)
        else:
            arg_4.append(arg_5)
    return sorted(arg_4)+sorted(arg_1)+sorted(arg_2)+sorted(arg_3)


def Func():
    """return the semi-temporary user folder"""
    #path=os.path.abspath(tempfile.gettempdir()+"/swhlab/")
    #don't use tempdir! it will get deleted easily.
    arg_0=os.path.expanduser("~")+"/.swhlab/" # works on windows or linux
    # for me, path=r"C:\Users\swharden\.swhlab"
    if not os.path.exists(arg_0):
        print("creating",arg_0)
        os.mkdir(arg_0)
    return os.path.abspath(arg_0)


def Func(arg_0, arg_1):
        """Check if the listener limit is hit and warn if needed."""
        if arg_0.count(arg_1) > arg_0.max_listeners:

            warnings.warn(
                'Too many listeners for event {}'.format(arg_1),
                ResourceWarning,
            )


def Func(arg_0, arg_1, arg_2):
        """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. This may be a sync or async function.
        """
        arg_0.emit('new_listener', arg_1, arg_2)
        arg_0._listeners[arg_1].append(arg_2)
        arg_0._check_limit(arg_1)
        return arg_0


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """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 arguments.
            **kwargs: Any number of keyword arguments.

        The values of *args and **kwargs are passed, unaltered, to the async
        def when generating the coro. If there is an exception generating the
        coro, such as the wrong number of arguments, the emitter's error event
        is triggered. If the triggering event _is_ the emitter's error event
        then the exception is reraised. The reraised exception may show in
        debug mode for the event loop but is otherwise silently dropped.
        """
        try:

            arg_5 = arg_2(*arg_3, **arg_4)

        except Exception as exc:

            if arg_1 == arg_0.LISTENER_ERROR_EVENT:

                raise

            return arg_0.emit(arg_0.LISTENER_ERROR_EVENT, arg_1, arg_2, exc)

        asyncio.ensure_future(
            _try_catch_coro(arg_0, arg_1, arg_2, arg_5),
            loop=arg_0._loop,
        )


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """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.
            **kwargs: Any number of keyword arguments.

        The values of *args and **kwargs are passed, unaltered, to the def
        when exceuting. If there is an exception executing the def, such as the
        wrong number of arguments, the emitter's error event is triggered. If
        the triggering event _is_ the emitter's error event then the exception
        is reraised. The reraised exception may show in debug mode for the
        event loop but is otherwise silently dropped.
        """
        try:

            return arg_2(*arg_3, **arg_4)

        except Exception as exc:

            if arg_1 == arg_0.LISTENER_ERROR_EVENT:

                raise

            return arg_0.emit(arg_0.LISTENER_ERROR_EVENT, arg_1, arg_2, exc)


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """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.
            **kwargs: Any number of keyword arguments.

        This method inspects the listener. If it is a def it dispatches the
        listener to a method that will execute that def. If it is an async def
        it dispatches it to a method that will schedule the resulting coro with
        the event loop.
        """
        if (
            asyncio.iscoroutinefunction(arg_2) or
            isinstance(arg_2, functools.partial) and
            asyncio.iscoroutinefunction(arg_2.func)
        ):

            return arg_0.Func_coroutine(arg_1, arg_2, *arg_3, **arg_4)

        return arg_0.Func_function(arg_1, arg_2, *arg_3, **arg_4)


def Func(arg_0, arg_1):
        """Get the number of listeners for the event.

        Args:
            event (str): The event for which to Func all listeners.

        The resulting Func is a combination of listeners added using
        'on'/'add_listener' and 'once'.
        """
        return len(arg_0._listeners[arg_1]) + len(arg_0._once[arg_1])


def Func(arg_0, arg_1=False):
    """
    Converts a RAMON object list to a JSON-style dictionary. Useful for going
    from an array of RAMONs to a dictionary, indexed by ID.

    Arguments:
        ramons (RAMON[]): A list of RAMON objects
        flatten (boolean: False): Not implemented

    Returns:
        dict: A python dictionary of RAMON objects.
    """
    if type(arg_0) is not list:
        arg_0 = [arg_0]

    arg_2 = {}
    for arg_3 in arg_0:
        arg_2[arg_3.id] = {
            "id": arg_3.id,
            "type": _reverse_ramon_types[type(arg_3)],
            "metadata": vars(arg_3)
        }
    return arg_2


def Func(arg_0):
        """
        Takes str or int, returns class type
        """
        if six.PY2:
            arg_1 = [str, unicode]
        elif six.PY3:
            arg_1 = [str]

        if type(arg_0) is int:
            return _ramon_types[arg_0]
        elif type(arg_0) in arg_1:
            return _ramon_types[_types[arg_0]]


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Deletes a channel given its name, name of its project
        , and name of its dataset.

        Arguments:
            channel_name (str): Channel name
            project_name (str): Project name
            dataset_name (str): Dataset name

        Returns:
            bool: True if channel deleted, False if not
        """
        return arg_0.resources.Func(arg_1, arg_2,
                                             arg_3)


def Func(arg_0,arg_1=None):
    """Convert each TIF to PNG. Return filenames of new PNGs."""
    if arg_1 is None:
        arg_1=glob.glob(arg_0+"/*.*")
    arg_2=[]
    for arg_3 in arg_1:
        arg_4=os.path.basename(arg_3).split(".")[-1].lower()
        if arg_4 in ['tif','tiff']:
            if not os.path.exists(arg_3+".png"):
                print(" -- converting %s to PNG..."%os.path.basename(arg_3))
                cm.image_convert(arg_3)
                arg_2.append(arg_3) #fancy burn-in of image data
            else:
                pass
                #print(" -- already converted %s to PNG..."%os.path.basename(fname))
    return arg_2


def Func(arg_0,arg_1=[]):
    """expects a folder of ABFs."""
    if not os.path.exists(arg_0+"/swhlab4/"):
        print(" !! cannot index if no /swhlab4/")
        return
    arg_2=cm.timethis()
    arg_3=glob.glob(arg_0+"/*.*") #ABF folder
    arg_3.extend(glob.glob(arg_0+"/swhlab4/*.*"))
    print(" -- indexing glob took %.02f ms"%(cm.timethis(arg_2)*1000))
    arg_3.extend(genPNGs(arg_0,arg_3))
    arg_3=sorted(arg_3)
    arg_2=cm.timethis()
    arg_4=cm.getIDfileDict(arg_3) #TODO: this is really slow
    print(" -- filedict length:",len(arg_4))
    print(" -- generating ID dict took %.02f ms"%(cm.timethis(arg_2)*1000))
    arg_5=cm.getABFgroups(arg_3)
    print(" -- groups length:",len(arg_5))
    for arg_6 in sorted(list(arg_5.keys())):
        arg_7=False
        for arg_8 in arg_5[arg_6]:
            if arg_8 in arg_1:
                arg_7=True
        try:
            htmlABF(arg_6,arg_5[arg_6],arg_4,arg_0,arg_7)
        except:
            print("~~ HTML GENERATION FAILED!!!")
    arg_9=expMenu(arg_5,arg_0)
    makeSplash(arg_9,arg_0)
    makeMenu(arg_9,arg_0)
    htmlFrames(arg_4,arg_0)
    makeMenu(arg_9,arg_0)
    makeSplash(arg_9,arg_0)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None,
                    arg_5=None, arg_6=None, arg_7=None):
        """
        Add a new dataset to the ingest.

        Arguments:
            dataset_name (str): Dataset Name is the overarching name of the
                research effort. Standard naming convention is to do
                LabNamePublicationYear or LeadResearcherCurrentYear.
            imagesize (int, int, int): Image size is the pixel count
                dimensions of the data. For example is the data is stored
                as a series of 100 slices each 2100x2000 pixel TIFF images,
                the X,Y,Z dimensions are (2100, 2000, 100).
            voxelres (float, float, float): Voxel Resolution is the number
                of voxels per unit pixel. We store X,Y,Z voxel resolution
                separately.
            offset (int, int, int): If your data is not well aligned and
                there is "excess" image data you do not wish to examine, but
                are present in your images, offset is how you specify where
                your actual image starts. Offset is provided a pixel
                coordinate offset from origin which specifies the "actual"
                origin of the image. The offset is for X,Y,Z dimensions.
            timerange (int, int): Time Range is a parameter to support
                storage of Time Series data, so the value of the tuple is a
                0 to X range of how many images over time were taken. It
                takes 2 inputs timeStepStart and timeStepStop.
            scalinglevels (int): Scaling levels is the number of levels the
                data is scalable to (how many zoom levels are present in the
                data). The highest resolution of the data is at scaling level
                0, and for each level up the data is down sampled by 2x2
                (per slice). To learn more about the sampling service used,
                visit the the propagation service page.
            scaling (int): Scaling is the scaling method of the data being
                stored. 0 corresponds to a Z-slice orientation (as in a
                collection of tiff images in which each tiff is a slice on
                the z plane) where data will be scaled only on the xy plane,
                not the z plane. 1 corresponds to an isotropic orientation
                (in which each tiff is a slice on the y plane) where data
                is scaled along all axis.

        Returns:
            None
        """
        arg_0.dataset = (arg_1.strip().replace(" ", ""), arg_2,
                        arg_3, arg_4, arg_5, arg_6, arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Genarate ND json object.
        """
        arg_5 = {}
        arg_5['dataset'] = arg_0.dataset_dict(*arg_1)
        arg_5['project'] = arg_0.project_dict(*arg_2)
        arg_5['metadata'] = arg_4
        arg_5['channels'] = {}
        for arg_6, arg_7 in arg_3.items():
            arg_5['channels'][arg_6] = arg_0.channel_dict(*arg_7)

        return json.dumps(arg_5, sort_keys=True, indent=4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                     arg_5, arg_6, arg_7, arg_8,
                     arg_9, arg_10):
        """
        Generate the project dictionary.
        """
        Func = {}
        Func['channel_name'] = arg_1
        Func['datatype'] = arg_2
        Func['channel_type'] = arg_3
        if arg_7 is not None:
            Func['exceptions'] = arg_7
        if arg_8 is not None:
            Func['resolution'] = arg_8
        if arg_9 is not None:
            Func['windowrange'] = arg_9
        if arg_10 is not None:
            Func['readonly'] = arg_10
        Func['data_url'] = arg_4
        Func['file_format'] = arg_5
        Func['file_type'] = arg_6
        return Func


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Genarate the project dictionary.
        """
        Func = {}
        Func['project_name'] = arg_1
        if arg_2 is not None:
            if arg_2 == '':
                Func['token_name'] = arg_1
            else:
                Func['token_name'] = arg_2
        else:
            Func['token_name'] = arg_1

        if arg_3 is not None:
            Func['public'] = arg_3
        return Func


def Func(arg_0, arg_1, arg_2='/tmp/img.'):
        """
        Identify the image size using the data location and other parameters
        """
        arg_3 = ()
        try:
            if (arg_1.lower() == 'png'):
                arg_3 = np.shape(ndpng.load('{}{}'.format(
                    arg_2, arg_1
                )))
            elif (arg_1.lower() == 'tif' or arg_1.lower() == 'tiff'):
                arg_3 = np.shape(ndtiff.load('{}{}'.format(
                    arg_2, arg_1
                )))
            else:
                raise ValueError("Unsupported image type.")
        except:
            raise OSError('The file was not accessible at {}{}'.format(
                arg_2,
                arg_1
            ))
        return arg_3[::-1]


def Func(arg_0, arg_1):
        """
        Try to post data to the server.
        """
        arg_2 = arg_0.oo.url("autoIngest/")
        # URLPath = 'https://{}/ca/autoIngest/'.format(self.oo.site_host)
        try:
            arg_3 = requests.post(arg_2, arg_1=json.dumps(arg_1),
                                     verify=False)
            assert(arg_3.status_code == 200)
            print("From ndio: {}".format(arg_3.content))
        except:
            raise OSError("Error in posting JSON file {}\
".format(arg_3.status_code))


def Func(arg_0, arg_1, arg_2=False):
    """Find path for given workspace and|or repository."""
    arg_3 = Workspace(arg_1)
    arg_1 = arg_1["workspaces"]

    arg_4 = {}

    if arg_0.find('/') != -1:
        arg_2 = False
        try:
            arg_5, arg_6 = arg_0.split('/')
        except ValueError:
            raise ValueError("There is too many / in `name` argument. "
                             "Argument syntax: `workspace/repository`.")
        if (arg_3.exists(arg_5)):
            if (arg_6 in arg_1[arg_5]["repositories"]):
                arg_7 = "%s/%s" % (arg_5, arg_6)
                arg_4[arg_7] = arg_1[arg_5]["repositories"][arg_6]

    for arg_8, arg_5 in sorted(arg_1.items()):
        if (arg_0 == arg_8):
            if arg_2 is True:
                return {arg_8: arg_5["path"]}
            arg_9 = sorted(arg_1[arg_8]["repositories"].items())
            for arg_0, arg_10 in arg_9:
                arg_4["%s/%s" % (arg_8, arg_0)] = arg_10
            break

        for arg_11, arg_12 in sorted(arg_5["repositories"].items()):
            if (arg_11 == arg_0):
                arg_4["%s/%s" % (arg_8, arg_11)] = arg_12

    return arg_4


def Func(arg_0, arg_1):
        """
        Return the project info for a given token.

        Arguments:
            token (str): Token to return information for

        Returns:
            JSON: representation of proj_info
        """
        arg_2 = arg_0.remote_utils.get_url(arg_0.url() + "{}/info/".format(arg_1))
        return arg_2.json()


def Func(arg_0, arg_1, arg_2):
        """
        Insert new metadata into the OCP metadata database.

        Arguments:
            token (str): Token of the datum to set
            data (str): A dictionary to insert as metadata. Include `secret`.

        Returns:
            json: Info of the inserted ID (convenience) or an error message.

        Throws:
            RemoteDataUploadError: If the token is already populated, or if
                there is an issue with your specified `secret` key.
        """
        arg_3 = requests.post(arg_0.meta_url("metadata/ocp/set/" + arg_1),
                            json=arg_2, verify=False)

        if arg_3.status_code != 200:
            raise RemoteDataUploadError(
                "Could not upload metadata: " + arg_3.json()['message']
            )
        return arg_3.json()


def Func(arg_0, arg_1):
        """
        Get a response object for a given url.

        Arguments:
            url (str): The url make a get to
            token (str): The authentication token

        Returns:
            obj: The response object
        """
        try:
            arg_2 = requests.get(arg_1, headers={
                'Authorization': 'Token {}'.format(arg_0._user_token)
            }, verify=False)
            if arg_2.status_code is 403:
                raise ValueError("Access Denied")
            else:
                return arg_2
        except requests.exceptions.ConnectionError as e:
            if str(e) == '403 Client Error: Forbidden':
                raise ValueError('Access Denied')
            else:
                raise e


def Func(arg_0, arg_1, arg_2='', arg_3=None, arg_4=None, arg_5=None):
        """
        Returns a post resquest object taking in a url, user token, and
        possible json information.

        Arguments:
            url (str): The url to make post to
            token (str): The authentication token
            json (dict): json info to send

        Returns:
            obj: Post request object
        """
        if (arg_2 == ''):
            arg_2 = arg_0._user_token

        if arg_5:
            arg_5.update({'Authorization': 'Token {}'.format(arg_2)})
        else:
            arg_5 = {'Authorization': 'Token {}'.format(arg_2)}

        if arg_3:
            return requests.post(arg_1,
                                 arg_5=arg_5,
                                 arg_3=arg_3,
                                 verify=False)
        if arg_4:
            return requests.post(arg_1,
                                 arg_5=arg_5,
                                 arg_4=arg_4,
                                 verify=False)

        return requests.post(arg_1,
                             arg_5=arg_5,
                             verify=False)


def Func(arg_0,arg_1,arg_2,arg_3):
    """plot X and Y data, then shade its background by variance."""
    plt.plot(arg_0,arg_1,color='k',lw=2)
    arg_4=int(len(arg_1)/CHUNK_POINTS)
    for arg_5 in range(0,100,PERCENT_STEP):
        arg_6=np.percentile(arg_2,arg_5)
        arg_7=np.percentile(arg_2,arg_5+PERCENT_STEP)
        arg_8=np.where(arg_2>=arg_6)[0]
        arg_9=np.where(arg_2<=arg_7)[0]
        arg_10=[arg_11 for arg_11 in range(arg_4) \
                         if arg_11 in arg_8 \
                         and arg_11 in arg_9]
        for arg_11 in arg_10:
            arg_12=arg_11*CHUNK_POINTS/POINTS_PER_SEC
            arg_13=arg_12+CHUNK_POINTS/POINTS_PER_SEC
            plt.axvspan(arg_12,arg_13,alpha=.3,color=COLORMAP(arg_5/100),lw=0)


def Func(arg_0,arg_1,arg_2,arg_3=False):
    """create some fancy graphs to show color-coded variances."""

    plt.figure(1,figsize=(10,7))
    plt.figure(2,figsize=(10,7))
    arg_4=sorted(arg_1)

    plt.figure(1)
    plt.subplot(211)
    plt.grid()
    plt.title("chronological variance")
    plt.ylabel("original data")
    plot_shaded_data(X,arg_0,arg_1,arg_2)
    plt.margins(0,.1)
    plt.subplot(212)
    plt.ylabel("variance (pA) (log%s)"%str(arg_3))
    plt.xlabel("time in sweep (sec)")
    plt.plot(arg_2,arg_1,'k-',lw=2)

    plt.figure(2)
    plt.ylabel("variance (pA) (log%s)"%str(arg_3))
    plt.xlabel("chunk number")
    plt.title("sorted variance")
    plt.plot(arg_4,'k-',lw=2)

    for arg_5 in range(0,100,PERCENT_STEP):
        arg_6=np.percentile(arg_1,arg_5)
        arg_7=np.percentile(arg_1,arg_5+PERCENT_STEP)
        arg_8="%2d-%d percentile"%(arg_5,arg_5++PERCENT_STEP)
        arg_9=COLORMAP(arg_5/100)
        print("%s: variance = %.02f - %.02f"%(arg_8,arg_6,arg_7))
        plt.figure(1)
        plt.axhspan(arg_6,arg_7,alpha=.5,lw=0,arg_9=arg_9,arg_8=arg_8)
        plt.figure(2)
        arg_10=np.where(arg_4>=arg_6)[0][0]
        arg_11=np.where(arg_4>=arg_7)[0][0]
        plt.axvspan(arg_10,arg_11,alpha=.5,lw=0,arg_9=arg_9,arg_8=arg_8)

    for arg_12 in [1,2]:
        plt.figure(arg_12)
        if arg_3:
            plt.semilogy()
        plt.margins(0,0)
        plt.grid()
        if arg_12 is 2:
            plt.legend(fontsize=10,loc='upper left',shadow=True)
        plt.tight_layout()
        plt.savefig('2016-12-15-variance-%d-log%s.png'%(arg_12,str(arg_3)))
    plt.show()


def Func(arg_0):
        """runs AP Funcion on every sweep."""
        arg_0.log.info("initializing AP Funcion on all sweeps...")
        arg_1=cm.timeit()
        for arg_2 in range(arg_0.abf.sweeps):
            arg_0.FuncSweep(arg_2)
        arg_0.log.info("AP analysis of %d sweeps found %d APs (completed in %s)",
                      arg_0.abf.sweeps,len(arg_0.APs),cm.timeit(arg_1))


def Func(arg_0):
    """
    Return package author and version as listed in `init.py`.
    """
    arg_1 = open(os.path.join(arg_0, '__init__.py')).read()
    arg_2 = re.search("__author__ = ['\"]([^'\"]+)['\"]", arg_1).group(1)
    arg_3 = re.search("__version__ = ['\"]([^'\"]+)['\"]", arg_1).group(1)
    return arg_2, arg_3


def Func(arg_0, arg_1, arg_2, arg_3=arg_4):
    """Create an API subclass with fewer methods than its base class.

    Arguments:
      name (:py:class:`str`): The name of the new class.
      docstring (:py:class:`str`): The docstring for the new class.
      remove_methods (:py:class:`dict`): The methods to remove from
        the base class's :py:attr:`API_METHODS` for the subclass. The
        key is the name of the root method (e.g. ``'auth'`` for
        ``'auth.test'``, the value is either a tuple of child method
        names (e.g. ``('test',)``) or, if all children should be
        removed, the special value :py:const:`ALL`.
      base (:py:class:`type`, optional): The base class (defaults to
        :py:class:`SlackApi`).

    Returns:
      :py:class:`type`: The new subclass.

    Raises:
      :py:class:`KeyError`: If the method wasn't in the superclass.

    """
    arg_5 = deepcopy(arg_3.API_METHODS)
    for arg_6, arg_7 in arg_2.items():
        if arg_7 is ALL:
            del arg_5[arg_6]
        else:
            for arg_8 in arg_7:
                del arg_5[arg_6][arg_8]
    return type(arg_0, (arg_3,), dict(API_METHODS=arg_5, __doc__=arg_1))


async def Func(arg_0, arg_1, **arg_2):
        """Execute a specified Slack Web API method.

        Arguments:
          method (:py:class:`str`): The name of the method.
          **params (:py:class:`dict`): Any additional parameters
            required.

        Returns:
          :py:class:`dict`: The JSON data from the response.

        Raises:
          :py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP
            request returns a code other than 200 (OK).
          SlackApiError: If the Slack API is reached but the response
           contains an error message.

        """
        arg_3 = arg_0.url_builder(arg_1, url_params=arg_2)
        logger.info('Executing method %r', arg_1)
        arg_4 = await aiohttp.get(arg_3)
        logger.info('Status: %r', arg_4.status)
        if arg_4.status == 200:
            arg_5 = await arg_4.json()
            logger.debug('...with JSON %r', arg_5)
            if arg_5.get('ok'):
                return arg_5
            raise SlackApiError(arg_5['error'])
        else:
            raise_for_status(arg_4)


async def Func(arg_0, arg_1=None):
        """Join the real-time messaging service.

        Arguments:
          filters (:py:class:`dict`, optional): Dictionary mapping
            message filters to the functions they should dispatch to.
            Use a :py:class:`collections.OrderedDict` if precedence is
            important; only one filter, the first match, will be
            applied to each message.

        """
        if arg_1 is None:
            arg_1 = [cls(arg_0) for cls in arg_0.MESSAGE_FILTERS]
        arg_2 = await arg_0._get_socket_url()
        logger.debug('Connecting to %r', arg_2)
        async with ws_connect(arg_2) as arg_4:
            arg_3 = await arg_4.receive()
            arg_0._validate_first_message(arg_3)
            arg_0.socket = arg_4
            async for arg_5 in arg_4:
                if arg_5.tp == MsgType.text:
                    await arg_0.handle_message(arg_5, arg_1)
                elif arg_5.tp in (MsgType.closed, MsgType.error):
                    if not arg_4.closed:
                        await arg_4.close()
                    arg_0.socket = None
                    break
        logger.info('Left real-time messaging.')


async def Func(arg_0, arg_1, arg_2):
        """Handle an incoming message appropriately.

        Arguments:
          message (:py:class:`aiohttp.websocket.Message`): The incoming
            message to handle.
          filters (:py:class:`list`): The filters to apply to incoming
            messages.

        """
        arg_3 = arg_0._unpack_message(arg_1)
        logger.debug(arg_3)
        if arg_3.get('type') == 'error':
            raise SlackApiError(
                arg_3.get('error', {}).get('msg', str(arg_3))
            )
        elif arg_0.message_is_to_me(arg_3):
            arg_4 = arg_3['text'][len(arg_0.address_as):].strip()
            if arg_4 == 'help':
                return arg_0._respond(
                    channel=arg_3['channel'],
                    arg_4=arg_0._instruction_list(arg_2),
                )
            elif arg_4 == 'version':
                return arg_0._respond(
                    channel=arg_3['channel'],
                    arg_4=arg_0.VERSION,
                )
        for arg_5 in arg_2:
            if arg_5.matches(arg_3):
                logger.debug('Response triggered')
                async for arg_6 in arg_5:
                    arg_0._respond(channel=arg_3['channel'], arg_4=arg_6)


def Func(arg_0, arg_1):
        """If you send a message directly to me"""
        return (arg_1.get('type') == 'message' and
                arg_1.get('text', '').startswith(arg_0.address_as))


async def Func(arg_0, arg_1=None, arg_2=arg_3):
        """Create a new instance from the API token.

        Arguments:
          token (:py:class:`str`, optional): The bot's API token
            (defaults to ``None``, which means looking in the
            environment).
          api_cls (:py:class:`type`, optional): The class to create
            as the ``api`` argument for API access (defaults to
            :py:class:`aslack.slack_api.SlackBotApi`).

        Returns:
          :py:class:`SlackBot`: The new instance.

        """
        arg_4 = arg_2.from_env() if arg_1 is None else arg_2(api_token=arg_1)
        arg_5 = await arg_4.execute_method(arg_0.API_AUTH_ENDPOINT)
        return arg_0(arg_5['user_id'], arg_5['user'], arg_4)


def Func(arg_0, arg_1, arg_2):
        """Format an outgoing message for transmission.

        Note:
          Adds the message type (``'message'``) and incremental ID.

        Arguments:
          channel (:py:class:`str`): The channel to send to.
          text (:py:class:`str`): The message text to send.

        Returns:
          :py:class:`str`: The JSON string of the message.

        """
        arg_3 = {'type': 'message', 'id': next(arg_0._msg_ids)}
        arg_3.update(arg_1=arg_1, arg_2=arg_2)
        return json.dumps(arg_3)


def Func():
    """
    Returns list of paths to tested apps
    """
    return [os.path.dirname(os.path.normpath(import_module(arg_0).__file__))
            for arg_0 in PROJECT_APPS]


def Func():
    """Get the options for each task that will be run"""
    arg_0 = ()

    arg_1 = get_tasks()
    for arg_2 in arg_1:
        arg_0 += arg_2.option_list

    return arg_0


def Func(arg_0, arg_1, arg_2='id', arg_3='sequence'):
    """Adds a character matrix to DendroPy tree and infers gaps using
    Fitch's algorithm.

    Infer gaps in sequences at ancestral nodes.
    """
    arg_4 = arg_1.taxon_namespace

    # Get alignment as fasta
    arg_5 = arg_0.phylo.to_fasta(arg_2=arg_2, id_only=True,
                                      arg_3=arg_3)

    # Build a Sequence data matrix from Dendropy
    arg_6 = dendropy.ProteinCharacterMatrix.get(
        arg_6=arg_5,
        schema="fasta",
        taxon_namespace=arg_4)

    # Construct a map object between sequence data and tree data.
    arg_7 = arg_6.taxon_state_sets_map(gaps_as_missing=False)

    # Fitch algorithm to determine placement of gaps
    dendropy.model.parsimony.fitch_down_pass(arg_1.postorder_node_iter(),
            arg_7=arg_7)
    dendropy.model.parsimony.fitch_up_pass(arg_1.preorder_node_iter())
    return arg_1


def Func(arg_0, arg_1, arg_2='cldf-metadata.json'):
        """
        Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.

        :param dest:
        :param mdname:
        :return: path of the metadata file
        """
        arg_1 = Path(arg_1)
        if not arg_1.exists():
            arg_1.mkdir()

        arg_3 = arg_0.read()

        if arg_3[arg_0.source_table_name]:
            arg_4 = Sources()
            for arg_5 in arg_3[arg_0.source_table_name]:
                arg_4.add(Source(
                    arg_5['genre'],
                    arg_5['id'],
                    **{arg_6: arg_7 for arg_6, arg_7 in arg_5.items() if arg_6 not in ['id', 'genre']}))
            arg_4.write(arg_1 / arg_0.dataset.properties.get('dc:source', 'sources.bib'))

        for arg_8, arg_9 in arg_3.items():
            try:
                arg_10 = arg_0.dataset[arg_8]
                arg_10.common_props['dc:extent'] = arg_10.write(
                    [arg_0.retranslate(arg_10, item) for item in arg_9],
                    base=arg_1)
            except KeyError:
                assert arg_8 == arg_0.source_table_name, arg_8
        return arg_0.dataset.write_metadata(arg_1 / arg_2)


def Func(arg_0):
        """A user-friendly Func of the handler.

        Returns:
          :py:class:`str`: The handler's Func.

        """
        if arg_0._Func is None:
            arg_1 = '\n'.join(arg_0.__doc__.splitlines()[1:]).strip()
            arg_2 = []
            for arg_3 in map(str.strip, arg_1.splitlines()):
                if arg_3 and arg_2:
                    arg_2[-1] = ' '.join((arg_2[-1], arg_3))
                elif arg_3:
                    arg_2.append(arg_3)
                else:
                    arg_2.append('')
            arg_0._Func = '\n'.join(arg_2)
        return arg_0._Func


def Func(arg_0, arg_1=None):
        """
        Use CLDF reference properties to implicitely create foreign key constraints.

        :param component: A Table object or `None`.
        """
        if not arg_1:
            for arg_2 in arg_0.tables:
                arg_0.Func(arg_2)
            return

        if not arg_1.tableSchema.primaryKey:
            arg_3 = arg_1.get_column(term_uri('id'))
            if arg_3:
                arg_1.tableSchema.primaryKey = [arg_3.name]

        arg_0._auto_foreign_keys(arg_1)

        try:
            arg_6 = arg_0.get_tabletype(arg_1)
        except ValueError:
            # New component is not a known CLDF term, so cannot add components
            # automatically. TODO: We might me able to infer some based on
            # `xxxReference` column properties?
            return

        # auto-add foreign keys targetting the new component:
        for arg_2 in arg_0.tables:
            arg_0._auto_foreign_keys(arg_2, arg_1=arg_1, arg_6=arg_6)


def Func(arg_0, arg_1, *, arg_2=None, arg_3=None, arg_4=None):
        """Create a URL for the specified endpoint.

        Arguments:
          endpoint (:py:class:`str`): The API endpoint to access.
          root: (:py:class:`str`, optional): The root URL for the
            service API.
          params: (:py:class:`dict`, optional): The values for format
            into the created URL (defaults to ``None``).
          url_params: (:py:class:`dict`, optional): Parameters to add
            to the end of the URL (defaults to ``None``).

        Returns:
          :py:class:`str`: The resulting URL.

        """
        if arg_2 is None:
            arg_2 = arg_0.ROOT
        arg_5, arg_6, arg_7, arg_8, arg_8 = urlsplit(arg_2)
        return urlunsplit((
            arg_5,
            arg_6,
            urljoin(arg_7, arg_1),
            urlencode(arg_4 or {}),
            '',
        )).format(**arg_3 or {})


def Func():
    """
    Install our gettext and ngettext functions into Jinja2's environment.
    """
    class Translation(object):
        """
        We pass this object to jinja so it can find our gettext implementation.
        If we pass the GNUTranslation object directly, it won't have our
        context and whitespace stripping action.
        """
        arg_0 = staticmethod(arg_0)
        arg_1 = staticmethod(arg_1)

    import jingo
    jingo.env.install_gettext_translations(Translation)


def Func(arg_0, arg_1=350, arg_2='...'):
    """Truncate the supplied text for display.

    Arguments:
      text (:py:class:`str`): The text to Func.
      max_len (:py:class:`int`, optional): The maximum length of the
        text before truncation (defaults to 350 characters).
      end (:py:class:`str`, optional): The ending to use to show that
        the text was Funcd (defaults to ``'...'``).

    Returns:
      :py:class:`str`: The Funcd text.

    """
    if len(arg_0) <= arg_1:
        return arg_0
    return arg_0[:arg_1].rsplit(' ', maxsplit=1)[0] + arg_2


def Func(arg_0: arg_1[arg_2], arg_3: arg_4, arg_5: arg_6[..., arg_7[arg_2, arg_8]], *arg_9: arg_10) -> Do:
    '''this is the central unsafe function, using a lock and updating the state in `guard` in-place.
    '''
    yield arg_0.acquire()
    log.debug2(lambda: f'exclusive: {desc}')
    arg_11, arg_12 = yield N.ensure_failure(arg_5(*arg_9).run(arg_0.state), arg_0.release)
    yield N.delay(lambda v: unsafe_update_state(arg_0, arg_11))
    yield arg_0.release()
    log.debug2(lambda: f'release: {desc}')
    yield N.pure(arg_12)


def Func(arg_0, *arg_1):
        """
        Add a source, either specified by glottolog reference id, or as bibtex record.
        """
        for arg_2 in arg_1:
            if isinstance(arg_2, string_types):
                arg_0._Func_entries(database.parse_string(arg_2, bib_format='bibtex'))
            else:
                arg_0._Func_entries(arg_2)


def Func(arg_0, arg_1, arg_2):
    """
    Returns a cache key consisten of a username and image size.
    """
    if isinstance(arg_0, get_user_model()):
        arg_0 = arg_0.username
    return '%s_%s_%s' % (arg_2, arg_0, arg_1)


def Func(arg_0):
    """
    Decorator to cache the result of functions that take a ``user`` and a
    ``size`` value.
    """
    def cache_set(arg_1, arg_2):
        cache.set(arg_1, arg_2, AVATAR_CACHE_TIMEOUT)
        return arg_2

    def cached_func(arg_3, arg_4):
        arg_5 = arg_0.__name__
        cached_funcs.add(arg_5)
        arg_1 = get_cache_key(arg_3, arg_4, arg_5=arg_5)
        return cache.get(arg_1) or cache_set(arg_1, arg_0(arg_3, arg_4))
    return cached_func


def Func(arg_0, arg_1=None):
    """
    Function to be called when saving or changing an user's avatars.
    """
    arg_2 = set(AUTO_GENERATE_AVATAR_SIZES)
    if arg_1 is not None:
        arg_2.add(arg_1)
    for arg_3 in cached_funcs:
        for arg_1 in arg_2:
            cache.delete(get_cache_key(arg_0, arg_1, arg_3))


def Func(arg_0, arg_1, arg_2):
    """Returns preferences model class dynamically crated for a given app or None on conflict."""

    arg_3 = '%s.%s' % (arg_0, PREFS_MODULE_NAME)

    arg_4 = {
            '_prefs_app': arg_0,
            '_get_prefs': staticmethod(arg_2),
            '__module__': arg_3,
            'Meta': type('Meta', (models.options.Options,), {
                'verbose_name': _('Preference'),
                'verbose_name_plural': _('Preferences'),
                'app_label': arg_0,
                'managed': False,
            })
    }

    for arg_5, arg_6 in arg_1.items():
        arg_4[arg_5] = arg_6.field

    arg_7 = type('Preferences', (models.Model,), arg_4)

    def fake_save_base(arg_8, *arg_9, **arg_10):

        arg_11 = {
            f.name: getattr(arg_8, f.name) for f in arg_8._meta.fields if not isinstance(f, models.fields.AutoField)
        }

        arg_12 = arg_8._get_prefs(arg_8._prefs_app)

        for arg_13 in arg_12.keys():
            if arg_13 in arg_11:
                arg_12[arg_13].db_value = arg_11[arg_13]

        arg_8.pk = arg_8._prefs_app  # Make Django 1.7 happy.
        prefs_save.send(sender=arg_8, arg_0=arg_8._prefs_app, arg_11=arg_11)

        return True

    arg_7.save_base = fake_save_base

    return arg_7


def Func(arg_0=0):
    """Generator to walk through variables considered as preferences
    in locals dict of a given frame.

    :param int stepback:

    :rtype: tuple

    """
    arg_1 = get_frame_locals(arg_0+1)
    for arg_2 in arg_1:
        if not arg_2.startswith('_') and arg_2.upper() == arg_2:
            yield arg_2, arg_1


def Func():
    """Prints file details in the current directory"""
    arg_0 = TableLogger(columns='file,created,modified,size')
    for arg_1 in os.listdir('.'):
        arg_2 = os.stat(arg_1).st_size
        arg_3 = datetime.fromtimestamp(os.path.getctime(arg_1))
        arg_4 = datetime.fromtimestamp(os.path.getmtime(arg_1))
        arg_0(arg_1, arg_3, arg_4, arg_2)


def Func(arg_0, arg_1, arg_2):
    """
    Calculate a percentage.
    """
    try:
        return round(100 * float(arg_0[arg_1]) / float(arg_0[arg_2]), 1)
    except ZeroDivisionError:
        return 0


def Func(arg_0=None):
    """
    Get slabs info.
    """
    arg_1 = {}
    for arg_2 in mc_client.get_slabs():
        arg_3 = arg_2[0].split(' ')
        arg_4 = arg_3[0]
        if arg_0 and arg_0 == arg_4:
            return arg_2[1]
        arg_1[arg_4] = arg_2[1]
    return arg_1


def Func(arg_0, arg_1=None):
    """
    Add admin global context, for compatibility with Django 1.7
    """
    try:
        return dict(site.each_context(arg_1).items() + arg_0.items())
    except AttributeError:
        return arg_0


def Func(arg_0):
    """
    Return the status of all servers.
    """
    arg_1 = {
        'cache_stats': _get_cache_stats(),
        'can_get_slabs': hasattr(mc_client, 'get_slabs'),
    }
    return render_to_response('memcache_admin/Func.html', arg_1, RequestContext(arg_0))