output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_latex_name(func_in, **kwargs):
"""
Produce a latex formatted name for each function for use in labelling
results.
Parameters
----------
func_in: function
kwargs: dict, optional
Kwargs for function.
Returns
-------
latex_name: str
Latex formatted name for... | Write a Python 3 script to
produce a latex formatted name for each function in the sequence. | You are a Python code analyst, evaluating scripts for potential improvements. |
def weighted_quantile(probability, values, weights):
"""
Get quantile estimate for input probability given weighted samples using
linear interpolation.
Parameters
----------
probability: float
Quantile to estimate - must be in open interval (0, 1).
For example, use 0.5 for the m... | Can you implement a function in Python 3 that
gets quantile estimate for input probability given weighted samples using linear interpolation. | As a python code expert, you are capable of creating scripts from specifications. |
Writes the output files corresponding to the input nested sampling
run. | Given the following Python 3 function, write the documentation
def write_run_output(run, **kwargs):
write_dead = kwargs.pop('write_dead', True)
write_stats = kwargs.pop('write_stats', True)
posteriors = kwargs.pop('posteriors', False)
equals = kwargs.pop('equals', False)
stats_means_errs = kwargs.po... | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts input run into an array of the format of a PolyChord
<root >_dead - birth. txt file. | Explain what the following Python 3 code does
def run_dead_birth_array(run, **kwargs):
nestcheck.ns_run_utils.check_ns_run(run, **kwargs)
threads = nestcheck.ns_run_utils.get_run_threads(run)
samp_arrays = []
ndim = run['theta'].shape[1]
for th in threads:
samp_arr = np.zeros((th['theta'].sh... | You are a Python code generator, capable of creating scripts from specifications. |
Writes a dummy PolyChord format. stats file for tests functions for
processing stats files. This is written to file_root base_dir. stats
Also returns the data in the file as a dict for comparison. | Can you generate a brief explanation for the following Python 3 code
def write_stats_file(run_output_dict):
mandatory_keys = ['file_root', 'base_dir']
for key in mandatory_keys:
assert key in run_output_dict, key + ' not in run_output_dict'
default_output = {'logZ': 0.0,
'logZe... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run_list_error_values(run_list, estimator_list, estimator_names,
n_simulate=100, **kwargs):
"""Gets a data frame with calculation values and error diagnostics for each
run in the input run list.
NB when parallelised the results will not be produced in order (so results
fro... | Write a Python 3 function that can
return a dataframe with calculation values and error diagnostics for each nested sampling run in the input run list. | As a python code expert, you are capable of creating scripts from specifications. |
Get a dataframe of estimator values for each run in run_list. | Given the following Python 3 function, write the documentation
def estimator_values_df(run_list, estimator_list, **kwargs):
estimator_names = kwargs.pop(
'estimator_names',
['est_' + str(i) for i in range(len(estimator_list))])
parallel = kwargs.pop('parallel', True)
if kwargs:
raise... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get summary statistics about calculation errors including estimated
Taxonomy implementation errors. | Given the following Python 3 function, write the documentation
def error_values_summary(error_values, **summary_df_kwargs):
df = pf.summary_df_from_multi(error_values, **summary_df_kwargs)
# get implementation stds
imp_std, imp_std_unc, imp_frac, imp_frac_unc = \
nestcheck.error_analysis.implementat... | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_list_error_summary(run_list, estimator_list, estimator_names,
n_simulate, **kwargs):
"""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... | Implement a function in Python 3 to
wrap which runs run_list_error_values then applies error_values_summary to the resulting dataframe | As a Python code analyst, you investigate and solve complex coding mysteries |
Computes a data frame of bootstrap resampled values for each run in the cluster. | Explain what the following Python 3 code does
def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,
**kwargs):
"""Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimato... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates estimator values for the constituent threads of the input
runs. | Given the following Python 3 function, write the documentation
def thread_values_df(run_list, estimator_list, estimator_names, **kwargs):
tqdm_kwargs = kwargs.pop('tqdm_kwargs', {'desc': 'thread values'})
assert len(estimator_list) == len(estimator_names), (
'len(estimator_list) = {0} != len(estimator_n... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Computes pairwise statistical distance measures on the columns of df_in. | Given the following Python 3 function, write the documentation
def pairwise_dists_on_cols(df_in, earth_mover_dist=True, energy_dist=True):
df = pd.DataFrame()
for col in df_in.columns:
df[col] = nestcheck.error_analysis.pairwise_distances(
df_in[col].values, earth_mover_dist=earth_mover_dist... | You are a Python code generator, capable of creating scripts from specifications. |
Return the column names that are used in the SQL query. | How would you explain what the following Python 3 function does
def _backtick_columns(cols):
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] == '#':
formatted.a... | You are a Python code generator, capable of creating scripts from specifications. |
Parse the value of the key - value pair into a SQL string. | Explain what the following Python 3 code does
def _value_parser(self, value, columnname=False, placeholder='%s'):
if not isinstance(value, dict):
raise TypeError('Input value should be a dictionary')
q = []
a = []
for k, v in value.items():
if k[0] == '#': # if i... | You are a Python code generator, capable of creating scripts from specifications. |
Return a list of column names to be used in the select. | Explain what the following Python 3 code does
def _by_columns(self, columns):
return columns if self.isstr(columns) else self._backtick_columns(columns) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def select(self, table, columns=None, join=None, where=None, group=None, having=None, order=None, limit=None,
iterator=False, fetch=True):
"""
:type table: string
:type columns: list
:type join: dict
:param join: {'[>]table1(t1)': {'user.id': 't1.user_id'}} -> "LEF... | Can you write a function in Python 3 where it
selects all the entries in the specified table. | You are a Python code architect, reviewing and designing scalable and efficient code |
def select_page(self, limit, offset=0, **kwargs):
"""
:type limit: int
:param limit: The max row number for each page
:type offset: int
:param offset: The starting position of the page
:return:
"""
start = offset
while True:
result = se... | Write a Python 3 script to
return a generator that yields the page of the available n - topic entries. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get(self, table, column, join=None, where=None, insert=False, ifnone=None):
"""
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
... | Create a Python 3 function for
returning the first result in one column only. | You are a Python code generator, capable of creating scripts from specifications. |
Insert a dict into db. | Explain what the following Python 3 code does
def insert(self, table, value, ignore=False, commit=True):
value_q, _args = self._value_parser(value, columnname=False)
_sql = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
' (', self._backtick_colum... | You are a Python code generator, capable of creating scripts from specifications. |
def upsert(self, table, value, update_columns=None, commit=True):
"""
: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
"""
if not isinstanc... | Can you write a function in Python 3 where it
inserts a record in the specified table with the given value. | As a python code expert, you are capable of creating scripts from specifications. |
def insertmany(self, table, columns, value, ignore=False, commit=True):
"""
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_colu... | How would you implement a function in Python 3 that
inserts multiple records within one query. | As a python code expert, you are capable of creating scripts from specifications. |
Update the entry in the specified table with the given value and where. | Here you have a function in Python 3, explain what it does
def update(self, table, value, where, join=None, commit=True):
value_q, _value_args = self._value_parser(value, columnname=True)
where_q, _where_args = self._where_parser(where)
_sql = ''.join(['UPDATE ', self._tablename_parser(table)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Delete all the entries in the specified table. | How would you explain what the following Python 3 function does
def delete(self, table, where=None, commit=True):
where_q, _args = self._where_parser(where)
alias = self._tablename_parser(table)['alias']
_sql = ''.join(['DELETE ',
alias + ' ' if alias else '',
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a list containing the whitespace to the left and right of a string as its two elements
| How would you explain what the following Python 3 function does
def get_whitespace(txt):
# if the entire parameter is whitespace
rall = re.search(r'^([\s])+$', txt)
if rall:
tmp = txt.split('\n', 1)
if len(tmp) == 2:
return (tmp[0], '\n' + tmp[1]) # left, right
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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_ws = []
for entry in self._entries:
name_ws.append(get_whitespace(entry.name))
... | Create a Python 3 function for
trying to find a whitespace pattern in the existing parameters to be applied to a newly added parameter . | As a python code expert, you are capable of creating scripts from specifications. |
def _path_for_file(self, project_name, date):
"""
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... | Can you implement a function in Python 3 that
generates the path on disk for a specific project and date. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the cache data for a specified project and date. | Can you generate the documentation for the following Python 3 function
def get(self, project, date):
fpath = self._path_for_file(project, date)
logger.debug('Cache GET project=%s date=%s - path=%s',
project, date.strftime('%Y-%m-%d'), fpath)
try:
with open(fpath,... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the cache data for a specified project for the specified date. | Given the following Python 3 function, write the documentation
def set(self, project, date, data, data_ts):
data['cache_metadata'] = {
'project': project,
'date': date.strftime('%Y%m%d'),
'updated': time.time(),
'version': VERSION,
'data_ts': data_ts
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a list of the dates we have in cache for the specified project sorted in ascending date order. | Here you have a function in Python 3, explain what it does
def get_dates_for_project(self, project):
file_re = re.compile(r'^%s_([0-9]{8})\.json$' % project)
all_dates = []
for f in os.listdir(self.cache_path):
if not os.path.isfile(os.path.join(self.cache_path, f)):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse command - line arguments. | Can you generate a brief explanation for the following Python 3 code
def parse_args(argv):
p = argparse.ArgumentParser(
description='pypi-download-stats - Calculate detailed download stats '
'and generate HTML and badges for PyPI packages - '
'<%s>' % PROJECT_URL,
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set logger level and format. | Given the following Python 3 function, write the documentation
def set_log_level_format(level, format):
formatter = logging.Formatter(fmt=format)
logger.handlers[0].setFormatter(formatter)
logger.setLevel(level) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of all of the user s
projects from the XMLRPC interface. | Can you generate a brief explanation for the following Python 3 code
def _pypi_get_projects_for_user(username):
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
pkgs = client.user_packages(username) # returns [role, package]
return [x[1] for x in pkgs] | You are a Python code architect, reviewing and designing scalable and efficient code |
Entry point for pypi
. | Make a summary of the following Python 3 code
def main(args=None):
# 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.expanduser(... | You are a Python code generator, capable of creating scripts from specifications. |
Generate the graph for the current object. | Can you tell what is the following Python 3 function doing
def generate_graph(self):
logger.debug('Generating graph for %s', self._graph_id)
# tools to use
tools = [
PanTool(),
BoxZoomTool(),
WheelZoomTool(),
SaveTool(),
ResetTool(),
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _line_for_patches(self, data, chart, renderer, series_name):
"""
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... | Create a Python 3 function for
adding 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: GlyphRenderer containing o... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a list of dates that are present in the cache. | How would you explain what the following Python 3 function does
def _get_cache_dates(self):
all_dates = self.cache.get_dates_for_project(self.project_name)
dates = []
last_date = None
for val in sorted(all_dates):
if last_date is None:
last_date = val
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _is_empty_cache_record(self, rec):
"""
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
"""
... | Create a Python 3 function to
return True if the specified cache record has no data False otherwise. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the cache data for the specified day. | Here you have a function in Python 3, explain what it does
def _cache_get(self, date):
if date in self.cache_data:
logger.debug('Using class-cached data for date %s',
date.strftime('%Y-%m-%d'))
return self.cache_data[date]
logger.debug('Getting data from ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Like _column_value but collapses two unknowns into one. | Can you tell what is the following Python 3 function doing
def _compound_column_value(k1, k2):
k1 = ProjectStats._column_value(k1)
k2 = ProjectStats._column_value(k2)
if k1 == 'unknown' and k2 == 'unknown':
return 'unknown'
return '%s %s' % (k1, k2) | As a python code expert, you are capable of creating scripts from specifications. |
def _shorten_version(ver, num_components=2):
"""
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) ver... | Create a Python 3 function for
shortening the version string to be a number of components. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return download data by version. | Explain what the following Python 3 code does
def per_version_data(self):
ret = {}
for cache_date in self.cache_dates:
data = self._cache_get(cache_date)
if len(data['by_version']) == 0:
data['by_version'] = {'other': 0}
ret[cache_date] = data['by_vers... | You are a Python code generator, capable of creating scripts from specifications. |
def per_file_type_data(self):
"""
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
"""
ret = {}
for cache_date in self.cache_dates:
data... | Create a Python 3 function for
returning download data by file type. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return download data by installer name and version. | How would you explain what the following Python 3 function does
def per_installer_data(self):
ret = {}
for cache_date in self.cache_dates:
data = self._cache_get(cache_date)
ret[cache_date] = {}
for inst_name, inst_data in data['by_installer'].items():
... | As a python code expert, you are capable of creating scripts from specifications. |
def per_implementation_data(self):
"""
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
"""
ret = {}
... | Write a Python 3 script for
returning download data by python impelementation name and version. | You are a Python code architect, reviewing and designing scalable and efficient code |
def per_system_data(self):
"""
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
"""
ret = {}
for cache_date in self.cache_dates:
data = self._... | Create a Python 3 function to
return download data by system. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def per_country_data(self):
"""
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
"""
ret = {}
for cache_date in self.cache_dates:
data = sel... | Create a Python 3 function to
return download data by country. | As a Python code analyst, you investigate and solve complex coding mysteries |
def per_distro_data(self):
"""
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
"""
ret = {}
for cache_date in self.cache_d... | Can you create a Python 3 function that
returns download data by distro name and version. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the number of downloads per day average over the past 7 days
of data. | Here you have a function in Python 3, explain what it does
def downloads_per_day(self):
count, num_days = self._downloads_for_num_days(7)
res = ceil(count / num_days)
logger.debug("Downloads per day = (%d / %d) = %d", count, num_days, res)
return res | You are a Python code generator, capable of creating scripts from specifications. |
def downloads_per_week(self):
"""
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
"""
if len(self.cache_dates) < 7:
logger.error("Only... | Implement a function in Python 3 to
return the number of downloads per week in the last 7 days of data. | As a Python code composer, you craft elegant and concise scripts. |
def _downloads_for_num_days(self, num_days):
"""
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... | Write a Python 3 function that can
get the total number of downloads for a given number of days of data. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get our projectId from the GOOGLE_APPLICATION_CREDENTIALS file. | How would you explain what the following Python 3 function does
def _get_project_id(self):
fpath = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None)
if fpath is None:
raise Exception('ERROR: No project ID specified, and '
'GOOGLE_APPLICATION_CREDENTIALS env v... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_bigquery_service(self):
"""
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 c... | How would you implement a function in Python 3 that
connects to the BigQuery service. | You are a Python code generator, capable of creating scripts from specifications. |
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``
"""
all_table_names = [] # matching per-date table names
logger.info('Querying for all tables in dataset')
... | Write a Python 3 script for
getting a list of PyPI downloads table IDs. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a datetime object for the date of the data in the specified table name. | Can you generate the documentation for the following Python 3 function
def _datetime_for_table_name(self, table_name):
m = self._table_re.match(table_name)
dt = datetime.strptime(m.group(1), '%Y%m%d')
return dt | As a Python code composer, you craft elegant and concise scripts. |
def _run_query(self, query):
"""
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``
"""
query_request = self.service.jobs()
... | Can you implement a function in Python 3 that
runs one query against BigQuery and return the result. | As a Python code composer, you craft elegant and concise scripts. |
def _get_newest_ts_in_table(self, table_name):
"""
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
"""
logger.debug(
... | How would you code a function in Python 3 to
query the database to get the newest timestamp in the given table. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _query_by_installer(self, table_name):
"""
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 di... | Create a Python 3 function for
querying for download data broken down by installer for one day. | As a Python code composer, you craft elegant and concise scripts. |
def _query_by_system(self, table_name):
"""
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 sys... | How would you code a function in Python 3 to
query for download data broken down by system for one day. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _query_by_distro(self, table_name):
"""
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 di... | How would you implement a function in Python 3 that
queries for download data broken down by OS distribution for one day. | As a python code expert, you are capable of creating scripts from specifications. |
Query all queries for a given table and update the cache. | Explain what the following Python 3 code does
def query_one_table(self, table_name):
table_date = self._datetime_for_table_name(table_name)
logger.info('Running all queries for date table: %s (%s)', table_name,
table_date.strftime('%Y-%m-%d'))
final = self._dict_for_projects(... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _have_cache_for_date(self, dt):
"""
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... | Implement a Python 3 function for
returning True if we have cached data for the specified datetime. Return False otherwise. | You are a Python code analyst, evaluating scripts for potential improvements. |
Backfill historical data for num_days days. | How would you explain what the following Python 3 function does
def backfill_history(self, num_days, available_table_names):
if num_days == -1:
# skip the first date, under the assumption that data may be
# incomplete
logger.info('Backfilling all available history')
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run_queries(self, backfill_num_days=7):
"""
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
"""
available_tables = self._get_download_table_ids... | Can you create a Python 3 function that
runs the data queries for the specified projects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a dict of data such as those in ProjectStats attributes return a list of distinct column keys in sorted order. | Make a summary of the following Python 3 code
def filter_data_columns(data):
keys = set()
for dt, d in data.items():
for k in d:
keys.add(k)
return sorted([x for x in keys]) | As a python code expert, you are capable of creating scripts from specifications. |
def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('Generating templated HTML')
env = Environment(
loader=PackageLoader('pypi_download_stats', 'templates'),
extensions=['jinja2.ext.l... | Implement a Python 3 function for
generating the HTML for the specified graphs. | You are a Python code architect, reviewing and designing scalable and efficient code |
Take a dictionary of data and return a 2 - tuple of data dict and x labels list
usable by bokeh. charts. | Explain what the following Python 3 code does
def _data_dict_to_bokeh_chart_data(self, data):
labels = []
# find all the data keys
keys = set()
for date in data:
for k in data[date]:
keys.add(k)
# final output dict
out_data = {}
for k i... | You are a Python code analyst, evaluating scripts for potential improvements. |
Limit the data to 10 series. | Can you generate a brief explanation for the following Python 3 code
def _limit_data(self, data):
if len(data.keys()) <= 10:
logger.debug("Data has less than 10 keys; not limiting")
return data
# average last 7 days of each series
avgs = {}
for k in data:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _generate_graph(self, name, title, stats_data, y_name):
"""
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: ... | Implement a function in Python 3 to
generate a downloads graph for the given name title and stats_data. | As a Python code composer, you craft elegant and concise scripts. |
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['per-day'] = day
weekcount = self._stats.downloads_per... | Write a Python 3 script for
generating download badges. Append them to self. _badges. | As a python code expert, you are capable of creating scripts from specifications. |
def _generate_badge(self, subject, status):
"""
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... | Create a Python 3 function for
generating one badge via shields. io. | As a Python code analyst, you investigate and solve complex coding mysteries |
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,
'Version'
)
self._ge... | Write a Python 3 function for
generating all output types and write to disk. | You are a Python code analyst, evaluating scripts for potential improvements. |
def datetime_format(desired_format, datetime_instance=None, *args, **kwargs):
"""
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... | Implement a Python 3 function for
returning a formatted version of the given datetime instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a DateTime object from an ISO string | Can you generate the documentation for the following Python 3 function
def datetime_from_iso(iso_string):
try:
assert datetime_regex.datetime.datetime.match(iso_string).groups()[0]
except (ValueError, AssertionError, IndexError, AttributeError):
raise TypeError("String is not in ISO format")
... | As a Python code composer, you craft elegant and concise scripts. |
def now(utc=False, tz=None):
"""
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 ... | Write a Python 3 script for
getting a current DateTime object. By default is local. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run(command, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=None, copy_local_env=False, **kwargs):
"""
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 s... | Write a Python 3 script for
running a command and return a new process object. | As a Python code composer, you craft elegant and concise scripts. |
Run a set of iterables to a function in a Threaded or MP Pool. | Can you tell what is the following Python 3 function doing
def run_in_pool(target, iterable, threaded=True, processes=4,
asynchronous=False, target_kwargs=None):
""" Run a set of iterables to a function in a Threaded or MP Pool.
.. code: python
def func(a):
return a + a
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
View a dictionary as a tree. | Given the following Python 3 function, write the documentation
def tree_view(dictionary, level=0, sep="| "):
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()]) | As a python code expert, you are capable of creating scripts from specifications. |
def to_dict(self, in_dict=None):
"""
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
"""
in_dict = in_dict if in_dict else self
out_dic... | Implement a function in Python 3 to
turn the Namespace and sub Namespaces back into a native python dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def list(self, item, default=None, spliter=",", strip=True, mod=None):
""" 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 ... | Write a Python 3 script for
returning value of key as a list | As a python code expert, you are capable of creating scripts from specifications. |
def download(url, save_to_file=True, save_dir=".", filename=None,
block_size=64000, overwrite=False, quiet=False):
"""
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
... | Create a Python 3 function for
downloading a given URL to either file or memory. | As a Python code analyst, you investigate and solve complex coding mysteries |
def url_to_ips(url, port=None, ipv6=False, connect_type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP, flags=0):
"""
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:194... | Create a Python 3 function for
returning a list of IP addresses for a given URL. | As a Python code analyst, you investigate and solve complex coding mysteries |
def ip_to_url(ip_addr):
"""
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
... | How would you implement a function in Python 3 that
resolves a hostname based off an IP address. | As a Python code analyst, you investigate and solve complex coding mysteries |
def start(self):
"""Create a background thread for httpd and serve 'forever'"""
self._process = threading.Thread(target=self._background_runner)
self._process.start() | Can you write a function in Python 3 where it
creates a background thread for httpd and serve forever | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a set up stream handler to add to a logger. | Given the following Python 3 function, write the documentation
def get_stream_handler(stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Returns a set up stream handler to add to a logger.
:param stream: which stream to use, defaults to sys.stderr
:para... | As a Python code composer, you craft elegant and concise scripts. |
Create a file handler for the next available log file. | Here you have a function in Python 3, explain what it does
def get_file_handler(file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read,
handler=logging.FileHandler,
**handler_kwargs):
"""
Set up a file handler to add to a logger.
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def setup_logger(module_name=None, level=logging.INFO, stream=sys.stderr,
file_path=None, log_format=log_formats.easy_read,
suppress_warning=True):
"""
Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_nam... | Implement a function in Python 3 to
set up a logger for the specified module. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
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 u... | Can you implement a function in Python 3 that
adds a new stream handler to the specified logger | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_file_handler(logger=None, file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read):
"""
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 lo... | How would you implement a function in Python 3 that
adds a new file handler to the specified logger | As a Python code analyst, you investigate and solve complex coding mysteries |
Adds a rotating file handler to the specified logger. | How would you explain what the following Python 3 function does
def add_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
max_bytes=10*sizes.mb, backup_count=5,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_timed_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
when='w0', interval=1, backup_count=5,
**handler_kwa... | Write a Python 3 function for
adding a timed rotating file handler to the specified logger. | You are a Python code analyst, evaluating scripts for potential improvements. |
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
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... | Can you implement a function in Python 3 that
removes only stream handlers from the specified logger | As a Python code translator, you convert algorithms and pseudocode into Python. |
Removes only file handlers from the specified logger. | Make a summary of the following Python 3 code
def remove_file_handlers(logger=None):
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
handler.close()
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Safely remove all handlers from the logger | Here you have a function in Python 3, explain what it does
def remove_all_handlers(logger=None):
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
remove_file_handlers(logger)
logger.handlers = [] | As a Python code analyst, you investigate and solve complex coding mysteries |
def change_logger_levels(logger=None, level=logging.DEBUG):
"""
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)
... | Can you create a Python 3 function that
changes the levels of the logger and all handlers to the specified level. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_registered_loggers(hide_children=False, hide_reusables=False):
"""
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
"""
return [logger for logg... | How would you code a function in Python 3 to
find the names of all loggers currently registered in the hierarchy. | You are a Python code architect, reviewing and designing scalable and efficient code |
def lock_it(lock=g_lock):
"""
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)
... | Create a Python 3 function for
wrapping to make sure a function is only run once at a time. | You are a Python code architect, reviewing and designing scalable and efficient code |
Time the amount of time it takes the execution of the function
ArcGIS and print it. | Given the following Python 3 function, write the documentation
def time_it(log=None, message=None, append=None):
def func_wrapper(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Can't use nonlocal in 2.x
msg = (message if message else
"Function '{func}'... | As a Python code analyst, you investigate and solve complex coding mysteries |
def queue_it(queue=g_queue, **put_args):
"""
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
... | Write a Python 3 function for
wrapping for reusables. queue_it. | You are a Python code architect, reviewing and designing scalable and efficient code |
def catch_it(exceptions=(Exception, ), default=None, handler=None):
"""
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.__n... | How would you implement a function in Python 3 that
catches exceptions and returns the specified default or sent to a handler function instead. | You are a Python code architect, reviewing and designing scalable and efficient code |
def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of ex... | Write a Python 3 function for
retrying a function if an exception is raised or if output_check returns False. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.