Search is not available for this dataset
text
stringlengths
75
104k
def _dispatch_coroutine(self, event, listener, *args, **kwargs): """Schedule a coroutine for execution. Args: event (str): The name of the event that triggered this call. listener (async def): The async def that needs to be executed. *args: Any number of positional a...
def _dispatch_function(self, event, listener, *args, **kwargs): """Execute a sync function. Args: event (str): The name of the event that triggered this call. listener (def): The def that needs to be executed. *args: Any number of positional arguments. **...
def _dispatch(self, event, listener, *args, **kwargs): """Dispatch an event to a listener. Args: event (str): The name of the event that triggered this call. listener (def or async def): The listener to trigger. *args: Any number of positional arguments. ...
def emit(self, event, *args, **kwargs): """Call each listener for the event with the given arguments. Args: event (str): The event to trigger listeners on. *args: Any number of positional arguments. **kwargs: Any number of keyword arguments. This method pass...
def count(self, event): """Get the number of listeners for the event. Args: event (str): The event for which to count all listeners. The resulting count is a combination of listeners added using 'on'/'add_listener' and 'once'. """ return len(self._listeners[...
def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10, histResolution=.5,plotToo=False): """ let's keep the chunkMs as high as we reasonably can. 50ms is good. Things get flakey at lower numbers like 10ms. IMPORTANT! for this to work, prevent 0s...
def genPNGs(folder,files=None): """Convert each TIF to PNG. Return filenames of new PNGs.""" if files is None: files=glob.glob(folder+"/*.*") new=[] for fname in files: ext=os.path.basename(fname).split(".")[-1].lower() if ext in ['tif','tiff']: if not os.path.exists(...
def htmlABFcontent(ID,group,d): """generate text to go inside <body> for single ABF page.""" html="" files=[] for abfID in group: files.extend(d[abfID]) files=sorted(files) #start with root images html+="<hr>" for fname in files: if ".png" in fname.lower() and not "swhla...
def htmlABF(ID,group,d,folder,overwrite=False): """given an ID and the dict of files, generate a static html for that abf.""" fname=folder+"/swhlab4/%s_index.html"%ID if overwrite is False and os.path.exists(fname): return html=TEMPLATES['abf'] html=html.replace("~ID~",ID) html=html.repl...
def expMenu(groups,folder): """read experiment.txt and return a dict with [firstOfNewExp, color, star, comments].""" ### GENERATE THE MENU DATA BASED ON EXPERIMENT FILE orphans = sorted(list(groups.keys())) menu=[] if os.path.exists(folder+'/experiment.txt'): with open(folder+'/experiment.tx...
def genIndex(folder,forceIDs=[]): """expects a folder of ABFs.""" if not os.path.exists(folder+"/swhlab4/"): print(" !! cannot index if no /swhlab4/") return timestart=cm.timethis() files=glob.glob(folder+"/*.*") #ABF folder files.extend(glob.glob(folder+"/swhlab4/*.*")) print(" ...
def drawPhasePlot(abf,m1=0,m2=None): """ Given an ABF object (SWHLab), draw its phase plot of the current sweep. m1 and m2 are optional marks (in seconds) for plotting only a range of data. Assume a matplotlib figure is already open and just draw on top if it. """ if not m2: m2 = abf.sw...
def plotAllSweeps(abfFile): """simple example how to load an ABF file and plot every sweep.""" r = io.AxonIO(filename=abfFile) bl = r.read_block(lazy=False, cascade=True) print(abfFile+"\nplotting %d sweeps..."%len(bl.segments)) plt.figure(figsize=(12,10)) plt.title(abfFile) for sweep i...
def TIF_to_jpg(fnameTiff, overwrite=False, saveAs=""): """ given a TIF taken by our cameras, make it a pretty labeled JPG. if the filename contains "f10" or "f20", add appropraite scale bars. automatic contrast adjustment is different depending on if its a DIC image or fluorescent image (which is ...
def TIF_to_jpg_all(path): """run TIF_to_jpg() on every TIF of a folder.""" for fname in sorted(glob.glob(path+"/*.tif")): print(fname) TIF_to_jpg(fname)
def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False): """ m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs] """ abf.setsweep(sweep) if m1 is None: m1=0 else: m1=m1*abf.pointsPerSec if m2 is None: m2=-1 else: m2=m2*abf.pointsPerSec # obtain X and Y Yorig=ab...
def convert(fname,saveAs=True,showToo=False): """ Convert weird TIF files into web-friendly versions. Auto contrast is applied (saturating lower and upper 0.1%). make saveAs True to save as .TIF.png make saveAs False and it won't save at all make saveAs "someFile.jpg" to save it as a...
def plot_shaded_data(X,Y,variances,varianceX): """plot X and Y data, then shade its background by variance.""" plt.plot(X,Y,color='k',lw=2) nChunks=int(len(Y)/CHUNK_POINTS) for i in range(0,100,PERCENT_STEP): varLimitLow=np.percentile(variances,i) varLimitHigh=np.percentile(variances,i+P...
def show_variances(Y,variances,varianceX,logScale=False): """create some fancy graphs to show color-coded variances.""" plt.figure(1,figsize=(10,7)) plt.figure(2,figsize=(10,7)) varSorted=sorted(variances) plt.figure(1) plt.subplot(211) plt.grid() plt.title("chronological varia...
def ensureDetection(self): """ run this before analysis. Checks if event detection occured. If not, runs AP detection on all sweeps. """ if self.APs==False: self.log.debug("analysis attempted before event detection...") self.detect()
def detect(self): """runs AP detection on every sweep.""" self.log.info("initializing AP detection on all sweeps...") t1=cm.timeit() for sweep in range(self.abf.sweeps): self.detectSweep(sweep) self.log.info("AP analysis of %d sweeps found %d APs (completed in %s)", ...
def detectSweep(self,sweep=0): """perform AP detection on current sweep.""" if self.APs is False: # indicates detection never happened self.APs=[] # now indicates detection occured # delete every AP from this sweep from the existing array for i,ap in enumerate(self.APs): ...
def get_times(self): """return an array of times (in sec) of all APs.""" self.ensureDetection() times=[] for ap in self.APs: times.append(ap["T"]) return np.array(sorted(times))
def get_bySweep(self,feature="freqs"): """ returns AP info by sweep arranged as a list (by sweep). feature: * "freqs" - list of instantaneous frequencies by sweep. * "firsts" - list of first instantaneous frequency by sweep. * "times" - list of times of each ...
def get_author_and_version(package): """ Return package author and version as listed in `init.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() author = re.search("__author__ = ['\"]([^'\"]+)['\"]", init_py).group(1) version = re.search("__version__ = ['\"]([^'\"]+)['\"]", ini...
def api_subclass_factory(name, docstring, remove_methods, base=SlackApi): """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:`di...
async def execute_method(self, method, **params): """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 ...
def method_exists(cls, method): """Whether a given method exists in the known API. Arguments: method (:py:class:`str`): The name of the method. Returns: :py:class:`bool`: Whether the method is in the known API. """ methods = cls.API_METHODS for key ...
def _add_parsley_ns(cls, namespace_dict): """ Extend XPath evaluation with Parsley extensions' namespace """ namespace_dict.update({ 'parslepy' : cls.LOCAL_NAMESPACE, 'parsley' : cls.LOCAL_NAMESPACE, }) return namespace_dict
def make(self, selection): """ XPath expression can also use EXSLT functions (as long as they are understood by libxslt) """ cached = self._selector_cache.get(selection) if cached: return cached try: selector = lxml.etree.XPath(selection,...
def extract(self, document, selector, debug_offset=''): """ Try and convert matching Elements to unicode strings. If this fails, the selector evaluation probably already returned some string(s) of some sort, or boolean value, or int/float, so return that instead. """ ...
def make(self, selection): """ Scopes and selectors are tested in this order: * is this a CSS selector with an appended @something attribute? * is this a regular CSS selector? * is this an XPath expression? XPath expression can also use EXSLT functions (as long as they a...
async def join_rtm(self, filters=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 ...
async def handle_message(self, message, filters): """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. ...
def message_is_to_me(self, data): """If you send a message directly to me""" return (data.get('type') == 'message' and data.get('text', '').startswith(self.address_as))
async def from_api_token(cls, token=None, api_cls=SlackBotApi): """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:`...
def _format_message(self, channel, text): """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...
async def _get_socket_url(self): """Get the WebSocket URL for the RTM session. Warning: The URL expires if the session is not joined within 30 seconds of the API call to the start endpoint. Returns: :py:class:`str`: The socket URL. """ data = awai...
def _instruction_list(self, filters): """Generates the instructions for a bot and its filters. Note: The guidance for each filter is generated by combining the docstrings of the predicate filter and resulting dispatch function with a single space between. The class's ...
def _respond(self, channel, text): """Respond to a message on the current socket. Args: channel (:py:class:`str`): The channel to send to. text (:py:class:`str`): The message text to send. """ result = self._format_message(channel, text) if result is not Non...
def _validate_first_message(cls, msg): """Check the first message matches the expected handshake. Note: The handshake is provided as :py:attr:`RTM_HANDSHAKE`. Arguments: msg (:py:class:`aiohttp.Message`): The message to validate. Raises: :py:class:`SlackA...
def find_first_existing_executable(exe_list): """ Accepts list of [('executable_file_path', 'options')], Returns first working executable_file_path """ for filepath, opts in exe_list: try: proc = subprocess.Popen([filepath, opts], stdout=subpro...
def get_app_locations(): """ Returns list of paths to tested apps """ return [os.path.dirname(os.path.normpath(import_module(app_name).__file__)) for app_name in PROJECT_APPS]
def get_tasks(): """Get the imported task classes for each task that will be run""" task_classes = [] for task_path in TASKS: try: module, classname = task_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured('%s isn\'t a task module' % task_path) ...
def get_task_options(): """Get the options for each task that will be run""" options = () task_classes = get_tasks() for cls in task_classes: options += cls.option_list return options
def to_cldf(self, dest, mdname='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 """ dest = Path(dest) if not dest.exists(): ...
def validate(args): """ cldf validate <DATASET> Validate a dataset against the CLDF specification, i.e. check - whether required tables and columns are present - whether values for required columns are present - the referential integrity of the dataset """ ds = _get_dataset(args) ds...
def stats(args): """ cldf stats <DATASET> Print basic stats for CLDF dataset <DATASET>, where <DATASET> may be the path to - a CLDF metadata file - a CLDF core data file """ ds = _get_dataset(args) print(ds) md = Table('key', 'value') md.extend(ds.properties.items()) print(m...
def createdb(args): """ cldf createdb <DATASET> <SQLITE_DB_PATH> Load CLDF dataset <DATASET> into a SQLite DB, where <DATASET> may be the path to - a CLDF metadata file - a CLDF core data file """ if len(args.args) < 2: raise ParserError('not enough arguments') ds = _get_dataset...
def dumpdb(args): """ cldf dumpdb <DATASET> <SQLITE_DB_PATH> [<METADATA_PATH>] """ if len(args.args) < 2: raise ParserError('not enough arguments') # pragma: no cover ds = _get_dataset(args) db = Database(ds, fname=args.args[1]) mdpath = Path(args.args[2]) if len(args.args) > 2 else...
def description(self): """A user-friendly description of the handler. Returns: :py:class:`str`: The handler's description. """ if self._description is None: text = '\n'.join(self.__doc__.splitlines()[1:]).strip() lines = [] for line in map(...
def from_jsonfile(cls, fp, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from a file containing the Parsley script as a JSON object >>> import parslepy >>> with open('parselet.json') as fp: ... parslepy.Parselet.from_jsonfile(fp) ...
def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ...
def from_yamlstring(cls, s, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from s (str) containing the Parsley script as YAML >>> import parslepy >>> parsley_string = '''--- title: h1 link: a @href ''' >>...
def from_jsonstring(cls, s, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from s (str) containing the Parsley script as JSON >>> import parslepy >>> parsley_string = '{ "title": "h1", "link": "a @href"}' >>> p = parslepy.Parselet.from_...
def _from_jsonlines(cls, lines, selector_handler=None, strict=False, debug=False): """ Interpret input lines as a JSON Parsley script. Python-style comment lines are skipped. """ return cls(json.loads( "\n".join([l for l in lines if not cls.REGEX_COMMENT_LINE.mat...
def parse(self, fp, parser=None, context=None): """ Parse an HTML or XML document and return the extacted object following the Parsley rules give at instantiation. :param fp: file-like object containing an HTML or XML document, or URL or filename :param parser: *lxml.etree._Feed...
def parse_fromstring(self, s, parser=None, context=None): """ Parse an HTML or XML document and return the extacted object following the Parsley rules give at instantiation. :param string s: an HTML or XML document as a string :param parser: *lxml.etree._FeedParser* instance (op...
def compile(self): """ Build the abstract Parsley tree starting from the root node (recursive) """ if not isinstance(self.parselet, dict): raise ValueError("Parselet must be a dict of some sort. Or use .from_jsonstring(), " \ ".from_jsonfile(), .from_y...
def _compile(self, parselet_node, level=0): """ Build part of the abstract Parsley extraction tree Arguments: parselet_node (dict) -- part of the Parsley tree to compile (can be the root dict/node) level (int) -- current recursion depth (...
def extract(self, document, context=None): """ Extract values as a dict object following the structure of the Parsley script (recursive) :param document: lxml-parsed document :param context: user-supplied context that will be passed to custom XPath extensions (as first argument)...
def _extract(self, parselet_node, document, level=0): """ Extract values at this document node level using the parselet_node instructions: - go deeper in tree - or call selector handler in case of a terminal selector leaf """ if self.DEBUG: debug_offs...
def auto_constraints(self, component=None): """ Use CLDF reference properties to implicitely create foreign key constraints. :param component: A Table object or `None`. """ if not component: for table in self.tables: self.auto_constraints(table) ...
def url_builder(self, endpoint, *, root=None, params=None, url_params=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. para...
def raise_for_status(response): """Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. """ for er...
def truncate(text, max_len=350, end='...'): """Truncate the supplied text for display. Arguments: text (:py:class:`str`): The text to truncate. max_len (:py:class:`int`, optional): The maximum length of the text before truncation (defaults to 350 characters). end (:py:class:`str`, opt...
def add(self, *entries): """ Add a source, either specified by glottolog reference id, or as bibtex record. """ for entry in entries: if isinstance(entry, string_types): self._add_entries(database.parse_string(entry, bib_format='bibtex')) else: ...
def primary_avatar(user, size=AVATAR_DEFAULT_SIZE): """ This tag tries to get the default avatar for a user without doing any db requests. It achieve this by linking to a special view that will do all the work for us. If that special view is then cached by a CDN for instance, we will avoid many db ...
def get_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """ if isinstance(user_or_username, get_user_model()): user_or_username = user_or_username.username return '%s_%s_%s' % (prefix, user_or_username, size)
def cache_result(func): """ Decorator to cache the result of functions that take a ``user`` and a ``size`` value. """ def cache_set(key, value): cache.set(key, value, AVATAR_CACHE_TIMEOUT) return value def cached_func(user, size): prefix = func.__name__ cached_fu...
def invalidate_cache(user, size=None): """ Function to be called when saving or changing an user's avatars. """ sizes = set(AUTO_GENERATE_AVATAR_SIZES) if size is not None: sizes.add(size) for prefix in cached_funcs: for size in sizes: cache.delete(get_cache_key(user,...
def get_field_for_proxy(pref_proxy): """Returns a field object instance for a given PrefProxy object. :param PrefProxy pref_proxy: :rtype: models.Field """ field = { bool: models.BooleanField, int: models.IntegerField, float: models.FloatField, datetime: models.Da...
def update_field_from_proxy(field_obj, pref_proxy): """Updates field object with data from a PrefProxy object. :param models.Field field_obj: :param PrefProxy pref_proxy: """ attr_names = ('verbose_name', 'help_text', 'default') for attr_name in attr_names: setattr(field_obj, attr_na...
def get_pref_model_class(app, prefs, get_prefs_func): """Returns preferences model class dynamically crated for a given app or None on conflict.""" module = '%s.%s' % (app, PREFS_MODULE_NAME) model_dict = { '_prefs_app': app, '_get_prefs': staticmethod(get_prefs_func), ...
def get_frame_locals(stepback=0): """Returns locals dictionary from a given frame. :param int stepback: :rtype: dict """ with Frame(stepback=stepback) as frame: locals_dict = frame.f_locals return locals_dict
def traverse_local_prefs(stepback=0): """Generator to walk through variables considered as preferences in locals dict of a given frame. :param int stepback: :rtype: tuple """ locals_dict = get_frame_locals(stepback+1) for k in locals_dict: if not k.startswith('_') and k.upper() ==...
def import_prefs(): """Imports preferences modules from packages (apps) and project root.""" # settings.py locals if autodiscover_siteprefs() is in urls.py settings_locals = get_frame_locals(3) if 'self' not in settings_locals: # If not SiteprefsConfig.ready() # Try to import project-wide...
def print_file_info(): """Prints file details in the current directory""" tpl = TableLogger(columns='file,created,modified,size') for f in os.listdir('.'): size = os.stat(f).st_size date_created = datetime.fromtimestamp(os.path.getctime(f)) date_modified = datetime.fromtimestamp(os.p...
def _bind_args(sig, param_matchers, args, kwargs): ''' Attempt to bind the args to the type signature. First try to just bind to the signature, then ensure that all arguments match the parameter types. ''' #Bind to signature. May throw its own TypeError bound = si...
def _make_param_matcher(annotation, kind=None): ''' For a given annotation, return a function which, when called on a function argument, returns true if that argument matches the annotation. If the annotation is a type, it calls isinstance; if it's a callable, it calls it on the ...
def _make_all_matchers(cls, parameters): ''' For every parameter, create a matcher if the parameter has an annotation. ''' for name, param in parameters: annotation = param.annotation if annotation is not Parameter.empty: yield name, cls._m...
def _make_dispatch(cls, func): ''' Create a dispatch pair for func- a tuple of (bind_args, func), where bind_args is a function that, when called with (args, kwargs), attempts to bind those args to the type signature of func, or else raise a TypeError ''' sig = si...
def _make_wrapper(self, func): ''' Makes a wrapper function that executes a dispatch call for func. The wrapper has the dispatch and dispatch_first attributes, so that additional overloads can be added to the group. ''' #TODO: consider using a class to make attribute for...
def dispatch(self, func): ''' Adds the decorated function to this dispatch. ''' self.callees.append(self._make_dispatch(func)) return self._make_wrapper(func)
def dispatch_first(self, func): ''' Adds the decorated function to this dispatch, at the FRONT of the order. Useful for allowing third parties to add overloaded functionality to be executed before default functionality. ''' self.callees.appendleft(self._make_dispatch(func...
def lookup_explicit(self, args, kwargs): ''' Lookup the function that will be called with a given set of arguments, or raise DispatchError. Requires explicit tuple/dict grouping of arguments (see DispatchGroup.lookup for a function-like interface). ''' for bind_args, call...
def execute(self, args, kwargs): ''' Dispatch a call. Call the first function whose type signature matches the arguemts. ''' return self.lookup_explicit(args, kwargs)(*args, **kwargs)
def setup_formatters(self, *args): """Setup formatters by observing the first row. Args: *args: row cells """ formatters = [] col_offset = 0 # initialize formatters for row-id, timestamp and time-diff columns if self.rownum: format...
def setup(self, *args): """Do preparations before printing the first row Args: *args: first row cells """ self.setup_formatters(*args) if self.columns: self.print_header() elif self.border and not self.csv: self.print_line(sel...
def csv_format(self, row): """Converts row values into a csv line Args: row: a list of row cells as unicode Returns: csv_line (unicode) """ if PY2: buf = io.BytesIO() csvwriter = csv.writer(buf) csvwriter.writer...
def convertShpToExtend(pathToShp): """ reprojette en WGS84 et recupere l'extend """ driver = ogr.GetDriverByName('ESRI Shapefile') dataset = driver.Open(pathToShp) if dataset is not None: # from Layer layer = dataset.GetLayer() spatialRef = layer.GetSpatialRef() ...
def create_request_gfs(dateStart,dateEnd,stepList,levelList,grid,extent,paramList,typeData): """ Genere la structure de requete pour le téléchargement de données GFS INPUTS:\n -date : au format annee-mois-jour\n -heure : au format heure:minute:seconde\n -coord : une ...
def convertGribToTiff(listeFile,listParam,listLevel,liststep,grid,startDate,endDate,outFolder): """ Convert GRIB to Tif""" dicoValues={} for l in listeFile: grbs = pygrib.open(l) grbs.seek(0) index=1 for j in range(len(listLevel),0,-1): for i in range(le...
def on_pref_update(*args, **kwargs): """Triggered on dynamic preferences model save. Issues DB save and reread. """ Preference.update_prefs(*args, **kwargs) Preference.read_prefs(get_prefs())
def get_app_prefs(app=None): """Returns a dictionary with preferences for a certain app/module. :param str|unicode app: :rtype: dict """ if app is None: with Frame(stepback=1) as frame: app = frame.f_globals['__name__'].split('.')[0] prefs = get_prefs() if app not i...
def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='', static=True, readonly=False): """Binds PrefProxy objects to module variables used by apps as preferences. :param list|tuple values: Preference values. :param str|unicode category: Category name the preference belongs to. ...
def register_admin_models(admin_site): """Registers dynamically created preferences models for Admin interface. :param admin.AdminSite admin_site: AdminSite object. """ global __MODELS_REGISTRY prefs = get_prefs() for app_label, prefs_items in prefs.items(): model_class = get_pref_m...
def autodiscover_siteprefs(admin_site=None): """Automatically discovers and registers all preferences available in all apps. :param admin.AdminSite admin_site: Custom AdminSite object. """ if admin_site is None: admin_site = admin.site # Do not discover anything if called from manage.py (...
def patch_locals(depth=2): """Temporarily (see unpatch_locals()) replaces all module variables considered preferences with PatchedLocal objects, so that every variable has different hash returned by id(). """ for name, locals_dict in traverse_local_prefs(depth): locals_dict[name] = PatchedL...
def unpatch_locals(depth=3): """Restores the original values of module variables considered preferences if they are still PatchedLocal and not PrefProxy. """ for name, locals_dict in traverse_local_prefs(depth): if isinstance(locals_dict[name], PatchedLocal): locals_dict[name] =...