output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Parse the connection name into a tuple of the name read and write types. | Can you tell what is the following Python 3 function doing
def _parse_connection_name(self, name):
if name is None:
name = self.get_default_connection()
if name.endswith(('::read', '::write')):
return name.split('::', 1)
return name, None | You are a Python code analyst, evaluating scripts for potential improvements. |
Disconnect from the given database and remove from local cache. | Can you generate a brief explanation for the following Python 3 code
def purge(self, name=None):
self.disconnect(name)
if name in self._connections:
del self._connections[name] | You are a Python code analyst, evaluating scripts for potential improvements. |
Runs a callback with constraints disabled on the relation. | Here you have a function in Python 3, explain what it does
def no_constraints(cls, callback):
cls._constraints = False
results = callback()
cls._constraints = True
return results | As a python code expert, you are capable of creating scripts from specifications. |
def get_keys(self, models, key=None):
"""
Get all the primary keys for an array of models.
:type models: list
:type key: str
:rtype: list
"""
return list(set(map(lambda value: value.get_attribute(key) if key else value.get_key(), models))) | Implement a function in Python 3 to
get all the primary keys for an array of models. | As a python code expert, you are capable of creating scripts from specifications. |
Add constraints on the relation query. | Make a summary of the following Python 3 code
def add_constraints(self):
parent_table = self._parent.get_table()
self._set_join()
if self._constraints:
self._query.where('%s.%s' % (parent_table, self._first_key), '=', self._far_parent.get_key()) | You are a Python code analyst, evaluating scripts for potential improvements. |
Add the constraints for a relationship count query. | Make a summary of the following Python 3 code
def get_relation_count_query(self, query, parent):
parent_table = self._parent.get_table()
self._set_join(query)
query.select(QueryExpression('COUNT(*)'))
key = self.wrap('%s.%s' % (parent_table, self._first_key))
return query.whe... | As a Python code composer, you craft elegant and concise scripts. |
def _set_join(self, query=None):
"""
Set the join clause for the query.
"""
if not query:
query = self._query
foreign_key = '%s.%s' % (self._related.get_table(), self._second_key)
query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '='... | Write a Python 3 function for
setting the join clause for the query. | As a Python code composer, you craft elegant and concise scripts. |
def plot_best_worst_fits(assignments_df, data, modality_col='Modality',
score='$\log_2 K$'):
"""Violinplots of the highest and lowest scoring of each modality"""
ncols = 2
nrows = len(assignments_df.groupby(modality_col).groups.keys())
fig, axes = plt.subplots(nrows=nrows, ncol... | Write a Python 3 function that can
plot the highest and lowest scoring of each modality. | You are a Python code analyst, evaluating scripts for potential improvements. |
def violinplot(x=None, y=None, data=None, bw=0.2, scale='width',
inner=None, ax=None, **kwargs):
"""Wrapper around Seaborn's Violinplot specifically for [0, 1] ranged data
What's different:
- bw = 0.2: Sets bandwidth to be small and the same between datasets
- scale = 'width': Sets the w... | How would you implement a function in Python 3 that
wraps around Seaborn s Violinplot specifically for [ 0 1 ) ranged data | As a Python code translator, you convert algorithms and pseudocode into Python. |
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True):
"""Draw barplots grouped by modality of modality percentage per group
Parameters
----------
Returns
-------
Raises
------
"""
if percentages:
counts = 100 ... | Write a Python 3 script for
drawing a barplot grouped by modality of modality percentage per group. | As a Python code composer, you craft elegant and concise scripts. |
def event_estimation(self, event, logliks, logsumexps, renamed=''):
"""Show the values underlying bayesian modality estimations of an event
Parameters
----------
Returns
-------
Raises
------
"""
plotter = _ModelLoglikPlotter()
plotter... | Can you create a Python 3 function that
shows the values underlying bayesian modality estimations of an event | As a python code expert, you are capable of creating scripts from specifications. |
Assign the most likely modality given the fitted data. | Here you have a function in Python 3, explain what it does
def predict(self, fitted):
if fitted.shape[0] != len(self.modalities):
raise ValueError("This data doesn't look like it had the distance "
"between it and the five modalities calculated")
return fitted.id... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculate the log - likelihood of a feature x for each model. | Make a summary of the following Python 3 code
def logliks(self, x):
x = x.copy()
# Replace exactly 0 and exactly 1 values with a very small number
# (machine epsilon, the smallest number that this computer is capable
# of storing) because 0 and 1 are not in the Beta distribution.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def nice_number_string(number, decimal_places=2):
"""Convert floats to either integers or a nice looking fraction"""
if number == np.round(number):
return str(int(number))
elif number < 1 and number > 0:
inverse = 1 / number
if int(inverse) == np.round(inverse... | How would you code a function in Python 3 to
convert floats to integers or a nice looking fraction | You are a Python code analyst, evaluating scripts for potential improvements. |
Plot violins of each distribution in the model family. | Can you tell what is the following Python 3 function doing
def violinplot(self, n=1000, **kwargs):
kwargs.setdefault('palette', 'Purples')
dfs = []
for rv in self.rvs:
psi = rv.rvs(n)
df = pd.Series(psi, name=self.ylabel).to_frame()
alpha, beta = rv.args
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get log - likelihood of models at each parameterization for a single feature. | Can you generate the documentation for the following Python 3 function
def _single_feature_logliks_one_step(self, feature, models):
x_non_na = feature[~feature.isnull()]
if x_non_na.empty:
return pd.DataFrame()
else:
dfs = []
for name, model in models.items():... | You are a Python code architect, reviewing and designing scalable and efficient code |
def fit(self, data):
"""Get the modality assignments of each splicing event in the data
Parameters
----------
data : pandas.DataFrame
A (n_samples, n_events) dataframe of splicing events' PSI scores.
Must be psi scores which range from 0 to 1
Returns
... | How would you implement a function in Python 3 that
fits the log2 bayes factor for each modality assignment in the data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def predict(self, log2_bayes_factors, reset_index=False):
"""Guess the most likely modality for each event
For each event that has at least one non-NA value, if no modalilites
have logsumexp'd logliks greater than the log Bayes factor threshold,
then they are assigned the 'multimodal' m... | Can you implement a function in Python 3 that
predicts the most likely modality for each event. | As a Python code analyst, you investigate and solve complex coding mysteries |
def single_feature_logliks(self, feature):
"""Calculate log-likelihoods of each modality's parameterization
Used for plotting the estimates of a single feature
Parameters
----------
featre : pandas.Series
A single feature's values. All values must range from 0 to 1.... | Can you write a function in Python 3 where it
calculates log - likelihoods of each modality s parameterization for each single feature. | You are a Python code generator, capable of creating scripts from specifications. |
def single_feature_fit(self, feature):
"""Get the log2 bayes factor of the fit for each modality"""
if np.isfinite(feature).sum() == 0:
series = pd.Series(index=MODALITY_ORDER)
else:
logbf_one_param = pd.Series(
{k: v.logsumexp_logliks(feature) for
... | Write a Python 3 function that can
get the log2 bayes factor of the fit for each modality | As a Python code composer, you craft elegant and concise scripts. |
Given a list of bins make a list of strings of those bin ranges | Can you generate a brief explanation for the following Python 3 code
def bin_range_strings(bins, fmt=':g'):
return [('{' + fmt + '}-{' + fmt + '}').format(i, j)
for i, j in zip(bins, bins[1:])] | As a Python code analyst, you investigate and solve complex coding mysteries |
def binify(data, bins):
"""Makes a histogram of each column the provided binsize
Parameters
----------
data : pandas.DataFrame
A samples x features dataframe. Each feature (column) will be binned
into the provided bins
bins : iterable
Bins you would like to use for this data... | Can you implement a function in Python 3 that
makes a histogram of each column into a set of binsize | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the Kullback - Leiber divergence of two probability distributions pandas
dataframes p and q. | Make a summary of the following Python 3 code
def kld(p, q):
try:
_check_prob_dist(p)
_check_prob_dist(q)
except ValueError:
return np.nan
# If one of them is zero, then the other should be considered to be 0.
# In this problem formulation, log0 = 0
p = p.replace(0, np.nan)
... | As a Python code composer, you craft elegant and concise scripts. |
def jsd(p, q):
"""Finds the per-column JSD between dataframes p and q
Jensen-Shannon divergence of two probability distrubutions pandas
dataframes, p and q. These distributions are usually created by running
binify() on the dataframe.
Parameters
----------
p : pandas.DataFrame
An n... | Can you implement a function in Python 3 that
calculates the Jensen - Shannon divergence between two probability distributions pandasDataFrame p and q. | You are a Python code architect, reviewing and designing scalable and efficient code |
Find the entropy of each column of a dataframe. | Make a summary of the following Python 3 code
def entropy(binned, base=2):
try:
_check_prob_dist(binned)
except ValueError:
np.nan
return -((np.log(binned) / np.log(base)) * binned).sum(axis=0) | You are a Python code analyst, evaluating scripts for potential improvements. |
Binify and calculate jensen - shannon divergence between two dataframes. | Explain what the following Python 3 code does
def binify_and_jsd(df1, df2, bins, pair=None):
binned1 = binify(df1, bins=bins).dropna(how='all', axis=1)
binned2 = binify(df2, bins=bins).dropna(how='all', axis=1)
binned1, binned2 = binned1.align(binned2, axis=1, join='inner')
series = np.sqrt(jsd(binned... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def jsd_df_to_2d(jsd_df):
"""Transform a tall JSD dataframe to a square matrix of mean JSDs
Parameters
----------
jsd_df : pandas.DataFrame
A (n_features, n_phenotypes^2) dataframe of the JSD between each
feature between and within phenotypes
Returns
-------
jsd_2d : pandas... | Write a Python 3 script to
transform a tall JSD dataframe to a square matrix of mean JSDs | As a python code expert, you are capable of creating scripts from specifications. |
def run(self, callback=None, limit=0):
"""
Start pcap's loop over the interface, calling the given callback for each packet
:param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted
:param limit: how many packets to capture (A value of -1 or 0 ... | Create a Python 3 function for
starting the loop over the interface calling the given callback for each packet intercepted . | As a Python code analyst, you investigate and solve complex coding mysteries |
def send(self, packet_buffer):
"""
send a buffer as a packet to the network interface
:param packet_buffer: buffer to send (length shouldn't exceed MAX_INT)
"""
if self._handle is None:
raise self.DeviceIsNotOpen()
buffer_length = len(packet_buffer)
bu... | Write a Python 3 function that can
send a packet to the network interface. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def capture_on(pattern, callback):
"""
:param pattern: a wildcard pattern to match the description of a network interface to capture packets on
:param callback: a function to call with each intercepted packet
"""
device_name, desc = WinPcapDevices.get_matching_device(pattern)
... | Can you implement a function in Python 3 that
captures packets on a specific network interface. | As a Python code analyst, you investigate and solve complex coding mysteries |
def capture_on_device_name(device_name, callback):
"""
:param device_name: the name (guid) of a device as provided by WinPcapDevices.list_devices()
:param callback: a function to call with each intercepted packet
"""
with WinPcap(device_name) as capture:
capture.run(c... | How would you implement a function in Python 3 that
captures on a device name. | As a Python code composer, you craft elegant and concise scripts. |
def send_packet(self, pattern, packet_buffer, callback=None, limit=10):
"""
Send a buffer as a packet to a network interface and optionally capture a response
:param pattern: a wildcard pattern to match the description of a network interface to capture packets on
:param packet_buffer: a ... | Create a Python 3 function for
sending a packet to a network interface and optionally capture a response on the next request. | As a python code expert, you are capable of creating scripts from specifications. |
def get_next_value(
sequence_name='default', initial_value=1, reset_value=None,
*, nowait=False, using=None):
"""
Return the next value for a given sequence.
"""
# Inner import because models cannot be imported before their application.
from .models import Sequence
if reset_val... | Can you create a Python 3 function that
gets the next value for a given sequence. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check the status of all provided data and update the suite. | Can you generate the documentation for the following Python 3 function
def check(self, final_line_count):
if self._lines_seen["version"]:
self._process_version_lines()
self._process_plan_lines(final_line_count) | You are a Python code architect, reviewing and designing scalable and efficient code |
Process version line rules. | Can you generate a brief explanation for the following Python 3 code
def _process_version_lines(self):
if len(self._lines_seen["version"]) > 1:
self._add_error(_("Multiple version lines appeared."))
elif self._lines_seen["version"][0] != 1:
self._add_error(_("The version must be ... | As a python code expert, you are capable of creating scripts from specifications. |
def _process_plan_lines(self, final_line_count):
"""Process plan line rules."""
if not self._lines_seen["plan"]:
self._add_error(_("Missing a plan."))
return
if len(self._lines_seen["plan"]) > 1:
self._add_error(_("Only one plan line is permitted per file."))... | Write a Python 3 function for
processing plan line rules. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _plan_on_valid_line(self, at_line, final_line_count):
"""Check if a plan is on a valid line."""
# Put the common cases first.
if at_line == 1 or at_line == final_line_count:
return True
# The plan may only appear on line 2 if the version is at line 1.
after_versi... | Create a Python 3 function to
check if a plan is on a valid line. | As a python code expert, you are capable of creating scripts from specifications. |
def handle_bail(self, bail):
"""Handle a bail line."""
self._add_error(_("Bailed: {reason}").format(reason=bail.reason)) | Write a Python 3 function that can
handle a bail line. | As a python code expert, you are capable of creating scripts from specifications. |
def handle_skipping_plan(self, skip_plan):
"""Handle a plan that contains a SKIP directive."""
skip_line = Result(True, None, skip_plan.directive.text, Directive("SKIP"))
self._suite.addTest(Adapter(self._filename, skip_line)) | Can you write a function in Python 3 where it
handles a SKIP plan that contains a SKIP directive. | As a Python code composer, you craft elegant and concise scripts. |
def _add_error(self, message):
"""Add an error test to the suite."""
error_line = Result(False, None, message, Directive(""))
self._suite.addTest(Adapter(self._filename, error_line)) | Write a Python 3 function for
adding an error test to the suite. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def format_exception(exception):
"""Format an exception as diagnostics output.
exception is the tuple as expected from sys.exc_info.
"""
exception_lines = traceback.format_exception(*exception)
# The lines returned from format_exception do not strictly contain
# one line per element in the list... | Can you write a function in Python 3 where it
formats an exception as diagnostics output. | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse(self, fh):
"""Generate tap.line.Line objects, given a file-like object `fh`.
`fh` may be any object that implements both the iterator and
context management protocol (i.e. it can be used in both a
"with" statement and a "for...in" statement.)
Trailing whitespace and n... | Create a Python 3 function to
parse a file - like object fh and return a generator of tap. line. Line objects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse a line into whatever TAP category it belongs. | Here you have a function in Python 3, explain what it does
def parse_line(self, text, fh=None):
match = self.ok.match(text)
if match:
return self._parse_result(True, match, fh)
match = self.not_ok.match(text)
if match:
return self._parse_result(False, match, fh)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse a matching plan line. | Here you have a function in Python 3, explain what it does
def _parse_plan(self, match):
expected_tests = int(match.group("expected"))
directive = Directive(match.group("directive"))
# Only SKIP directives are allowed in the plan.
if directive.text and not directive.skip:
re... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _parse_result(self, ok, match, fh=None):
"""Parse a matching result line into a result instance."""
peek_match = None
try:
if fh is not None and self._try_peeking:
peek_match = self.yaml_block_start.match(fh.peek())
except StopIteration:
pass
... | Can you write a function in Python 3 where it
parses a matching result line into a result instance. | As a python code expert, you are capable of creating scripts from specifications. |
Extract a raw yaml block from a file handler | Can you tell what is the following Python 3 function doing
def _extract_yaml_block(self, indent, fh):
raw_yaml = []
indent_match = re.compile(r"^{}".format(indent))
try:
fh.next()
while indent_match.match(fh.peek()):
raw_yaml.append(fh.next().replace(inden... | As a python code expert, you are capable of creating scripts from specifications. |
Lazy load a yaml_block. | Given the following Python 3 function, write the documentation
def yaml_block(self):
if LOAD_YAML and self._yaml_block is not None:
try:
yaml_dict = yaml.load(self._yaml_block)
return yaml_dict
except yaml.error.YAMLError:
print("Error pars... | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(self, files):
"""Load any files found into a suite.
Any directories are walked and their files are added as TAP files.
:returns: A ``unittest.TestSuite`` instance
"""
suite = unittest.TestSuite()
for filepath in files:
if os.path.isdir(filepath):
... | Implement a function in Python 3 to
load any files found into a test suite. | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_suite_from_file(self, filename):
"""Load a test suite with test lines from the provided TAP file.
:returns: A ``unittest.TestSuite`` instance
"""
suite = unittest.TestSuite()
rules = Rules(filename, suite)
if not os.path.exists(filename):
rules.hand... | Implement a function in Python 3 to
load a test suite with test lines from the provided TAP file. | You are a Python code generator, capable of creating scripts from specifications. |
def load_suite_from_stdin(self):
"""Load a test suite with test lines from the TAP stream on STDIN.
:returns: A ``unittest.TestSuite`` instance
"""
suite = unittest.TestSuite()
rules = Rules("stream", suite)
line_generator = self._parser.parse_stdin()
return self... | How would you code a function in Python 3 to
load a test suite with test lines from the TAP stream on STDIN. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load a suite with lines produced by the line generator. | Can you tell what is the following Python 3 function doing
def _load_lines(self, filename, line_generator, suite, rules):
line_counter = 0
for line in line_generator:
line_counter += 1
if line.category in self.ignored_lines:
continue
if line.category... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _track(self, class_name):
"""Keep track of which test cases have executed."""
if self._test_cases.get(class_name) is None:
if self.streaming and self.header:
self._write_test_case_header(class_name, self.stream)
self._test_cases[class_name] = []
i... | Write a Python 3 function for
keeping track of which test cases have executed. | You are a Python code analyst, evaluating scripts for potential improvements. |
Notify the tracker how many total tests there will be. | Explain what the following Python 3 code does
def set_plan(self, total):
self.plan = total
if self.streaming:
# This will only write the plan if we haven't written it
# already but we want to check if we already wrote a
# test out (in which case we can't just write th... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate TAP reports.
The results are either combined into a single output file or
the output file name is generated from the test case. | Given the following Python 3 function, write the documentation
def generate_tap_reports(self):
# We're streaming but set_plan wasn't called, so we can only
# know the plan now (at the end).
if self.streaming and not self._plan_written:
print("1..{0}".format(self.combined_line_number)... | As a python code expert, you are capable of creating scripts from specifications. |
def _write_plan(self, stream):
"""Write the plan line to the stream.
If we have a plan and have not yet written it out, write it to
the given stream.
"""
if self.plan is not None:
if not self._plan_written:
print("1..{0}".format(self.plan), file=strea... | How would you implement a function in Python 3 that
writes the plan line to the given stream. | As a python code expert, you are capable of creating scripts from specifications. |
Get the TAP output file path for the test case. | Can you tell what is the following Python 3 function doing
def _get_tap_file_path(self, test_case):
sanitized_test_case = test_case.translate(self._sanitized_table)
tap_file = sanitized_test_case + ".tap"
if self.outdir:
return os.path.join(self.outdir, tap_file)
return tap_f... | You are a Python code generator, capable of creating scripts from specifications. |
Entry point for tappy command. | Here you have a function in Python 3, explain what it does
def main(argv=sys.argv, stream=sys.stderr):
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result) | As a Python code analyst, you investigate and solve complex coding mysteries |
Build a test suite by loading TAP files or a TAP stream. | Make a summary of the following Python 3 code
def build_suite(args):
loader = Loader()
if len(args.files) == 0 or args.files[0] == "-":
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite | As a python code expert, you are capable of creating scripts from specifications. |
def addFailure(self, result):
"""Add a failure to the result."""
result.addFailure(self, (Exception, Exception(), None))
# Since TAP will not provide assertion data, clean up the assertion
# section so it is not so spaced out.
test, err = result.failures[-1]
result.failur... | Implement a Python 3 function for
adding a failure to the result. | You are a Python code generator, capable of creating scripts from specifications. |
def mptt_before_insert(mapper, connection, instance):
""" Based on example
https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master
"""
table = _get_tree_table(mapper)
db_pk = instance.get_pk_column()
table_pk = getattr(table.c, db_pk.name)
if i... | Can you write a function in Python 3 where it
bases on example https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master | As a python code expert, you are capable of creating scripts from specifications. |
This function is used to move a node in nested set to the new tree. | How would you explain what the following Python 3 function does
def mptt_before_update(mapper, connection, instance):
node_id = getattr(instance, instance.get_pk_name())
table = _get_tree_table(mapper)
db_pk = instance.get_pk_column()
default_level = instance.get_default_level()
table_pk = getattr(t... | As a Python code analyst, you investigate and solve complex coding mysteries |
def after_flush_postexec(self, session, context):
"""
Event listener to recursively expire `left` and `right` attributes the
parents of all modified instances part of this flush.
"""
instances = self.instances[session]
while instances:
instance = instances.pop... | Write a Python 3 function for
calling by the flush event listener to recursively expire left and right attributes of all modified instances in the specified session. | As a Python code composer, you craft elegant and concise scripts. |
class or instance level method which returns True if self is an ancestor of other else False. | How would you explain what the following Python 3 function does
def is_ancestor_of(self, other, inclusive=False):
if inclusive:
return (self.tree_id == other.tree_id) \
& (self.left <= other.left) \
& (other.right <= self.right)
return (self.tree_id == other.t... | As a Python code composer, you craft elegant and concise scripts. |
Moving one node of tree inside another node | How would you explain what the following Python 3 function does
def move_inside(self, parent_id):
session = Session.object_session(self)
self.parent_id = parent_id
self.mptt_move_inside = parent_id
session.add(self) | You are a Python code architect, reviewing and designing scalable and efficient code |
def move_after(self, node_id):
""" Moving one node of tree after another
For example see :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_after_function`
""" # noqa
session = Session.object_session(self)
self.parent_id = self.parent_id
self.mptt_move_after = node_i... | Write a Python 3 function that can
move one node of tree after another node | As a Python code analyst, you investigate and solve complex coding mysteries |
Moving one node of tree before another node | Make a summary of the following Python 3 code
def move_before(self, node_id):
session = Session.object_session(self)
table = _get_tree_table(self.__mapper__)
pk = getattr(table.c, self.get_pk_column().name)
node = session.query(table).filter(pk == node_id).one()
self.parent_id = ... | As a Python code analyst, you investigate and solve complex coding mysteries |
This method generates a branch from a tree. | Can you tell what is the following Python 3 function doing
def drilldown_tree(self, session=None, json=False, json_fields=None):
if not session:
session = object_session(self)
return self.get_tree(
session,
json=json,
json_fields=json_fields,
q... | You are a Python code generator, capable of creating scripts from specifications. |
Generate a path from a leaf or intermediate node to the root. | Can you tell what is the following Python 3 function doing
def path_to_root(self, session=None, order=desc):
table = self.__class__
query = self._base_query_obj(session=session)
query = query.filter(table.is_ancestor_of(self, inclusive=True))
return self._base_order(query, order=order) | You are a Python code generator, capable of creating scripts from specifications. |
This method rebuid tree. | How would you explain what the following Python 3 function does
def rebuild_tree(cls, session, tree_id):
session.query(cls).filter_by(tree_id=tree_id)\
.update({cls.left: 0, cls.right: 0, cls.level: 0})
top = session.query(cls).filter_by(parent_id=None)\
.filter_by(tree_id=tree_i... | You are a Python code architect, reviewing and designing scalable and efficient code |
def rebuild(cls, session, tree_id=None):
""" This function rebuid tree.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session
Kwargs:
tree_id (int or str): id of tree, default None
Example:
* :mod:`sqlalchemy_mptt.tests.TestTree.tes... | Write a Python 3 function for
rebuilding the tree of the related objects. | As a Python code composer, you craft elegant and concise scripts. |
def qx(mt, x):
""" qx: Returns the probability that a life aged x dies before 1 year
With the convention: the true probability is qx/1000
Args:
mt: the mortality table
x: the age as integer number.
"""
if x < len(mt.qx):
return mt.qx[x]
else:
return 0 | Write a Python 3 script to
return the probability that a life aged x dies before 1 year Returns 0 if the age is not in the mortality table qx | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the number of survivors at begining of age x | Given the following Python 3 function, write the documentation
def lx(mt, x):
if x < len(mt.lx):
return mt.lx[x]
else:
return 0 | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the number of dying at begining of age x | Can you generate a brief explanation for the following Python 3 code
def dx(mt, x):
end_x_val = mt.lx.index(0)
if x < end_x_val:
return mt.lx[x] - mt.lx[x + 1]
else:
return 0.0 | As a Python code analyst, you investigate and solve complex coding mysteries |
def tpx(mt, x, t):
""" tpx : Returns the probability that x will survive within t years """
""" npx : Returns n years survival probability at age x """
return mt.lx[x + t] / mt.lx[x] | Can you write a function in Python 3 where it
returns the probability that x will survive within t years | As a Python code translator, you convert algorithms and pseudocode into Python. |
ex - Returns the curtate expectation of life. Life expectancy | Can you generate a brief explanation for the following Python 3 code
def ex(mt, x):
sum1 = 0
for j in mt.lx[x + 1:-1]:
sum1 += j
#print sum1
try:
return sum1 / mt.lx[x] + 0.5
except:
return 0 | You are a Python code architect, reviewing and designing scalable and efficient code |
def Sx(mt, x):
""" Return the Sx """
n = len(mt.Nx)
sum1 = 0
for j in range(x, n):
k = mt.Nx[j]
sum1 += k
return sum1 | Can you create a Python 3 function that
returns the Sx of the given MT | As a Python code analyst, you investigate and solve complex coding mysteries |
def Cx(mt, x):
""" Return the Cx """
return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5) | Can you create a Python 3 function that
returns the Cx of the given mt | You are a Python code generator, capable of creating scripts from specifications. |
def Mx(mt, x):
""" Return the Mx """
n = len(mt.Cx)
sum1 = 0
for j in range(x, n):
k = mt.Cx[j]
sum1 += k
return sum1 | Write a Python 3 script to
return the Mx of the given MT | As a python code expert, you are capable of creating scripts from specifications. |
(A^1)x:n : Returns the EPV (net single premium) of a term insurance. | Can you generate the documentation for the following Python 3 function
def Axn(mt, x, n):
return (mt.Mx[x] - mt.Mx[x + n]) / mt.Dx[x] | You are a Python code generator, capable of creating scripts from specifications. |
Returns the EPV of a term insurance. | How would you explain what the following Python 3 function does
def AExn(mt, x, n):
return (mt.Mx[x] - mt.Mx[x + n]) / mt.Dx[x] + mt.Dx[x + n] / mt.Dx[x] | As a Python code translator, you convert algorithms and pseudocode into Python. |
n/Ax : Returns the EPV (net single premium) of a deferred whole life insurance. | Make a summary of the following Python 3 code
def tAx(mt, x, t):
return mt.Mx[x + t] / mt.Dx[x] | You are a Python code analyst, evaluating scripts for potential improvements. |
def aaxn(mt, x, n, m=1):
""" äxn : Return the actuarial present value of a (immediate) temporal (term certain) annuity:
n-year temporary life annuity-anticipatory. Payable 'm' per year at the beginning of the period
"""
if m == 1:
return (mt.Nx[x] - mt.Nx[x + n]) / mt.Dx[x]
else:
r... | How would you implement a function in Python 3 that
returns the actuarial present value of a temporal annuity | As a Python code translator, you convert algorithms and pseudocode into Python. |
äx : Returns the actuarial present value of an annuity of 1 per time period
| Can you generate the documentation for the following Python 3 function
def aax(mt, x, m=1):
return mt.Nx[x] / mt.Dx[x] - (float(m - 1) / float(m * 2)) | As a Python code composer, you craft elegant and concise scripts. |
def ax(mt, x, m=1):
""" ax : Returns the actuarial present value of an (immediate) annuity of 1 per time period
(whole life annuity-late). Payable 'm' per year at the ends of the period
"""
return (mt.Nx[x] / mt.Dx[x] - 1) + (float(m - 1) / float(m * 2)) | Can you write a function in Python 3 where it
returns the actuarial present value of an annuity of 1 per time period | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the actuarial present value of a deferred annuity at a given time. | Make a summary of the following Python 3 code
def taax(mt, x, t, m=1):
return mt.Nx[x + t] / mt.Dx[x] - ((float(m - 1) / float(m * 2)) * (1 - nEx(mt, x, t))) | As a Python code analyst, you investigate and solve complex coding mysteries |
during a term certain, IAn | Can you generate a brief explanation for the following Python 3 code
def Iaaxn(mt, x, n, *args):
return (Sx(mt, x) - Sx(nt, x + n) - n * Nx(nt, x + n)) / Dx(nt, x) | You are a Python code analyst, evaluating scripts for potential improvements. |
during a term certain, IAn | Can you generate a brief explanation for the following Python 3 code
def Iaxn(mt, x, n, *args):
return (Sx(mt, x + 1) - Sx(mt, x + n + 1) - n * Nx(mt, x + n + 1)) / Dx(mt, x) | As a Python code composer, you craft elegant and concise scripts. |
Itaax of a given time. | Can you tell what is the following Python 3 function doing
def Itaax(mt, x, t):
return (Sx(mt, x) - Sx(mt, x + t)) / Dx(mt, x) | As a Python code composer, you craft elegant and concise scripts. |
find new position of vertex v according to adjacency in prevlayer and return the mean value of adjacent positions. | Can you generate a brief explanation for the following Python 3 code
def _meanvalueattr(self,v):
sug = self.layout
if not self.prevlayer(): return sug.grx[v].bar
bars = [sug.grx[x].bar for x in self._neighbors(v)]
return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars) | As a Python code analyst, you investigate and solve complex coding mysteries |
def _medianindex(self,v):
"""
find new position of vertex v according to adjacency in layer l+dir.
position is given by the median value of adjacent positions.
median heuristic is proven to achieve at most 3 times the minimum
of crossings (while barycenter achieve in theory the o... | Implement a Python 3 function for
finding new position of vertex v according to adjacency in layer l + dir | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _neighbors(self,v):
"""
neighbors refer to upper/lower adjacent nodes.
Note that v.N() provides neighbors of v in the graph, while
this method provides the Vertex and DummyVertex adjacent to v in the
upper or lower layer (depending on layout.dirv state).
"""
a... | Create a Python 3 function for
getting neighbors of a node in the graph | You are a Python code architect, reviewing and designing scalable and efficient code |
def _crossings(self):
"""
counts (inefficently but at least accurately) the number of
crossing edges between layer l and l+dirv.
P[i][j] counts the number of crossings from j-th edge of vertex i.
The total count of crossings is the sum of flattened P:
x = sum(sum(P,[]))
... | Implement a function in Python 3 to
count the number of crossings between two layers. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the number of inversions in the cross count of the current instance of the class. | Can you generate a brief explanation for the following Python 3 code
def _cc(self):
g=self.layout.grx
P=[]
for v in self:
P.extend(sorted([g[x].pos for x in self._neighbors(v)]))
# count inversions in P:
s = []
count = 0
for i,p in enumerate(P):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def init_all(self,roots=None,inverted_edges=None,optimize=False):
"""initializes the layout algorithm by computing roots (unless provided),
inverted edges (unless provided), vertices ranks and creates all dummy
vertices and layers.
Parameters:
ro... | Write a Python 3 function that can
initialize the layout algorithm by computing all roots and inverted edges and creates all dummy vertex and edge for long edges. | As a python code expert, you are capable of creating scripts from specifications. |
draws every node coordinates after converging to optimal ordering by N - 1. 5 rounds and performs edge routing. | Make a summary of the following Python 3 code
def draw(self,N=1.5):
while N>0.5:
for (l,mvmt) in self.ordering_step():
pass
N = N-1
if N>0:
for (l,mvmt) in self.ordering_step(oneway=True):
pass
self.setxy()
self.draw_edg... | You are a Python code generator, capable of creating scripts from specifications. |
Computes the rank of all vertices in the graph. | Can you generate a brief explanation for the following Python 3 code
def rank_all(self,roots,optimize=False):
self._edge_inverter()
r = [x for x in self.g.sV if (len(x.e_in())==0 and x not in roots)]
self._rank_init(roots+r)
if optimize: self._rank_optimize()
self._edge_inverter(... | You are a Python code generator, capable of creating scripts from specifications. |
def _rank_init(self,unranked):
"""Computes rank of provided unranked list of vertices and all
their children. A vertex will be asign a rank when all its
inward edges have been *scanned*. When a vertex is asigned
a rank, its outward edges are marked *scanned*.
"""
... | Implement a function in Python 3 to
initialize the rank of the unranked list of vertices and all . | You are a Python code analyst, evaluating scripts for potential improvements. |
def _rank_optimize(self):
"""optimize ranking by pushing long edges toward lower layers as much as possible.
see other interersting network flow solver to minimize total edge length
(http://jgaa.info/accepted/2005/EiglspergerSiebenhallerKaufmann2005.9.3.pdf)
"""
assert self.dag
... | Write a Python 3 script to
optimize ranking by pushing long edges toward lower layers as much as possible. | As a python code expert, you are capable of creating scripts from specifications. |
def setrank(self,v):
"""set rank value for vertex v and add it to the corresponding layer.
The Layer is created if it is the first vertex with this rank.
"""
assert self.dag
r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1
self.grx[v].rank=r
# add it to its la... | Write a Python 3 script for
setting rank value for vertex v and add it to the corresponding layer. | You are a Python code analyst, evaluating scripts for potential improvements. |
creates a DummyVertex at rank r inserted in the ctrl dict and adds it to the edge s control vertices and returns it | Can you tell what is the following Python 3 function doing
def dummyctrl(self,r,ctrl):
dv = DummyVertex(r)
dv.view.w,dv.view.h=self.dw,self.dh
self.grx[dv] = dv
dv.ctrl = ctrl
ctrl[r] = dv
self.layers[r].append(dv)
return dv | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.