Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
def cmd():
return putils.execute()
class FakeDemo():
<|code_end|>
, predict the next line using imports from the current file:
import os
import mock
import testtools
from tests import base
from virtman.openstack.common import processutils as putils
from virtman.utils import exception
and context including class names, function names, and sometimes code from other files:
# Path: tests/base.py
# LOG = oslo_logging.getLogger(__name__)
# class TestCase(base.BaseTestCase):
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=None, **kwargs):
# def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
# def raise_assertion(msg):
#
# Path: virtman/openstack/common/processutils.py
# LOG = logging.getLogger(__name__)
# _PIPE = subprocess.PIPE # pylint: disable=E1101
# class InvalidArgumentError(Exception):
# class UnknownArgumentError(Exception):
# class ProcessExecutionError(Exception):
# class NoRootWrapSpecified(Exception):
# def __init__(self, message=None):
# def __init__(self, message=None):
# def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
# description=None):
# def __init__(self, message=None):
# def _subprocess_setup():
# def execute(*cmd, **kwargs):
# def trycmd(*args, **kwargs):
# def ssh_execute(ssh, cmd, process_input=None,
# addl_env=None, check_exit_code=True):
#
# Path: virtman/utils/exception.py
# LOG = logging.getLogger(__name__)
# class VirtmanException(Exception):
# class CreateBaseImageFailed(VirtmanException):
# class CreateSnapshotFailed(VirtmanException):
# class TestException(VirtmanException):
# def __init__(self, message=None, **kwargs):
# def __unicode__(self):
. Output only the next line. | def show(self): |
Based on the snippet: <|code_start|>class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
def cmd():
return putils.execute()
class FakeDemo():
def show(self):
print 'FakeDemo'
class TestDemo(base.TestCase):
def setUp(self):
super(TestDemo, self).setUp()
self.fun = FunDemo()
def test_fun_add(self):
result = self.fun.add(1, 2)
self.assertEqual(3, result)
def test_fun_cmd(self):
self.mock_object(putils, 'execute',
mock.Mock(return_value=1))
result = self.fun.cmd()
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import mock
import testtools
from tests import base
from virtman.openstack.common import processutils as putils
from virtman.utils import exception
and context (classes, functions, sometimes code) from other files:
# Path: tests/base.py
# LOG = oslo_logging.getLogger(__name__)
# class TestCase(base.BaseTestCase):
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=None, **kwargs):
# def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
# def raise_assertion(msg):
#
# Path: virtman/openstack/common/processutils.py
# LOG = logging.getLogger(__name__)
# _PIPE = subprocess.PIPE # pylint: disable=E1101
# class InvalidArgumentError(Exception):
# class UnknownArgumentError(Exception):
# class ProcessExecutionError(Exception):
# class NoRootWrapSpecified(Exception):
# def __init__(self, message=None):
# def __init__(self, message=None):
# def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
# description=None):
# def __init__(self, message=None):
# def _subprocess_setup():
# def execute(*cmd, **kwargs):
# def trycmd(*args, **kwargs):
# def ssh_execute(ssh, cmd, process_input=None,
# addl_env=None, check_exit_code=True):
#
# Path: virtman/utils/exception.py
# LOG = logging.getLogger(__name__)
# class VirtmanException(Exception):
# class CreateBaseImageFailed(VirtmanException):
# class CreateSnapshotFailed(VirtmanException):
# class TestException(VirtmanException):
# def __init__(self, message=None, **kwargs):
# def __unicode__(self):
. Output only the next line. | self.assertEqual(1, result) |
Given the code snippet: <|code_start|>
class FunDemo():
def show(self):
print 'funDemo'
def add(self, a, b):
return a + b
@staticmethod
<|code_end|>
, generate the next line using the imports in this file:
import os
import mock
import testtools
from tests import base
from virtman.openstack.common import processutils as putils
from virtman.utils import exception
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# LOG = oslo_logging.getLogger(__name__)
# class TestCase(base.BaseTestCase):
# def setUp(self):
# def _common_cleanup(self):
# def log_level(self, level):
# def mock_object(self, obj, attr_name, new_attr=None, **kwargs):
# def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
# def raise_assertion(msg):
#
# Path: virtman/openstack/common/processutils.py
# LOG = logging.getLogger(__name__)
# _PIPE = subprocess.PIPE # pylint: disable=E1101
# class InvalidArgumentError(Exception):
# class UnknownArgumentError(Exception):
# class ProcessExecutionError(Exception):
# class NoRootWrapSpecified(Exception):
# def __init__(self, message=None):
# def __init__(self, message=None):
# def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
# description=None):
# def __init__(self, message=None):
# def _subprocess_setup():
# def execute(*cmd, **kwargs):
# def trycmd(*args, **kwargs):
# def ssh_execute(ssh, cmd, process_input=None,
# addl_env=None, check_exit_code=True):
#
# Path: virtman/utils/exception.py
# LOG = logging.getLogger(__name__)
# class VirtmanException(Exception):
# class CreateBaseImageFailed(VirtmanException):
# class CreateSnapshotFailed(VirtmanException):
# class TestException(VirtmanException):
# def __init__(self, message=None, **kwargs):
# def __unicode__(self):
. Output only the next line. | def cmd(): |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior",
"boxplot", "violinplot", "step"]
def get_simple_prior(prior, xlim, num=1000):
<|code_end|>
. Use current file imports:
(import numpy as np
from .corner import _quantile
from ..models.priors import TopHat as Uniform
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection)
and context including class names, function names, or small code snippets from other files:
# Path: prospect/plotting/corner.py
# def _quantile(x, q, weights=None):
# """Compute (weighted) quantiles from an input set of samples.
#
# Parameters
# ----------
# x : `~numpy.ndarray` with shape (nsamps,)
# Input samples.
#
# q : `~numpy.ndarray` with shape (nquantiles,)
# The list of quantiles to compute from `[0., 1.]`.
#
# weights : `~numpy.ndarray` with shape (nsamps,), optional
# The associated weight from each sample.
#
# Returns
# -------
# quantiles : `~numpy.ndarray` with shape (nquantiles,)
# The weighted sample quantiles computed at `q`.
#
# """
# # Initial check.
# x = np.atleast_1d(x)
# q = np.atleast_1d(q)
#
# # Quantile check.
# if np.any(q < 0.0) or np.any(q > 1.0):
# raise ValueError("Quantiles must be between 0. and 1.")
#
# if weights is None:
# # If no weights provided, this simply calls `np.percentile`.
# return np.percentile(x, list(100.0 * q))
# else:
# # If weights are provided, compute the weighted quantiles.
# weights = np.atleast_1d(weights)
# if len(x) != len(weights):
# raise ValueError("Dimension mismatch: len(weights) != len(x).")
# idx = np.argsort(x) # sort samples
# sw = weights[idx] # sort weights
# cdf = np.cumsum(sw)[:-1] # compute CDF
# cdf /= cdf[-1] # normalize CDF
# cdf = np.append(0, cdf) # ensure proper span
# quantiles = np.interp(q, cdf, x[idx]).tolist()
# return quantiles
#
# Path: prospect/models/priors.py
# class TopHat(Uniform):
# """Uniform distribution between two bounds, renamed for backwards compatibility
# :param mini:
# Minimum of the distribution
#
# :param maxi:
# Maximum of the distribution
# """
. Output only the next line. | xx = np.linspace(*xlim, num=num) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["get_best", "best_sample", "get_simple_prior", "sample_prior", "sample_posterior",
"boxplot", "violinplot", "step"]
def get_simple_prior(prior, xlim, num=1000):
xx = np.linspace(*xlim, num=num)
px = np.array([prior(x) for x in xx])
px = np.exp(px)
return xx, px / px.max()
<|code_end|>
using the current file's imports:
import numpy as np
from .corner import _quantile
from ..models.priors import TopHat as Uniform
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
and any relevant context from other files:
# Path: prospect/plotting/corner.py
# def _quantile(x, q, weights=None):
# """Compute (weighted) quantiles from an input set of samples.
#
# Parameters
# ----------
# x : `~numpy.ndarray` with shape (nsamps,)
# Input samples.
#
# q : `~numpy.ndarray` with shape (nquantiles,)
# The list of quantiles to compute from `[0., 1.]`.
#
# weights : `~numpy.ndarray` with shape (nsamps,), optional
# The associated weight from each sample.
#
# Returns
# -------
# quantiles : `~numpy.ndarray` with shape (nquantiles,)
# The weighted sample quantiles computed at `q`.
#
# """
# # Initial check.
# x = np.atleast_1d(x)
# q = np.atleast_1d(q)
#
# # Quantile check.
# if np.any(q < 0.0) or np.any(q > 1.0):
# raise ValueError("Quantiles must be between 0. and 1.")
#
# if weights is None:
# # If no weights provided, this simply calls `np.percentile`.
# return np.percentile(x, list(100.0 * q))
# else:
# # If weights are provided, compute the weighted quantiles.
# weights = np.atleast_1d(weights)
# if len(x) != len(weights):
# raise ValueError("Dimension mismatch: len(weights) != len(x).")
# idx = np.argsort(x) # sort samples
# sw = weights[idx] # sort weights
# cdf = np.cumsum(sw)[:-1] # compute CDF
# cdf /= cdf[-1] # normalize CDF
# cdf = np.append(0, cdf) # ensure proper span
# quantiles = np.interp(q, cdf, x[idx]).tolist()
# return quantiles
#
# Path: prospect/models/priors.py
# class TopHat(Uniform):
# """Uniform distribution between two bounds, renamed for backwards compatibility
# :param mini:
# Minimum of the distribution
#
# :param maxi:
# Maximum of the distribution
# """
. Output only the next line. | def sample_prior(model, nsample=1e6): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["params_to_sfh", "parametric_pset",
"parametric_cmf", "parametric_mwa", "parametric_sfr",
"compute_mass_formed",
"ratios_to_sfrs", "sfh_quantiles",
"sfh_to_cmf", "nonpar_mwa", "nonpar_recent_sfr"]
def params_to_sfh(params, time=None, agebins=None):
parametric = (time is not None)
if parametric:
taus, tages, masses = params["tau"], params["tage"], params["mass"]
sfhs = []
cmfs = []
for tau, tage, mass in zip(taus, tages, masses):
sfpar = dict(tau=tau, tage=tage, mass=mass, sfh=params["sfh"])
sfhs.append(parametric_sfr(times=time, tavg=0, **sfpar))
cmfs.append(parametric_cmf(times=time, **sfpar))
<|code_end|>
, generate the next line using the imports in this file:
from argparse import Namespace
from copy import deepcopy
from scipy.special import gamma, gammainc
from ..models.transforms import logsfr_ratios_to_masses
from ..sources.constants import cosmo
from .corner import quantile
import numpy as np
import matplotlib.pyplot as pl
and context (functions, classes, or occasionally code) from other files:
# Path: prospect/models/transforms.py
# def logsfr_ratios_to_masses(logmass=None, logsfr_ratios=None, agebins=None,
# **extras):
# """This converts from an array of log_10(SFR_j / SFR_{j+1}) and a value of
# log10(\Sum_i M_i) to values of M_i. j=0 is the most recent bin in lookback
# time.
# """
# nbins = agebins.shape[0]
# sratios = 10**np.clip(logsfr_ratios, -100, 100) # numerical issues...
# dt = (10**agebins[:, 1] - 10**agebins[:, 0])
# coeffs = np.array([ (1. / np.prod(sratios[:i])) * (np.prod(dt[1: i+1]) / np.prod(dt[: i]))
# for i in range(nbins)])
# m1 = (10**logmass) / coeffs.sum()
#
# return m1 * coeffs
#
# Path: prospect/sources/constants.py
#
# Path: prospect/plotting/corner.py
# def quantile(xarr, q, weights=None):
# """Compute (weighted) quantiles from an input set of samples.
#
# :param x: `~numpy.darray` with shape (nvar, nsamples)
# The input array to compute quantiles of.
#
# :param q: list of quantiles, from [0., 1.]
#
# :param weights: shape (nsamples)
#
# :returns quants: ndarray of shape (nvar, nq)
# The quantiles of each varaible.
# """
# qq = [_quantile(x, q, weights=weights) for x in xarr]
# return np.array(qq)
. Output only the next line. | lookback = time.max() - time |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ["params_to_sfh", "parametric_pset",
"parametric_cmf", "parametric_mwa", "parametric_sfr",
"compute_mass_formed",
"ratios_to_sfrs", "sfh_quantiles",
"sfh_to_cmf", "nonpar_mwa", "nonpar_recent_sfr"]
def params_to_sfh(params, time=None, agebins=None):
parametric = (time is not None)
if parametric:
taus, tages, masses = params["tau"], params["tage"], params["mass"]
sfhs = []
cmfs = []
for tau, tage, mass in zip(taus, tages, masses):
sfpar = dict(tau=tau, tage=tage, mass=mass, sfh=params["sfh"])
sfhs.append(parametric_sfr(times=time, tavg=0, **sfpar))
cmfs.append(parametric_cmf(times=time, **sfpar))
lookback = time.max() - time
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from argparse import Namespace
from copy import deepcopy
from scipy.special import gamma, gammainc
from ..models.transforms import logsfr_ratios_to_masses
from ..sources.constants import cosmo
from .corner import quantile
import numpy as np
import matplotlib.pyplot as pl
and context:
# Path: prospect/models/transforms.py
# def logsfr_ratios_to_masses(logmass=None, logsfr_ratios=None, agebins=None,
# **extras):
# """This converts from an array of log_10(SFR_j / SFR_{j+1}) and a value of
# log10(\Sum_i M_i) to values of M_i. j=0 is the most recent bin in lookback
# time.
# """
# nbins = agebins.shape[0]
# sratios = 10**np.clip(logsfr_ratios, -100, 100) # numerical issues...
# dt = (10**agebins[:, 1] - 10**agebins[:, 0])
# coeffs = np.array([ (1. / np.prod(sratios[:i])) * (np.prod(dt[1: i+1]) / np.prod(dt[: i]))
# for i in range(nbins)])
# m1 = (10**logmass) / coeffs.sum()
#
# return m1 * coeffs
#
# Path: prospect/sources/constants.py
#
# Path: prospect/plotting/corner.py
# def quantile(xarr, q, weights=None):
# """Compute (weighted) quantiles from an input set of samples.
#
# :param x: `~numpy.darray` with shape (nvar, nsamples)
# The input array to compute quantiles of.
#
# :param q: list of quantiles, from [0., 1.]
#
# :param weights: shape (nsamples)
#
# :returns quants: ndarray of shape (nvar, nq)
# The quantiles of each varaible.
# """
# qq = [_quantile(x, q, weights=weights) for x in xarr]
# return np.array(qq)
which might include code, classes, or functions. Output only the next line. | sfhs = np.array(sfhs) |
Continue the code snippet: <|code_start|>
try:
except(ImportError):
pass
__all__ = ["BlackBodyDustBasis"]
# cgs constants
<|code_end|>
. Use current file imports:
import numpy as np
from sedpy.observate import getSED
from .constants import lsun, pc, kboltz, hplanck
and context (classes, functions, or code) from other files:
# Path: prospect/sources/constants.py
. Output only the next line. | lightspeed = 29979245800.0 |
Given snippet: <|code_start|>
try:
except(ImportError):
pass
__all__ = ["BlackBodyDustBasis"]
# cgs constants
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from sedpy.observate import getSED
from .constants import lsun, pc, kboltz, hplanck
and context:
# Path: prospect/sources/constants.py
which might include code, classes, or functions. Output only the next line. | lightspeed = 29979245800.0 |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
except(ImportError):
pass
__all__ = ["get_best", "get_truths", "get_percentiles", "get_stats",
"posterior_samples", "hist_samples", "joint_pdf", "compute_sigma_level",
"trim_walkers", "fill_between", "figgrid"]
def get_truths(res):
try:
mock = pickle.loads(res['obs']['mock_params'])
res['obs']['mock_params'] = mock
except:
pass
try:
return res['obs']['mock_params']
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import matplotlib.pyplot as pl
import pickle
from ..plotting.utils import get_best
from matplotlib import gridspec
and context (classes, functions, sometimes code) from other files:
# Path: prospect/plotting/utils.py
# def get_best(res, **kwargs):
# """Get the maximum a posteriori parameters and their names
#
# :param res:
# A ``results`` dictionary with the keys 'lnprobability', 'chain', and
# 'theta_labels'
#
# :returns theta_names:
# List of strings giving the names of the parameters, of length ``ndim``
#
# :returns best:
# ndarray with shape ``(ndim,)`` of parameter values corresponding to the
# sample with the highest posterior probaility
# """
# theta_best = best_sample(res)
#
# try:
# theta_names = res["theta_labels"]
# except(KeyError):
# theta_names = res["model"].theta_labels()
# return theta_names, theta_best
. Output only the next line. | except(KeyError): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary around which the constellation orbits\n'
'SIZE is the number of satellites in the constellation\n'
% sys.argv[0], file=sys.stderr)
sys.exit(1)
primary = spyce.load.from_name(sys.argv[1])
# antennas from RemoteTech
antennas = [
('Reflectron DP-10', 0.5e6),
('Communotron 16', 2.5e6),
('CommTech EXP-VR-2T', 3e6),
<|code_end|>
. Use current file imports:
import sys
import spyce.load
from spyce.orbit import Orbit
from spyce.human import to_human_time, to_si_prefix
and context (classes, functions, or code) from other files:
# Path: spyce/orbit.py
# class Orbit(
# spyce.orbit_determination.OrbitDetermination,
# spyce.orbit_angles.OrbitAngles,
# spyce.orbit_state.OrbitState,
# spyce.orbit_target.OrbitTarget,
# ):
# """Kepler orbit
#
# Two-body approximation of a body orbiting a mass-point.
# """
# def __init__(
# self, primary, periapsis, eccentricity=0,
# inclination=0, longitude_of_ascending_node=0, argument_of_periapsis=0,
# epoch=0, mean_anomaly_at_epoch=0, **_
# ):
# """Orbit from the orbital elements
#
# Arguments:
# primary object with a "gravitational_parameter"
# periapsis m
# eccentricity -, optional
# inclination rad, optional
# longitude_of_ascending_node rad, optional
# argument_of_periapsis rad, optional
# epoch s, optional
# mean_anomaly_at_epoch rad, optional
# """
#
# # normalize inclination within [0, math.pi]
# # a retrograde orbit has an inclination of exactly math.pi
# inclination %= 2*math.pi
# if inclination > math.pi:
# inclination = 2*math.pi - inclination
# longitude_of_ascending_node -= math.pi
# argument_of_periapsis -= math.pi
# longitude_of_ascending_node %= 2*math.pi
# argument_of_periapsis %= 2*math.pi
#
# self.primary = primary
# self.periapsis = float(periapsis)
# self.eccentricity = float(eccentricity)
# self.inclination = float(inclination)
# self.longitude_of_ascending_node = float(longitude_of_ascending_node)
# self.argument_of_periapsis = float(argument_of_periapsis)
# self.epoch = float(epoch)
# self.mean_anomaly_at_epoch = float(mean_anomaly_at_epoch)
#
# # semi-major axis
# if self.eccentricity == 1: # parabolic trajectory
# self.semi_major_axis = math.inf
# else:
# self.semi_major_axis = self.periapsis / (1 - self.eccentricity)
#
# # other distances
# self.apoapsis = self.semi_major_axis * (1 + self.eccentricity)
# self.semi_latus_rectum = self.periapsis * (1 + self.eccentricity)
# e2 = 1-self.eccentricity**2
# self.semi_minor_axis = self.semi_major_axis * math.sqrt(abs(e2))
# self.focus = self.semi_major_axis * self.eccentricity
#
# # mean motion
# mu = self.primary.gravitational_parameter
# if self.eccentricity == 1: # parabolic trajectory
# self.mean_motion = 3 * math.sqrt(mu / self.semi_latus_rectum**3)
# else:
# self.mean_motion = math.sqrt(mu / abs(self.semi_major_axis)**3)
#
# # period
# if self.eccentricity >= 1: # parabolic/hyperbolic trajectory
# self.period = math.inf
# else: # circular/elliptic orbit
# self.period = 2*math.pi / self.mean_motion
#
# self.transform = Mat3.from_euler_angles(
# self.longitude_of_ascending_node,
# self.inclination,
# self.argument_of_periapsis,
# )
#
# def __repr__(self):
# return (
# "Orbit(%(primary)s, %(periapsis)g, %(eccentricity)g, "
# "%(inclination)g, %(longitude_of_ascending_node)g, "
# "%(argument_of_periapsis)g, %(epoch)g, %(mean_anomaly_at_epoch)g)"
# % self.__dict__
# )
#
# def darkness_time(self):
# """How long the object stays in the shadow of its primary
#
# For instance, this gives how long a satellite orbiting a planet stays
# in the dark (assuming the primary's rotation around the star is slow
# relatively to that of the satellite around its primary).
# """
#
# a = self.semi_major_axis
# b = self.semi_minor_axis
# h = math.sqrt(self.semi_latus_rectum * self.primary.gravitational_parameter)
# e = self.eccentricity
# R = self.primary.radius
# return 2*a*b/h * (math.asin(R/b) + e*R/b)
#
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
. Output only the next line. | ('Communotron 32', 5e6), |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary around which the constellation orbits\n'
'SIZE is the number of satellites in the constellation\n'
% sys.argv[0], file=sys.stderr)
sys.exit(1)
primary = spyce.load.from_name(sys.argv[1])
# antennas from RemoteTech
antennas = [
('Reflectron DP-10', 0.5e6),
('Communotron 16', 2.5e6),
('CommTech EXP-VR-2T', 3e6),
('Communotron 32', 5e6),
('Comms DTS-M1', 50e6),
<|code_end|>
, predict the next line using imports from the current file:
import sys
import spyce.load
from spyce.orbit import Orbit
from spyce.human import to_human_time, to_si_prefix
and context including class names, function names, and sometimes code from other files:
# Path: spyce/orbit.py
# class Orbit(
# spyce.orbit_determination.OrbitDetermination,
# spyce.orbit_angles.OrbitAngles,
# spyce.orbit_state.OrbitState,
# spyce.orbit_target.OrbitTarget,
# ):
# """Kepler orbit
#
# Two-body approximation of a body orbiting a mass-point.
# """
# def __init__(
# self, primary, periapsis, eccentricity=0,
# inclination=0, longitude_of_ascending_node=0, argument_of_periapsis=0,
# epoch=0, mean_anomaly_at_epoch=0, **_
# ):
# """Orbit from the orbital elements
#
# Arguments:
# primary object with a "gravitational_parameter"
# periapsis m
# eccentricity -, optional
# inclination rad, optional
# longitude_of_ascending_node rad, optional
# argument_of_periapsis rad, optional
# epoch s, optional
# mean_anomaly_at_epoch rad, optional
# """
#
# # normalize inclination within [0, math.pi]
# # a retrograde orbit has an inclination of exactly math.pi
# inclination %= 2*math.pi
# if inclination > math.pi:
# inclination = 2*math.pi - inclination
# longitude_of_ascending_node -= math.pi
# argument_of_periapsis -= math.pi
# longitude_of_ascending_node %= 2*math.pi
# argument_of_periapsis %= 2*math.pi
#
# self.primary = primary
# self.periapsis = float(periapsis)
# self.eccentricity = float(eccentricity)
# self.inclination = float(inclination)
# self.longitude_of_ascending_node = float(longitude_of_ascending_node)
# self.argument_of_periapsis = float(argument_of_periapsis)
# self.epoch = float(epoch)
# self.mean_anomaly_at_epoch = float(mean_anomaly_at_epoch)
#
# # semi-major axis
# if self.eccentricity == 1: # parabolic trajectory
# self.semi_major_axis = math.inf
# else:
# self.semi_major_axis = self.periapsis / (1 - self.eccentricity)
#
# # other distances
# self.apoapsis = self.semi_major_axis * (1 + self.eccentricity)
# self.semi_latus_rectum = self.periapsis * (1 + self.eccentricity)
# e2 = 1-self.eccentricity**2
# self.semi_minor_axis = self.semi_major_axis * math.sqrt(abs(e2))
# self.focus = self.semi_major_axis * self.eccentricity
#
# # mean motion
# mu = self.primary.gravitational_parameter
# if self.eccentricity == 1: # parabolic trajectory
# self.mean_motion = 3 * math.sqrt(mu / self.semi_latus_rectum**3)
# else:
# self.mean_motion = math.sqrt(mu / abs(self.semi_major_axis)**3)
#
# # period
# if self.eccentricity >= 1: # parabolic/hyperbolic trajectory
# self.period = math.inf
# else: # circular/elliptic orbit
# self.period = 2*math.pi / self.mean_motion
#
# self.transform = Mat3.from_euler_angles(
# self.longitude_of_ascending_node,
# self.inclination,
# self.argument_of_periapsis,
# )
#
# def __repr__(self):
# return (
# "Orbit(%(primary)s, %(periapsis)g, %(eccentricity)g, "
# "%(inclination)g, %(longitude_of_ascending_node)g, "
# "%(argument_of_periapsis)g, %(epoch)g, %(mean_anomaly_at_epoch)g)"
# % self.__dict__
# )
#
# def darkness_time(self):
# """How long the object stays in the shadow of its primary
#
# For instance, this gives how long a satellite orbiting a planet stays
# in the dark (assuming the primary's rotation around the star is slow
# relatively to that of the satellite around its primary).
# """
#
# a = self.semi_major_axis
# b = self.semi_minor_axis
# h = math.sqrt(self.semi_latus_rectum * self.primary.gravitational_parameter)
# e = self.eccentricity
# R = self.primary.radius
# return 2*a*b/h * (math.asin(R/b) + e*R/b)
#
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
. Output only the next line. | ('Reflectron KR-7', 90e6), |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [SIZE]\n'
'Give information on possible satellites constellations\n'
'BODY is the primary around which the constellation orbits\n'
'SIZE is the number of satellites in the constellation\n'
% sys.argv[0], file=sys.stderr)
sys.exit(1)
primary = spyce.load.from_name(sys.argv[1])
# antennas from RemoteTech
antennas = [
('Reflectron DP-10', 0.5e6),
('Communotron 16', 2.5e6),
('CommTech EXP-VR-2T', 3e6),
('Communotron 32', 5e6),
<|code_end|>
with the help of current file imports:
import sys
import spyce.load
from spyce.orbit import Orbit
from spyce.human import to_human_time, to_si_prefix
and context from other files:
# Path: spyce/orbit.py
# class Orbit(
# spyce.orbit_determination.OrbitDetermination,
# spyce.orbit_angles.OrbitAngles,
# spyce.orbit_state.OrbitState,
# spyce.orbit_target.OrbitTarget,
# ):
# """Kepler orbit
#
# Two-body approximation of a body orbiting a mass-point.
# """
# def __init__(
# self, primary, periapsis, eccentricity=0,
# inclination=0, longitude_of_ascending_node=0, argument_of_periapsis=0,
# epoch=0, mean_anomaly_at_epoch=0, **_
# ):
# """Orbit from the orbital elements
#
# Arguments:
# primary object with a "gravitational_parameter"
# periapsis m
# eccentricity -, optional
# inclination rad, optional
# longitude_of_ascending_node rad, optional
# argument_of_periapsis rad, optional
# epoch s, optional
# mean_anomaly_at_epoch rad, optional
# """
#
# # normalize inclination within [0, math.pi]
# # a retrograde orbit has an inclination of exactly math.pi
# inclination %= 2*math.pi
# if inclination > math.pi:
# inclination = 2*math.pi - inclination
# longitude_of_ascending_node -= math.pi
# argument_of_periapsis -= math.pi
# longitude_of_ascending_node %= 2*math.pi
# argument_of_periapsis %= 2*math.pi
#
# self.primary = primary
# self.periapsis = float(periapsis)
# self.eccentricity = float(eccentricity)
# self.inclination = float(inclination)
# self.longitude_of_ascending_node = float(longitude_of_ascending_node)
# self.argument_of_periapsis = float(argument_of_periapsis)
# self.epoch = float(epoch)
# self.mean_anomaly_at_epoch = float(mean_anomaly_at_epoch)
#
# # semi-major axis
# if self.eccentricity == 1: # parabolic trajectory
# self.semi_major_axis = math.inf
# else:
# self.semi_major_axis = self.periapsis / (1 - self.eccentricity)
#
# # other distances
# self.apoapsis = self.semi_major_axis * (1 + self.eccentricity)
# self.semi_latus_rectum = self.periapsis * (1 + self.eccentricity)
# e2 = 1-self.eccentricity**2
# self.semi_minor_axis = self.semi_major_axis * math.sqrt(abs(e2))
# self.focus = self.semi_major_axis * self.eccentricity
#
# # mean motion
# mu = self.primary.gravitational_parameter
# if self.eccentricity == 1: # parabolic trajectory
# self.mean_motion = 3 * math.sqrt(mu / self.semi_latus_rectum**3)
# else:
# self.mean_motion = math.sqrt(mu / abs(self.semi_major_axis)**3)
#
# # period
# if self.eccentricity >= 1: # parabolic/hyperbolic trajectory
# self.period = math.inf
# else: # circular/elliptic orbit
# self.period = 2*math.pi / self.mean_motion
#
# self.transform = Mat3.from_euler_angles(
# self.longitude_of_ascending_node,
# self.inclination,
# self.argument_of_periapsis,
# )
#
# def __repr__(self):
# return (
# "Orbit(%(primary)s, %(periapsis)g, %(eccentricity)g, "
# "%(inclination)g, %(longitude_of_ascending_node)g, "
# "%(argument_of_periapsis)g, %(epoch)g, %(mean_anomaly_at_epoch)g)"
# % self.__dict__
# )
#
# def darkness_time(self):
# """How long the object stays in the shadow of its primary
#
# For instance, this gives how long a satellite orbiting a planet stays
# in the dark (assuming the primary's rotation around the star is slow
# relatively to that of the satellite around its primary).
# """
#
# a = self.semi_major_axis
# b = self.semi_minor_axis
# h = math.sqrt(self.semi_latus_rectum * self.primary.gravitational_parameter)
# e = self.eccentricity
# R = self.primary.radius
# return 2*a*b/h * (math.asin(R/b) + e*R/b)
#
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
, which may contain function names, class names, or code. Output only the next line. | ('Comms DTS-M1', 50e6), |
Next line prediction: <|code_start|> glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
gspyce.mesh.Sphere(1, 16, 16).draw()
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def set_and_draw(self):
"""Setup the camera and draw"""
# reset everything
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.shader_set()
# set camera
self.set_modelview_matrix(
Mat4.translate(0, 0, -1/self.zoom) @
Mat4.rotate(radians(self.phi), 1, 0, 0) @
Mat4.rotate(radians(self.theta), 0, 0, 1)
)
# draw!
self.draw()
def shader_set(self, program=None):
"""Change the current shader
If program is None, use the default shader."""
if program is None:
program = self.default_shader
self.current_shader = program
glUseProgram(self.current_shader)
<|code_end|>
. Use current file imports:
(import sys
import gspyce.mesh
import gspyce.textures
from math import radians
from spyce.vector import Mat4
from gspyce.graphics import *)
and context including class names, function names, or small code snippets from other files:
# Path: spyce/vector.py
# class Mat4:
# def __init__(self, v=None):
# if v is None:
# self.v = [
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]
# ]
# else:
# self.v = v
#
# def __sub__(A, B):
# return Mat4([x - y for a, b in zip(A, B) for x, y in zip(a, b)])
#
# def __abs__(A):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(a) for a in A)
#
# def transpose(self):
# return Mat4(list(zip(*self.v)))
#
# def __matmul__(self, other):
# if isinstance(other, Mat4): # matrix-matrix multiplication
# m = other.transpose()
# return Mat4([m @ row for row in self.v])
# else: # matrix-vector multiplication
# return [sum(a * b for a, b in zip(row, other)) for row in self.v]
#
# def row_major(self):
# return [v for row in self.v for v in row]
#
# def column_major(self):
# return [v for col in zip(*self.v) for v in col]
#
# @classmethod
# def translate(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [1, 0, 0, x],
# [0, 1, 0, y],
# [0, 0, 1, z],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def scale(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [x, 0, 0, 0],
# [0, y, 0, 0],
# [0, 0, z, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def rotate(cls, angle, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# s = math.sin(angle)
# c = math.cos(angle)
# d = math.sqrt(x*x + y*y + z*z)
# x, y, z = x/d, y/d, z/d
# return cls([
# [x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
# [y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s, 0],
# [z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def frustrum(cls, left, right, bottom, top, near, far):
# A = (right + left) / (right - left)
# B = (top + bottom) / (top - bottom)
# C = - (far + near) / (far - near)
# D = - (2*far * near) / (far - near)
# return cls([
# [2 * near / (right - left), 0, A, 0],
# [0, 2 * near / (top - bottom), B, 0],
# [0, 0, C, D],
# [0, 0, -1, 0],
# ])
#
# @classmethod
# def ortho(cls, left, right, bottom, top, near, far):
# tx = - (right + left) / (right - left)
# ty = - (top + bottom) / (top - bottom)
# tz = - (far + near) / (far - near)
# return cls([
# [2 / (right - left), 0, 0, tx],
# [0, 2 / (top - bottom), 0, ty],
# [0, 0, -2 / (far - near), tz],
# [0, 0, 0, 1],
# ])
. Output only the next line. | self.set_shader_matrices() |
Here is a snippet: <|code_start|> self.pick_objects = []
def set_and_draw(self):
"""Setup the camera and draw"""
self.pick_reset()
super().set_and_draw()
self.clear_pick_object()
def shader_set(self, program=None):
super().shader_set(program)
# update uniforms
if program is None:
program = self.default_shader
var = glGetUniformLocation(program, b'picking_enabled')
glUniform1i(var, self.picking_enabled)
self.set_picking_name(self.picking_name)
def pick(self, x, y, default=None):
"""Find object around given screen coordinates
If several objects match, return the one that was provided first."""
# draw with color picking
original_color = self.color
self.picking_enabled = True
glDisable(GL_MULTISAMPLE)
self.set_and_draw()
glEnable(GL_MULTISAMPLE)
self.picking_enabled = False
<|code_end|>
. Write the next line using the current file imports:
from spyce.vector import Mat4
from gspyce.graphics import *
import gspyce.hud
and context from other files:
# Path: spyce/vector.py
# class Mat4:
# def __init__(self, v=None):
# if v is None:
# self.v = [
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]
# ]
# else:
# self.v = v
#
# def __sub__(A, B):
# return Mat4([x - y for a, b in zip(A, B) for x, y in zip(a, b)])
#
# def __abs__(A):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(a) for a in A)
#
# def transpose(self):
# return Mat4(list(zip(*self.v)))
#
# def __matmul__(self, other):
# if isinstance(other, Mat4): # matrix-matrix multiplication
# m = other.transpose()
# return Mat4([m @ row for row in self.v])
# else: # matrix-vector multiplication
# return [sum(a * b for a, b in zip(row, other)) for row in self.v]
#
# def row_major(self):
# return [v for row in self.v for v in row]
#
# def column_major(self):
# return [v for col in zip(*self.v) for v in col]
#
# @classmethod
# def translate(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [1, 0, 0, x],
# [0, 1, 0, y],
# [0, 0, 1, z],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def scale(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [x, 0, 0, 0],
# [0, y, 0, 0],
# [0, 0, z, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def rotate(cls, angle, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# s = math.sin(angle)
# c = math.cos(angle)
# d = math.sqrt(x*x + y*y + z*z)
# x, y, z = x/d, y/d, z/d
# return cls([
# [x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
# [y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s, 0],
# [z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def frustrum(cls, left, right, bottom, top, near, far):
# A = (right + left) / (right - left)
# B = (top + bottom) / (top - bottom)
# C = - (far + near) / (far - near)
# D = - (2*far * near) / (far - near)
# return cls([
# [2 * near / (right - left), 0, A, 0],
# [0, 2 * near / (top - bottom), B, 0],
# [0, 0, C, D],
# [0, 0, -1, 0],
# ])
#
# @classmethod
# def ortho(cls, left, right, bottom, top, near, far):
# tx = - (right + left) / (right - left)
# ty = - (top + bottom) / (top - bottom)
# tz = - (far + near) / (far - near)
# return cls([
# [2 / (right - left), 0, 0, tx],
# [0, 2 / (top - bottom), 0, ty],
# [0, 0, -2 / (far - near), tz],
# [0, 0, 0, 1],
# ])
, which may include functions, classes, or code. Output only the next line. | self.set_color(*original_color) |
Predict the next line for this snippet: <|code_start|>
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [ALTITUDE]\n'
'Compute the time spent in the dark by a satellite\n'
'If ALTITUDE is not given, the best one is computed\n'
% sys.argv[0], file=sys.stderr)
sys.exit(1)
primary = spyce.load.from_name(sys.argv[1])
R = primary.radius
mu = primary.gravitational_parameter
def f(a):
# note: a for semi-major axis
return 2 * math.asin(R / a) * math.sqrt(a*a*a / mu)
# f''(a) / f'(a)
def ratio(a):
r = R/a
x = 1 - r*r
s = math.asin(r)/r * math.sqrt(x)
return a * (1.5*s - 1) / (.75*s - 2 + 1/x)
if len(sys.argv) > 2:
altitude = float(sys.argv[2])
<|code_end|>
with the help of current file imports:
import sys
import math
import spyce.load
from spyce.human import to_human_time, to_si_prefix
from spyce.analysis import newton_raphson
and context from other files:
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
#
# Path: spyce/analysis.py
# def newton_raphson(x_0, f=None, f_prime=None, ratio=None):
# """Newton-Raphson method
#
# Look around `x_0` for a root of `f`, of derivative `f_prime`. For
# optimization, their ratio (`f` over `f_prime`) can be directly given
# instead.
# """
# # handle arguments
# if ratio is None:
# def ratio(x):
# return f(x) / f_prime(x)
# else:
# if f is not None or f_prime is not None:
# raise TypeError('specify either ratio or (f and f_prime)')
#
# # run Newton-Raphson
# x = x_0
# previous_x = 0
# for _ in range(30): # upper limit on iteration count
# previous_previous_x, previous_x = previous_x, x
# x -= ratio(x)
# if x in (previous_x, previous_previous_x):
# # best accuracy reached
# break
# return x
, which may contain function names, class names, or code. Output only the next line. | semi_major_axis = primary.radius + altitude |
Next line prediction: <|code_start|>#!/usr/bin/env python
def main():
# parse orbited body
if len(sys.argv) <= 1:
print(
'Usage: %s BODY [ALTITUDE]\n'
'Compute the time spent in the dark by a satellite\n'
'If ALTITUDE is not given, the best one is computed\n'
% sys.argv[0], file=sys.stderr)
sys.exit(1)
primary = spyce.load.from_name(sys.argv[1])
R = primary.radius
mu = primary.gravitational_parameter
def f(a):
# note: a for semi-major axis
return 2 * math.asin(R / a) * math.sqrt(a*a*a / mu)
# f''(a) / f'(a)
def ratio(a):
r = R/a
x = 1 - r*r
s = math.asin(r)/r * math.sqrt(x)
<|code_end|>
. Use current file imports:
(import sys
import math
import spyce.load
from spyce.human import to_human_time, to_si_prefix
from spyce.analysis import newton_raphson)
and context including class names, function names, or small code snippets from other files:
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
#
# Path: spyce/analysis.py
# def newton_raphson(x_0, f=None, f_prime=None, ratio=None):
# """Newton-Raphson method
#
# Look around `x_0` for a root of `f`, of derivative `f_prime`. For
# optimization, their ratio (`f` over `f_prime`) can be directly given
# instead.
# """
# # handle arguments
# if ratio is None:
# def ratio(x):
# return f(x) / f_prime(x)
# else:
# if f is not None or f_prime is not None:
# raise TypeError('specify either ratio or (f and f_prime)')
#
# # run Newton-Raphson
# x = x_0
# previous_x = 0
# for _ in range(30): # upper limit on iteration count
# previous_previous_x, previous_x = previous_x, x
# x -= ratio(x)
# if x in (previous_x, previous_previous_x):
# # best accuracy reached
# break
# return x
. Output only the next line. | return a * (1.5*s - 1) / (.75*s - 2 + 1/x) |
Based on the snippet: <|code_start|> # f''(a) / f'(a)
def ratio(a):
r = R/a
x = 1 - r*r
s = math.asin(r)/r * math.sqrt(x)
return a * (1.5*s - 1) / (.75*s - 2 + 1/x)
if len(sys.argv) > 2:
altitude = float(sys.argv[2])
semi_major_axis = primary.radius + altitude
altitude = to_si_prefix(altitude, 'm')
night_time = to_human_time(f(semi_major_axis))
print('Consider a satellite in a circular orbit around %s' % primary)
print('Time in the dark at altitude %s: %s' % (altitude, night_time))
print('This ignores possible eclipses from natural satellites')
sys.exit(0)
# find a root of f'
# i.e. a local extremum of f
semi_major_axis = newton_raphson(primary.radius+1e-6, ratio=ratio)
night_time = to_human_time(f(semi_major_axis))
altitude = to_si_prefix(semi_major_axis - primary.radius, 'm')
print('Consider a satellite in a circular orbit around %s' % primary)
print('The time spent in the dark is at least %s' % night_time)
print('This is achieved at altitude %s' % altitude)
print('Note that this ignores possible eclipses from natural satellites')
if __name__ == '__main__':
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import math
import spyce.load
from spyce.human import to_human_time, to_si_prefix
from spyce.analysis import newton_raphson
and context (classes, functions, sometimes code) from other files:
# Path: spyce/human.py
# def to_human_time(seconds):
# """Convert a timespan in seconds into a human-readable format"""
# return str(datetime.timedelta(seconds=seconds))
#
# def to_si_prefix(value, unit=''):
# """Format value with SI-prefix for easier reading"""
# exponent_group = math.log(abs(value), 10) // 3
# mantissa = value / 10**(exponent_group*3)
# prefix = u'afpnµm kMGTPE'[int(exponent_group) + 6].strip()
# return '%.4g%s%s' % (mantissa, prefix, unit)
#
# Path: spyce/analysis.py
# def newton_raphson(x_0, f=None, f_prime=None, ratio=None):
# """Newton-Raphson method
#
# Look around `x_0` for a root of `f`, of derivative `f_prime`. For
# optimization, their ratio (`f` over `f_prime`) can be directly given
# instead.
# """
# # handle arguments
# if ratio is None:
# def ratio(x):
# return f(x) / f_prime(x)
# else:
# if f is not None or f_prime is not None:
# raise TypeError('specify either ratio or (f and f_prime)')
#
# # run Newton-Raphson
# x = x_0
# previous_x = 0
# for _ in range(30): # upper limit on iteration count
# previous_previous_x, previous_x = previous_x, x
# x -= ratio(x)
# if x in (previous_x, previous_previous_x):
# # best accuracy reached
# break
# return x
. Output only the next line. | main() |
Based on the snippet: <|code_start|>
class OrbitState:
def __init__(self):
raise NotImplementedError
<|code_end|>
, predict the immediate next line with the help of imports:
import math
from spyce.vector import Vec3
and context (classes, functions, sometimes code) from other files:
# Path: spyce/vector.py
# class Vec3(list):
# def norm(u):
# return math.sqrt(u.dot(u))
#
# def dot(u, v):
# """Dot product"""
# u1, u2, u3 = u
# v1, v2, v3 = v
# return math.fsum([u1*v1, u2*v2, u3*v3])
#
# def cross(u, v):
# """Cross product"""
# u1, u2, u3 = u
# v1, v2, v3 = v
# return Vec3([
# u2*v3 - u3*v2,
# u3*v1 - u1*v3,
# u1*v2 - u2*v1,
# ])
#
# def angle(u, v):
# """Angle formed by two vectors"""
# r = u.dot(v)/u.norm()/v.norm()
# r = max(-1, min(1, r))
# return math.acos(r)
#
# def oriented_angle(u, v, normal=None):
# """Angle formed by two vectors"""
# if normal is None:
# normal = Vec3([0, 0, 1])
# geometric_angle = u.angle(v)
# if normal.dot(u.cross(v)) < 0:
# return -geometric_angle
# else:
# return geometric_angle
#
# def __mul__(u, s):
# x, y, z = u
# return Vec3([x*s, y*s, z*s])
#
# def __div__(u, s):
# x, y, z = u
# return Vec3([x/s, y/s, z/s])
#
# def __add__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x+a, y+b, z+c])
#
# def __iadd__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x+a, y+b, z+c])
#
# def __sub__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x-a, y-b, z-c])
#
# def __isub__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x-a, y-b, z-c])
#
# def __neg__(u):
# x, y, z = u
# return Vec3([-x, -y, -z])
#
# def __abs__(u):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(x) for x in u)
. Output only the next line. | def distance_at_true_anomaly(self, true_anomaly): |
Using the snippet: <|code_start|>
class OrbitTarget:
def __init__(self):
raise NotImplementedError
def position_to_target(self, target, time):
return target.position_at_time(time) - self.position_at_time(time)
def distance_to_target(self, target, time):
return self.position_to_target(target, time).norm()
def velocity_to_target(self, target, time):
return target.velocity_at_time(time) - self.velocity_at_time(time)
def speed_to_target(self, target, time):
<|code_end|>
, determine the next line of code. You have imports:
import math
from spyce.analysis import golden_section_search, bisection_method
and context (class names, function names, or code) available:
# Path: spyce/analysis.py
# def golden_section_search(f, a, b, tolerance=0):
# """Golden section search
#
# Look for a minima of unimodal function `f` within `(a, b)`"""
# # golden_ratio = (math.sqrt(5) + 1) / 2
# golden_ratio = 1.618033988749895
#
# old_a, old_b = a, b
# for _ in range(54):
# c = b - (b - a) / golden_ratio
# d = a + (b - a) / golden_ratio
# fc = f(c)
# if abs(fc) < tolerance:
# return c
# if fc < f(d):
# b = d
# else:
# a = c
#
# if a == old_a or b == old_b:
# return None
# return (b + a) / 2
#
# def bisection_method(f, a, b):
# """Bisection method
#
# Look for a root of `f` in [a, b]"""
# fa = f(a)
# for _ in range(54):
# c = (a + b) / 2
# fc = f(c)
# if fa*fc >= 0:
# # f(a) and f(c) have the same sign
# a, fa = c, fc
# else:
# # f(a) and f(c) have opposite signs
# b = c
# return a
. Output only the next line. | return self.velocity_to_target(target, time).norm() |
Using the snippet: <|code_start|>
class OrbitTarget:
def __init__(self):
raise NotImplementedError
def position_to_target(self, target, time):
return target.position_at_time(time) - self.position_at_time(time)
def distance_to_target(self, target, time):
return self.position_to_target(target, time).norm()
def velocity_to_target(self, target, time):
return target.velocity_at_time(time) - self.velocity_at_time(time)
def speed_to_target(self, target, time):
return self.velocity_to_target(target, time).norm()
<|code_end|>
, determine the next line of code. You have imports:
import math
from spyce.analysis import golden_section_search, bisection_method
and context (class names, function names, or code) available:
# Path: spyce/analysis.py
# def golden_section_search(f, a, b, tolerance=0):
# """Golden section search
#
# Look for a minima of unimodal function `f` within `(a, b)`"""
# # golden_ratio = (math.sqrt(5) + 1) / 2
# golden_ratio = 1.618033988749895
#
# old_a, old_b = a, b
# for _ in range(54):
# c = b - (b - a) / golden_ratio
# d = a + (b - a) / golden_ratio
# fc = f(c)
# if abs(fc) < tolerance:
# return c
# if fc < f(d):
# b = d
# else:
# a = c
#
# if a == old_a or b == old_b:
# return None
# return (b + a) / 2
#
# def bisection_method(f, a, b):
# """Bisection method
#
# Look for a root of `f` in [a, b]"""
# fa = f(a)
# for _ in range(54):
# c = (a + b) / 2
# fc = f(c)
# if fa*fc >= 0:
# # f(a) and f(c) have the same sign
# a, fa = c, fc
# else:
# # f(a) and f(c) have opposite signs
# b = c
# return a
. Output only the next line. | def time_at_next_approach(self, target, t, tolerance=0): |
Given the following code snippet before the placeholder: <|code_start|> # save orbit
body = bodies.setdefault(name, {})
body['orbit'] = {
'primary': primary,
'semi_major_axis': semi_major_axis,
'eccentricity': eccentricity,
'inclination': inclination,
'longitude_of_ascending_node': longitude_of_ascending_node,
'argument_of_periapsis': argument_of_periapsis,
'epoch': epoch,
'mean_anomaly_at_epoch': mean_anomaly_at_epoch,
}
def get_dwarf_planet_data(bodies, name):
"""Get physical and orbital information of dwarf planets"""
# retrieve relevant page
html = urlopen('http://ssd.jpl.nasa.gov/sbdb.cgi?sstr={}'.format(name)).read().decode()
body = bodies.setdefault(name, {})
# extract physical information
pattern = r"""<tr>
<td.*>(.*)</font></a></td>
.*
<td.*>(.*)</font></td>"""
matches = re.findall(pattern, html)
for name, value in matches:
<|code_end|>
, predict the next line using imports from the current file:
import json
import re
from math import acos, asin, cos, pi, radians, sin
from urllib.request import urlopen
from spyce.physics import au
from spyce.coordinates import CelestialCoordinates
and context including class names, function names, and sometimes code from other files:
# Path: spyce/physics.py
# def _(tabulated, uncertainty=None, computed=None):
# G = _(6.67384e-11, 80e-16) # gravitational constant (N.(m/kg)^2)
# N_A = _(6.02214129e23, 27e15, A_r_e*M_u/m_e) # Avogadro constant (1/mol)
# R = _(8.3144621, 75e-7) # molar gas constant (J/mol/K)
# T_P = _(1.416833e32, 85e26, m_P * c**2 / k_B) # Planck temperature (K)
# T0 = _(288.15) # standard temperature (K)
#
# Path: spyce/coordinates.py
# class CelestialCoordinates:
# """Celestial coordinates of a point or a direction
#
# Celestial coordinates are spherical coordinates. The referential is thus
# given by an origin, a fundamental plane and a primary direction.
#
# * ecliptic coordinates: planet center, ecliptic, vernal equinox
# * equatorial coordinates: planet center, celestial equator, vernal equinox
#
# Note that the vernal equinox, the celestial equator and the ecliptic are
# respectively the northward equinox, the equatorial plane and the orbital
# plane *of the Earth*. It does mean that the direction of the north pole of
# Mars is given within a referential centered on Mars, oriented with Earth.
# """
#
# # the obliquity of the ecliptic is Earth's obliquity (tilt); that is, the
# # angle between the celestial equator (Earth's equatorial plane) and the
# # ecliptic (Earth's orbital plane)
# obliquity_of_the_ecliptic = 0.40910517666747087
#
# def __init__(self, right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance):
# """Use from_equatorial() or from_ecliptic()"""
# self.right_ascension = right_ascension
# self.declination = declination
# self.ecliptic_longitude = ecliptic_longitude
# self.ecliptic_latitude = ecliptic_latitude
# self.distance = distance
#
# @classmethod
# def from_equatorial(cls, right_ascension, declination, distance=math.inf):
# """Locate an object from its equatorial coordinates (see class doc)
#
# If distance is omitted, it is assumed to be infinite; the coordinates
# then refer either to a point infinitely far away, or to a direction.
# """
# e = cls.obliquity_of_the_ecliptic
# ecliptic_longitude = math.atan(
# (
# math.sin(right_ascension) * math.cos(e) +
# math.tan(declination) * math.sin(e)
# )
# / math.cos(right_ascension)
# )
# ecliptic_latitude = math.asin(
# math.sin(declination) * math.cos(e) -
# math.cos(declination) * math.sin(e) * math.sin(right_ascension)
# )
# return cls(right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance)
#
# @classmethod
# def from_ecliptic(cls, ecliptic_longitude, ecliptic_latitude,
# distance=math.inf):
# """Locate an object from its ecliptic coordinates (see class doc)
#
# If distance is omitted, it is assumed to be infinite; the coordinates
# then refer either to a point infinitely far away, or to a direction.
# """
# e = cls.obliquity_of_the_ecliptic
# right_ascension = math.atan(
# (
# math.sin(ecliptic_longitude) * math.cos(e) -
# math.tan(ecliptic_latitude) * math.sin(e)
# ) / math.cos(ecliptic_longitude)
# )
# declination = math.asin(
# math.sin(ecliptic_latitude) * math.cos(e) +
# math.cos(ecliptic_latitude) * math.sin(e) *
# math.sin(ecliptic_longitude)
# )
# return cls(right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance)
. Output only the next line. | if name == 'diameter': |
Given the code snippet: <|code_start|> 'epoch': epoch,
'mean_anomaly_at_epoch': mean_anomaly_at_epoch,
}
def get_dwarf_planet_data(bodies, name):
"""Get physical and orbital information of dwarf planets"""
# retrieve relevant page
html = urlopen('http://ssd.jpl.nasa.gov/sbdb.cgi?sstr={}'.format(name)).read().decode()
body = bodies.setdefault(name, {})
# extract physical information
pattern = r"""<tr>
<td.*>(.*)</font></a></td>
.*
<td.*>(.*)</font></td>"""
matches = re.findall(pattern, html)
for name, value in matches:
if name == 'diameter':
body['radius'] = float(value) * 500
elif name == 'GM':
body['gravitational_parameter'] = float(value) * 1e9
elif name == 'rotation period':
body['rotational_period'] = float(value) * 3600
# extract epoch
pattern = r'<b>Orbital Elements at Epoch ([0-9]+(\.[0-9])?) '
<|code_end|>
, generate the next line using the imports in this file:
import json
import re
from math import acos, asin, cos, pi, radians, sin
from urllib.request import urlopen
from spyce.physics import au
from spyce.coordinates import CelestialCoordinates
and context (functions, classes, or occasionally code) from other files:
# Path: spyce/physics.py
# def _(tabulated, uncertainty=None, computed=None):
# G = _(6.67384e-11, 80e-16) # gravitational constant (N.(m/kg)^2)
# N_A = _(6.02214129e23, 27e15, A_r_e*M_u/m_e) # Avogadro constant (1/mol)
# R = _(8.3144621, 75e-7) # molar gas constant (J/mol/K)
# T_P = _(1.416833e32, 85e26, m_P * c**2 / k_B) # Planck temperature (K)
# T0 = _(288.15) # standard temperature (K)
#
# Path: spyce/coordinates.py
# class CelestialCoordinates:
# """Celestial coordinates of a point or a direction
#
# Celestial coordinates are spherical coordinates. The referential is thus
# given by an origin, a fundamental plane and a primary direction.
#
# * ecliptic coordinates: planet center, ecliptic, vernal equinox
# * equatorial coordinates: planet center, celestial equator, vernal equinox
#
# Note that the vernal equinox, the celestial equator and the ecliptic are
# respectively the northward equinox, the equatorial plane and the orbital
# plane *of the Earth*. It does mean that the direction of the north pole of
# Mars is given within a referential centered on Mars, oriented with Earth.
# """
#
# # the obliquity of the ecliptic is Earth's obliquity (tilt); that is, the
# # angle between the celestial equator (Earth's equatorial plane) and the
# # ecliptic (Earth's orbital plane)
# obliquity_of_the_ecliptic = 0.40910517666747087
#
# def __init__(self, right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance):
# """Use from_equatorial() or from_ecliptic()"""
# self.right_ascension = right_ascension
# self.declination = declination
# self.ecliptic_longitude = ecliptic_longitude
# self.ecliptic_latitude = ecliptic_latitude
# self.distance = distance
#
# @classmethod
# def from_equatorial(cls, right_ascension, declination, distance=math.inf):
# """Locate an object from its equatorial coordinates (see class doc)
#
# If distance is omitted, it is assumed to be infinite; the coordinates
# then refer either to a point infinitely far away, or to a direction.
# """
# e = cls.obliquity_of_the_ecliptic
# ecliptic_longitude = math.atan(
# (
# math.sin(right_ascension) * math.cos(e) +
# math.tan(declination) * math.sin(e)
# )
# / math.cos(right_ascension)
# )
# ecliptic_latitude = math.asin(
# math.sin(declination) * math.cos(e) -
# math.cos(declination) * math.sin(e) * math.sin(right_ascension)
# )
# return cls(right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance)
#
# @classmethod
# def from_ecliptic(cls, ecliptic_longitude, ecliptic_latitude,
# distance=math.inf):
# """Locate an object from its ecliptic coordinates (see class doc)
#
# If distance is omitted, it is assumed to be infinite; the coordinates
# then refer either to a point infinitely far away, or to a direction.
# """
# e = cls.obliquity_of_the_ecliptic
# right_ascension = math.atan(
# (
# math.sin(ecliptic_longitude) * math.cos(e) -
# math.tan(ecliptic_latitude) * math.sin(e)
# ) / math.cos(ecliptic_longitude)
# )
# declination = math.asin(
# math.sin(ecliptic_latitude) * math.cos(e) +
# math.cos(ecliptic_latitude) * math.sin(e) *
# math.sin(ecliptic_longitude)
# )
# return cls(right_ascension, declination, ecliptic_longitude,
# ecliptic_latitude, distance)
. Output only the next line. | epoch = re.search(pattern, html).group(1) |
Based on the snippet: <|code_start|>
def __init__(self, mode):
"""Create a new mesh
A Vertex Buffer Object is filled with data from self.vertices()
A Texcoord Buffer Object is filled with data from self.texcoords()
A Normal Buffer Object is filled with data from self.normals()
Mesh will be drawn using given OpenGL mode (GL_TRIANGLES, etc.)
"""
# save meta-data
self.mode = mode
vertices = list(self.vertices())
self.length = len(vertices)
self.components = len(vertices[0])
# fill vertex buffer object
self.vertex_buffer = BufferObject(vertices, flatten=True)
# fill texcoord buffer object
if hasattr(self, "texcoords"):
self.texcoord_buffer = BufferObject(self.texcoords(), flatten=True)
# fill normal buffer boject
if hasattr(self, "normals"):
self.normal_buffer = BufferObject(self.normals(), flatten=True)
def bind(self):
""""Bind the mesh for glDrawArrays()
Return True if the mesh was already bound"""
<|code_end|>
, predict the immediate next line with the help of imports:
import math
from spyce.vector import Vec4, Mat4
from gspyce.graphics import *
and context (classes, functions, sometimes code) from other files:
# Path: spyce/vector.py
# class Vec4(list):
# def __init__(cls, x=0, y=0, z=0, w=1):
# super().__init__([x, y, z, w])
#
# class Mat4:
# def __init__(self, v=None):
# if v is None:
# self.v = [
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]
# ]
# else:
# self.v = v
#
# def __sub__(A, B):
# return Mat4([x - y for a, b in zip(A, B) for x, y in zip(a, b)])
#
# def __abs__(A):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(a) for a in A)
#
# def transpose(self):
# return Mat4(list(zip(*self.v)))
#
# def __matmul__(self, other):
# if isinstance(other, Mat4): # matrix-matrix multiplication
# m = other.transpose()
# return Mat4([m @ row for row in self.v])
# else: # matrix-vector multiplication
# return [sum(a * b for a, b in zip(row, other)) for row in self.v]
#
# def row_major(self):
# return [v for row in self.v for v in row]
#
# def column_major(self):
# return [v for col in zip(*self.v) for v in col]
#
# @classmethod
# def translate(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [1, 0, 0, x],
# [0, 1, 0, y],
# [0, 0, 1, z],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def scale(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [x, 0, 0, 0],
# [0, y, 0, 0],
# [0, 0, z, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def rotate(cls, angle, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# s = math.sin(angle)
# c = math.cos(angle)
# d = math.sqrt(x*x + y*y + z*z)
# x, y, z = x/d, y/d, z/d
# return cls([
# [x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
# [y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s, 0],
# [z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def frustrum(cls, left, right, bottom, top, near, far):
# A = (right + left) / (right - left)
# B = (top + bottom) / (top - bottom)
# C = - (far + near) / (far - near)
# D = - (2*far * near) / (far - near)
# return cls([
# [2 * near / (right - left), 0, A, 0],
# [0, 2 * near / (top - bottom), B, 0],
# [0, 0, C, D],
# [0, 0, -1, 0],
# ])
#
# @classmethod
# def ortho(cls, left, right, bottom, top, near, far):
# tx = - (right + left) / (right - left)
# ty = - (top + bottom) / (top - bottom)
# tz = - (far + near) / (far - near)
# return cls([
# [2 / (right - left), 0, 0, tx],
# [0, 2 / (top - bottom), 0, ty],
# [0, 0, -2 / (far - near), tz],
# [0, 0, 0, 1],
# ])
. Output only the next line. | if Mesh.bound_mesh is not None: |
Here is a snippet: <|code_start|> return True
else:
raise RuntimeError("Another mesh is already bound")
Mesh.bound_mesh = self
program = glGetIntegerv(GL_CURRENT_PROGRAM)
# select vertex buffer object
var = glGetAttribLocation(program, "vertex")
glEnableVertexAttribArray(var)
self.vertex_buffer.bind()
glVertexAttribPointer(var, self.components, GL_FLOAT, False, 0, None)
self.vertex_buffer.unbind()
# select texcoord buffer object
if hasattr(self, "texcoord_buffer"):
var = glGetAttribLocation(program, "texcoord")
if var != -1: # active attribute
glEnableVertexAttribArray(var)
self.texcoord_buffer.bind()
glVertexAttribPointer(var, 2, GL_FLOAT, False, 0, None)
self.texcoord_buffer.unbind()
# select normal buffer object
if hasattr(self, "normal_buffer"):
var = glGetAttribLocation(program, "normal")
if var != -1: # active attribute
glEnableVertexAttribArray(var)
self.normal_buffer.bind()
glVertexAttribPointer(var, 3, GL_FLOAT, False, 0, None)
<|code_end|>
. Write the next line using the current file imports:
import math
from spyce.vector import Vec4, Mat4
from gspyce.graphics import *
and context from other files:
# Path: spyce/vector.py
# class Vec4(list):
# def __init__(cls, x=0, y=0, z=0, w=1):
# super().__init__([x, y, z, w])
#
# class Mat4:
# def __init__(self, v=None):
# if v is None:
# self.v = [
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]
# ]
# else:
# self.v = v
#
# def __sub__(A, B):
# return Mat4([x - y for a, b in zip(A, B) for x, y in zip(a, b)])
#
# def __abs__(A):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(a) for a in A)
#
# def transpose(self):
# return Mat4(list(zip(*self.v)))
#
# def __matmul__(self, other):
# if isinstance(other, Mat4): # matrix-matrix multiplication
# m = other.transpose()
# return Mat4([m @ row for row in self.v])
# else: # matrix-vector multiplication
# return [sum(a * b for a, b in zip(row, other)) for row in self.v]
#
# def row_major(self):
# return [v for row in self.v for v in row]
#
# def column_major(self):
# return [v for col in zip(*self.v) for v in col]
#
# @classmethod
# def translate(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [1, 0, 0, x],
# [0, 1, 0, y],
# [0, 0, 1, z],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def scale(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [x, 0, 0, 0],
# [0, y, 0, 0],
# [0, 0, z, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def rotate(cls, angle, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# s = math.sin(angle)
# c = math.cos(angle)
# d = math.sqrt(x*x + y*y + z*z)
# x, y, z = x/d, y/d, z/d
# return cls([
# [x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
# [y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s, 0],
# [z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def frustrum(cls, left, right, bottom, top, near, far):
# A = (right + left) / (right - left)
# B = (top + bottom) / (top - bottom)
# C = - (far + near) / (far - near)
# D = - (2*far * near) / (far - near)
# return cls([
# [2 * near / (right - left), 0, A, 0],
# [0, 2 * near / (top - bottom), B, 0],
# [0, 0, C, D],
# [0, 0, -1, 0],
# ])
#
# @classmethod
# def ortho(cls, left, right, bottom, top, near, far):
# tx = - (right + left) / (right - left)
# ty = - (top + bottom) / (top - bottom)
# tz = - (far + near) / (far - near)
# return cls([
# [2 / (right - left), 0, 0, tx],
# [0, 2 / (top - bottom), 0, ty],
# [0, 0, -2 / (far - near), tz],
# [0, 0, 0, 1],
# ])
, which may include functions, classes, or code. Output only the next line. | self.normal_buffer.unbind() |
Using the snippet: <|code_start|> gravitational_parameter = 1e20
def __repr__(self):
return 'X'
primary = DummyPrimary()
class TestOrbit(unittest.TestCase):
longMessage = True
def assertIsClose(self, first, second, rel_tol=1e-9, msg=None, abs_tol=0.):
ok = isclose(first, second, rel_tol=rel_tol, abs_tol=abs_tol)
self.assertTrue(ok, msg=msg)
def assertAlmostEqualAngle(self, first, second, places=7, msg=None,
delta=None):
angle_diff = (first-second + math.pi) % (2*math.pi) - math.pi
self.assertAlmostEqual(angle_diff, 0, places, msg, delta)
def assertAlmostEqualOrbits(self, a, b):
msg = '\n' + str(a) + ' != ' + str(b)
self.assertIsClose(a.periapsis, b.periapsis, msg=msg)
self.assertIsClose(a.eccentricity, b.eccentricity, msg=msg,
abs_tol=1e-7)
self.assertAlmostEqualAngle(a.inclination, b.inclination, msg=msg)
# longitude of ascending node
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import math
import itertools
from spyce.orbit import Orbit
from spyce.orbit_determination import InvalidElements
from math import isclose
and context (class names, function names, or code) available:
# Path: spyce/orbit.py
# class Orbit(
# spyce.orbit_determination.OrbitDetermination,
# spyce.orbit_angles.OrbitAngles,
# spyce.orbit_state.OrbitState,
# spyce.orbit_target.OrbitTarget,
# ):
# """Kepler orbit
#
# Two-body approximation of a body orbiting a mass-point.
# """
# def __init__(
# self, primary, periapsis, eccentricity=0,
# inclination=0, longitude_of_ascending_node=0, argument_of_periapsis=0,
# epoch=0, mean_anomaly_at_epoch=0, **_
# ):
# """Orbit from the orbital elements
#
# Arguments:
# primary object with a "gravitational_parameter"
# periapsis m
# eccentricity -, optional
# inclination rad, optional
# longitude_of_ascending_node rad, optional
# argument_of_periapsis rad, optional
# epoch s, optional
# mean_anomaly_at_epoch rad, optional
# """
#
# # normalize inclination within [0, math.pi]
# # a retrograde orbit has an inclination of exactly math.pi
# inclination %= 2*math.pi
# if inclination > math.pi:
# inclination = 2*math.pi - inclination
# longitude_of_ascending_node -= math.pi
# argument_of_periapsis -= math.pi
# longitude_of_ascending_node %= 2*math.pi
# argument_of_periapsis %= 2*math.pi
#
# self.primary = primary
# self.periapsis = float(periapsis)
# self.eccentricity = float(eccentricity)
# self.inclination = float(inclination)
# self.longitude_of_ascending_node = float(longitude_of_ascending_node)
# self.argument_of_periapsis = float(argument_of_periapsis)
# self.epoch = float(epoch)
# self.mean_anomaly_at_epoch = float(mean_anomaly_at_epoch)
#
# # semi-major axis
# if self.eccentricity == 1: # parabolic trajectory
# self.semi_major_axis = math.inf
# else:
# self.semi_major_axis = self.periapsis / (1 - self.eccentricity)
#
# # other distances
# self.apoapsis = self.semi_major_axis * (1 + self.eccentricity)
# self.semi_latus_rectum = self.periapsis * (1 + self.eccentricity)
# e2 = 1-self.eccentricity**2
# self.semi_minor_axis = self.semi_major_axis * math.sqrt(abs(e2))
# self.focus = self.semi_major_axis * self.eccentricity
#
# # mean motion
# mu = self.primary.gravitational_parameter
# if self.eccentricity == 1: # parabolic trajectory
# self.mean_motion = 3 * math.sqrt(mu / self.semi_latus_rectum**3)
# else:
# self.mean_motion = math.sqrt(mu / abs(self.semi_major_axis)**3)
#
# # period
# if self.eccentricity >= 1: # parabolic/hyperbolic trajectory
# self.period = math.inf
# else: # circular/elliptic orbit
# self.period = 2*math.pi / self.mean_motion
#
# self.transform = Mat3.from_euler_angles(
# self.longitude_of_ascending_node,
# self.inclination,
# self.argument_of_periapsis,
# )
#
# def __repr__(self):
# return (
# "Orbit(%(primary)s, %(periapsis)g, %(eccentricity)g, "
# "%(inclination)g, %(longitude_of_ascending_node)g, "
# "%(argument_of_periapsis)g, %(epoch)g, %(mean_anomaly_at_epoch)g)"
# % self.__dict__
# )
#
# def darkness_time(self):
# """How long the object stays in the shadow of its primary
#
# For instance, this gives how long a satellite orbiting a planet stays
# in the dark (assuming the primary's rotation around the star is slow
# relatively to that of the satellite around its primary).
# """
#
# a = self.semi_major_axis
# b = self.semi_minor_axis
# h = math.sqrt(self.semi_latus_rectum * self.primary.gravitational_parameter)
# e = self.eccentricity
# R = self.primary.radius
# return 2*a*b/h * (math.asin(R/b) + e*R/b)
#
# Path: spyce/orbit_determination.py
# class InvalidElements(Exception):
# pass
. Output only the next line. | if a.inclination not in (0, math.pi): # gimpbal lock |
Based on the snippet: <|code_start|>
class InvalidElements(Exception):
pass
class OrbitDetermination:
def __init__(self, *args, **kwargs):
raise NotImplementedError
@classmethod
def from_semi_major_axis(
cls, primary, semi_major_axis, eccentricity,
inclination=0, longitude_of_ascending_node=0, argument_of_periapsis=0,
epoch=0, mean_anomaly_at_epoch=0, **_
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import math
import spyce.orbit_angles
from spyce.vector import Vec3
from spyce.cext import orbit as cext
and context (classes, functions, sometimes code) from other files:
# Path: spyce/vector.py
# class Vec3(list):
# def norm(u):
# return math.sqrt(u.dot(u))
#
# def dot(u, v):
# """Dot product"""
# u1, u2, u3 = u
# v1, v2, v3 = v
# return math.fsum([u1*v1, u2*v2, u3*v3])
#
# def cross(u, v):
# """Cross product"""
# u1, u2, u3 = u
# v1, v2, v3 = v
# return Vec3([
# u2*v3 - u3*v2,
# u3*v1 - u1*v3,
# u1*v2 - u2*v1,
# ])
#
# def angle(u, v):
# """Angle formed by two vectors"""
# r = u.dot(v)/u.norm()/v.norm()
# r = max(-1, min(1, r))
# return math.acos(r)
#
# def oriented_angle(u, v, normal=None):
# """Angle formed by two vectors"""
# if normal is None:
# normal = Vec3([0, 0, 1])
# geometric_angle = u.angle(v)
# if normal.dot(u.cross(v)) < 0:
# return -geometric_angle
# else:
# return geometric_angle
#
# def __mul__(u, s):
# x, y, z = u
# return Vec3([x*s, y*s, z*s])
#
# def __div__(u, s):
# x, y, z = u
# return Vec3([x/s, y/s, z/s])
#
# def __add__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x+a, y+b, z+c])
#
# def __iadd__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x+a, y+b, z+c])
#
# def __sub__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x-a, y-b, z-c])
#
# def __isub__(u, v):
# x, y, z = u
# a, b, c = v
# return Vec3([x-a, y-b, z-c])
#
# def __neg__(u):
# x, y, z = u
# return Vec3([-x, -y, -z])
#
# def __abs__(u):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(x) for x in u)
. Output only the next line. | ): |
Given the code snippet: <|code_start|>
class MissionGUI(gspyce.simulation.SimulationGUI):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
<|code_end|>
, generate the next line using the imports in this file:
import time
import gspyce.simulation
import gspyce.textures
import gspyce.mesh
import spyce.ksp_cfg
import spyce.rocket
from math import radians
from spyce.vector import Mat4
from gspyce.graphics import *
and context (functions, classes, or occasionally code) from other files:
# Path: spyce/vector.py
# class Mat4:
# def __init__(self, v=None):
# if v is None:
# self.v = [
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]
# ]
# else:
# self.v = v
#
# def __sub__(A, B):
# return Mat4([x - y for a, b in zip(A, B) for x, y in zip(a, b)])
#
# def __abs__(A):
# """Maximum metric (see Chebyshev distance)"""
# return max(abs(a) for a in A)
#
# def transpose(self):
# return Mat4(list(zip(*self.v)))
#
# def __matmul__(self, other):
# if isinstance(other, Mat4): # matrix-matrix multiplication
# m = other.transpose()
# return Mat4([m @ row for row in self.v])
# else: # matrix-vector multiplication
# return [sum(a * b for a, b in zip(row, other)) for row in self.v]
#
# def row_major(self):
# return [v for row in self.v for v in row]
#
# def column_major(self):
# return [v for col in zip(*self.v) for v in col]
#
# @classmethod
# def translate(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [1, 0, 0, x],
# [0, 1, 0, y],
# [0, 0, 1, z],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def scale(cls, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# return cls([
# [x, 0, 0, 0],
# [0, y, 0, 0],
# [0, 0, z, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def rotate(cls, angle, x, y, z):
# """Rotation matrix of given angle (radians) around axis (x,y,z)"""
# s = math.sin(angle)
# c = math.cos(angle)
# d = math.sqrt(x*x + y*y + z*z)
# x, y, z = x/d, y/d, z/d
# return cls([
# [x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
# [y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s, 0],
# [z*x*(1-c)-y*s, z*y*(1-c)+x*s, z*z*(1-c)+c, 0],
# [0, 0, 0, 1],
# ])
#
# @classmethod
# def frustrum(cls, left, right, bottom, top, near, far):
# A = (right + left) / (right - left)
# B = (top + bottom) / (top - bottom)
# C = - (far + near) / (far - near)
# D = - (2*far * near) / (far - near)
# return cls([
# [2 * near / (right - left), 0, A, 0],
# [0, 2 * near / (top - bottom), B, 0],
# [0, 0, C, D],
# [0, 0, -1, 0],
# ])
#
# @classmethod
# def ortho(cls, left, right, bottom, top, near, far):
# tx = - (right + left) / (right - left)
# ty = - (top + bottom) / (top - bottom)
# tz = - (far + near) / (far - near)
# return cls([
# [2 / (right - left), 0, 0, tx],
# [0, 2 / (top - bottom), 0, ty],
# [0, 0, -2 / (far - near), tz],
# [0, 0, 0, 1],
# ])
. Output only the next line. | self.rocket_mesh = gspyce.mesh.Square(1) |
Given snippet: <|code_start|>#import twistedpg
#dbpool = adbapi.ConnectionPool("twistedpg", "host=borch.frikanalen.no port=5433 user=postgres password=SECRET dbname=frikanalen") # fyll inn!
def date_to_cache_filename(date):
"""Return a schedule-pickle filename based on a datetime
Not tested"""
return lookup.cache_path(os.path.join(configuration.schedule_cache_root,"plan%4i%02i%02i.pickle" % (date.year, date.month, date.day)))
def get_schedule_by_date(date):
"""Fetch schedule from picklecache by date
Not tested (properly)"""
fn = date_to_cache_filename(date)
try:
f = open(fn, "rb")
except IOError:
return None
l = pickle.load(f)
f.close()
return l
if __name__=="__main__":
date = datetime.date.today()
#date = datetime.date(year=2011, month=1, day=1)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import pickle
import os
import pprint
from twisted.python import log
from twisted.enterprise import adbapi
from . import lookup
from .configuration import configuration
from twisted.internet import reactor
and context:
# Path: src/vision/configuration.py
# class Configuration(object):
# class FKConfiguration(Configuration):
# class DeveloperConfiguration(Configuration):
# def config_strings(self):
# def config_tuples(self):
which might include code, classes, or functions. Output only the next line. | cache_schedule(date, 14).addCallback(lambda x: pprint.pprint(get_schedule_by_date(date)[0])).addCallback(lambda x: reactor.stop()) |
Using the snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_decoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [str(cell, 'utf-8') for cell in row]
def utf_8_decoder(unicode_csv_data):
<|code_end|>
, determine the next line of code. You have imports:
import os
import csv
import random
import logging
import pprint
from . import lookup
from .configuration import configuration
and context (class names, function names, or code) available:
# Path: src/vision/configuration.py
# class Configuration(object):
# class FKConfiguration(Configuration):
# class DeveloperConfiguration(Configuration):
# def config_strings(self):
# def config_tuples(self):
. Output only the next line. | for line in unicode_csv_data: |
Here is a snippet: <|code_start|> raise RuntimeError(
"No default tenant available in this context. Specify one in "
"'DRIFT_DEFAULT_TENANT' environment variable, or use the --tenant command "
"line argument."
)
def uuid_string():
return str(uuid.uuid4()).split("-")[0]
def is_ec2():
"""Naive check if this is an ec2 instance"""
return host_name and host_name.startswith("ip")
def json_response(message, status=200, fields=None):
d = {
"message": message,
"status": status
}
if fields:
d.update(fields)
log.info("Generated json response %s : %s", status, message)
return make_response(jsonify(d), status)
def client_debug_message(message):
"""write a message to the response header for consumption by the client.
Used the Drift-Debug-Message header"""
<|code_end|>
. Write the next line using the current file imports:
import os
import os.path
import logging
import uuid
import json
import six
import textwrap
import flask_smorest
from functools import wraps
from socket import gethostname
from pygments import highlight, util
from pygments.lexers import get_lexer_by_name
from pygments.formatters import get_formatter_by_name, get_all_formatters
from pygments.styles import get_style_by_name, get_all_styles
from flask import g, make_response, jsonify, request, current_app, url_for
from click import echo
from flask_marshmallow.fields import AbsoluteURLFor
from driftconfig.util import get_drift_config
from drift.core.extensions.tenancy import tenant_from_hostname
from drift.flaskfactory import load_flask_config
and context from other files:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
, which may include functions, classes, or code. Output only the next line. | g.client_debug_messages.append(message) |
Predict the next line for this snippet: <|code_start|>
class HTTPMethodTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
self.app = app
app.config['TESTING'] = True
@app.route('/some-endpoint', methods=['PATCH'])
def some_endpoint():
return 'success'
def test_httpmethod(self):
with self.app.test_client() as c:
# Try and fail to access a PATCH endpoint using GET.
resp = c.get('/some-endpoint')
self.assertEqual(resp.status_code, http_client.METHOD_NOT_ALLOWED)
# Try and fail to access a PATCH endpoint using GET and override, but without
# the handler installed.
resp = c.get('/some-endpoint', headers={'X-HTTP-Method-Override': 'PATCH'})
self.assertEqual(resp.status_code, http_client.METHOD_NOT_ALLOWED)
# Install the handler, then try and succeed to access a PATCH endpoint
# using GET and override.
drift_init_extension(self.app, api=None)
resp = c.get('/some-endpoint', headers={'X-HTTP-Method-Override': 'PATCH'})
self.assertEqual(resp.status_code, http_client.OK)
<|code_end|>
with the help of current file imports:
import unittest
from six.moves import http_client
from flask import Flask
from drift.core.extensions.httpmethod import drift_init_extension
and context from other files:
# Path: drift/core/extensions/httpmethod.py
# def drift_init_extension(app, **kwargs):
# app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(resp.data.decode("ascii"), 'success') |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
log = logging.getLogger(__name__)
# defaults when making a new tier
TIER_DEFAULTS = {
"server": "<PLEASE FILL IN>",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import os.path
import importlib
import socket
import getpass
import time
import logging
from contextlib import contextmanager
from six.moves import http_client
from click import echo
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from werkzeug.local import LocalProxy
from sqlalchemy import create_engine
from flask import g, abort
from flask import _app_ctx_stack as stack, current_app
from flask_sqlalchemy import SQLAlchemy
from drift.flaskfactory import load_flask_config
from drift.core.extensions.driftconfig import check_tenant
from alembic.config import Config
from alembic import command
from drift.utils import get_app_root
and context:
# Path: drift/flaskfactory.py
# def load_flask_config(app_root=None):
# if _sticky_app_config is not None:
# return _sticky_app_config
#
# app_root = app_root or get_app_root()
# config_filename = os.path.join(app_root, 'config', 'config.json')
# if not os.path.exists(config_filename):
# raise AppRootNotFound("No config file found at: '{}'".format(config_filename))
#
# log.info("Loading configuration from %s", config_filename)
# with open(config_filename) as f:
# config_values = json.load(f)
#
# config_values['app_root'] = app_root
# return config_values
#
# Path: drift/core/extensions/driftconfig.py
# def check_tenant(f):
# """Make sure current tenant is provided, provisioned and active."""
# @wraps(f)
# def _check(*args, **kwargs):
# if not tenant_from_hostname:
# abort(
# http_client.BAD_REQUEST,
# description="No tenant specified. Please specify one using host name prefix or "
# "the environment variable DRIFT_DEFAULT_TENANT."
# )
#
# conf = current_app.extensions['driftconfig'].get_config()
# if not conf.tenant:
# # This will trigger a proper exception
# try:
# get_config_for_request(allow_missing_tenant=False)
# raise RuntimeError("Should not reach this.")
# except TenantNotConfigured as e:
# abort(http_client.BAD_REQUEST, description=str(e))
#
# check_tenant_state(g.conf.tenant)
# return f(*args, **kwargs)
#
# return _check
which might include code, classes, or functions. Output only the next line. | "database": None, |
Given snippet: <|code_start|> # stamp the db with the latest alembic upgrade version
approot = get_app_root()
ini_path = os.path.join(approot, "alembic.ini")
alembic_cfg = Config(ini_path)
script_path = os.path.join(os.path.split(os.path.abspath(ini_path))[0], "alembic")
alembic_cfg.set_main_option("script_location", script_path)
db_names = alembic_cfg.get_main_option('databases')
connection_string = format_connection_string(params)
alembic_cfg.set_section_option(db_names, "sqlalchemy.url", connection_string)
command.stamp(alembic_cfg, "head")
for schema in SCHEMAS:
# Note that this does not automatically grant on tables added later
sql = '''
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA "{schema}" TO {user};
GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA "{schema}" TO {user};
GRANT ALL ON SCHEMA "{schema}" TO {user};'''.format(schema=schema, user=username)
try:
engine.execute(sql)
except Exception as e:
echo("{!r} {!r}".format(sql, e))
if report:
report.append("Created a new DB: '{}' in {:.3f} seconds.".format(db_name, time.time() - t))
return db_name
def drop_db(_params, force=False):
params = process_connection_values(_params)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import os.path
import importlib
import socket
import getpass
import time
import logging
from contextlib import contextmanager
from six.moves import http_client
from click import echo
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from werkzeug.local import LocalProxy
from sqlalchemy import create_engine
from flask import g, abort
from flask import _app_ctx_stack as stack, current_app
from flask_sqlalchemy import SQLAlchemy
from drift.flaskfactory import load_flask_config
from drift.core.extensions.driftconfig import check_tenant
from alembic.config import Config
from alembic import command
from drift.utils import get_app_root
and context:
# Path: drift/flaskfactory.py
# def load_flask_config(app_root=None):
# if _sticky_app_config is not None:
# return _sticky_app_config
#
# app_root = app_root or get_app_root()
# config_filename = os.path.join(app_root, 'config', 'config.json')
# if not os.path.exists(config_filename):
# raise AppRootNotFound("No config file found at: '{}'".format(config_filename))
#
# log.info("Loading configuration from %s", config_filename)
# with open(config_filename) as f:
# config_values = json.load(f)
#
# config_values['app_root'] = app_root
# return config_values
#
# Path: drift/core/extensions/driftconfig.py
# def check_tenant(f):
# """Make sure current tenant is provided, provisioned and active."""
# @wraps(f)
# def _check(*args, **kwargs):
# if not tenant_from_hostname:
# abort(
# http_client.BAD_REQUEST,
# description="No tenant specified. Please specify one using host name prefix or "
# "the environment variable DRIFT_DEFAULT_TENANT."
# )
#
# conf = current_app.extensions['driftconfig'].get_config()
# if not conf.tenant:
# # This will trigger a proper exception
# try:
# get_config_for_request(allow_missing_tenant=False)
# raise RuntimeError("Should not reach this.")
# except TenantNotConfigured as e:
# abort(http_client.BAD_REQUEST, description=str(e))
#
# check_tenant_state(g.conf.tenant)
# return f(*args, **kwargs)
#
# return _check
which might include code, classes, or functions. Output only the next line. | db_name = params["database"] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
log = logging.getLogger(__name__)
REDIS_DB = 0 # We always use the main redis db for now
# defaults when making a new tier
TIER_DEFAULTS = {
"host": "<PLEASE FILL IN>",
<|code_end|>
. Use current file imports:
(import os
import datetime
import logging
import redis
from six.moves import cPickle as pickle, http_client
from flask import g, abort
from flask import _app_ctx_stack as stack
from werkzeug._compat import integer_types
from werkzeug.local import LocalProxy
from driftconfig.util import get_parameters
from drift.core.extensions.driftconfig import check_tenant)
and context including class names, function names, or small code snippets from other files:
# Path: drift/core/extensions/driftconfig.py
# def check_tenant(f):
# """Make sure current tenant is provided, provisioned and active."""
# @wraps(f)
# def _check(*args, **kwargs):
# if not tenant_from_hostname:
# abort(
# http_client.BAD_REQUEST,
# description="No tenant specified. Please specify one using host name prefix or "
# "the environment variable DRIFT_DEFAULT_TENANT."
# )
#
# conf = current_app.extensions['driftconfig'].get_config()
# if not conf.tenant:
# # This will trigger a proper exception
# try:
# get_config_for_request(allow_missing_tenant=False)
# raise RuntimeError("Should not reach this.")
# except TenantNotConfigured as e:
# abort(http_client.BAD_REQUEST, description=str(e))
#
# check_tenant_state(g.conf.tenant)
# return f(*args, **kwargs)
#
# return _check
. Output only the next line. | "port": 6379, |
Given snippet: <|code_start|>
Set up logging based on config dict.
"""
from __future__ import absolute_import
def get_stream_handler():
"""returns a stream handler with standard formatting for use in local development"""
stream_handler = logging.StreamHandler()
stream_formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)-8s %(name)-15s %(message)s"
)
stream_handler.setFormatter(stream_formatter)
return stream_handler
def get_caller():
"""returns a nice string representing caller for logs
Note: This is heavy"""
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller = "{} ({}#{})".format(calframe[2][3], calframe[2][1], calframe[2][2])
return caller
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import logging
import logging.config
import json
import datetime
import sys
import time
import uuid
import six
import inspect
from logging.handlers import SysLogHandler
from socket import gethostname
from collections import OrderedDict
from functools import wraps
from logstash_formatter import LogstashFormatterV1
from six.moves.urllib.parse import urlsplit
from flask import g, request
from drift.core.extensions.jwt import current_user
from drift.utils import get_tier_name
and context:
# Path: drift/core/extensions/jwt.py
# JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
# JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
# JWT_ALGORITHM = 'RS256'
# JWT_EXPIRATION_DELTA = 60 * 60 * 24
# JWT_LEEWAY = 10
# JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 365
# TRUSTED_ISSUERS = {'drift-base'}
# WHITELIST_ENDPOINTS = [
# r"^api-docs\.", # the marshmalloc documentation endpoint
# r"^static$", # the marshmalloc documentation endpoint
# ]
# SESSION_COOKIE_NAME = 'drift-session'
# ALPHABET = string.ascii_uppercase + string.ascii_lowercase + string.digits + '-_'
# ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
# BASE = len(ALPHABET)
# SIGN_CHARACTER = '$'
# def drift_init_extension(app, api, **kwargs):
# def check_jwt_authorization():
# def query_current_user():
# def requires_auth(got_auth):
# def abort_unauthorized(description):
# def register_auth_provider(app, provider, handler):
# def requires_roles(_roles):
# def wrapper(fn):
# def decorator(*args, **kwargs):
# def jwt_not_required(fn):
# def error_handler(error):
# def _fix_legacy_auth(auth_info):
# def _authenticate(auth_info, conf):
# def post(self, auth_info):
# def post(self, auth_info):
# def get(self):
# def post(self):
# def authenticate_with_provider(auth_info):
# def issue_token(payload, expire=None):
# def get_auth_token_and_type():
# def verify_jwt(token, conf):
# def _is_jwt(token):
# def lookup_bearer_token(token, conf):
# def verify_token(token, auth_type, conf):
# def create_standard_claims(expire=None):
# def cache_token(payload, expire=None):
# def get_cached_token(jti):
# def num_encode(n):
# def num_decode(s):
# def get(self):
# def endpoint_info(current_user):
# class AuthRequestSchema(ma.Schema):
# class Meta:
# class AuthSchema(ma.Schema):
# class Meta:
# class AuthApi(MethodView):
# class AuthLoginApi(MethodView):
# class AuthLogoutApi(MethodView):
# class JwkSchema(ma.Schema):
# class Meta:
# class JwksSchema(ma.Schema):
# class Meta:
# class JWKSApi(MethodView):
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
which might include code, classes, or functions. Output only the next line. | def get_clean_path_from_url(url): |
Given the following code snippet before the placeholder: <|code_start|>
Set up logging based on config dict.
"""
from __future__ import absolute_import
def get_stream_handler():
"""returns a stream handler with standard formatting for use in local development"""
stream_handler = logging.StreamHandler()
stream_formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)-8s %(name)-15s %(message)s"
)
stream_handler.setFormatter(stream_formatter)
return stream_handler
def get_caller():
"""returns a nice string representing caller for logs
Note: This is heavy"""
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
caller = "{} ({}#{})".format(calframe[2][3], calframe[2][1], calframe[2][2])
return caller
<|code_end|>
, predict the next line using imports from the current file:
import os
import logging
import logging.config
import json
import datetime
import sys
import time
import uuid
import six
import inspect
from logging.handlers import SysLogHandler
from socket import gethostname
from collections import OrderedDict
from functools import wraps
from logstash_formatter import LogstashFormatterV1
from six.moves.urllib.parse import urlsplit
from flask import g, request
from drift.core.extensions.jwt import current_user
from drift.utils import get_tier_name
and context including class names, function names, and sometimes code from other files:
# Path: drift/core/extensions/jwt.py
# JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
# JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
# JWT_ALGORITHM = 'RS256'
# JWT_EXPIRATION_DELTA = 60 * 60 * 24
# JWT_LEEWAY = 10
# JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 365
# TRUSTED_ISSUERS = {'drift-base'}
# WHITELIST_ENDPOINTS = [
# r"^api-docs\.", # the marshmalloc documentation endpoint
# r"^static$", # the marshmalloc documentation endpoint
# ]
# SESSION_COOKIE_NAME = 'drift-session'
# ALPHABET = string.ascii_uppercase + string.ascii_lowercase + string.digits + '-_'
# ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
# BASE = len(ALPHABET)
# SIGN_CHARACTER = '$'
# def drift_init_extension(app, api, **kwargs):
# def check_jwt_authorization():
# def query_current_user():
# def requires_auth(got_auth):
# def abort_unauthorized(description):
# def register_auth_provider(app, provider, handler):
# def requires_roles(_roles):
# def wrapper(fn):
# def decorator(*args, **kwargs):
# def jwt_not_required(fn):
# def error_handler(error):
# def _fix_legacy_auth(auth_info):
# def _authenticate(auth_info, conf):
# def post(self, auth_info):
# def post(self, auth_info):
# def get(self):
# def post(self):
# def authenticate_with_provider(auth_info):
# def issue_token(payload, expire=None):
# def get_auth_token_and_type():
# def verify_jwt(token, conf):
# def _is_jwt(token):
# def lookup_bearer_token(token, conf):
# def verify_token(token, auth_type, conf):
# def create_standard_claims(expire=None):
# def cache_token(payload, expire=None):
# def get_cached_token(jti):
# def num_encode(n):
# def num_decode(s):
# def get(self):
# def endpoint_info(current_user):
# class AuthRequestSchema(ma.Schema):
# class Meta:
# class AuthSchema(ma.Schema):
# class Meta:
# class AuthApi(MethodView):
# class AuthLoginApi(MethodView):
# class AuthLogoutApi(MethodView):
# class JwkSchema(ma.Schema):
# class Meta:
# class JwksSchema(ma.Schema):
# class Meta:
# class JWKSApi(MethodView):
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | def get_clean_path_from_url(url): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
@click.command()
@click.option(
'--tier-name', '-t', help='Tier name.'
)
@click.option('--offline', '-o', is_flag=True, help="Run serverless-offline.")
@click.option('--preview', '-p', is_flag=True, help="Preview, do not run 'sls' command.")
@click.option('--verbose', '-v', is_flag=True, help="Verbose output.")
<|code_end|>
using the current file's imports:
import sys
import os
import os.path
import subprocess
import time
import shutil
import yaml
import json
import boto3
import click
from click import echo, secho
from jinja2 import Environment, FileSystemLoader
from driftconfig.config import get_redis_cache_backend
from drift.utils import get_config, pretty
and any relevant context from other files:
# Path: drift/utils.py
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# def pretty(ob, lexer=None):
# """
# Return a pretty console text representation of 'ob'.
# If 'ob' is something else than plain text, specify it in 'lexer'.
#
# If 'ob' is not string, Json lexer is assumed.
#
# If 'pretty.unicorns' are enabled, the world is a happier place.
#
# Command line switches can be used to control highlighting and style.
# """
# if lexer is None:
# if isinstance(ob, six.string_types):
# lexer = 'text'
# else:
# lexer = 'json'
#
# if lexer == 'json':
# ob = json.dumps(ob, indent=4, sort_keys=True)
#
# if got_pygments:
# lexerob = get_lexer_by_name(lexer)
# formatter = get_formatter_by_name(PRETTY_FORMATTER, style=PRETTY_STYLE)
# # from pygments.filters import *
# # lexerob.add_filter(VisibleWhitespaceFilter(spaces=True, tabs=True, newlines=True))
# ret = highlight(ob, lexerob, formatter)
# else:
# if pretty.unicorns:
# pretty.unicorns = False
# print(textwrap.dedent("""\
#
#
# Note! All this blurb would look much better with colors!.
# "Plese Run the following command for the sake of rainbows and unicorns:
# "pip install pygments
#
# """))
#
# ret = ob
#
# return ret.rstrip()
. Output only the next line. | @click.option('--clean', '-c', is_flag=True, help="Clean autogenerated files and folders and exit.") |
Given the code snippet: <|code_start|>#!/usr/bin/env python
@click.command()
@click.option(
'--tier-name', '-t', help='Tier name.'
)
@click.option('--offline', '-o', is_flag=True, help="Run serverless-offline.")
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
import os.path
import subprocess
import time
import shutil
import yaml
import json
import boto3
import click
from click import echo, secho
from jinja2 import Environment, FileSystemLoader
from driftconfig.config import get_redis_cache_backend
from drift.utils import get_config, pretty
and context (functions, classes, or occasionally code) from other files:
# Path: drift/utils.py
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# def pretty(ob, lexer=None):
# """
# Return a pretty console text representation of 'ob'.
# If 'ob' is something else than plain text, specify it in 'lexer'.
#
# If 'ob' is not string, Json lexer is assumed.
#
# If 'pretty.unicorns' are enabled, the world is a happier place.
#
# Command line switches can be used to control highlighting and style.
# """
# if lexer is None:
# if isinstance(ob, six.string_types):
# lexer = 'text'
# else:
# lexer = 'json'
#
# if lexer == 'json':
# ob = json.dumps(ob, indent=4, sort_keys=True)
#
# if got_pygments:
# lexerob = get_lexer_by_name(lexer)
# formatter = get_formatter_by_name(PRETTY_FORMATTER, style=PRETTY_STYLE)
# # from pygments.filters import *
# # lexerob.add_filter(VisibleWhitespaceFilter(spaces=True, tabs=True, newlines=True))
# ret = highlight(ob, lexerob, formatter)
# else:
# if pretty.unicorns:
# pretty.unicorns = False
# print(textwrap.dedent("""\
#
#
# Note! All this blurb would look much better with colors!.
# "Plese Run the following command for the sake of rainbows and unicorns:
# "pip install pygments
#
# """))
#
# ret = ob
#
# return ret.rstrip()
. Output only the next line. | @click.option('--preview', '-p', is_flag=True, help="Preview, do not run 'sls' command.") |
Predict the next line for this snippet: <|code_start|>
log = logging.getLogger(__name__)
APP_INIT_THRESHOLD = .250 # If app creation takes longer a warning is logged.
MODULE_INIT_THRESHOLD = .050 # If module initialization takes longer a warning is logged.
<|code_end|>
with the help of current file imports:
import os
import sys
import logging
import importlib
import json
import os.path
import time
import warnings
import pkgutil
import drift.core.extensions
from flask import Flask
from flask_smorest import Api
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.utils import import_string, ImportStringError
from drift.fixers import ReverseProxied, CustomJSONEncoder
from drift.utils import get_app_root
and context from other files:
# Path: drift/fixers.py
# class ReverseProxied(object):
# '''Wrap the application in this middleware and configure the
# front-end server to add these headers, to let you quietly bind
# this to a URL other than / and to an HTTP scheme that is
# different than what is used locally.
#
# In nginx:
# location /myprefix {
# proxy_pass http://192.168.0.1:5001;
# proxy_set_header Host $host;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Scheme $scheme;
# proxy_set_header X-Script-Name /myprefix;
# }
#
# :param app: the WSGI application
# '''
# def __init__(self, app):
# self.app = app
#
# def __call__(self, environ, start_response):
# script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
# if script_name:
# environ['SCRIPT_NAME'] = script_name
# path_info = environ['PATH_INFO']
# if path_info.startswith(script_name):
# environ['PATH_INFO'] = path_info[len(script_name):]
#
# scheme = environ.get('HTTP_X_SCHEME', environ.get('X-Forwarded-Proto', ''))
# if scheme:
# environ['wsgi.url_scheme'] = scheme
#
# server = environ.get('HTTP_X_FORWARDED_SERVER', '')
# if server:
# environ['HTTP_HOST'] = server
#
# return self.app(environ, start_response)
#
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_app_root():
# """Returns absolute path to the current application root directory."""
# return os.path.expanduser(os.environ.get('DRIFT_APP_ROOT', os.path.abspath('.')))
, which may contain function names, class names, or code. Output only the next line. | class AppRootNotFound(RuntimeError): |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
JWT_ALGORITHM = 'RS256'
JWT_EXPIRATION_DELTA = 60 * 60 * 24
JWT_LEEWAY = 10
# Tis a hack:
JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 365
# Implicitly trust following issuers:
TRUSTED_ISSUERS = {'drift-base'}
# list of regular expression objects matching endpoint definitions
WHITELIST_ENDPOINTS = [
r"^api-docs\.", # the marshmalloc documentation endpoint
r"^static$", # the marshmalloc documentation endpoint
]
SESSION_COOKIE_NAME = 'drift-session'
# List of open endpoints, i.e. not requiring a valid JWT.
# these are the view functions themselves
_open_endpoints = set()
log = logging.getLogger(__name__)
<|code_end|>
. Use current file imports:
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
from drift.flaskfactory import load_flask_config
from driftconfig.util import get_default_drift_config
from driftconfig.util import get_default_drift_config
and context (classes, functions, or code) from other files:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
#
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
# """
# A class to register endpoint defitions functions
# at import time
# """
# def __init__(self):
# self.registry_funcs = []
#
# def init_app(self, app):
# """
# when app is initialized, the registered endpoints are handed to the registry
# """
# for f in self.registry_funcs:
# registry.register_app_endpoints(app, f)
#
# def register(self, f):
# """
# At import time, register endpoint functions here
# """
# self.registry_funcs.append(f)
# return f
#
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | bp = Blueprint('auth', 'Authentication', url_prefix='/auth', description='Authentication endpoints') |
Using the snippet: <|code_start|>JWT_EXPIRATION_DELTA_FOR_SERVICES = 60 * 60 * 24 * 365
# Implicitly trust following issuers:
TRUSTED_ISSUERS = {'drift-base'}
# list of regular expression objects matching endpoint definitions
WHITELIST_ENDPOINTS = [
r"^api-docs\.", # the marshmalloc documentation endpoint
r"^static$", # the marshmalloc documentation endpoint
]
SESSION_COOKIE_NAME = 'drift-session'
# List of open endpoints, i.e. not requiring a valid JWT.
# these are the view functions themselves
_open_endpoints = set()
log = logging.getLogger(__name__)
bp = Blueprint('auth', 'Authentication', url_prefix='/auth', description='Authentication endpoints')
bpjwks = Blueprint('jwks', 'JSON Web Key Set', url_prefix='/.well-known')
endpoints = Endpoints()
def drift_init_extension(app, api, **kwargs):
api.register_blueprint(bp)
api.register_blueprint(bpjwks)
endpoints.init_app(app)
# Flask Secret must be set for cookies and other secret things
# HACK WARNING: It is weirdly difficult to get a drift config at this point.
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
from drift.flaskfactory import load_flask_config
from driftconfig.util import get_default_drift_config
from driftconfig.util import get_default_drift_config
and context (class names, function names, or code) available:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
#
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
# """
# A class to register endpoint defitions functions
# at import time
# """
# def __init__(self):
# self.registry_funcs = []
#
# def init_app(self, app):
# """
# when app is initialized, the registered endpoints are handed to the registry
# """
# for f in self.registry_funcs:
# registry.register_app_endpoints(app, f)
#
# def register(self, f):
# """
# At import time, register endpoint functions here
# """
# self.registry_funcs.append(f)
# return f
#
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | ts = get_default_drift_config() |
Based on the snippet: <|code_start|># Implicitly trust following issuers:
TRUSTED_ISSUERS = {'drift-base'}
# list of regular expression objects matching endpoint definitions
WHITELIST_ENDPOINTS = [
r"^api-docs\.", # the marshmalloc documentation endpoint
r"^static$", # the marshmalloc documentation endpoint
]
SESSION_COOKIE_NAME = 'drift-session'
# List of open endpoints, i.e. not requiring a valid JWT.
# these are the view functions themselves
_open_endpoints = set()
log = logging.getLogger(__name__)
bp = Blueprint('auth', 'Authentication', url_prefix='/auth', description='Authentication endpoints')
bpjwks = Blueprint('jwks', 'JSON Web Key Set', url_prefix='/.well-known')
endpoints = Endpoints()
def drift_init_extension(app, api, **kwargs):
api.register_blueprint(bp)
api.register_blueprint(bpjwks)
endpoints.init_app(app)
# Flask Secret must be set for cookies and other secret things
# HACK WARNING: It is weirdly difficult to get a drift config at this point.
ts = get_default_drift_config()
public_keys = ts.get_table('public-keys')
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
from drift.flaskfactory import load_flask_config
from driftconfig.util import get_default_drift_config
from driftconfig.util import get_default_drift_config
and context (classes, functions, sometimes code) from other files:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
#
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
# """
# A class to register endpoint defitions functions
# at import time
# """
# def __init__(self):
# self.registry_funcs = []
#
# def init_app(self, app):
# """
# when app is initialized, the registered endpoints are handed to the registry
# """
# for f in self.registry_funcs:
# registry.register_app_endpoints(app, f)
#
# def register(self, f):
# """
# At import time, register endpoint functions here
# """
# self.registry_funcs.append(f)
# return f
#
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | row = public_keys.get({ |
Continue the code snippet: <|code_start|>
def drift_init_extension(app, api, **kwargs):
api.register_blueprint(bp)
api.register_blueprint(bpjwks)
endpoints.init_app(app)
# Flask Secret must be set for cookies and other secret things
# HACK WARNING: It is weirdly difficult to get a drift config at this point.
ts = get_default_drift_config()
public_keys = ts.get_table('public-keys')
row = public_keys.get({
'tier_name': get_tier_name(),
'deployable_name': load_flask_config()['name'],
})
# If there is no 'secret_key' specified then session cookies are not supported.
if row and 'secret_key' in row:
app.config['SECRET_KEY'] = row['secret_key']
app.config['SESSION_COOKIE_NAME'] = SESSION_COOKIE_NAME
if not hasattr(app, "jwt_auth_providers"):
app.jwt_auth_providers = {}
# Always trust myself
TRUSTED_ISSUERS.add(app.config['name'])
# Install authorization check
app.before_request(check_jwt_authorization)
<|code_end|>
. Use current file imports:
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
from drift.flaskfactory import load_flask_config
from driftconfig.util import get_default_drift_config
from driftconfig.util import get_default_drift_config
and context (classes, functions, or code) from other files:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
#
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
# """
# A class to register endpoint defitions functions
# at import time
# """
# def __init__(self):
# self.registry_funcs = []
#
# def init_app(self, app):
# """
# when app is initialized, the registered endpoints are handed to the registry
# """
# for f in self.registry_funcs:
# registry.register_app_endpoints(app, f)
#
# def register(self, f):
# """
# At import time, register endpoint functions here
# """
# self.registry_funcs.append(f)
# return f
#
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | def check_jwt_authorization(): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
JWT_VERIFY_CLAIMS = ['signature', 'exp', 'iat']
JWT_REQUIRED_CLAIMS = ['exp', 'iat', 'jti']
JWT_ALGORITHM = 'RS256'
JWT_EXPIRATION_DELTA = 60 * 60 * 24
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
from drift.flaskfactory import load_flask_config
from driftconfig.util import get_default_drift_config
from driftconfig.util import get_default_drift_config
and context (classes, functions, sometimes code) from other files:
# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
#
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
# """
# A class to register endpoint defitions functions
# at import time
# """
# def __init__(self):
# self.registry_funcs = []
#
# def init_app(self, app):
# """
# when app is initialized, the registered endpoints are handed to the registry
# """
# for f in self.registry_funcs:
# registry.register_app_endpoints(app, f)
#
# def register(self, f):
# """
# At import time, register endpoint functions here
# """
# self.registry_funcs.append(f)
# return f
#
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
# '''Extend the JSON encoder to treat date-time objects as strict
# rfc3339 types.
# '''
# def default(self, obj):
# from drift.orm import ModelBase
# if isinstance(obj, date):
# return obj.isoformat() + "Z"
# elif isinstance(obj, ModelBase):
# return obj.as_dict()
# else:
# return JSONEncoder.default(self, obj)
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
. Output only the next line. | JWT_LEEWAY = 10 |
Predict the next line after this snippet: <|code_start|>MASTER_USERNAME = 'postgres'
MASTER_PASSWORD = 'postgres'
def run_migrations():
conf = get_config()
pick_tenant = context.get_x_argument(as_dictionary=True).get('tenant')
dry_run = context.get_x_argument(as_dictionary=True).get('dry-run')
for tenant in conf.tenants:
tenant_name = tenant['tenant_name']
secho("Tenant '{}': ".format(tenant_name), nl=False)
pginfo = tenant.get('postgres')
if not pginfo:
secho("Missing postgres resource info!", fg='red')
continue
if pick_tenant and tenant_name != pick_tenant:
secho("Skipping this tenant.", fg='yellow')
continue
if dry_run:
secho("Dry run, not taking any further actions.")
if context.is_offline_mode():
sql_filename = '{}.{}.sql'.format(conf.tier['tier_name'], tenant_name)
echo("Writing SQL code to ", nl=False)
secho(sql_filename, fg='magenta')
with open(sql_filename, 'w') as out:
<|code_end|>
using the current file's imports:
from click import echo, secho
from alembic import context
from sqlalchemy import pool, create_engine
from drift.flaskfactory import drift_app
from drift.core.resources.postgres import format_connection_string, connect
from drift.utils import get_tier_name, get_config
from drift.orm import Base
and any relevant context from other files:
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
#
# Path: drift/core/resources/postgres.py
# def format_connection_string(postgres_parameters):
# postgres_parameters = process_connection_values(postgres_parameters)
# connection_string = '{driver}://{username}:{password}@{server}:{port}/{database}'.format(**postgres_parameters)
# return connection_string
#
# def connect(params, connect_timeout=None):
#
# engine = create_engine(
# format_connection_string(params),
# echo=ECHO_SQL,
# isolation_level='AUTOCOMMIT',
# connect_args={
# 'connect_timeout': connect_timeout or 10,
# 'application_name': params.get('application_name', 'drift.core.resources.postgres'),
# }
# )
# return engine
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
#
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# Path: drift/orm.py
# class ModelBase(Base):
# def create_date(cls):
# def modify_date(cls):
# def as_dict(self):
. Output only the next line. | context.configure( |
Based on the snippet: <|code_start|> for tenant in conf.tenants:
tenant_name = tenant['tenant_name']
secho("Tenant '{}': ".format(tenant_name), nl=False)
pginfo = tenant.get('postgres')
if not pginfo:
secho("Missing postgres resource info!", fg='red')
continue
if pick_tenant and tenant_name != pick_tenant:
secho("Skipping this tenant.", fg='yellow')
continue
if dry_run:
secho("Dry run, not taking any further actions.")
if context.is_offline_mode():
sql_filename = '{}.{}.sql'.format(conf.tier['tier_name'], tenant_name)
echo("Writing SQL code to ", nl=False)
secho(sql_filename, fg='magenta')
with open(sql_filename, 'w') as out:
context.configure(
url=format_connection_string(pginfo),
output_buffer=out,
target_metadata=Base.metadata,
process_revision_directives=process_revision_directives,
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
<|code_end|>
, predict the immediate next line with the help of imports:
from click import echo, secho
from alembic import context
from sqlalchemy import pool, create_engine
from drift.flaskfactory import drift_app
from drift.core.resources.postgres import format_connection_string, connect
from drift.utils import get_tier_name, get_config
from drift.orm import Base
and context (classes, functions, sometimes code) from other files:
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
#
# Path: drift/core/resources/postgres.py
# def format_connection_string(postgres_parameters):
# postgres_parameters = process_connection_values(postgres_parameters)
# connection_string = '{driver}://{username}:{password}@{server}:{port}/{database}'.format(**postgres_parameters)
# return connection_string
#
# def connect(params, connect_timeout=None):
#
# engine = create_engine(
# format_connection_string(params),
# echo=ECHO_SQL,
# isolation_level='AUTOCOMMIT',
# connect_args={
# 'connect_timeout': connect_timeout or 10,
# 'application_name': params.get('application_name', 'drift.core.resources.postgres'),
# }
# )
# return engine
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
#
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# Path: drift/orm.py
# class ModelBase(Base):
# def create_date(cls):
# def modify_date(cls):
# def as_dict(self):
. Output only the next line. | else: |
Using the snippet: <|code_start|> continue
else:
raise
transaction = connection.begin()
secho("OK", fg="green")
secho("\tRunning migration...", nl=False)
context.configure(
connection=connection,
upgrade_token="%s_upgrades" % tenant_name,
downgrade_token="%s_downgrades" % tenant_name,
target_metadata=Base.metadata,
)
context.run_migrations()
transaction.commit()
connection.close()
secho("OK", fg="green")
def process_revision_directives(context, revision, directives):
if context.config.cmd_opts.autogenerate:
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
def run():
app = drift_app()
run_migrations()
<|code_end|>
, determine the next line of code. You have imports:
from click import echo, secho
from alembic import context
from sqlalchemy import pool, create_engine
from drift.flaskfactory import drift_app
from drift.core.resources.postgres import format_connection_string, connect
from drift.utils import get_tier_name, get_config
from drift.orm import Base
and context (class names, function names, or code) available:
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
#
# Path: drift/core/resources/postgres.py
# def format_connection_string(postgres_parameters):
# postgres_parameters = process_connection_values(postgres_parameters)
# connection_string = '{driver}://{username}:{password}@{server}:{port}/{database}'.format(**postgres_parameters)
# return connection_string
#
# def connect(params, connect_timeout=None):
#
# engine = create_engine(
# format_connection_string(params),
# echo=ECHO_SQL,
# isolation_level='AUTOCOMMIT',
# connect_args={
# 'connect_timeout': connect_timeout or 10,
# 'application_name': params.get('application_name', 'drift.core.resources.postgres'),
# }
# )
# return engine
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
#
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# Path: drift/orm.py
# class ModelBase(Base):
# def create_date(cls):
# def modify_date(cls):
# def as_dict(self):
. Output only the next line. | del app |
Given the following code snippet before the placeholder: <|code_start|>
MASTER_USERNAME = 'postgres'
MASTER_PASSWORD = 'postgres'
def run_migrations():
conf = get_config()
pick_tenant = context.get_x_argument(as_dictionary=True).get('tenant')
dry_run = context.get_x_argument(as_dictionary=True).get('dry-run')
for tenant in conf.tenants:
tenant_name = tenant['tenant_name']
secho("Tenant '{}': ".format(tenant_name), nl=False)
pginfo = tenant.get('postgres')
if not pginfo:
<|code_end|>
, predict the next line using imports from the current file:
from click import echo, secho
from alembic import context
from sqlalchemy import pool, create_engine
from drift.flaskfactory import drift_app
from drift.core.resources.postgres import format_connection_string, connect
from drift.utils import get_tier_name, get_config
from drift.orm import Base
and context including class names, function names, and sometimes code from other files:
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
#
# Path: drift/core/resources/postgres.py
# def format_connection_string(postgres_parameters):
# postgres_parameters = process_connection_values(postgres_parameters)
# connection_string = '{driver}://{username}:{password}@{server}:{port}/{database}'.format(**postgres_parameters)
# return connection_string
#
# def connect(params, connect_timeout=None):
#
# engine = create_engine(
# format_connection_string(params),
# echo=ECHO_SQL,
# isolation_level='AUTOCOMMIT',
# connect_args={
# 'connect_timeout': connect_timeout or 10,
# 'application_name': params.get('application_name', 'drift.core.resources.postgres'),
# }
# )
# return engine
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
#
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# Path: drift/orm.py
# class ModelBase(Base):
# def create_date(cls):
# def modify_date(cls):
# def as_dict(self):
. Output only the next line. | secho("Missing postgres resource info!", fg='red') |
Continue the code snippet: <|code_start|> continue
else:
raise
transaction = connection.begin()
secho("OK", fg="green")
secho("\tRunning migration...", nl=False)
context.configure(
connection=connection,
upgrade_token="%s_upgrades" % tenant_name,
downgrade_token="%s_downgrades" % tenant_name,
target_metadata=Base.metadata,
)
context.run_migrations()
transaction.commit()
connection.close()
secho("OK", fg="green")
def process_revision_directives(context, revision, directives):
if context.config.cmd_opts.autogenerate:
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
def run():
app = drift_app()
run_migrations()
<|code_end|>
. Use current file imports:
from click import echo, secho
from alembic import context
from sqlalchemy import pool, create_engine
from drift.flaskfactory import drift_app
from drift.core.resources.postgres import format_connection_string, connect
from drift.utils import get_tier_name, get_config
from drift.orm import Base
and context (classes, functions, or code) from other files:
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
#
# Path: drift/core/resources/postgres.py
# def format_connection_string(postgres_parameters):
# postgres_parameters = process_connection_values(postgres_parameters)
# connection_string = '{driver}://{username}:{password}@{server}:{port}/{database}'.format(**postgres_parameters)
# return connection_string
#
# def connect(params, connect_timeout=None):
#
# engine = create_engine(
# format_connection_string(params),
# echo=ECHO_SQL,
# isolation_level='AUTOCOMMIT',
# connect_args={
# 'connect_timeout': connect_timeout or 10,
# 'application_name': params.get('application_name', 'drift.core.resources.postgres'),
# }
# )
# return engine
#
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
# """
# Get tier name from environment
# """
# if 'DRIFT_TIER' in os.environ:
# return os.environ['DRIFT_TIER']
#
# if fail_hard:
# raise RuntimeError(
# "No tier specified. Specify one in "
# "'DRIFT_TIER' environment variable, or use the --tier command "
# "line argument."
# )
#
# def get_config(ts=None, tier_name=None, tenant_name=None):
# """Wraps get_drift_config() by providing default values for tier, tenant and drift_app."""
# # Hack: Must delay import this
# # TODO: Stop using this function. Who is doing it anyways?
# from drift.flaskfactory import load_flask_config
# if current_app:
# app_ts = current_app.extensions['driftconfig'].table_store
# if ts is not app_ts:
# log.warning("Mismatching table_store objects in get_config(): ts=%s, app ts=%s", ts, app_ts)
# ts = app_ts
#
# conf = get_drift_config(
# ts=ts,
# tier_name=tier_name or get_tier_name(),
# tenant_name=tenant_name or tenant_from_hostname,
# drift_app=load_flask_config(),
# )
# return conf
#
# Path: drift/orm.py
# class ModelBase(Base):
# def create_date(cls):
# def modify_date(cls):
# def as_dict(self):
. Output only the next line. | del app |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
service_username = "user+pass:$SERVICE$"
service_password = "SERVICE"
local_password = "LOCAL"
AUTH_TEST_PROVIDER = 'unit_test'
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import uuid
import copy
import unittest
import responses
import requests
import re
import jwt
import driftconfig.testhelpers
import logging
from six.moves import http_client
from driftconfig.util import set_sticky_config, get_default_drift_config
from drift.core.extensions.jwt import JWT_ALGORITHM, register_auth_provider
from .flaskfactory import drift_app
from drift.flaskfactory import load_flask_config, set_sticky_app_config
from drift.flaskfactory import set_sticky_app_config
and context from other files:
# Path: drift/core/extensions/jwt.py
# JWT_ALGORITHM = 'RS256'
#
# def register_auth_provider(app, provider, handler):
# if not hasattr(app, "jwt_auth_providers"):
# app.jwt_auth_providers = {}
# app.jwt_auth_providers[provider] = handler
#
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
, which may include functions, classes, or code. Output only the next line. | big_number = 9999999999 |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
service_username = "user+pass:$SERVICE$"
service_password = "SERVICE"
local_password = "LOCAL"
AUTH_TEST_PROVIDER = 'unit_test'
big_number = 9999999999
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import uuid
import copy
import unittest
import responses
import requests
import re
import jwt
import driftconfig.testhelpers
import logging
from six.moves import http_client
from driftconfig.util import set_sticky_config, get_default_drift_config
from drift.core.extensions.jwt import JWT_ALGORITHM, register_auth_provider
from .flaskfactory import drift_app
from drift.flaskfactory import load_flask_config, set_sticky_app_config
from drift.flaskfactory import set_sticky_app_config
and context from other files:
# Path: drift/core/extensions/jwt.py
# JWT_ALGORITHM = 'RS256'
#
# def register_auth_provider(app, provider, handler):
# if not hasattr(app, "jwt_auth_providers"):
# app.jwt_auth_providers = {}
# app.jwt_auth_providers[provider] = handler
#
# Path: drift/flaskfactory.py
# def drift_app(app=None):
# try:
# return _drift_app(app=app)
# except Exception:
# log.exception("Flask app creation failed.")
, which may include functions, classes, or code. Output only the next line. | def uuid_string(): |
Given snippet: <|code_start|>
class ProjectSerializer(serializers.Serializer):
project_name = serializers.CharField(label='Project name', max_length=50)
overlap = serializers.BooleanField(label='Allow class overlap in this project', default=False)
classes = serializers.MultipleChoiceField(choices=[])
# Creation of the project and the required ClassInstance objects
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.models import User
from django.db.models import Q
from rest_framework import serializers
from django.utils import timezone
from aiorest_ws.utils.fields import to_choices_dict, flatten_choices_dict
from annotation_tool import models
import colorsys
and context:
# Path: annotation_tool/models.py
# class Project(models.Model):
# class Class(models.Model):
# class Meta:
# class ClassInstance(models.Model):
# class Meta:
# class Wav(models.Model):
# class Segment(models.Model):
# class Annotation(models.Model):
# class Meta:
# class Event(models.Model):
# class Meta:
# class Region(models.Model):
# class Meta:
# class ClassProminence(models.Model):
# class Meta:
# class Tag(models.Model):
# class Log(models.Model):
# def __str__(self):
# def __str__(self):
# def get_wav_file_path(self, filename):
# def __str__(self):
# def auto_delete_file_on_delete(sender, instance, **kwargs):
# def get_project(self):
# def __str__(self):
# def get_project(self):
# def __str__(self):
# def get_project(self):
# def __str__(self):
# def get_project(self):
# def __str__(self):
# def __str__(self):
# def get_tag_names():
# def __str__(self):
# def __str__(self):
# FINISHED = 'finished'
# UNFINISHED = 'unfinished'
# STATUS_CHOICES = (
# (FINISHED, FINISHED),
# (UNFINISHED, UNFINISHED)
# )
# VERY_LOW = 1
# LOW = 2
# MID = 3
# LOUD = 4
# VERY_LOUD = 5
# PROMINENCE_CHOICES = (
# (VERY_LOW, ''),
# (LOW, ''),
# (MID, ''),
# (LOUD, ''),
# (VERY_LOUD, 'Most salient')
# )
which might include code, classes, or functions. Output only the next line. | def create(self, validated_data): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
<|code_end|>
, determine the next line of code. You have imports:
import logging
import numpy as np
from scipy.integrate import simps
from scipy.interpolate import interp1d
from scipy.ndimage.filters import gaussian_filter
from .helpers import get_smoothed_bins, get_grid_bins, get_latex_table_frame
from .kde import MegKDE
and context (class names, function names, or code) available:
# Path: chainconsumer/helpers.py
# def get_smoothed_bins(smooth, bins, data, weight, marginalised=True, plot=False, pad=False):
# minv, maxv = get_extents(data, weight, plot=plot, pad=pad)
# if smooth is None or not smooth or smooth == 0:
# return np.linspace(minv, maxv, int(bins)), 0
# else:
# return np.linspace(minv, maxv, int((2 if marginalised else 2) * smooth * bins)), smooth
#
# def get_grid_bins(data):
# bin_c = np.sort(np.unique(data))
# delta = 0.5 * (bin_c[1] - bin_c[0])
# bins = np.concatenate((bin_c - delta, [bin_c[-1] + delta]))
# return bins
#
# def get_latex_table_frame(caption, label): # pragma: no cover
# base_string = r"""\begin{table}
# \centering
# \caption{%s}
# \label{%s}
# \begin{tabular}{%s}
# %s \end{tabular}
# \end{table}"""
# return base_string % (caption, label, "%s", "%s")
#
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
. Output only the next line. | self._summaries = { |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
self._summaries = {
"max": self.get_parameter_summary_max,
"mean": self.get_parameter_summary_mean,
"cumulative": self.get_parameter_summary_cumulative,
<|code_end|>
using the current file's imports:
import logging
import numpy as np
from scipy.integrate import simps
from scipy.interpolate import interp1d
from scipy.ndimage.filters import gaussian_filter
from .helpers import get_smoothed_bins, get_grid_bins, get_latex_table_frame
from .kde import MegKDE
and any relevant context from other files:
# Path: chainconsumer/helpers.py
# def get_smoothed_bins(smooth, bins, data, weight, marginalised=True, plot=False, pad=False):
# minv, maxv = get_extents(data, weight, plot=plot, pad=pad)
# if smooth is None or not smooth or smooth == 0:
# return np.linspace(minv, maxv, int(bins)), 0
# else:
# return np.linspace(minv, maxv, int((2 if marginalised else 2) * smooth * bins)), smooth
#
# def get_grid_bins(data):
# bin_c = np.sort(np.unique(data))
# delta = 0.5 * (bin_c[1] - bin_c[0])
# bins = np.concatenate((bin_c - delta, [bin_c[-1] + delta]))
# return bins
#
# def get_latex_table_frame(caption, label): # pragma: no cover
# base_string = r"""\begin{table}
# \centering
# \caption{%s}
# \label{%s}
# \begin{tabular}{%s}
# %s \end{tabular}
# \end{table}"""
# return base_string % (caption, label, "%s", "%s")
#
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
. Output only the next line. | "max_symmetric": self.get_paramater_summary_max_symmetric, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Analysis(object):
summaries = ["max", "mean", "cumulative", "max_symmetric", "max_shortest", "max_central"]
def __init__(self, parent):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import numpy as np
from scipy.integrate import simps
from scipy.interpolate import interp1d
from scipy.ndimage.filters import gaussian_filter
from .helpers import get_smoothed_bins, get_grid_bins, get_latex_table_frame
from .kde import MegKDE
and context (classes, functions, sometimes code) from other files:
# Path: chainconsumer/helpers.py
# def get_smoothed_bins(smooth, bins, data, weight, marginalised=True, plot=False, pad=False):
# minv, maxv = get_extents(data, weight, plot=plot, pad=pad)
# if smooth is None or not smooth or smooth == 0:
# return np.linspace(minv, maxv, int(bins)), 0
# else:
# return np.linspace(minv, maxv, int((2 if marginalised else 2) * smooth * bins)), smooth
#
# def get_grid_bins(data):
# bin_c = np.sort(np.unique(data))
# delta = 0.5 * (bin_c[1] - bin_c[0])
# bins = np.concatenate((bin_c - delta, [bin_c[-1] + delta]))
# return bins
#
# def get_latex_table_frame(caption, label): # pragma: no cover
# base_string = r"""\begin{table}
# \centering
# \caption{%s}
# \label{%s}
# \begin{tabular}{%s}
# %s \end{tabular}
# \end{table}"""
# return base_string % (caption, label, "%s", "%s")
#
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
. Output only the next line. | self.parent = parent |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Plotter(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
self.usetex_old = matplotlib.rcParams["text.usetex"]
<|code_end|>
, generate the next line using the imports in this file:
import logging
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MaxNLocator, ScalarFormatter, LogLocator
from matplotlib.textpath import TextPath
from numpy import meshgrid
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter
from scipy.stats import norm
from .helpers import get_extents, get_smoothed_bins, get_grid_bins
from .kde import MegKDE
and context (functions, classes, or occasionally code) from other files:
# Path: chainconsumer/helpers.py
# def get_extents(data, weight, plot=False, wide_extents=True, tiny=False, pad=False):
# hist, be = np.histogram(data, weights=weight, bins=2000)
# bc = 0.5 * (be[1:] + be[:-1])
# cdf = hist.cumsum()
# cdf = cdf / cdf.max()
# icdf = (1 - cdf)[::-1]
# icdf = icdf / icdf.max()
# cdf = 1 - icdf[::-1]
# threshold = 1e-4 if plot else 1e-5
# if plot and not wide_extents:
# threshold = 0.05
# if tiny:
# threshold = 0.3
# i1 = np.where(cdf > threshold)[0][0]
# i2 = np.where(icdf > threshold)[0][0]
# lower = bc[i1]
# upper = bc[-i2]
# if pad:
# width = upper - lower
# lower -= 0.2 * width
# upper += 0.2 * width
# return lower, upper
#
# def get_smoothed_bins(smooth, bins, data, weight, marginalised=True, plot=False, pad=False):
# minv, maxv = get_extents(data, weight, plot=plot, pad=pad)
# if smooth is None or not smooth or smooth == 0:
# return np.linspace(minv, maxv, int(bins)), 0
# else:
# return np.linspace(minv, maxv, int((2 if marginalised else 2) * smooth * bins)), smooth
#
# def get_grid_bins(data):
# bin_c = np.sort(np.unique(data))
# delta = 0.5 * (bin_c[1] - bin_c[0])
# bins = np.concatenate((bin_c - delta, [bin_c[-1] + delta]))
# return bins
#
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
. Output only the next line. | self.serif_old = matplotlib.rcParams["font.family"] |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class Plotter(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
self.usetex_old = matplotlib.rcParams["text.usetex"]
self.serif_old = matplotlib.rcParams["font.family"]
def plot(
<|code_end|>
. Use current file imports:
(import logging
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MaxNLocator, ScalarFormatter, LogLocator
from matplotlib.textpath import TextPath
from numpy import meshgrid
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter
from scipy.stats import norm
from .helpers import get_extents, get_smoothed_bins, get_grid_bins
from .kde import MegKDE)
and context including class names, function names, or small code snippets from other files:
# Path: chainconsumer/helpers.py
# def get_extents(data, weight, plot=False, wide_extents=True, tiny=False, pad=False):
# hist, be = np.histogram(data, weights=weight, bins=2000)
# bc = 0.5 * (be[1:] + be[:-1])
# cdf = hist.cumsum()
# cdf = cdf / cdf.max()
# icdf = (1 - cdf)[::-1]
# icdf = icdf / icdf.max()
# cdf = 1 - icdf[::-1]
# threshold = 1e-4 if plot else 1e-5
# if plot and not wide_extents:
# threshold = 0.05
# if tiny:
# threshold = 0.3
# i1 = np.where(cdf > threshold)[0][0]
# i2 = np.where(icdf > threshold)[0][0]
# lower = bc[i1]
# upper = bc[-i2]
# if pad:
# width = upper - lower
# lower -= 0.2 * width
# upper += 0.2 * width
# return lower, upper
#
# def get_smoothed_bins(smooth, bins, data, weight, marginalised=True, plot=False, pad=False):
# minv, maxv = get_extents(data, weight, plot=plot, pad=pad)
# if smooth is None or not smooth or smooth == 0:
# return np.linspace(minv, maxv, int(bins)), 0
# else:
# return np.linspace(minv, maxv, int((2 if marginalised else 2) * smooth * bins)), smooth
#
# def get_grid_bins(data):
# bin_c = np.sort(np.unique(data))
# delta = 0.5 * (bin_c[1] - bin_c[0])
# bins = np.concatenate((bin_c - delta, [bin_c[-1] + delta]))
# return bins
#
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
. Output only the next line. | self, |
Here is a snippet: <|code_start|>
def test_megkde_1d_basic():
# Draw from normal, fit KDE, see if sampling from kde's pdf recovers norm
np.random.seed(0)
data = np.random.normal(loc=0, scale=1.0, size=2000)
xs = np.linspace(-3, 3, 100)
ys = MegKDE(data).evaluate(xs)
cs = ys.cumsum()
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from scipy.interpolate import interp1d
from scipy.stats import norm
from chainconsumer.kde import MegKDE
and context from other files:
# Path: chainconsumer/kde.py
# class MegKDE(object):
# """ Matched Elliptical Gaussian Kernel Density Estimator
#
# Adapted from the algorithm specified in the BAMBIS's model specified Wolf 2017
# to support weighted samples.
# """
#
# def __init__(self, train, weights=None, truncation=3.0, nmin=4, factor=1.0):
# """
# Parameters
# ----------
# train : np.ndarray
# The training data set. Should be a 1D array of samples or a 2D array of shape (n_samples, n_dim).
# weights : np.ndarray, optional
# An array of weights. If not specified, equal weights are assumed.
# truncation : float, optional
# The maximum deviation (in sigma) to use points in the KDE
# nmin : int, optional
# The minimum number of points required to estimate the density
# factor : float, optional
# Send bandwidth to this factor of the data estimate
# """
#
# self.truncation = truncation
# self.nmin = nmin
# self.train = train
# if len(train.shape) == 1:
# train = np.atleast_2d(train).T
# self.num_points, self.num_dim = train.shape
# if weights is None:
# weights = np.ones(self.num_points)
# self.weights = weights
#
# self.mean = np.average(train, weights=weights, axis=0)
# dx = train - self.mean
# cov = np.atleast_2d(np.cov(dx.T, aweights=weights))
# self.A = np.linalg.cholesky(np.linalg.inv(cov)) # The sphere-ifying transform
#
# self.d = np.dot(dx, self.A) # Sphere-ified data
# self.tree = spatial.cKDTree(self.d) # kD tree of data
#
# self.sigma = 2.0 * factor * np.power(self.num_points, -1.0 / (4 + self.num_dim)) # Starting sigma (bw) of Gauss
# self.sigma_fact = -0.5 / (self.sigma * self.sigma)
#
# # Cant get normed probs to work atm, turning off for now as I don't need normed pdfs for contours
# # self.norm = np.product(np.diagonal(self.A)) * (2 * np.pi) ** (-0.5 * self.num_dim) # prob norm
# # self.scaling = np.power(self.norm * self.sigma, -self.num_dim)
#
# def evaluate(self, data):
# """ Estimate un-normalised probability density at target points
#
# Parameters
# ----------
# data : np.ndarray
# A `(num_targets, num_dim)` array of points to investigate.
#
# Returns
# -------
# np.ndarray
# A `(num_targets)` length array of estimates
#
# Returns array of probability densities
# """
# if len(data.shape) == 1 and self.num_dim == 1:
# data = np.atleast_2d(data).T
#
# _d = np.dot(data - self.mean, self.A)
#
# # Get all points within range of kernels
# neighbors = self.tree.query_ball_point(_d, self.sigma * self.truncation)
# out = []
# for i, n in enumerate(neighbors):
# if len(n) >= self.nmin:
# diff = self.d[n, :] - _d[i]
# distsq = np.sum(diff * diff, axis=1)
# else:
# # If too few points get nmin closest
# dist, n = self.tree.query(_d[i], k=self.nmin)
# distsq = dist * dist
# out.append(np.sum(self.weights[n] * np.exp(self.sigma_fact * distsq)))
# return np.array(out) # * self.scaling
, which may include functions, classes, or code. Output only the next line. | cs /= cs[-1] |
Given snippet: <|code_start|>def test_colors_rgb2hex_2():
c = np.array([0, 0, 0.5, 1])
colourmap = Colors()
assert colourmap.get_formatted([c])[0] == "#000080"
def test_colors_alias_works():
colourmap = Colors()
assert colourmap.get_formatted(["b"])[0] == colourmap.color_map["blue"]
def test_colors_name_works():
colourmap = Colors()
assert colourmap.get_formatted(["blue"])[0] == colourmap.color_map["blue"]
def test_colors_error_on_garbage():
colourmap = Colors()
with pytest.raises(ValueError):
colourmap.get_formatted(["java"])
def test_clamp1():
assert Colors()._clamp(-10) == 0
def test_clamp2():
assert Colors()._clamp(10) == 10
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import pytest
from chainconsumer.colors import Colors
and context:
# Path: chainconsumer/colors.py
# class Colors(object):
# def __init__(self):
# self.color_map = {
# "blue": "#1976D2",
# "lblue": "#4FC3F7",
# "red": "#E53935",
# "green": "#43A047",
# "lgreen": "#8BC34A",
# "purple": "#673AB7",
# "cyan": "#4DD0E1",
# "magenta": "#E91E63",
# "yellow": "#F2D026",
# "black": "#333333",
# "grey": "#9E9E9E",
# "orange": "#FB8C00",
# "amber": "#FFB300",
# "brown": "#795548",
# }
# self.aliases = {
# "b": "blue",
# "r": "red",
# "g": "green",
# "k": "black",
# "m": "magenta",
# "c": "cyan",
# "o": "orange",
# "y": "yellow",
# "a": "amber",
# "p": "purple",
# "e": "grey",
# "lg": "lgreen",
# "lb": "lblue",
# }
# self.default_colors = ["blue", "lgreen", "red", "purple", "yellow", "grey", "lblue", "magenta", "green", "brown", "black", "orange"]
#
# def format(self, color):
# if isinstance(color, np.ndarray):
# color = rgb2hex(color)
# if color[0] == "#":
# return color
# elif color in self.color_map:
# return self.color_map[color]
# elif color in self.aliases:
# alias = self.aliases[color]
# return self.color_map[alias]
# else:
# raise ValueError("Color %s is not mapped. Please give a hex code" % color)
#
# def get_formatted(self, list_colors):
# return [self.format(c) for c in list_colors]
#
# def get_default(self):
# return self.get_formatted(self.default_colors)
#
# def get_colormap(self, num, cmap_name, scale=0.7): # pragma: no cover
# color_list = self.get_formatted(plt.get_cmap(cmap_name)(np.linspace(0.05, 0.9, num)))
# scales = scale + (1 - scale) * np.abs(1 - np.linspace(0, 2, num))
# scaled = [self.scale_colour(c, s) for c, s in zip(color_list, scales)]
# return scaled
#
# def scale_colour(self, colour, scalefactor): # pragma: no cover
# if isinstance(colour, np.ndarray):
# r, g, b = colour[:3] * 255.0
# else:
# hexx = colour.strip("#")
# if scalefactor < 0 or len(hexx) != 6:
# return hexx
# r, g, b = int(hexx[:2], 16), int(hexx[2:4], 16), int(hexx[4:], 16)
# r = self._clamp(int(r * scalefactor))
# g = self._clamp(int(g * scalefactor))
# b = self._clamp(int(b * scalefactor))
# return "#%02x%02x%02x" % (r, g, b)
#
# def _clamp(self, val, minimum=0, maximum=255):
# if val < minimum:
# return minimum
# if val > maximum:
# return maximum
# return val
which might include code, classes, or functions. Output only the next line. | def test_clamp3(): |
Here is a snippet: <|code_start|>
def test_extents():
xs = np.random.normal(size=1000000)
weights = np.ones(xs.shape)
low, high = get_extents(xs, weights)
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from scipy.stats import norm
from chainconsumer.helpers import get_extents
and context from other files:
# Path: chainconsumer/helpers.py
# def get_extents(data, weight, plot=False, wide_extents=True, tiny=False, pad=False):
# hist, be = np.histogram(data, weights=weight, bins=2000)
# bc = 0.5 * (be[1:] + be[:-1])
# cdf = hist.cumsum()
# cdf = cdf / cdf.max()
# icdf = (1 - cdf)[::-1]
# icdf = icdf / icdf.max()
# cdf = 1 - icdf[::-1]
# threshold = 1e-4 if plot else 1e-5
# if plot and not wide_extents:
# threshold = 0.05
# if tiny:
# threshold = 0.3
# i1 = np.where(cdf > threshold)[0][0]
# i2 = np.where(icdf > threshold)[0][0]
# lower = bc[i1]
# upper = bc[-i2]
# if pad:
# width = upper - lower
# lower -= 0.2 * width
# upper += 0.2 * width
# return lower, upper
, which may include functions, classes, or code. Output only the next line. | threshold = 0.5 |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Comparison(object):
def __init__(self, parent):
self.parent = parent
self._logger = logging.getLogger("chainconsumer")
<|code_end|>
, generate the next line using the imports in this file:
from scipy.interpolate import griddata
from .helpers import get_latex_table_frame
import numpy as np
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: chainconsumer/helpers.py
# def get_latex_table_frame(caption, label): # pragma: no cover
# base_string = r"""\begin{table}
# \centering
# \caption{%s}
# \label{%s}
# \begin{tabular}{%s}
# %s \end{tabular}
# \end{table}"""
# return base_string % (caption, label, "%s", "%s")
. Output only the next line. | def dic(self): |
Predict the next line for this snippet: <|code_start|> new_vocab_file, new_w2v_file, new_metadata_file, in_new_vocab, \
in_new_w2v, in_new_metadata = self.create_vocab(min_frequency,
tokenizer, downcase,
max_vocab_size, name)
self.validate_vocabulary(in_new_vocab, in_new_w2v, in_new_metadata)
def test_create_vocab_default_tokenizer(self):
name, min_frequency, tokenizer, downcase, max_vocab_size = \
'test', 10, 'default', True, None
new_vocab_file, new_w2v_file, new_metadata_file, in_new_vocab, \
in_new_w2v, in_new_metadata = self.create_vocab(min_frequency,
tokenizer, downcase,
max_vocab_size, name)
self.validate_vocabulary(in_new_vocab, in_new_w2v, in_new_metadata)
def test_batch_size(self):
train_batch = self.ds.train.next_batch()
validation_batch = self.ds.validation.next_batch()
test_batch = self.ds.test.next_batch()
assert_equal(len(train_batch.s1), 64)
assert_equal(len(train_batch.s2), 64)
assert_equal(len(train_batch.sim), 64)
assert_equal(len(validation_batch.s1), 64)
assert_equal(len(validation_batch.s2), 64)
assert_equal(len(validation_batch.sim), 64)
assert_equal(len(test_batch.s1), 64)
assert_equal(len(test_batch.s2), 64)
assert_equal(len(test_batch.sim), 64)
<|code_end|>
with the help of current file imports:
import os
from datasets import STS
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools import assert_is_instance
and context from other files:
# Path: datasets/sts.py
# class STS(object):
# def __init__(self, train_validation_split=None, test_split=None,
# use_defaults=True, subset='sts_small'):
# if train_validation_split is not None or test_split is not None or \
# use_defaults is False:
# raise NotImplementedError('This Dataset does not implement '
# 'train_validation_split, test_split or use_defaults as the '
# 'dataset is big enough and uses dedicated splits from '
# 'the original datasets')
# self.dataset_name = 'Semantic Text Similarity - All'
# self.dataset_description = 'This dataset has been generated by ' \
# 'merging MPD, SICK, Quora, StackExchange and and SemEval ' \
# 'datasets. \n It has 258537 Training sentence pairs, 133102 ' \
# 'Test sentence pairs and 59058 validation sentence pairs.'
# self.test_split = 'large'
# self.dataset = subset
# self.dataset_path = os.path.join(datasets.data_root_directory,
# self.dataset)
# self.train_path = os.path.join(self.dataset_path, 'train', 'train.txt')
# self.validation_path = os.path.join(self.dataset_path, 'validation',
# 'validation.txt')
# self.test_path = os.path.join(self.dataset_path, 'test', 'test.txt')
# self.vocab_path = os.path.join(self.dataset_path, 'vocab.txt')
# self.metadata_path = os.path.abspath(os.path.join(self.dataset_path,
# 'metadata.txt'))
# self.w2v_path = os.path.join(self.dataset_path, 'w2v.npy')
#
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.w2v = datasets.load_w2v(self.w2v_path)
#
# self.vocab_size = len(self.w2i)
# self.train = DataSet(self.train_path, (self.w2i, self.i2w))
# self.validation = DataSet(self.validation_path, (self.w2i, self.i2w))
# self.test = DataSet(self.test_path, (self.w2i, self.i2w))
# self.__refresh(load_w2v=False)
#
# def create_vocabulary(self, min_frequency=5, tokenizer='spacy',
# downcase=False, max_vocab_size=None,
# name='new', load_w2v=True):
# self.vocab_path, self.w2v_path, self.metadata_path = \
# datasets.new_vocabulary([self.train_path], self.dataset_path,
# min_frequency, tokenizer=tokenizer, downcase=downcase,
# max_vocab_size=max_vocab_size, name=name)
# self.__refresh(load_w2v)
#
# def __refresh(self, load_w2v):
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.vocab_size = len(self.w2i)
# if load_w2v:
# self.w2v = datasets.preload_w2v(self.w2i)
# datasets.save_w2v(self.w2v_path, self.w2v)
# self.train.set_vocab((self.w2i, self.i2w))
# self.validation.set_vocab((self.w2i, self.i2w))
# self.test.set_vocab((self.w2i, self.i2w))
, which may contain function names, class names, or code. Output only the next line. | train_batch = self.ds.train.next_batch(100) |
Using the snippet: <|code_start|> assert_equal(len(batch.ner1[0]), 20)
assert_equal(len(batch.ner2[0]), 20)
def test_next_batch_big_with_seq_lens(self):
# batch of 128, rescaled, sequence lengths
batch = self.ds.train.next_batch(
batch_size=128,
pad=20)
assert_equal(len(batch.sentences), 128)
assert_equal(len(batch.ner1), 128)
assert_equal(len(batch.ner2), 128)
assert_equal(len(batch.sentences[0]), 20)
assert_equal(len(batch.ner1[0]), 20)
assert_equal(len(batch.ner2[0]), 20)
# This is exactly how it is constructed. Makes no sense. Find other way
#assert_true(lens == [len(x) for x in batch.x])
def test_next_batch_get_raw(self):
batch = self.ds.train.next_batch(raw=True)
assert_is_instance(batch.sentences[0][0], str)
assert_is_instance(batch.ner1[0][0], str)
assert_is_instance(batch.ner2[0][0], str)
class TestGermevalCreateVocabulary(object):
@classmethod
def setup_class(self):
self.ds = Germeval(use_defaults=True)
<|code_end|>
, determine the next line of code. You have imports:
import os
import datasets
from nose.tools import *
from datasets.germeval import Germeval
and context (class names, function names, or code) available:
# Path: datasets/germeval.py
# class Germeval(Acner):
# def __init__(self, train_validate_split=None, test_split=None,
# use_defaults=False, shuffle=True):
# # It makes less sense to try to change the sizes of the stuff in this
# # dataset: it already comes with a Train/Dev/Test cutting
# super(Germeval, self).__init__(None, None, None, None)
#
# def load(self, train_validate_split=None, test_split=None,
# use_defaults=None, shuffle=None):
# # Ignore all the parameters passed to `load`. This method signature is
# # here only to agree with the Base Class' signature.
# # It makes less sense to try to change the sizes of the stuff in this
# # dataset: it already comes with a Train/Dev/Test cutting
#
# all_data = self.load_all_data(self.dataset_path)
#
# self.dump_all_data(*all_data)
# self.initialize_vocabulary()
# self.initialize_datasets(*all_data)
#
# def initialize_datasets(self, train_data, validate_data, test_data, shuffle=True):
# self.train = DataSet(train_data, self.w2i, self.i2w)
# self.validation = DataSet(validate_data, self.w2i, self.i2w)
# self.test = DataSet(test_data, self.w2i, self.i2w)
#
# def initialize_vocabulary(self):
# self.initialize_vocabulary_ll(['texts', 'ner1', 'ner2'], [5,1,1],
# [False, False, False], ['spacy', 'split', 'split'])
#
# def construct(self):
# self.dataset_name = 'GermEval 2014: Named Entity Recognition Shared Task'
# self.dataset_description = \
# 'The GermEval 2014 NER Shared Task builds on a new dataset with' \
# 'German Named Entity annotation [1].' \
# 'This data set is distributed under the CC-BY license.'
# self.dataset_path = os.path.join(datasets.data_root_directory, 'germeval2014')
#
# self.train_path = os.path.join(self.dataset_path, 'train.txt')
# self.validate_path = os.path.join(self.dataset_path, 'validate.txt')
# self.test_path = os.path.join(self.dataset_path, 'test.txt')
#
# self.vocab_paths = [os.path.join(self.dataset_path, 'vocab.txt'),
# os.path.join(self.dataset_path, 'ner1_vocab.txt'),
# os.path.join(self.dataset_path, 'ner2_vocab.txt')]
#
# self.metadata_paths = [os.path.join(self.dataset_path, 'metadata.txt'),
# os.path.join(self.dataset_path, 'ner1_metadata.txt'),
# os.path.join(self.dataset_path, 'ner2_metadata.txt')]
#
# self.w2v_paths = [os.path.join(self.dataset_path, 'w2v.npy'),
# os.path.join(self.dataset_path, 'ner1_w2v.npy'),
# os.path.join(self.dataset_path, 'ner2_w2v.npy')]
#
# self.w2i = [None, None, None]
# self.i2w = [None, None, None]
# self.w2v = [None, None, None]
#
# def load_all_data(self, path):
# file_names = ['NER-de-train.tsv', 'NER-de-dev.tsv', 'NER-de-test.tsv']
# ret = []
# for fn in file_names:
# path_plus_file_name = os.path.join(path, fn)
# with open(path_plus_file_name, 'r', encoding='utf-8') as f:
# csv_reader = csv.reader(f, delimiter='\t', quotechar=None)
#
# # Skip one line
# next(csv_reader)
#
# all_lines = [i for i in csv_reader]
# ret.append(self.group_words_into_sentences(all_lines))
# return ret
#
# def group_words_into_sentences(self, lines):
# words = []
# ner_tags1 = []
# ner_tags2 = []
# ret = []
# curr_sentence = 0
# for i, l in enumerate(lines):
# if len(l) == 0:
# ret.append([" ".join(words),
# " ".join(ner_tags1),
# " ".join(ner_tags2),
# str(curr_sentence)])
# words = []
# ner_tags1 = []
# ner_tags2 = []
# curr_sentence += 1
# continue
#
# if l[0] == '#':
# continue
#
# words.append(l[1])
# ner_tags1.append(l[2])
# ner_tags2.append(l[3])
#
# # Add the last one
# ret.append([" ".join(words),
# " ".join(ner_tags1),
# " ".join(ner_tags2),
# curr_sentence])
# return ret
. Output only the next line. | name = 'test_vocab' |
Based on the snippet: <|code_start|>
class Sick(STS):
def __init__(self, train_validation_split=None, test_split=None,
use_defaults=True, name='sick'):
<|code_end|>
, predict the immediate next line with the help of imports:
from datasets.sts import STS
and context (classes, functions, sometimes code) from other files:
# Path: datasets/sts.py
# class STS(object):
# def __init__(self, train_validation_split=None, test_split=None,
# use_defaults=True, subset='sts_small'):
# if train_validation_split is not None or test_split is not None or \
# use_defaults is False:
# raise NotImplementedError('This Dataset does not implement '
# 'train_validation_split, test_split or use_defaults as the '
# 'dataset is big enough and uses dedicated splits from '
# 'the original datasets')
# self.dataset_name = 'Semantic Text Similarity - All'
# self.dataset_description = 'This dataset has been generated by ' \
# 'merging MPD, SICK, Quora, StackExchange and and SemEval ' \
# 'datasets. \n It has 258537 Training sentence pairs, 133102 ' \
# 'Test sentence pairs and 59058 validation sentence pairs.'
# self.test_split = 'large'
# self.dataset = subset
# self.dataset_path = os.path.join(datasets.data_root_directory,
# self.dataset)
# self.train_path = os.path.join(self.dataset_path, 'train', 'train.txt')
# self.validation_path = os.path.join(self.dataset_path, 'validation',
# 'validation.txt')
# self.test_path = os.path.join(self.dataset_path, 'test', 'test.txt')
# self.vocab_path = os.path.join(self.dataset_path, 'vocab.txt')
# self.metadata_path = os.path.abspath(os.path.join(self.dataset_path,
# 'metadata.txt'))
# self.w2v_path = os.path.join(self.dataset_path, 'w2v.npy')
#
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.w2v = datasets.load_w2v(self.w2v_path)
#
# self.vocab_size = len(self.w2i)
# self.train = DataSet(self.train_path, (self.w2i, self.i2w))
# self.validation = DataSet(self.validation_path, (self.w2i, self.i2w))
# self.test = DataSet(self.test_path, (self.w2i, self.i2w))
# self.__refresh(load_w2v=False)
#
# def create_vocabulary(self, min_frequency=5, tokenizer='spacy',
# downcase=False, max_vocab_size=None,
# name='new', load_w2v=True):
# self.vocab_path, self.w2v_path, self.metadata_path = \
# datasets.new_vocabulary([self.train_path], self.dataset_path,
# min_frequency, tokenizer=tokenizer, downcase=downcase,
# max_vocab_size=max_vocab_size, name=name)
# self.__refresh(load_w2v)
#
# def __refresh(self, load_w2v):
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.vocab_size = len(self.w2i)
# if load_w2v:
# self.w2v = datasets.preload_w2v(self.w2i)
# datasets.save_w2v(self.w2v_path, self.w2v)
# self.train.set_vocab((self.w2i, self.i2w))
# self.validation.set_vocab((self.w2i, self.i2w))
# self.test.set_vocab((self.w2i, self.i2w))
. Output only the next line. | super().__init__(subset=name) |
Continue the code snippet: <|code_start|>
class SemEval(STS):
def __init__(self, train_validation_split=None, test_split=None,
use_defaults=True, name='semEval'):
<|code_end|>
. Use current file imports:
from datasets.sts import STS
and context (classes, functions, or code) from other files:
# Path: datasets/sts.py
# class STS(object):
# def __init__(self, train_validation_split=None, test_split=None,
# use_defaults=True, subset='sts_small'):
# if train_validation_split is not None or test_split is not None or \
# use_defaults is False:
# raise NotImplementedError('This Dataset does not implement '
# 'train_validation_split, test_split or use_defaults as the '
# 'dataset is big enough and uses dedicated splits from '
# 'the original datasets')
# self.dataset_name = 'Semantic Text Similarity - All'
# self.dataset_description = 'This dataset has been generated by ' \
# 'merging MPD, SICK, Quora, StackExchange and and SemEval ' \
# 'datasets. \n It has 258537 Training sentence pairs, 133102 ' \
# 'Test sentence pairs and 59058 validation sentence pairs.'
# self.test_split = 'large'
# self.dataset = subset
# self.dataset_path = os.path.join(datasets.data_root_directory,
# self.dataset)
# self.train_path = os.path.join(self.dataset_path, 'train', 'train.txt')
# self.validation_path = os.path.join(self.dataset_path, 'validation',
# 'validation.txt')
# self.test_path = os.path.join(self.dataset_path, 'test', 'test.txt')
# self.vocab_path = os.path.join(self.dataset_path, 'vocab.txt')
# self.metadata_path = os.path.abspath(os.path.join(self.dataset_path,
# 'metadata.txt'))
# self.w2v_path = os.path.join(self.dataset_path, 'w2v.npy')
#
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.w2v = datasets.load_w2v(self.w2v_path)
#
# self.vocab_size = len(self.w2i)
# self.train = DataSet(self.train_path, (self.w2i, self.i2w))
# self.validation = DataSet(self.validation_path, (self.w2i, self.i2w))
# self.test = DataSet(self.test_path, (self.w2i, self.i2w))
# self.__refresh(load_w2v=False)
#
# def create_vocabulary(self, min_frequency=5, tokenizer='spacy',
# downcase=False, max_vocab_size=None,
# name='new', load_w2v=True):
# self.vocab_path, self.w2v_path, self.metadata_path = \
# datasets.new_vocabulary([self.train_path], self.dataset_path,
# min_frequency, tokenizer=tokenizer, downcase=downcase,
# max_vocab_size=max_vocab_size, name=name)
# self.__refresh(load_w2v)
#
# def __refresh(self, load_w2v):
# self.w2i, self.i2w = datasets.load_vocabulary(self.vocab_path)
# self.vocab_size = len(self.w2i)
# if load_w2v:
# self.w2v = datasets.preload_w2v(self.w2i)
# datasets.save_w2v(self.w2v_path, self.w2v)
# self.train.set_vocab((self.w2i, self.i2w))
# self.validation.set_vocab((self.w2i, self.i2w))
# self.test.set_vocab((self.w2i, self.i2w))
. Output only the next line. | super().__init__(subset=name) |
Given the following code snippet before the placeholder: <|code_start|> pprint (dimension)
if dimension.get('measure_type').startswith('W-'):
continue
attrs = ['name', 'label']
if 'ZI' in dimension.get('measure_type'):
attrs = ['text', 'from', 'until']
dim = {
'name': dimension.get('name'),
'label': dimension.get('title_de'),
'description': dimension.get('definition_de'),
'attributes': attrs
}
dimensions.append(dim)
return dimensions
def generate_cubes():
cubes = []
for cube in get_cubes():
dimensions = []
measures = []
joins = []
mappings = {}
cube_name = cube.get('cube_name')
for dim in get_dimensions(cube_name):
dn = dim.get('dim_name')
if dim.get('dim_measure_type').startswith('W-'):
measures.append(dn)
continue
<|code_end|>
, predict the next line using imports from the current file:
import json
from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions
from pprint import pprint
and context including class names, function names, and sometimes code from other files:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def get_all_dimensions():
# return list(dimension_table)
#
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
. Output only the next line. | dimensions.append(dn) |
Given snippet: <|code_start|>
dimensions.append(dn)
if dim.get('dim_measure_type').startswith('ZI-'):
mappings[dn + '.text'] = 'fact_%s.%s' % (cube_name, dn)
mappings[dn + '.from'] = 'fact_%s.%s_from' % (cube_name, dn)
mappings[dn + '.until'] = 'fact_%s.%s_until' % (cube_name, dn)
else:
tn = 'tbl_' + dn
joins.append({
'master': dn,
'detail': 'value.value_id',
'alias': tn
})
mappings[dn + '.name'] = tn + '.name'
mappings[dn + '.label'] = tn + '.title_de'
cubes.append({
'dimensions': dimensions,
'measures': measures,
'mappings': mappings,
'joins': joins,
'fact': 'fact_%s' % cube_name,
'name': cube.get('cube_name'),
'label': cube.get('statistic_title_de'),
'description': cube.get('statistic_description_de'),
})
return cubes
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions
from pprint import pprint
and context:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def get_all_dimensions():
# return list(dimension_table)
#
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
which might include code, classes, or functions. Output only the next line. | def generate_model(): |
Predict the next line for this snippet: <|code_start|> cubes = []
for cube in get_cubes():
dimensions = []
measures = []
joins = []
mappings = {}
cube_name = cube.get('cube_name')
for dim in get_dimensions(cube_name):
dn = dim.get('dim_name')
if dim.get('dim_measure_type').startswith('W-'):
measures.append(dn)
continue
dimensions.append(dn)
if dim.get('dim_measure_type').startswith('ZI-'):
mappings[dn + '.text'] = 'fact_%s.%s' % (cube_name, dn)
mappings[dn + '.from'] = 'fact_%s.%s_from' % (cube_name, dn)
mappings[dn + '.until'] = 'fact_%s.%s_until' % (cube_name, dn)
else:
tn = 'tbl_' + dn
joins.append({
'master': dn,
'detail': 'value.value_id',
'alias': tn
})
mappings[dn + '.name'] = tn + '.name'
mappings[dn + '.label'] = tn + '.title_de'
cubes.append({
<|code_end|>
with the help of current file imports:
import json
from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions
from pprint import pprint
and context from other files:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def get_all_dimensions():
# return list(dimension_table)
#
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
, which may contain function names, class names, or code. Output only the next line. | 'dimensions': dimensions, |
Here is a snippet: <|code_start|>log = logging.getLogger(__name__)
cube_table = engine.get_table('cube')
statistic_table = engine.get_table('statistic')
dimension_table = engine.get_table('dimension')
value_table = engine.get_table('value')
reference_table = engine.get_table('reference')
def get_fact_table(cube_name):
return engine.get_table('fact_' + cube_name)
def load_cube(cube, update=False):
if cube_table.find_one(name=cube.name) and not update:
return
engine.begin()
cube_table.upsert(cube.to_row(), ['name'])
statistic_table.upsert(cube.metadata.get('statistic'), ['name'])
for dimension in cube.dimensions.values():
dimension_table.upsert(dimension.to_row(), ['name'])
for value in dimension.values:
value_table.upsert(value.to_row(), ['value_id'])
for reference in cube.references:
reference_table.upsert(reference.to_row(), ['cube_name', 'dimension_name'])
<|code_end|>
. Write the next line using the current file imports:
import logging
from sqlalchemy.types import BigInteger
from regenesis.core import app, engine
and context from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
, which may include functions, classes, or code. Output only the next line. | fact_table = get_fact_table(cube.name) |
Continue the code snippet: <|code_start|> params = {}
for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
field = '%s; %s' % (field, unit)
field = '%s (%s)' % (title, field)
type_ = dim.get('ref_type')
if type_ == 'measure':
selects.append(fact_table.columns[name].label(field))
if not readable:
selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
if type_ == 'time':
selects.append(fact_table.columns[name].label(field))
if not readable:
selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
elif type_ == 'axis':
vt = value_table.table.alias('value_%s' % name)
id_col = field + ' - ID' if readable else field + '_CODE'
selects.append(vt.c.name.label(id_col))
selects.append(vt.c.title_de.label(field))
tables.append(vt)
params[name] = name
<|code_end|>
. Use current file imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context (classes, functions, or code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
. Output only the next line. | wheres.append(vt.c.dimension_name==bindparam(name, value=name)) |
Using the snippet: <|code_start|> q = q.where(rt.c.cube_name==cube_name)
res = engine.query(q)
return list(res)
def get_all_dimensions():
return list(dimension_table)
def get_all_statistics():
return list(statistic_table)
def query_cube(cube_name, readable=True):
cube = get_cube(cube_name)
dimensions = get_dimensions(cube_name)
fact_table = get_fact_table(cube_name).table.alias('fact')
q = fact_table.select()
selects, wheres, tables = [], [], [fact_table]
if not readable:
selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
params = {}
for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
<|code_end|>
, determine the next line of code. You have imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context (class names, function names, or code) available:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
. Output only the next line. | field = '%s; %s' % (field, unit) |
Using the snippet: <|code_start|> if not readable:
selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
if type_ == 'time':
selects.append(fact_table.columns[name].label(field))
if not readable:
selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
elif type_ == 'axis':
vt = value_table.table.alias('value_%s' % name)
id_col = field + ' - ID' if readable else field + '_CODE'
selects.append(vt.c.name.label(id_col))
selects.append(vt.c.title_de.label(field))
tables.append(vt)
params[name] = name
wheres.append(vt.c.dimension_name==bindparam(name, value=name))
wheres.append(vt.c.value_id==fact_table.c[name])
q = select(selects, and_(*wheres), tables)
return q, params
#return engine.query(q)
#pprint(list(engine.query(q)))
def generate_cuboids(cube_name):
cube = get_cube(cube_name)
statistic = cube.get('statistic_name')
dimensions = get_dimensions(cube_name)
pprint(dimensions)
#dimensions = [d for d in dimensions if not d['dim_measure_type'].startswith('K-REG-MM')]
<|code_end|>
, determine the next line of code. You have imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context (class names, function names, or code) available:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
. Output only the next line. | dims = [(d['dim_name'], d['ref_type']) for d in dimensions] |
Using the snippet: <|code_start|> res = engine.query(q)
return list(res)
def get_all_dimensions():
return list(dimension_table)
def get_all_statistics():
return list(statistic_table)
def query_cube(cube_name, readable=True):
cube = get_cube(cube_name)
dimensions = get_dimensions(cube_name)
fact_table = get_fact_table(cube_name).table.alias('fact')
q = fact_table.select()
selects, wheres, tables = [], [], [fact_table]
if not readable:
selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
params = {}
for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
field = '%s; %s' % (field, unit)
<|code_end|>
, determine the next line of code. You have imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context (class names, function names, or code) available:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
. Output only the next line. | field = '%s (%s)' % (title, field) |
Given snippet: <|code_start|>def get_dimensions(cube_name):
rt = reference_table.table.alias('ref')
dt = dimension_table.table.alias('dim')
q = rt.join(dt, rt.c.dimension_name==dt.c.name)
q = q.select(use_labels=True)
q = q.where(rt.c.cube_name==cube_name)
res = engine.query(q)
return list(res)
def get_all_dimensions():
return list(dimension_table)
def get_all_statistics():
return list(statistic_table)
def query_cube(cube_name, readable=True):
cube = get_cube(cube_name)
dimensions = get_dimensions(cube_name)
fact_table = get_fact_table(cube_name).table.alias('fact')
q = fact_table.select()
selects, wheres, tables = [], [], [fact_table]
if not readable:
selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
params = {}
for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
which might include code, classes, or functions. Output only the next line. | title = dim.get('dim_title_de') |
Given snippet: <|code_start|> for dim in dimensions:
name = dim.get('dim_name')
field = name.upper()
title = dim.get('dim_title_de')
if readable:
unit = dim.get('ref_unit_name')
if unit is not None:
field = '%s; %s' % (field, unit)
field = '%s (%s)' % (title, field)
type_ = dim.get('ref_type')
if type_ == 'measure':
selects.append(fact_table.columns[name].label(field))
if not readable:
selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
if type_ == 'time':
selects.append(fact_table.columns[name].label(field))
if not readable:
selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
elif type_ == 'axis':
vt = value_table.table.alias('value_%s' % name)
id_col = field + ' - ID' if readable else field + '_CODE'
selects.append(vt.c.name.label(id_col))
selects.append(vt.c.title_de.label(field))
tables.append(vt)
params[name] = name
wheres.append(vt.c.dimension_name==bindparam(name, value=name))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sqlalchemy import func, select, and_
from sqlalchemy.sql.expression import bindparam
from regenesis.core import engine, app
from regenesis.database import cube_table, value_table, statistic_table
from regenesis.database import dimension_table, reference_table, get_fact_table
from pprint import pprint
and context:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
which might include code, classes, or functions. Output only the next line. | wheres.append(vt.c.value_id==fact_table.c[name]) |
Next line prediction: <|code_start|>
def cube_path(catalog, cube_name, ext='raw'):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
catalog,
cube_name + '.' + ext
)
def exists_raw(catalog, cube_name):
<|code_end|>
. Use current file imports:
(import os
import json
from regenesis.core import app)
and context including class names, function names, or small code snippets from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
. Output only the next line. | return os.path.isfile(cube_path(catalog, cube_name)) |
Next line prediction: <|code_start|>warnings.filterwarnings('ignore', 'Unicode type received non-unicode bind param value.')
warnings.filterwarnings('ignore', category=SAWarning)
app = Flask(__name__)
app.config.from_object(default_settings)
app.config.from_envvar('REGENESIS_SETTINGS', silent=True)
engine = dataset.connect(app.config.get('ETL_URL'))
logging.basicConfig(level=logging.INFO)
def get_catalog(catalog_name):
catalog = app.config.get('CATALOG').get(catalog_name)
if catalog is None:
raise ValueError('No such catalog: %s' % catalog_name)
<|code_end|>
. Use current file imports:
(import logging
import warnings;
import dataset
from sqlalchemy.exc import SAWarning
from flask import Flask
from regenesis import default_settings)
and context including class names, function names, or small code snippets from other files:
# Path: regenesis/default_settings.py
# DEBUG = True
# ETL_URL = 'postgresql://localhost/regenesis'
# DATA_DIRECTORY = 'exports/'
# API_ENDPOINT = 'http://api.regenesis.pudo.org'
# CATALOG = {
# 'regional': {
# 'title': 'Regionalstatistik',
# 'url': 'https://www.regionalstatistik.de/',
# 'username': '',
# 'password': '',
# 'export_url': 'https://www.regionalstatistik.de/genesisws/services/ExportService_2010',
# 'index_url': 'https://www.regionalstatistik.de/genesisws/services/RechercheService_2010'
# }
# }
. Output only the next line. | catalog['name'] = catalog_name |
Given the following code snippet before the placeholder: <|code_start|>
def find_denormalized():
res = {}
for cube in get_cubes():
statistic = cube.get('statistic_name')
if not statistic in res:
res[statistic] = {}
<|code_end|>
, predict the next line using imports from the current file:
from pprint import pprint
from regenesis.core import app, engine
from regenesis.database import statistic_table, cube_table, reference_table
from regenesis.queries import get_cubes, get_dimensions
and context including class names, function names, and sometimes code from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
. Output only the next line. | cube_name = cube.get('cube_name') |
Continue the code snippet: <|code_start|>
def find_denormalized():
res = {}
for cube in get_cubes():
statistic = cube.get('statistic_name')
if not statistic in res:
res[statistic] = {}
cube_name = cube.get('cube_name')
dimensions = get_dimensions(cube_name)
#pprint(dimensions)
<|code_end|>
. Use current file imports:
from pprint import pprint
from regenesis.core import app, engine
from regenesis.database import statistic_table, cube_table, reference_table
from regenesis.queries import get_cubes, get_dimensions
and context (classes, functions, or code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
. Output only the next line. | dimensions = [d for d in dimensions if not d['dim_measure_type'].startswith('K-REG-MM')] |
Given the code snippet: <|code_start|>@app.context_processor
def set_template_globals():
return {
'slugify': _slugify,
'API': app.config.get('API_ENDPOINT')
}
@app.template_filter()
def dimension_type_text(type_name):
return _dimension_type_text(type_name)
@app.route('/favicon.ico')
def nop():
return Response(status=404)
@app.route('/api.html')
def page_api():
return render_template('api.html')
@app.route('/faq.html')
def page_faq():
return render_template('faq.html')
@app.route('/contact.html')
<|code_end|>
, generate the next line using the imports in this file:
from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint
and context (functions, classes, or occasionally code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
. Output only the next line. | def page_contact(): |
Next line prediction: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n', '<br>\n')
return Markup(s)
@app.template_filter('wraptext')
<|code_end|>
. Use current file imports:
(from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint)
and context including class names, function names, or small code snippets from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
. Output only the next line. | def text_filter_wrapped(s): |
Given the following code snippet before the placeholder: <|code_start|>
@app.template_filter()
def dimension_type_text(type_name):
return _dimension_type_text(type_name)
@app.route('/favicon.ico')
def nop():
return Response(status=404)
@app.route('/api.html')
def page_api():
return render_template('api.html')
@app.route('/faq.html')
def page_faq():
return render_template('faq.html')
@app.route('/contact.html')
def page_contact():
return render_template('contact.html')
@app.route('/index.html')
def index():
<|code_end|>
, predict the next line using imports from the current file:
from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint
and context including class names, function names, and sometimes code from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
. Output only the next line. | return render_template('index.html') |
Based on the snippet: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n', '<br>\n')
return Markup(s)
@app.template_filter('wraptext')
def text_filter_wrapped(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n \n', '</p><p>\n')
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint
and context (classes, functions, sometimes code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
. Output only the next line. | return Markup('<p>' + s + '</p>') |
Given snippet: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n', '<br>\n')
return Markup(s)
@app.template_filter('wraptext')
def text_filter_wrapped(s):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint
and context:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
which might include code, classes, or functions. Output only the next line. | if s is None: |
Given the following code snippet before the placeholder: <|code_start|>#coding: utf-8
app.register_blueprint(dimension_blueprint)
app.register_blueprint(statistic_blueprint)
app.register_blueprint(catalog_blueprint)
@app.template_filter('text')
def text_filter(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n', '<br>\n')
return Markup(s)
@app.template_filter('wraptext')
def text_filter_wrapped(s):
if s is None:
return ''
if type(s) == 'Markup':
s = s.unescape()
s = s.replace('\n \n', '</p><p>\n')
<|code_end|>
, predict the next line using imports from the current file:
from flask import render_template, Response, request
from flask import session, redirect, flash, Markup, url_for
from regenesis.core import app
from regenesis.util import slugify as _slugify
from regenesis.views.util import dimension_type_text as _dimension_type_text
from regenesis.views.dimension import blueprint as dimension_blueprint
from regenesis.views.statistic import blueprint as statistic_blueprint
from regenesis.views.catalog import blueprint as catalog_blueprint
and context including class names, function names, and sometimes code from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/views/dimension.py
# def get_statistics(dimension_name=None):
# def view(catalog, name):
#
# Path: regenesis/views/statistic.py
# ADM_RANKS = {
# 'gemein': 1,
# 'kreise': 2,
# 'regbez': 3,
# 'dland': 4,
# 'dinsg': 5
# }
# def make_keywords(titles):
# def get_cubes(statistic_name=None):
# def view(catalog, slug, name):
#
# Path: regenesis/views/catalog.py
# def view(catalog):
. Output only the next line. | return Markup('<p>' + s + '</p>') |
Next line prediction: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q, params = query_cube(cube.get('cube_name'), readable=False)
q = 'CREATE VIEW ' + slug + ' AS ' + unicode(q)
engine.query(q, **params)
print [slug, q]
if __name__ == '__main__':
<|code_end|>
. Use current file imports:
(from regenesis.queries import get_cubes, query_cube
from regenesis.core import engine
from regenesis.util import slugify)
and context including class names, function names, or small code snippets from other files:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
. Output only the next line. | make_views() |
Predict the next line for this snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q, params = query_cube(cube.get('cube_name'), readable=False)
q = 'CREATE VIEW ' + slug + ' AS ' + unicode(q)
engine.query(q, **params)
print [slug, q]
if __name__ == '__main__':
<|code_end|>
with the help of current file imports:
from regenesis.queries import get_cubes, query_cube
from regenesis.core import engine
from regenesis.util import slugify
and context from other files:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
, which may contain function names, class names, or code. Output only the next line. | make_views() |
Given snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from regenesis.queries import get_cubes, query_cube
from regenesis.core import engine
from regenesis.util import slugify
and context:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
which might include code, classes, or functions. Output only the next line. | slug = slug.replace('-', '_') |
Continue the code snippet: <|code_start|>
def make_views():
for cube in get_cubes():
slug = slugify(cube.get('statistic_title_de'))
slug = slug.replace('-', '_')
slug = slug + '_' + cube.get('cube_name')
q = 'DROP VIEW IF EXISTS ' + slug
engine.query(q)
q, params = query_cube(cube.get('cube_name'), readable=False)
<|code_end|>
. Use current file imports:
from regenesis.queries import get_cubes, query_cube
from regenesis.core import engine
from regenesis.util import slugify
and context (classes, functions, or code) from other files:
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
. Output only the next line. | q = 'CREATE VIEW ' + slug + ' AS ' + unicode(q) |
Continue the code snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
<|code_end|>
. Use current file imports:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context (classes, functions, or code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
. Output only the next line. | 'dinsg': 5 |
Here is a snippet: <|code_start|> s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_catalog(catalog)
statistic = statistic_table.find_one(name=name)
desc = parse_description(statistic['description_de'] or '')
cubes = []
dims = defaultdict(int)
titles = set([statistic['title_de']])
for cube in get_cubes(name):
cube['dimensions'] = get_dimensions(cube['name'])
for dim in cube['dimensions']:
dim['show'] = True
dims[dim['dim_name']] += 1
titles.add(dim['dim_title_de'])
dim['type_text'] = dimension_type_text(dim['dim_measure_type'])
if dim['dim_measure_type'].startswith('K-REG'):
cube['admlevel'] = (ADM_RANKS[dim['dim_name']], dim['dim_title_de'], dim['dim_name'])
dim['show'] = False
<|code_end|>
. Write the next line using the current file imports:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
, which may include functions, classes, or code. Output only the next line. | cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip() |
Given the following code snippet before the placeholder: <|code_start|> s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_catalog(catalog)
statistic = statistic_table.find_one(name=name)
desc = parse_description(statistic['description_de'] or '')
cubes = []
dims = defaultdict(int)
titles = set([statistic['title_de']])
for cube in get_cubes(name):
cube['dimensions'] = get_dimensions(cube['name'])
for dim in cube['dimensions']:
dim['show'] = True
dims[dim['dim_name']] += 1
titles.add(dim['dim_title_de'])
dim['type_text'] = dimension_type_text(dim['dim_measure_type'])
if dim['dim_measure_type'].startswith('K-REG'):
cube['admlevel'] = (ADM_RANKS[dim['dim_name']], dim['dim_title_de'], dim['dim_name'])
dim['show'] = False
<|code_end|>
, predict the next line using imports from the current file:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context including class names, function names, and sometimes code from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
. Output only the next line. | cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip() |
Next line prediction: <|code_start|> q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_catalog(catalog)
statistic = statistic_table.find_one(name=name)
desc = parse_description(statistic['description_de'] or '')
cubes = []
dims = defaultdict(int)
titles = set([statistic['title_de']])
for cube in get_cubes(name):
cube['dimensions'] = get_dimensions(cube['name'])
for dim in cube['dimensions']:
dim['show'] = True
dims[dim['dim_name']] += 1
titles.add(dim['dim_title_de'])
dim['type_text'] = dimension_type_text(dim['dim_measure_type'])
if dim['dim_measure_type'].startswith('K-REG'):
cube['admlevel'] = (ADM_RANKS[dim['dim_name']], dim['dim_title_de'], dim['dim_name'])
dim['show'] = False
cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip()
cubes.append(cube)
common = [d for d, i in dims.items() if i == len(cubes)]
commons = {}
for cube in cubes:
for dim in cube['dimensions']:
if dim['dim_name'] in common and dim['show']:
#dim['show'] = False
<|code_end|>
. Use current file imports:
(import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description)
and context including class names, function names, or small code snippets from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
. Output only the next line. | commons[dim['dim_name']] = dim |
Here is a snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
'dinsg': 5
}
def make_keywords(titles):
keywords = set()
for t in titles:
t = re.sub('\(.*\)', '', t)
for s in re.split('[\s\.\/]', t):
s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
<|code_end|>
. Write the next line using the current file imports:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
, which may include functions, classes, or code. Output only the next line. | @blueprint.route('/<catalog>/statistics/<slug>.<name>.html') |
Using the snippet: <|code_start|>
def get_cubes(statistic_name=None):
q = cube_table.table.select()
q = q.where(cube_table.table.c.statistic_name==statistic_name)
return list(engine.query(q))
@blueprint.route('/<catalog>/statistics/<slug>.<name>.html')
def view(catalog, slug, name):
catalog = get_catalog(catalog)
statistic = statistic_table.find_one(name=name)
desc = parse_description(statistic['description_de'] or '')
cubes = []
dims = defaultdict(int)
titles = set([statistic['title_de']])
for cube in get_cubes(name):
cube['dimensions'] = get_dimensions(cube['name'])
for dim in cube['dimensions']:
dim['show'] = True
dims[dim['dim_name']] += 1
titles.add(dim['dim_title_de'])
dim['type_text'] = dimension_type_text(dim['dim_measure_type'])
if dim['dim_measure_type'].startswith('K-REG'):
cube['admlevel'] = (ADM_RANKS[dim['dim_name']], dim['dim_title_de'], dim['dim_name'])
dim['show'] = False
cube['stand'] = cube['provenance'].split('hat am')[-1].split('um')[0].strip()
cubes.append(cube)
common = [d for d, i in dims.items() if i == len(cubes)]
commons = {}
for cube in cubes:
<|code_end|>
, determine the next line of code. You have imports:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context (class names, function names, or code) available:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
. Output only the next line. | for dim in cube['dimensions']: |
Given the code snippet: <|code_start|>
blueprint = Blueprint('statistic', __name__)
ADM_RANKS = {
'gemein': 1,
'kreise': 2,
'regbez': 3,
'dland': 4,
'dinsg': 5
}
def make_keywords(titles):
keywords = set()
for t in titles:
t = re.sub('\(.*\)', '', t)
for s in re.split('[\s\.\/]', t):
s = s.strip()
if not len(s) > 2 or s[0] != s[0].upper():
continue
keywords.add(s)
return ', '.join(keywords)
<|code_end|>
, generate the next line using the imports in this file:
import re
from flask import Blueprint, render_template
from collections import defaultdict
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, cube_table
from regenesis.queries import get_dimensions
from regenesis.views.util import parse_description
and context (functions, classes, or occasionally code) from other files:
# Path: regenesis/core.py
# def get_catalog(catalog_name):
#
# Path: regenesis/views/util.py
# def dimension_type_text(type_name):
# if type_name.startswith('ZI-MM'):
# return 'Zeitattribut'
# if type_name.startswith('K-REG'):
# return 'Geographisches Attribut'
# if type_name.startswith('K-SACH'):
# return 'Sachattribut'
# if type_name.startswith('W-MM'):
# return 'Messwert'
# return type_name
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/queries.py
# def get_dimensions(cube_name):
# rt = reference_table.table.alias('ref')
# dt = dimension_table.table.alias('dim')
# q = rt.join(dt, rt.c.dimension_name==dt.c.name)
# q = q.select(use_labels=True)
# q = q.where(rt.c.cube_name==cube_name)
# res = engine.query(q)
# return list(res)
#
# Path: regenesis/views/util.py
# def parse_description(description):
# description = '\n' + description
# parts = SPLITTER.split(description)[1:]
# data = {'method': 'Keine Angaben.', 'type': 'Keine Angaben.'}
# for i in range(0, len(parts), 2):
# section, text = parts[i], parts[i+1].strip()
# if 'Art der Statistik' in section:
# data['type'] = text
# elif 'Rechtsgrundlage' in section:
# data['legal'] = text
# elif 'Bereitstellung' in section:
# data['periodicity'] = text
# elif 'Stichtag' in section:
# data['stag'] = text
# elif 'Regionalebene' in section:
# data['geo'] = text
# elif 'Methodische' in section:
# data['method'] = text
# return data
. Output only the next line. | def get_cubes(statistic_name=None): |
Continue the code snippet: <|code_start|>
client = app.test_client()
def get_output_dir():
return os.path.join( app.root_path, '..', 'build')
#return '/Users/fl/tmp/regenesis'
def freeze_request(req_path):
print "Freezing %s..." % req_path
path = os.path.join(get_output_dir(), req_path.lstrip('/'))
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
fh = open(path, 'w')
<|code_end|>
. Use current file imports:
import os
import shutil
from dataset import freeze
from regenesis.queries import get_all_statistics, get_all_dimensions
from regenesis.queries import get_cubes, query_cube
from regenesis.database import value_table
from regenesis.util import slugify
from regenesis.web import app
from regenesis.core import engine
and context (classes, functions, or code) from other files:
# Path: regenesis/queries.py
# def get_all_statistics():
# return list(statistic_table)
#
# def get_all_dimensions():
# return list(dimension_table)
#
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/web.py
# def text_filter(s):
# def text_filter_wrapped(s):
# def slugify(text):
# def set_template_globals():
# def dimension_type_text(type_name):
# def nop():
# def page_api():
# def page_faq():
# def page_contact():
# def index():
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
. Output only the next line. | res = client.get(req_path) |
Predict the next line after this snippet: <|code_start|>
client = app.test_client()
def get_output_dir():
return os.path.join( app.root_path, '..', 'build')
#return '/Users/fl/tmp/regenesis'
def freeze_request(req_path):
print "Freezing %s..." % req_path
path = os.path.join(get_output_dir(), req_path.lstrip('/'))
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
fh = open(path, 'w')
<|code_end|>
using the current file's imports:
import os
import shutil
from dataset import freeze
from regenesis.queries import get_all_statistics, get_all_dimensions
from regenesis.queries import get_cubes, query_cube
from regenesis.database import value_table
from regenesis.util import slugify
from regenesis.web import app
from regenesis.core import engine
and any relevant context from other files:
# Path: regenesis/queries.py
# def get_all_statistics():
# return list(statistic_table)
#
# def get_all_dimensions():
# return list(dimension_table)
#
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/web.py
# def text_filter(s):
# def text_filter_wrapped(s):
# def slugify(text):
# def set_template_globals():
# def dimension_type_text(type_name):
# def nop():
# def page_api():
# def page_faq():
# def page_contact():
# def index():
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
. Output only the next line. | res = client.get(req_path) |
Based on the snippet: <|code_start|> if os.path.isdir(outdir):
shutil.rmtree(outdir)
shutil.copytree(app.static_folder, outdir)
freeze_request('/index.html')
freeze_request('/faq.html')
freeze_request('/api.html')
freeze_request('/contact.html')
for catalog in ['regional']:
freeze_request('/%s/index.html' % catalog)
for dimension in get_all_dimensions():
freeze_request('/%s/dimensions/%s.html' % (catalog, dimension['name']))
for statistic in get_all_statistics():
slug = slugify(statistic['title_de'])
freeze_request('/%s/statistics/%s.%s.html' % (catalog, slug, statistic['name']))
def freeze_data():
print "Freezing dimension values..."
prefix = os.path.join(get_output_dir(), 'data', 'dimensions')
freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.csv', format='csv')
freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.json', format='json')
print "Freezing cubes..."
for cube in get_cubes():
prefix = os.path.join(get_output_dir(), 'data',
cube['statistic_name'],
cube['cube_name'])
slug = slugify(cube['statistic_title_de'])
for (text, rb) in [('labeled', True), ('raw', False)]:
q, ps = query_cube(cube['cube_name'], readable=rb)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import shutil
from dataset import freeze
from regenesis.queries import get_all_statistics, get_all_dimensions
from regenesis.queries import get_cubes, query_cube
from regenesis.database import value_table
from regenesis.util import slugify
from regenesis.web import app
from regenesis.core import engine
and context (classes, functions, sometimes code) from other files:
# Path: regenesis/queries.py
# def get_all_statistics():
# return list(statistic_table)
#
# def get_all_dimensions():
# return list(dimension_table)
#
# Path: regenesis/queries.py
# def get_cubes(cube_name=None):
# ct = cube_table.table.alias('cube')
# st = statistic_table.table.alias('statistic')
# q = ct.join(st, st.c.name==ct.c.statistic_name)
# q = q.select(use_labels=True)
# if cube_name is not None:
# q = q.where(ct.c.name==cube_name)
# return list(engine.query(q))
#
# def query_cube(cube_name, readable=True):
# cube = get_cube(cube_name)
# dimensions = get_dimensions(cube_name)
#
# fact_table = get_fact_table(cube_name).table.alias('fact')
# q = fact_table.select()
# selects, wheres, tables = [], [], [fact_table]
#
# if not readable:
# selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID'))
#
# params = {}
# for dim in dimensions:
# name = dim.get('dim_name')
# field = name.upper()
# title = dim.get('dim_title_de')
#
# if readable:
# unit = dim.get('ref_unit_name')
# if unit is not None:
# field = '%s; %s' % (field, unit)
# field = '%s (%s)' % (title, field)
#
# type_ = dim.get('ref_type')
# if type_ == 'measure':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY'))
# selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR'))
# if type_ == 'time':
# selects.append(fact_table.columns[name].label(field))
# if not readable:
# selects.append(fact_table.columns[name + '_from'].label(field + '_FROM'))
# selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL'))
# elif type_ == 'axis':
# vt = value_table.table.alias('value_%s' % name)
# id_col = field + ' - ID' if readable else field + '_CODE'
# selects.append(vt.c.name.label(id_col))
# selects.append(vt.c.title_de.label(field))
# tables.append(vt)
# params[name] = name
# wheres.append(vt.c.dimension_name==bindparam(name, value=name))
# wheres.append(vt.c.value_id==fact_table.c[name])
#
# q = select(selects, and_(*wheres), tables)
# return q, params
# #return engine.query(q)
# #pprint(list(engine.query(q)))
#
# Path: regenesis/database.py
# def get_fact_table(cube_name):
# def load_cube(cube, update=False):
#
# Path: regenesis/util.py
# def make_key(*a):
# def flatten(d, sep='_'):
#
# Path: regenesis/web.py
# def text_filter(s):
# def text_filter_wrapped(s):
# def slugify(text):
# def set_template_globals():
# def dimension_type_text(type_name):
# def nop():
# def page_api():
# def page_faq():
# def page_contact():
# def index():
#
# Path: regenesis/core.py
# def get_catalog(catalog_name):
. Output only the next line. | fn = '%s-%s-%s.csv' % (slug, cube['cube_name'], text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.