text stringlengths 81 112k |
|---|
Get a dataframe of estimator values.
NB when parallelised the results will not be produced in order (so results
from some run number will not nessesarily correspond to that number run in
run_list).
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
est... |
Get summary statistics about calculation errors, including estimated
implementation errors.
Parameters
----------
error_values: pandas DataFrame
Of format output by run_list_error_values (look at it for more
details).
summary_df_kwargs: dict, optional
See pandas_functions.su... |
Wrapper which runs run_list_error_values then applies error_values
summary to the resulting dataframe. See the docstrings for those two
funcions for more details and for descriptions of parameters and output.
def run_list_error_summary(run_list, estimator_list, estimator_names,
n_sim... |
Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in estimator_list.
n_simul... |
Calculates estimator values for the constituent threads of the input
runs.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in e... |
Computes pairwise statistical distance measures.
parameters
----------
df_in: pandas data frame
Columns represent estimators and rows represent runs.
Each data frane element is an array of values which are used as samples
in the distance measures.
earth_mover_dist: bool, optiona... |
Quote the column names
def _backtick_columns(cols):
"""
Quote the column names
"""
def bt(s):
b = '' if s == '*' or not s else '`'
return [_ for _ in [b + (s or '') + b] if _]
formatted = []
for c in cols:
if c[0] == '#':
... |
Input: {'c1': 'v', 'c2': None, '#c3': 'uuid()'}
Output:
('%s, %s, uuid()', [None, 'v']) # insert; columnname=False
('`c2` = %s, `c1` = %s, `c3` = uuid()', [None, 'v']) # update; columnname=True
No need to transform NULL value since it's supported in exe... |
Allow select.group and select.order accepting string and list
def _by_columns(self, columns):
"""
Allow select.group and select.order accepting string and list
"""
return columns if self.isstr(columns) else self._backtick_columns(columns) |
:type table: string
:type columns: list
:type join: dict
:param join: {'[>]table1(t1)': {'user.id': 't1.user_id'}} -> "LEFT JOIN table AS t1 ON user.id = t1.user_id"
:type where: dict
:type group: string|list
:type having: string
:type order: string|list
:... |
:type limit: int
:param limit: The max row number for each page
:type offset: int
:param offset: The starting position of the page
:return:
def select_page(self, limit, offset=0, **kwargs):
"""
:type limit: int
:param limit: The max row number for each page
... |
A simplified method of select, for getting the first result in one column only. A common case of using this
method is getting id.
:type table: string
:type column: str
:type join: dict
:type where: dict
:type insert: bool
:param insert: If insert==True, insert the... |
Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert.
def insert(self, table, value, ignore=False, commit=True):
"""
Insert a dict into db.
:type table: string
:t... |
:type table: string
:type value: dict
:type update_columns: list
:param update_columns: specify the columns which will be updated if record exists
:type commit: bool
def upsert(self, table, value, update_columns=None, commit=True):
"""
:type table: string
:type v... |
Insert multiple records within one query.
:type table: string
:type columns: list
:type value: list|tuple
:param value: Doesn't support MySQL functions
:param value: Example: [(value1_column1, value1_column2,), ]
:type ignore: bool
:type commit: bool
:retu... |
:type table: string
:type value: dict
:type where: dict
:type join: dict
:type commit: bool
def update(self, table, value, where, join=None, commit=True):
"""
:type table: string
:type value: dict
:type where: dict
:type join: dict
:type c... |
:type table: string
:type where: dict
:type commit: bool
def delete(self, table, where=None, commit=True):
"""
:type table: string
:type where: dict
:type commit: bool
"""
where_q, _args = self._where_parser(where)
alias = self._tablename_parser(... |
Returns a list containing the whitespace to the left and
right of a string as its two elements
def get_whitespace(txt):
"""
Returns a list containing the whitespace to the left and
right of a string as its two elements
"""
# if the entire parameter is whitespace
rall = re.search(r'^([\s])+... |
Try to find a whitespace pattern in the existing parameters
to be applied to a newly added parameter
def find_whitespace_pattern(self):
"""
Try to find a whitespace pattern in the existing parameters
to be applied to a newly added parameter
"""
name_ws = []
value... |
Generate the path on disk for a specified project and date.
:param project_name: the PyPI project name for the data
:type project: str
:param date: the date for the data
:type date: datetime.datetime
:return: path for where to store this data on disk
:rtype: str
def _pa... |
Get the cache data for a specified project for the specified date.
Returns None if the data cannot be found in the cache.
:param project: PyPi project name to get data for
:type project: str
:param date: date to get data for
:type date: datetime.datetime
:return: dict of... |
Set the cache data for a specified project for the specified date.
:param project: project name to set data for
:type project: str
:param date: date to set data for
:type date: datetime.datetime
:param data: data to cache
:type data: dict
:param data_ts: maximum ... |
Return a list of the dates we have in cache for the specified project,
sorted in ascending date order.
:param project: project name
:type project: str
:return: list of datetime.datetime objects
:rtype: datetime.datetime
def get_dates_for_project(self, project):
"""
... |
Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: ``list``
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace`
def parse_args(argv):
"""
Use Argparse to parse command-line arguments.
:param argv: list of argum... |
Set logger level and format.
:param level: logging level; see the :py:mod:`logging` constants.
:type level: int
:param format: logging formatter format string
:type format: str
def set_log_level_format(level, format):
"""
Set logger level and format.
:param level: logging level; see the :... |
Given the username of a PyPI user, return a list of all of the user's
projects from the XMLRPC interface.
See: https://wiki.python.org/moin/PyPIXmlRpc
:param username: PyPI username
:type username: str
:return: list of string project names
:rtype: ``list``
def _pypi_get_projects_for_user(user... |
Main entry point
def main(args=None):
"""
Main entry point
"""
# parse args
if args is None:
args = parse_args(sys.argv[1:])
# set logging level
if args.verbose > 1:
set_log_debug()
elif args.verbose == 1:
set_log_info()
outpath = os.path.abspath(os.path.ex... |
Generate the graph; return a 2-tuple of strings, script to place in the
head of the HTML document and div content for the graph itself.
:return: 2-tuple (script, div)
:rtype: tuple
def generate_graph(self):
"""
Generate the graph; return a 2-tuple of strings, script to place in... |
Add a line along the top edge of a Patch in a stacked Area Chart; return
the new Glyph for addition to HoverTool.
:param data: original data for the graph
:type data: dict
:param chart: Chart to add the line to
:type chart: bokeh.charts.Chart
:param renderer: GlyphRender... |
Get s list of dates (:py:class:`datetime.datetime`) present in cache,
beginning with the longest contiguous set of dates that isn't missing
more than one date in series.
:return: list of datetime objects for contiguous dates in cache
:rtype: ``list``
def _get_cache_dates(self):
... |
Return True if the specified cache record has no data, False otherwise.
:param rec: cache record returned by :py:meth:`~._cache_get`
:type rec: dict
:return: True if record is empty, False otherwise
:rtype: bool
def _is_empty_cache_record(self, rec):
"""
Return True if ... |
Return cache data for the specified day; cache locally in this class.
:param date: date to get data for
:type date: datetime.datetime
:return: cache data for date
:rtype: dict
def _cache_get(self, date):
"""
Return cache data for the specified day; cache locally in this... |
Like :py:meth:`~._column_value` but collapses two unknowns into one.
:param k1: first (top-level) value
:param k2: second (bottom-level) value
:return: display key
:rtype: str
def _compound_column_value(k1, k2):
"""
Like :py:meth:`~._column_value` but collapses two unkn... |
If ``ver`` is a dot-separated string with at least (num_components +1)
components, return only the first two. Else return the original string.
:param ver: version string
:type ver: str
:return: shortened (major, minor) version
:rtype: str
def _shorten_version(ver, num_component... |
Return download data by version.
:return: dict of cache data; keys are datetime objects, values are
dict of version (str) to count (int)
:rtype: dict
def per_version_data(self):
"""
Return download data by version.
:return: dict of cache data; keys are datetime objec... |
Return download data by file type.
:return: dict of cache data; keys are datetime objects, values are
dict of file type (str) to count (int)
:rtype: dict
def per_file_type_data(self):
"""
Return download data by file type.
:return: dict of cache data; keys are dateti... |
Return download data by installer name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of installer name/version (str) to count (int).
:rtype: dict
def per_installer_data(self):
"""
Return download data by installer name and version.
... |
Return download data by python impelementation name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of implementation name/version (str) to count (int).
:rtype: dict
def per_implementation_data(self):
"""
Return download data by python imp... |
Return download data by system.
:return: dict of cache data; keys are datetime objects, values are
dict of system (str) to count (int)
:rtype: dict
def per_system_data(self):
"""
Return download data by system.
:return: dict of cache data; keys are datetime objects, ... |
Return download data by country.
:return: dict of cache data; keys are datetime objects, values are
dict of country (str) to count (int)
:rtype: dict
def per_country_data(self):
"""
Return download data by country.
:return: dict of cache data; keys are datetime objec... |
Return download data by distro name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of distro name/version (str) to count (int).
:rtype: dict
def per_distro_data(self):
"""
Return download data by distro name and version.
:return:... |
Return the number of downloads per day, averaged over the past 7 days
of data.
:return: average number of downloads per day
:rtype: int
def downloads_per_day(self):
"""
Return the number of downloads per day, averaged over the past 7 days
of data.
:return: aver... |
Return the number of downloads in the last 7 days.
:return: number of downloads in the last 7 days; if we have less than
7 days of data, returns None.
:rtype: int
def downloads_per_week(self):
"""
Return the number of downloads in the last 7 days.
:return: number of ... |
Given a number of days of historical data to look at (starting with
today and working backwards), return the total number of downloads
for that time range, and the number of days of data we had (in cases
where we had less data than requested).
:param num_days: number of days of data to ... |
Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds
JSON file.
:return: project ID
:rtype: str
def _get_project_id(self):
"""
Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds
JSON file.
:return: project ID
:rtype: str
... |
Connect to the BigQuery service.
Calling ``GoogleCredentials.get_application_default`` requires that
you either be running in the Google Cloud, or have the
``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the path
to a credentials JSON file.
:return: authenticated... |
Get a list of PyPI downloads table (sharded per day) IDs.
:return: list of table names (strings)
:rtype: ``list``
def _get_download_table_ids(self):
"""
Get a list of PyPI downloads table (sharded per day) IDs.
:return: list of table names (strings)
:rtype: ``list``
... |
Return a :py:class:`datetime.datetime` object for the date of the
data in the specified table name.
:param table_name: name of the table
:type table_name: str
:return: datetime that the table holds data for
:rtype: datetime.datetime
def _datetime_for_table_name(self, table_name... |
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
def _run_query(self, query):
"""
Run one query against BigQuery and return the result.
... |
Return the timestamp for the newest record in the given table.
:param table_name: name of the table to query
:type table_name: str
:return: timestamp of newest row in table
:rtype: int
def _get_newest_ts_in_table(self, table_name):
"""
Return the timestamp for the newes... |
Query for download data broken down by installer, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by installer; keys are project
name, values are a dict of installer names to dicts of installer
version t... |
Query for download data broken down by system, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by system; keys are project name,
values are a dict of system names to download count.
:rtype: dict
def _quer... |
Query for download data broken down by OS distribution, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by distro; keys are project name,
values are a dict of distro names to dicts of distro version to
d... |
Run all queries for the given table name (date) and update the cache.
:param table_name: table name to query against
:type table_name: str
def query_one_table(self, table_name):
"""
Run all queries for the given table name (date) and update the cache.
:param table_name: table ... |
Return True if we have cached data for all projects for the specified
datetime. Return False otherwise.
:param dt: datetime to find cache for
:type dt: datetime.datetime
:return: True if we have cache for all projects for this date, False
otherwise
:rtype: bool
def _h... |
Backfill historical data for days that are missing.
:param num_days: number of days of historical data to backfill,
if missing
:type num_days: int
:param available_table_names: names of available per-date tables
:type available_table_names: ``list``
def backfill_history(self,... |
Run the data queries for the specified projects.
:param backfill_num_days: number of days of historical data to backfill,
if missing
:type backfill_num_days: int
def run_queries(self, backfill_num_days=7):
"""
Run the data queries for the specified projects.
:param b... |
Given a dict of data such as those in :py:class:`~.ProjectStats` attributes,
made up of :py:class:`datetime.datetime` keys and values of dicts of column
keys to counts, return a list of the distinct column keys in sorted order.
:param data: data dict as returned by ProjectStats attributes
:type data: d... |
Generate the HTML for the specified graphs.
:return:
:rtype:
def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('Generating templated HTML')
env = Environment(
loader=PackageLo... |
Take a dictionary of data, as returned by the :py:class:`~.ProjectStats`
per_*_data properties, return a 2-tuple of data dict and x labels list
usable by bokeh.charts.
:param data: data dict from :py:class:`~.ProjectStats` property
:type data: dict
:return: 2-tuple of data dict,... |
Find the per-day average of each series in the data over the last 7
days; drop all but the top 10.
:param data: original graph data
:type data: dict
:return: dict containing only the top 10 series, based on average over
the last 7 days.
:rtype: dict
def _limit_data(se... |
Generate a downloads graph; append it to ``self._graphs``.
:param name: HTML name of the graph, also used in ``self.GRAPH_KEYS``
:type name: str
:param title: human-readable title for the graph
:type title: str
:param stats_data: data dict from ``self._stats``
:type stat... |
Generate download badges. Append them to ``self._badges``.
def _generate_badges(self):
"""
Generate download badges. Append them to ``self._badges``.
"""
daycount = self._stats.downloads_per_day
day = self._generate_badge('Downloads', '%d/day' % daycount)
self._badges['p... |
Generate SVG for one badge via shields.io.
:param subject: subject; left-hand side of badge
:type subject: str
:param status: status; right-hand side of badge
:type status: str
:return: badge SVG
:rtype: str
def _generate_badge(self, subject, status):
"""
... |
Generate all output types and write to disk.
def generate(self):
"""
Generate all output types and write to disk.
"""
logger.info('Generating graphs')
self._generate_graph(
'by-version',
'Downloads by Version',
self._stats.per_version_data,
... |
Replaces format style phrases (listed in the dt_exps dictionary)
with this datetime instance's information.
.. code :: python
reusables.datetime_format("Hey, it's {month-full} already!")
"Hey, it's March already!"
:param desired_format: string to add datetime details too
:param dateti... |
Create a DateTime object from a ISO string
.. code :: python
reusables.datetime_from_iso('2017-03-10T12:56:55.031863')
datetime.datetime(2017, 3, 10, 12, 56, 55, 31863)
:param iso_string: string of an ISO datetime
:return: DateTime object
def datetime_from_iso(iso_string):
"""
Cr... |
Get a current DateTime object. By default is local.
.. code:: python
reusables.now()
# DateTime(2016, 12, 8, 22, 5, 2, 517000)
reusables.now().format("It's {24-hour}:{min}")
# "It's 22:05"
:param utc: bool, default False, UTC time not local
:param tz: TimeZone as specifie... |
Cross platform compatible subprocess with CompletedProcess return.
No formatting or encoding is performed on the output of subprocess, so it's
output will appear the same on each version / interpreter as before.
.. code:: python
reusables.run('echo "hello world!', shell=True)
# CPython 3.... |
Run a set of iterables to a function in a Threaded or MP Pool.
.. code: python
def func(a):
return a + a
reusables.run_in_pool(func, [1,2,3,4,5])
# [1, 4, 9, 16, 25]
:param target: function to run
:param iterable: positional arg to pass to function
:param threade... |
View a dictionary as a tree.
def tree_view(dictionary, level=0, sep="| "):
"""
View a dictionary as a tree.
"""
return "".join(["{0}{1}\n{2}".format(sep * level, k,
tree_view(v, level + 1, sep=sep) if isinstance(v, dict)
else "") for k, v in dictionary.items()]) |
Turn the Namespace and sub Namespaces back into a native
python dictionary.
:param in_dict: Do not use, for self recursion
:return: python dictionary of this Namespace
def to_dict(self, in_dict=None):
"""
Turn the Namespace and sub Namespaces back into a native
python d... |
Return value of key as a list
:param item: key of value to transform
:param mod: function to map against list
:param default: value to return if item does not exist
:param spliter: character to split str on
:param strip: clean the list with the `strip`
:return: list of i... |
Download a given URL to either file or memory
:param url: Full url (with protocol) of path to download
:param save_to_file: boolean if it should be saved to file or not
:param save_dir: location of saved file, default is current working dir
:param filename: filename to save as
:param block_size: do... |
Provide a list of IP addresses, uses `socket.getaddrinfo`
.. code:: python
reusables.url_to_ips("example.com", ipv6=True)
# ['2606:2800:220:1:248:1893:25c8:1946']
:param url: hostname to resolve to IP addresses
:param port: port to send to getaddrinfo
:param ipv6: Return IPv6 address ... |
Resolve a hostname based off an IP address.
This is very limited and will
probably not return any results if it is a shared IP address or an
address with improperly setup DNS records.
.. code:: python
reusables.ip_to_url('93.184.216.34') # example.com
# None
reusables.ip_to_u... |
Create a background thread for httpd and serve 'forever
def start(self):
"""Create a background thread for httpd and serve 'forever'"""
self._process = threading.Thread(target=self._background_runner)
self._process.start() |
Returns a set up stream handler to add to a logger.
:param stream: which stream to use, defaults to sys.stderr
:param level: logging level to set handler at
:param log_format: formatter to use
:return: stream handler
def get_stream_handler(stream=sys.stderr, level=logging.INFO,
... |
Set up a file handler to add to a logger.
:param file_path: file to write the log to, defaults to out.log
:param level: logging level to set handler at
:param log_format: formatter to use
:param handler: logging handler to use, defaults to FileHandler
:param handler_kwargs: options to pass to the h... |
Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_name: logger name to use
:param level: logging level to set logger at
:param stream: stream to log to, or None
:param file_path: file path to log to, or None
:param log_format: form... |
Addes a newly created stream handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param stream: which stream to use, defaults to sys.stderr
:param level: logging level to set handler at
:param log_format: formatter to use
def add_stream_handler(logg... |
Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: formatter to use
def add_file_handler(logger=None, file_path="ou... |
Adds a rotating file handler to the specified logger.
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: log formatter
:param max_bytes: Max file size in bytes before rota... |
Adds a timed rotating file handler to the specified logger.
Defaults to weekly rotation, with 5 backups.
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: log formatter
... |
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
... |
Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger
def remove_file_handlers(logger=None):
"""
Remove only file handlers from the specified logger. Will go through
and close... |
Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger
def remove_all_handlers(logger=None):
"""
Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstan... |
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go ... |
Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names
def get_registered_loggers(hide_children=False, hide_reusables=False):
"""
Find the names of all loggers curre... |
Wrapper. Makes sure the function's return value has not been returned before
or else it run with the same inputs again.
.. code: python
import reusables
import random
@reusables.unique(max_retries=100)
def poor_uuid():
return random.randint(0, 10)
print([p... |
Wrapper. Simple wrapper to make sure a function is only run once at a time.
.. code: python
import reusables
import time
def func_one(_):
time.sleep(5)
@reusables.lock_it()
def func_two(_):
time.sleep(5)
@reusables.time_it(message="test_1 ... |
Wrapper. Time the amount of time it takes the execution of the function
and print it.
If log is true, make sure to set the logging level of 'reusables' to INFO
level or lower.
.. code:: python
import time
import reusables
reusables.add_stream_handler('reusables')
@re... |
Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
func(10)
print(my_queue.get())
# 1... |
Wrapper. Log the traceback to any exceptions raised. Possible to raise
custom exception.
.. code :: python
@reusables.log_exception()
def test():
raise Exception("Bad")
# 2016-12-26 12:38:01,381 - reusables ERROR Exception in test - Bad
# Traceback (most recent ... |
If the function encounters an exception, catch it, and
return the specified default or sent to a handler function instead.
.. code :: python
def handle_error(exception, func, *args, **kwargs):
print(f"{func.__name__} raised {exception} when called with {args}")
@reusables.catch_it... |
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:param tries: number of tries to retry the function
:param wait: time to wait between executions in seconds
:param handle... |
Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# ['test_structure.zip']
reusables.extract("test_structure.zip")
os.listdir(".")
# [ 'test_structure', 'test_structure.zip']
:param archive... |
Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz, tgz)
- bz2 (tar.bz2)
.. code:: python
reusables.archive(['reusables', '.travis.yml'],
name="my_archive.bz2")
# 'C:\\Users\\Me\\Reusables\\m... |
Save a matrix (list of lists) to a file as a CSV
.. code:: python
my_list = [["Name", "Location"],
["Chris", "South Pole"],
["Harry", "Depth of Winter"],
["Bob", "Skull"]]
reusables.list_to_csv(my_list, "example.csv")
example.csv
... |
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param csv_file: Path to CSV file as str
:r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.