code
stringlengths
1
18.2k
d in dirs if "_" not in d] for filename in files: p_content = convert_text(os.path.join(root, filename)) top = os.path.dirname(os.path.join(root, filename)) top2 = top.replace(os.path.join(cwd, "content"), "", 1) if platform != "win32": subfolder = top2.replace("/", "", 1) else: subfolder = top2.replace("\\", "", 1) if...
writing home_working_file = open(os.path.join(cwd, outdir, "index.html"), "w") home_working_file.write(header_file.read()) # Make sure there is actually a home page template file home_templ_dir = os.path.join(cwd, "templates", "home_page.html") if os.path.exists(home_templ_dir): home_templ_file = open(home_templ_dir, "...
subfolder, newFilename), "w") # Write the header currents_working_file.write(header_file.read()) text_cont1 = convert_text(os.path.join(root, filename)) if "+++++" in text_cont1.splitlines()[1]: page_template_file = text_cont1.splitlines()[0] text_cont1 = text_cont1.replace( text_cont1.splitlines()[0], "") text_cont1 =...
= nav_cont.read() nav_cont.close() forbidden_dirs = set(["assets", "templates"]) blended_version_message = "Built with Blended v" + \ str(app_version) build_date = str(datetime.now().date()) build_time = str(datetime.now().time()) build_datetime = str(datetime.now()) # Replace global variables such as site name and lan...
= time.ctime( os.path.getmtime(os.path.join(root, filename))) file_modified_day = str(datetime.strptime( file_modified, "%a %b %d %H:%M:%S %Y"))[8:10] file_modified_year = str(datetime.strptime( file_modified, "%a %b %d %H:%M:%S %Y"))[:4] file_modified_month = str(datetime.strptime( file_modified, "%a %b %d %H:%M:%S %Y...
= line.replace("{author_name}", author_name) line = line.replace("{author_bio}", author_bio) line = line.replace("{random_number}", str(randint(0, 100000000))) line = line.replace("{build_date}", build_date) line = line.replace("{build_time}", build_time) line = line.replace("{build_datetime}", build_datetime) line = l...
range(level): relative_path = relative_path + "../" line = line.replace("{relative_root}", relative_path) print(line.rstrip('\n')) fileinput.close() # Copy the asset folder to the build folder if os.path.exists(os.path.join(cwd, "templates", "assets")): if os.path.exists(os.path.join(cwd, outdir, "assets")): shutil.rmt...
if styl_text != "": text_file.write(Stylus().compile(styl_text)) else: print(file + " is empty! Not compiling Styl.") text_file.close() except: print("Not able to build with Stylus! Is it installed?") try: subprocess.call["npm", "install", "-g", "stylus"] except: print("NPM (NodeJS) not working. Is it installed?") if f...
def build(outdir): """Blends the generated files and outputs a HTML website""" print("Building your Blended files into a website!") reload(sys) sys.setdefaultencoding('utf8') build_files(outdir) print("The files are built! You can find them in the " + outdir + "/ directory. Run the view command to see what you have cre...
def interactive(outdir): """Blends the generated files and outputs a HTML website on file change""" print("Building your Blended files into a website!") global outdir_type outdir_type = outdir reload(sys) sys.setdefaultencoding('utf8') build_files(outdir) print("Watching the content and templates directories for change...
def view(outdir): """Opens the built index.html file in a web browser""" index_path = os.path.realpath(os.path.join(cwd, outdir, "index.html")) if os.path.exists(index_path): webbrowser.open('file://' + index_path) else: print("The index.html file could not be found in the " + outdir + "/ folder! Have you deleted it or...
def run(self): """Run the builder on changes""" event_handler = Handler() threads = [] paths = [os.path.join(cwd, "content"), os.path.join(cwd, "templates")] for i in paths: targetPath = str(i) self.observer.schedule(event_handler, targetPath, recursive=True) threads.append(self.observer) self.observer.start() try: whi...
def _sanitize_numbers(uncleaned_numbers): """ Convert strings to integers if possible """ cleaned_numbers = [] for x in uncleaned_numbers: try: cleaned_numbers.append(int(x)) except ValueError: cleaned_numbers.append(x) return cleaned_numbers
def _handle_negatives(numbers): """ Add the minimum negative number to all the numbers in the such that all the elements become >= 0 """ min_number = min(filter(lambda x : type(x)==int,numbers)) if min_number < 0: return [x+abs(min_number) if type(x)==int else x for x in numbers] else: return numbers
def _draw_tickgram(numbers): """ Takes a list of integers and generate the equivalent list of ticks corresponding to each of the number """ max_number = max(filter(lambda x : type(x)==int,numbers)) # If the maxium number is 0, then all the numbers should be 0 # coz we have called handle_negatives prior to this function...
def plot_multi_scale_output_b(fig, X='L5E'): '''docstring me''' show_ax_labels = True show_insets = False show_images = False T=[800, 1000] T_inset=[900, 920] left = 0.075 bottom = 0.05 top = 0.475 right = 0.95 axwidth = 0.16 numcols = 4 insetwidth = axwidth/2 insetheight = 0.5 lefts = np.linspace(left, right-axwidth, ...
fig.add_axes([lefts[1]+axwidth-insetwidth, top-insetheight, insetwidth, insetheight]) plt.locator_params(nbins=4) phlp.remove_axis_junk(ax6) plot_signal_sum_colorplot(ax6, params, os.path.join(params.savefolder, 'CSDsum.h5'), unit=r'$\mu$Amm$^{-3}$', T=T_inset, ylim=[ax4.axis()[2], ax4.axis()[3]], fancy=False,colorbar=...
def get_raw_gids(model_params): ''' Reads text file containing gids of neuron populations as created within the NEST simulation. These gids are not continuous as in the simulation devices get created in between. ''' gidfile = open(os.path.join(model_params.raw_nest_output_path, model_params.GID_filename), 'r') gids = [...
def replace_folder(path): """If the specified folder exists, it is deleted and recreated""" if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) else: os.makedirs(path)
def get_html_filename(filename): """Converts the filename to a .html extension""" if ".html" in filename: newFilename = filename elif ".md" in filename: newFilename = filename.replace(".md", ".html") elif ".tile" in filename: newFilename = filename.replace(".tile", ".html") elif ".jade" in filename: newFilename = filen...
def get_html_clear_filename(filename): """Clears the file extension from the filename and makes it nice looking""" newFilename = filename.replace(".html", "") newFilename = newFilename.replace(".md", "") newFilename = newFilename.replace(".txt", "") newFilename = newFilename.replace(".tile", "") newFilename = newFilena...
def getunzipped(username, repo, thedir): """Downloads and unzips a zip file""" theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip" name = os.path.join(thedir, 'temp.zip') try: name = urllib.urlretrieve(theurl, name) name = os.path.join(thedir, 'temp.zip') except IOError as e: print("Can't ret...
def checkConfig(): """If the config.py file exists, back it up""" config_file_dir = os.path.join(cwd, "config.py") if os.path.exists(config_file_dir): print("Making a backup of your config file!") config_file_dir2 = os.path.join(cwd, "config.py.oldbak") copyfile(config_file_dir, config_file_dir2)
def createConfig(app_version=5.0, wname="", wdesc="", wdescl="", wlic="", wlan="", wurl="", aname="", abio=""): """Generates a config file from the information""" config_file_dir = os.path.join(cwd, "config.py") config_file = open(config_file_dir, "w") config_file.write('blended_version = ' + app_version + '\n') config...
Place all custom variables in here\n') config_file.write('\n') config_file.write('minify_css = False\n') config_file.write('minify_js = False\n') config_file.write('\n') config_file.write('# The following values are used for FTP uploads') config_file.write('\n') config_file.write('ftp_server = "localhost"\n') config_fi...
def createBlendedFolders(): """Creates the standard folders for a Blended website""" # Create the templates folder create_folder(os.path.join(cwd, "templates")) # Create the templates/assets folder create_folder(os.path.join(cwd, "templates", "assets")) # Create the templates/assets/css folder create_folder(os.path.joi...
def get_environ(keys): """ Get environment variables from :data:`os.environ`. :type keys: [str] :rtype: dict Some additional features. * If 'HOST' is not in :data:`os.environ`, this function automatically fetch it using :meth:`platform.node`. * If 'TTY' is not in :data:`os.environ`, this function automatically fetch it...
def generate_session_id(data): """ Generate session ID based on HOST, TTY, PID [#]_ and start time. :type data: dict :rtype: str .. [#] PID of the shell, i.e., PPID of this Python process. """ host = data['environ']['HOST'] tty = data['environ'].get('TTY') or 'NO_TTY' return ':'.join(map(str, [ host, tty, os.getppid(),...
def record_run(record_type, print_session_id, **kwds): """ Record shell history. """ if print_session_id and record_type != 'init': raise RuntimeError( '--print-session-id should be used with --record-type=init') cfstore = ConfigStore() # SOMEDAY: Pass a list of environment variables to shell by "rash # init" and don't...
def format_html(format_string, *args, **kwargs): """ Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) kwar...
def normalize_directory(path): """ Append "/" to `path` if needed. """ if path is None: return None if path.endswith(os.path.sep): return path else: return path + os.path.sep
def sql_program_name_func(command): """ Extract program name from `command`. >>> sql_program_name_func('ls') 'ls' >>> sql_program_name_func('git status') 'git' >>> sql_program_name_func('EMACS=emacs make') 'make' :type command: str """ args = command.split(' ') for prog in args: if '=' not in prog: return prog return a...
def sql_pathdist_func(path1, path2, sep=os.path.sep): """ Return a distance between `path1` and `path2`. >>> sql_pathdist_func('a/b/', 'a/b/', sep='/') 0 >>> sql_pathdist_func('a/', 'a/b/', sep='/') 1 >>> sql_pathdist_func('a', 'a/', sep='/') 0 """ seq1 = path1.rstrip(sep).split(sep) seq2 = path2.rstrip(sep).split(sep)...
def _init_db(self): """Creates the database tables.""" with self._get_db() as db: with open(self.schemapath) as f: db.cursor().executescript(f.read()) db.commit()
def connection(self, commit=False): """ Context manager to keep around DB connection. :rtype: sqlite3.Connection SOMEDAY: Get rid of this function. Keeping connection around as an argument to the method using this context manager is probably better as it is more explicit. Also, holding "global state" as instance attrib...
def close_connection(self): """ Close connection kept by :meth:`connection`. If commit is needed, :meth:`sqlite3.Connection.commit` is called first and then :meth:`sqlite3.Connection.interrupt` is called. A few methods/generators support :meth:`close_connection`: - :meth:`search_command_record` - :meth:`select_by_comma...
def _executing(self, sql, params=[]): """ Execute and yield rows in a way to support :meth:`close_connection`. """ with self.connection() as connection: for row in connection.execute(sql, params): yield row if not self._db: return
def get_version_records(self): """ Yield RASH version information stored in DB. Latest first. :rtype: [VersionRecord] """ keys = ['id', 'rash_version', 'schema_version', 'updated'] sql = """ SELECT id, rash_version, schema_version, updated FROM rash_info ORDER BY id DESC """ with self.connection() as connection: for ro...
def update_version_records(self): """ Update rash_info table if necessary. """ from .__init__ import __version__ as version with self.connection(commit=True) as connection: for vrec in self.get_version_records(): if (vrec.rash_version == version and vrec.schema_version == schema_version): return # no need to insert the...
def select_by_command_record(self, crec): """ Yield records that matches to `crec`. All attributes of `crec` except for `environ` are concerned. """ keys = ['command_history_id', 'command', 'session_history_id', 'cwd', 'terminal', 'start', 'stop', 'exit_code'] sql = """ SELECT command_history.id, CL.command, session_id...
? IS NULL)) AND (exit_code = ? OR (exit_code IS NULL AND ? IS NULL)) """ desired_row = [ crec.command, normalize_directory(crec.cwd), crec.terminal, convert_ts(crec.start), convert_ts(crec.stop), crec.exit_code] params = list(itertools.chain(*zip(desired_row, desired_row))) return self._select_rows(CommandRecord, keys,...
def search_command_record( self, after_context, before_context, context, context_type, **kwds): """ Search command history. :rtype: [CommandRecord] """ if after_context or before_context or context: kwds['condition_as_column'] = True limit = kwds['limit'] kwds['limit'] = -1 kwds['unique'] = False kwds['sort_by'] = { 's...
SQLite does not support row_number function, let's # do the filtering at Python side when context modifier # is given. This is *very* inefficient but at least it # works.. return records
def get_full_command_record(self, command_history_id, merge_session_environ=True): """ Get fully retrieved :class:`CommandRecord` instance by ID. By "fully", it means that complex slots such as `environ` and `pipestatus` are available. :type command_history_id: int :type merge_session_environ: bool """ with self.connec...
def start_user_session(self, username, domain, resource, **kwargs): """Method to add a user session for debugging. Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. """ kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow())) kwargs.setdefault('priority', 0)...
def merge_gdf(model_params, raw_label='spikes_', file_type='gdf', fileprefix='spikes'): ''' NEST produces one file per virtual process containing recorder output. This function gathers and combines them into one single file per network population. Parameters ---------- model_params : object network parameters object Re...
[raw_gids[i][0] for i in np.arange(model_params.Npops)] converted_first_gids = [int(1 + np.sum(pop_sizes[:i])) for i in np.arange(model_params.Npops)] for pop_idx in np.arange(model_params.Npops): if pop_idx % SIZE == RANK: files = glob(os.path.join(model_params.raw_nest_output_path, raw_label + str(pop_idx) + '*.' + f...
def dict_of_numpyarray_to_dict_of_list(d): ''' Convert dictionary containing numpy arrays to dictionary containing lists Parameters ---------- d : dict sli parameter name and value as dictionary key and value pairs Returns ------- d : dict modified dictionary ''' for key,value in d.iteritems(): if isinstance(value,dict...
def send_nest_params_to_sli(p): ''' Read parameters and send them to SLI Parameters ---------- p : dict sli parameter name and value as dictionary key and value pairs Returns ------- None ''' for name in p.keys(): value = p[name] if type(value) == np.ndarray: value = value.tolist() if type(value) == dict: value = dict_...
def label_for_field(name, model, return_attr=False): """ Returns a sensible label for a field name. The name can be a callable, property (but not created with @property decorator) or the name of an object's attribute, as well as a genuine fields. If return_attr is True, the resolved attribute (which could be a callable...
on %s" % (name, model._meta.object_name) raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif (isinstance(attr, property) and hasattr(attr, "fget") and hasattr(attr.fget, "short_description")): label = attr.fget.short_description elif callable(attr): if attr.__name__ ...
def update(self, value): """ Update the current rate with the given value. The value must be an integer. """ value = int(value) with self.lock: self.value += value
def tick(self): """Decay the current rate according to the elapsed time""" instant_rate = float(self.value) / float(self.tick_interval) with self.lock: if self.initialized: self.rate += (self.alpha * (instant_rate - self.rate)) else: self.initialized = True self.rate = instant_rate self.value = 0
def notify(self, value): """Add a new observation to the metric""" with self.lock: #TODO: this could slow down slow-rate incoming updates # since the number of ticks depends on the actual time # passed since the latest notification. Consider using # a real timer to tick the EWMA. self.tick() for avg in (self.m1, self.m...
def tick_all(self, times): """ Tick all the EWMAs for the given number of times """ for i in range(times): for avg in (self.m1, self.m5, self.m15, self.day): avg.tick()
def tick(self): """ Emulate a timer: in order to avoid a real timer we "tick" a number of times depending on the actual time passed since the last tick """ now = time.time() elapsed = now - self.latest_tick if elapsed > self.tick_interval: ticks = int(elapsed / self.tick_interval) self.tick_all(ticks) self.latest_tick ...
def get(self): """ Return the computed statistics over the gathered data """ with self.lock: self.tick() data = dict( kind="meter", count=self.count, mean=self.count / (time.time() - self.started_on), one=self.m1.rate, five=self.m5.rate, fifteen=self.m15.rate, day=self.day.rate) return data
def open(lower_value, upper_value): """Helper function to construct an interval object with open lower and upper. For example: >>> open(100.2, 800.9) (100.2, 800.9) """ return Interval(Interval.OPEN, lower_value, upper_value, Interval.OPEN)
def closed(lower_value, upper_value): """Helper function to construct an interval object with closed lower and upper. For example: >>> closed(100.2, 800.9) [100.2, 800.9] """ return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED)
def openclosed(lower_value, upper_value): """Helper function to construct an interval object with a open lower and closed upper. For example: >>> openclosed(100.2, 800.9) (100.2, 800.9] """ return Interval(Interval.OPEN, lower_value, upper_value, Interval.CLOSED)
def closedopen(lower_value, upper_value): """Helper function to construct an interval object with a closed lower and open upper. For example: >>> closedopen(100.2, 800.9) [100.2, 800.9) """ return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN)
def copy(self): """Returns a new :class:`~pyinter.Interval` object with the same bounds and values.""" return Interval(self._lower, self._lower_value, self._upper_value, self._upper)
def _contains_value(self, value): """Helper function for __contains__ to check a single value is contained within the interval""" g = operator.gt if self._lower is self.OPEN else operator.ge l = operator.lt if self._upper is self.OPEN else operator.le return g(value, self.lower_value) and l(value, self._upper_value)
def overlaps(self, other): """If self and other have any overlapping values returns True, otherwise returns False""" if self > other: smaller, larger = other, self else: smaller, larger = self, other if larger.empty(): return False if smaller._upper_value == larger._lower_value: return smaller._upper == smaller.CLOSED ...
def intersect(self, other): """Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`""" if self.overlaps(other): newlower_value = max(self.lower_value, other.lower_value) new_upper_value = min(self._upper_value, other._upper_v...
def difference(self, other): """Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this :class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`. The result will contain everything that is contained by the left interval but not contained by the second interval. If the...
self._upper_value, self._upper) return Interval(self._lower, self._lower_value, self._upper_value, self._upper)
def register(callback, schedule, tag=None): """ Register a callback which will be called at scheduled intervals with the metrics that have the given tag (or all the metrics if None). Return an identifier which can be used to access the registered callback later. """ try: iter(schedule) except TypeError: raise TypeError...
def remove(id_): """ Remove the callback and its schedule """ with LOCK: thread = REGISTRY.pop(id_, None) if thread is not None: thread.cancel() return thread
def get_metrics(tag): """ Return the values for the metrics with the given tag or all the available metrics if None """ if tag is None: return metrics.metrics_by_name_list(metrics.metrics()) else: return metrics.metrics_by_tag(tag)
def fixed_interval_scheduler(interval): """ A scheduler that ticks at fixed intervals of "interval" seconds """ start = time.time() next_tick = start while True: next_tick += interval yield next_tick
def wrap_search(cls, response): """Wrap the response from a game search into instances and return them :param response: The response from searching a game :type response: :class:`requests.Response` :returns: the new game instances :rtype: :class:`list` of :class:`Game` :raises: None """ games = [] json = response.json(...
def wrap_topgames(cls, response): """Wrap the response from quering the top games into instances and return them :param response: The response for quering the top games :type response: :class:`requests.Response` :returns: the new game instances :rtype: :class:`list` of :class:`Game` :raises: None """ games = [] json = ...
def wrap_json(cls, json, viewers=None, channels=None): """Create a Game instance for the given json :param json: the dict with the information of the game :type json: :class:`dict` :param viewers: The viewer count :type viewers: :class:`int` :param channels: The viewer count :type channels: :class:`int` :returns: the n...
def wrap_search(cls, response): """Wrap the response from a channel search into instances and return them :param response: The response from searching a channel :type response: :class:`requests.Response` :returns: the new channel instances :rtype: :class:`list` of :class:`channel` :raises: None """ channels = [] json =...
def wrap_get_channel(cls, response): """Wrap the response from getting a channel into an instance and return it :param response: The response from getting a channel :type response: :class:`requests.Response` :returns: the new channel instance :rtype: :class:`list` of :class:`channel` :raises: None """ json = response.j...
def wrap_json(cls, json): """Create a Channel instance for the given json :param json: the dict with the information of the channel :type json: :class:`dict` :returns: the new channel instance :rtype: :class:`Channel` :raises: None """ c = Channel(name=json.get('name'), status=json.get('status'), displayname=json.get('...
def wrap_search(cls, response): """Wrap the response from a stream search into instances and return them :param response: The response from searching a stream :type response: :class:`requests.Response` :returns: the new stream instances :rtype: :class:`list` of :class:`stream` :raises: None """ streams = [] json = resp...
def wrap_get_stream(cls, response): """Wrap the response from getting a stream into an instance and return it :param response: The response from getting a stream :type response: :class:`requests.Response` :returns: the new stream instance :rtype: :class:`list` of :class:`stream` :raises: None """ json = response.json()...
def wrap_json(cls, json): """Create a Stream instance for the given json :param json: the dict with the information of the stream :type json: :class:`dict` | None :returns: the new stream instance :rtype: :class:`Stream` | None :raises: None """ if json is None: return None channel = Channel.wrap_json(json.get('channel...
def wrap_get_user(cls, response): """Wrap the response from getting a user into an instance and return it :param response: The response from getting a user :type response: :class:`requests.Response` :returns: the new user instance :rtype: :class:`list` of :class:`User` :raises: None """ json = response.json() u = cls.w...
def wrap_json(cls, json): """Create a User instance for the given json :param json: the dict with the information of the user :type json: :class:`dict` | None :returns: the new user instance :rtype: :class:`User` :raises: None """ u = User(usertype=json['type'], name=json['name'], logo=json['logo'], twitchid=json['_id'...
def _wrap_execute_after(funcname): """Warp the given method, so it gets executed by the reactor Wrap a method of :data:`IRCCLient.out_connection`. The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class. :param funcname: the name of a :class:`irc.client.ServerConnection` method :type fun...
def add_serverconnection_methods(cls): """Add a bunch of methods to an :class:`irc.client.SimpleIRCClient` to send commands and messages. Basically it wraps a bunch of methdos from :class:`irc.client.ServerConnection` to be :meth:`irc.schedule.IScheduler.execute_after`. That way, you can easily send, even if the IRCCli...
getattr(irc.client.ServerConnection, m) method.__doc__ = f.__doc__ setattr(cls, method.__name__, method) return cls
def process_forever(self, timeout=0.2): """Run an infinite loop, processing data from connections. This method repeatedly calls process_once. :param timeout: Parameter to pass to :meth:`irc.client.Reactor.process_once` :type timeout: :class:`float` """ # This loop should specifically *not* be mutex-locked. # Otherwise ...
def shutdown(self): """Disconnect all connections and end the loop :returns: None :rtype: None :raises: None """ log.debug('Shutting down %s' % self) self.disconnect_all() self._looping.clear()
def server(self, ): """Creates and returns a ServerConnection :returns: a server connection :rtype: :class:`connection.ServerConnection3` :raises: None """ c = connection.ServerConnection3(self) with self.mutex: self.connections.append(c) return c
def init_run(shell, no_daemon, daemon_options, daemon_outfile): """ Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell other than $SHELL, you can give --she...
daemon_outfile)
def cache_file(symbol, func, has_date, root, date_type='date'): """ Data file Args: symbol: symbol func: use function to categorize data has_date: contains date in data file root: root path date_type: parameters pass to utils.cur_time, [date, time, time_path, ...] Returns: str: date file """ cur_mod = sys.modules[func....
def update_data(func): """ Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function """ default = dict([ (param.name, param.default) for param in inspect.signature(func).parameters.values() if param.default != getattr(inspect, '_empty') ...
is_file=True) save_data(data=data, file_fmt=d_file, append=True, drop_dups=drop_dups) logger.info(f'Saved data file to {d_file} ...') return data return wrapper
def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs): """ Save data to file Args: data: pd.DataFrame file_fmt: data file format in terms of f-strings append: if append data to existing data drop_dups: list, drop duplicates in columns info: dict, infomation to be hashed and passed to f-string...
def data_file(file_fmt, info=None, **kwargs): """ Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name """ if is...
def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs): """ Plot data with multiple scaels together Args: data: DataFrame of data cols: columns to be plotted spacing: spacing between legends color_map: customized colors in map plot_kw: kwargs for each plot **kwargs: kwargs for the first pl...
dict() fig = plt.figure() ax, lines, labels, c_idx = None, [], [], 0 for n, col in enumerate(cols): if isinstance(col, (list, tuple)): ylabel = ' / '.join(cols[n]) color = [ color_map.get(cols[n][_ - c_idx], colors[_ % len(colors)]) for _ in range(c_idx, c_idx + len(cols[n])) ] c_idx += len(col) else: ylabel = col colo...
= ax_new.get_legend_handles_labels() ax_new.spines['right'].set_edgecolor('#D5C4A1') ax_new.spines['right'].set_alpha(.5) ax_new.grid(False) # Proper legend position lines += line labels += label fig.legend(lines, labels, loc=8, prop=dict(), ncol=num_colors).set_zorder(len(cols)) ax.set_xlabel(' \n ') return ax
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): """ Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for plots Examples: >>> import pandas as pd >>> import numpy as np >>> ...
def index_run(record_path, keep_json, check_duplicate): """ Convert raw JSON records into sqlite3 DB. Normally RASH launches a daemon that takes care of indexing. See ``rash daemon --help``. """ from .config import ConfigStore from .indexer import Indexer cfstore = ConfigStore() indexer = Indexer(cfstore, check_duplica...