Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
Parameters
----------
x, y, z : float or array_like of floats
Cartesian coordinates, in metres.
"""
@u.quantity_input
def __init__(self, x: u.m, y: u.m, z: u.m):
self._x = x
self._y = y
self._z = z
@classmethod
@u.quantity_input
def from_geodetic(cls, lat: u.deg, lon: u.deg, height: u.m, ell):
"""Position, initialized from geodetic coordinates.
Parameters
----------
lat : ~astropy.units.Quantity
Geodetic latitude.
lon : ~astropy.units.Quantity
Geodetic longitude.
height : ~astropy.units.Quantity
Geodetic height.
ell : instance of the `pygeoid.coordinates.ellipsoid.Ellipsoid`
Reference ellipsoid to which geodetic coordinates are referenced to.
"""
<|code_end|>
using the current file's imports:
import astropy.units as u
from pygeoid.coordinates import transform
and any relevant context from other files:
# Path: pygeoid/coordinates/transform.py
# def geodetic_to_cartesian(
# lat: u.deg, lon: u.deg, height: u.m, ell):
# def _cartesian_to_geodetic(x, y, z, ell, degrees=True):
# def cartesian_to_geodetic(x: u.m, y: u.m, z: u.m, ell):
# def cartesian_to_spherical(x: u.m, y: u.m, z: u.m):
# def spherical_to_cartesian(lat: u.deg, lon: u.deg, radius: u.m):
# def cartesian_to_ellipsoidal(x: u.m, y: u.m, z: u.m, ell):
# def ellipsoidal_to_cartesian(rlat: u.deg, lon: u.deg, u_ax: u.m, ell):
# def geodetic_to_spherical(lat: u.deg, lon: u.deg, height: u.m, ell):
# def spherical_to_geodetic(lat: u.deg, lon: u.deg, radius: u.m, ell):
# def geodetic_to_ellipsoidal(lat: u.deg, lon: u.deg, height: u.m, ell):
# def ellipsoidal_to_geodetic(rlat: u.deg, lon: u.deg, u_ax: u.m, ell):
# def _ecef_to_enu_rotation_matrix(lat: u.deg, lon: u.deg):
# def ecef_to_enu(x: u.m, y: u.m, z: u.m, origin: tuple[u.deg, u.deg, u.m], ell=None):
# def enu_to_ecef(x: u.m, y: u.m, z: u.m, origin: tuple[u.deg, u.deg, u.m], ell=None):
# def geodetic_to_enu(lat: u.deg, lon: u.deg, height: u.m,
# origin: tuple[u.deg, u.deg, u.m], ell):
# def enu_to_geodetic(x: u.m, y: u.m, z: u.m, origin: tuple[u.deg, u.deg, u.m], ell):
# def polar_to_cartesian(theta: u.deg, radius: u.m):
# def cartesian_to_polar(x: u.m, y: u.m):
# N = ell.prime_vertical_curvature_radius(lat)
# D = (k * _np.sqrt(x**2 + y**2)) / (k + e2)
. Output only the next line. | x, y, z = transform.geodetic_to_cartesian(lat, lon, height, ell=ell) |
Based on the snippet: <|code_start|> uncertainty=1e9,
reference='Jacobson, R. A., Antreasian, P. G., Bordi, J. J., '
'Criddle, K. E., Ionasescu,R., Jones, J. B., Mackenzie, R. A., '
'Pelletier, F. J., Owen Jr., W. M., Roth, D. C., and Stauch, J. R., '
'(2006), The gravity field of the Saturnian system from satellite '
'observations and spacecraft tracking data, '
'Astronomical Journal 132, 6.')
gm_uranus = _Constant(
abbrev='gm_uranus',
name='Gravitational constant times the mass of Uranus',
value=5793951.3e9,
unit='m3 / s2',
uncertainty=4.4e9,
reference='Jacobson, R. A. (2014), The Orbits of the Uranian '
'Satellites and Rings, the Gravity Field of the Uranian System, '
'and the Orientation of the Pole of Uranus, '
'Astronomical Journal 148, 76-88.')
gm_neptune = _Constant(
abbrev='gm_neptune',
name='Gravitational constant times the mass of Neptune',
value=6835100e9,
unit='m3 / s2',
uncertainty=10e9,
reference='Jacobson, R. A. (2009), The Orbits of the Neptunian '
'Satellites and the Orientation of the Pole of Neptune, '
'Astronomical Journal 137, 4322.')
<|code_end|>
, predict the immediate next line with the help of imports:
from astropy.constants import Constant as _Constant
from pyshtools.constants.Moon import gm as gm_moon
from .iers2010 import GM_sun as gm_sun
from pyshtools.constants.Mars import gm as gm_mars
from pyshtools.constants.Venus import gm as gm_venus
from pyshtools.constants.Mercury import gm as gm_mercury
and context (classes, functions, sometimes code) from other files:
# Path: pygeoid/constants/iers2010.py
# G = _Constant(
# abbrev='G',
# name='Constant of gravitation',
# value=6.67428e-11,
# unit='m**3 / (kg * s**2)',
# uncertainty=6.7e-15,
# reference='IERS Conventions(2010), '
# 'IERS Technical Note 36, '
# 'Verlagdes Bundesamts für Kartographie und Geodäsie, '
# 'Frankfurt am Main, Germany.')
# L_G = _Constant(
# abbrev='L_G',
# name='1 - d(TT)/d(TCG)',
# value=6.969290134e-10,
# unit='',
# uncertainty=0,
# reference='IERS Conventions(2010), '
# 'IERS Technical Note 36, '
# 'Verlagdes Bundesamts für Kartographie und Geodäsie, '
# 'Frankfurt am Main, Germany.')
# W0 = _Constant(
# abbrev='W0',
# name='Potential of the geoid',
# value=62636856.0,
# unit='m**2 / s**2',
# uncertainty=0.5,
# reference='IERS Conventions(2010), '
# 'IERS Technical Note 36, '
# 'Verlagdes Bundesamts für Kartographie und Geodäsie, '
# 'Frankfurt am Main, Germany.')
# R0 = _Constant(
# abbrev='R0',
# name='Geopotential scale factor (GM/W0)',
# value=6363672.6,
# unit='m',
# uncertainty=0.1,
# reference='IERS Conventions(2010), '
# 'IERS Technical Note 36, '
# 'Verlagdes Bundesamts für Kartographie und Geodäsie, '
# 'Frankfurt am Main, Germany.')
# H = _Constant(
# abbrev='H',
# name='Dynamical flattening',
# value=3273795e-9,
# unit='',
# uncertainty=1e-9,
# reference='IERS Conventions(2010), '
# 'IERS Technical Note 36, '
# 'Verlagdes Bundesamts für Kartographie und Geodäsie, '
# 'Frankfurt am Main, Germany.')
# DEGREE2_LOVE_NUMBERS = {'k': k2, 'l': l2, 'h': h2}
# def tcg_to_tt(x):
# def l2_shida_number(lat: _u.deg = None) -> _u.dimensionless_unscaled:
# def h2_love_number(lat: _u.deg = None) -> _u.dimensionless_unscaled:
. Output only the next line. | _gm_body = {'moon' : gm_moon, 'sun' : gm_sun, 'mars' : gm_mars, |
Next line prediction: <|code_start|>
def test_lplm_lplm_d_equality():
l_max = 2190
x_test = np.linspace(-1, 1, 10)
for x in x_test:
<|code_end|>
. Use current file imports:
(import numpy as np
from pygeoid.sharm import legendre)
and context including class names, function names, or small code snippets from other files:
# Path: pygeoid/sharm/legendre.py
# def _lplm_index(lmax):
# def lplm_d1(lmax, x):
# def lplm(lmax, x):
. Output only the next line. | lpmn_1 = legendre.lplm_d1(l_max, x)[0] |
Using the snippet: <|code_start|> 3 * cpsi * np.log(spsi2 + spsi2**2)
@u.quantity_input
def derivative_spherical_distance(self, spherical_distance):
r"""Evaluate Stokes's spherical kernel derivative.
The derivative of the Stokes function is the Vening-Meinesz function.
Parameters
----------
spherical_distance : ~astropy.units.Quantity
Spherical distance.
Notes
-----
The derivative of Stokes's kernel is the Vening-Meinesz and it depends
on the spherical distance :math:`\psi` by [1]_:
.. math ::
\dfrac{d S\left(\psi\right)}{d\psi} = - \dfrac{\cos{(\psi /
2)}}{2\sin^2{(\psi / 2)}} + 8\sin{\psi} -
6\cos{(\psi / 2)} - 3\dfrac{1 - \sin{(\psi / 2)}}{\sin{\psi}} +
3\sin{\psi}\ln{\left[\sin{(\psi/2)} + \sin^2{(\psi/2)}\right]}.
References
----------
.. [1] Heiskanen WA, Moritz H (1967) Physical geodesy.
Freeman, San Francisco
"""
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import astropy.units as u
from pygeoid.integrals.core import SphericalKernel
from pygeoid.integrals.veningmeinesz import VeningMeineszKernel
and context (class names, function names, or code) available:
# Path: pygeoid/integrals/core.py
# class SphericalKernel(Kernel):
# """Base class for all spherical kernels.
#
# """
#
# def _check_spherical_distance(self, spherical_distance):
# """Check spherical distance.
#
# """
# # if not np.logical_and(spherical_distance >= 0 * u.deg,
# # spherical_distance <= np.pi * u.rad).any():
# if not Angle(spherical_distance).is_within_bounds(0 * u.deg,
# 180 * u.deg):
# raise ValueError('spherical_distance must be between 0 and 180 degrees.')
#
# return spherical_distance
#
# Path: pygeoid/integrals/veningmeinesz.py
# class VeningMeineszKernel(SphericalKernel):
# r"""Vening Meinesz kernel class.
#
# """
#
# _name = 'Vening Meinesz'
#
# @u.quantity_input
# def kernel(self, spherical_distance: u.deg):
# r"""Evaluate Vening Meinesz kernel.
#
# Parameters
# ----------
# spherical_distance : float or array_like of floats
# Spherical distance, in radians.
# degrees : bool, optional
# If True, the spherical distance is given in degrees,
# otherwise radians.
#
# Notes
# -----
# The derivative is the Vening-Meinesz and it depends
# on the spherical distance :math:`\psi` by [1]_:
#
# .. math ::
# V\left(\psi\right) =
# \dfrac{d S\left(\psi\right)}{d\psi} = - \dfrac{\cos{(\psi /
# 2)}}{2\sin^2{(\psi / 2)}} + 8\sin{\psi} -
# 6\cos{(\psi / 2)} - 3\dfrac{1 - \sin{(\psi / 2)}}{\sin{\psi}} +
# 3\sin{\psi}\ln{\left[\sin{(\psi/2)} + \sin^2{(\psi/2)}\right]},
#
# which is the derivative of Stokes's kernel with respect to
# :math:`\psi`.
#
# References
# ----------
# .. [1] Heiskanen WA, Moritz H (1967) Physical geodesy.
# Freeman, San Francisco
#
# """
#
# psi = self._check_spherical_distance(
# spherical_distance=spherical_distance)
#
# cpsi2 = np.cos(psi / 2)
# spsi2 = np.sin(psi / 2)
# spsi = np.sin(psi)
#
# return -0.5 * cpsi2 / spsi2**2 + 8 * spsi - 6 * cpsi2 -\
# 3 * (1 - spsi2) / spsi + 3 * spsi * np.log(spsi2 + spsi2**2)
. Output only the next line. | return VeningMeineszKernel().kernel( |
Using the snippet: <|code_start|>
def test_bounds():
bounds = (0, 100, 0, 100, 0, 100)
density = 2670
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import numpy as np
from pygeoid.simple import prism
and context (class names, function names, or code) available:
# Path: pygeoid/simple/prism.py
# def _limits_sum(function):
# def wraper(self, x, y, z):
# def _radius(x, y, z):
# def __init__(self, bounds, density=1.0):
# def potential(self, x, y, z):
# def gx(self, x, y, z):
# def gy(self, x, y, z):
# def gz(self, x, y, z):
# def gxx(self, x, y, z):
# def gyy(self, x, y, z):
# def gzz(self, x, y, z):
# def gxz(self, x, y, z):
# def gyz(self, x, y, z):
# def gxy(self, x, y, z):
# class Prism(ForwardModel):
. Output only the next line. | p = prism.Prism(bounds, density=density) |
Given the code snippet: <|code_start|>
Will expand this function later to aid interactivity/updates.
"""
print("Training bot. CTRL-C to stop training.")
bot.train(dataset)
def start_chatting(bot):
"""Talk to bot.
Will re-add teacher mode soon. Old implementation in _decode.py."""
print("Initiating chat session.")
print("Your bot has a temperature of %.2f." % bot.temperature, end=" ")
if bot.temperature < 0.1:
print("Not very adventurous, are we?")
elif bot.temperature < 0.7:
print("This should be interesting . . . ")
else:
print("Enjoy your gibberish!")
bot.chat()
def main(argv):
if FLAGS.debug:
# Setting to '0': all tensorflow messages are logged.
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
logging.basicConfig(level=logging.INFO)
# Extract the merged configs/dictionaries.
<|code_end|>
, generate the next line using the imports in this file:
import os
import data
import chatbot
import logging
import tensorflow as tf
from pydoc import locate
from utils import io_utils
and context (functions, classes, or occasionally code) from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
. Output only the next line. | config = io_utils.parse_config(flags=FLAGS) |
Using the snippet: <|code_start|> @abstractproperty
def idx_to_word(self):
"""Return dictionary map from int -> str. """
pass
@abstractproperty
def name(self):
"""Returns name of the dataset as a string."""
pass
@abstractproperty
def max_seq_len(self):
"""Return the maximum allowed sentence length."""
pass
class Dataset(DatasetABC):
def __init__(self, dataset_params):
"""Implements the general of subset of operations that all
dataset subclasses can use.
Args:
dataset_params: dictionary of configuration parameters.
See DEFAULT_FULL_CONFIG at top of file for supported keys.
"""
self.__dict__['__params'] = Dataset.fill_params(dataset_params)
# We query io_utils to ensure all data files are organized properly,
# and io_utils returns the paths to files of interest.
<|code_end|>
, determine the next line of code. You have imports:
import os
import logging
import numpy as np
import tensorflow as tf
from utils import io_utils
from abc import ABCMeta, abstractmethod, abstractproperty
from chatbot.globals import DEFAULT_FULL_CONFIG
and context (class names, function names, or code) available:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
. Output only the next line. | id_paths, vocab_path, vocab_size = io_utils.prepare_data( |
Given snippet: <|code_start|>"""ABC for datasets. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import logging
import numpy as np
import tensorflow as tf
from utils import io_utils
from abc import ABCMeta, abstractmethod, abstractproperty
from chatbot.globals import DEFAULT_FULL_CONFIG
and context:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
which might include code, classes, or functions. Output only the next line. | DEFAULT_PARAMS = DEFAULT_FULL_CONFIG['dataset_params'] |
Given the code snippet: <|code_start|> lengths: (dict) parsed context feature from protobuf file.
Supports keys in LENGTHS.
sequences: (dict) parsed feature_list from protobuf file.
Supports keys in SEQUENCES.
"""
with tf.variable_scope(name + '_pipeline'):
proto_text = self._read_line(self.paths[name + '_tfrecords'])
context_pair, sequence_pair = self._assign_queue(proto_text)
input_length = tf.add(context_pair['encoder_sequence_length'],
context_pair['decoder_sequence_length'],
name=name + 'length_add')
return self._padded_bucket_batches(input_length, sequence_pair)
@property
def encoder_inputs(self):
"""Determines, via tensorflow control structures, which part of the pipeline to run
and retrieve inputs to a Model encoder component. """
if not self.is_chatting:
return self._cond_input('encoder')
else:
return self._user_input
@property
def decoder_inputs(self):
"""Determines, via tensorflow control structures, which part of the pipeline to run
and retrieve inputs to a Model decoder component. """
if not self.is_chatting:
return self._cond_input('decoder')
else:
# In a chat session, we just give the bot the go-ahead to respond!
<|code_end|>
, generate the next line using the imports in this file:
import logging
import tensorflow as tf
from utils import io_utils
from tensorflow.contrib.training import bucket_by_sequence_length
and context (functions, classes, or occasionally code) from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
. Output only the next line. | return tf.convert_to_tensor([[io_utils.GO_ID]]) |
Predict the next line for this snippet: <|code_start|> graph_def,
input_map=None,
return_elements=None,
op_dict=None,
producer_op_list=None
)
return graph
def unfreeze_bot(frozen_model_path):
"""Restores the frozen graph from file and grabs input/output tensors needed to
interface with a bot for conversation.
Args:
frozen_model_path: location of protobuf file containing frozen graph.
Returns:
outputs: tensor that can be run in a session.
"""
bot_graph = load_graph(frozen_model_path)
tensors = {'inputs': bot_graph.get_tensor_by_name('import/input_pipeline/user_input:0'),
'outputs': bot_graph.get_tensor_by_name('import/outputs:0')}
return tensors, bot_graph
def unfreeze_and_chat(frozen_model_path):
"""Summon a bot back from the dead and have a nice lil chat with it."""
tensor_dict, graph = unfreeze_bot(frozen_model_path)
<|code_end|>
with the help of current file imports:
import numpy as np
import tensorflow as tf
import os
import re
from utils import io_utils
from pydoc import locate
and context from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
, which may contain function names, class names, or code. Output only the next line. | config = io_utils.parse_config(pretrained_dir=frozen_model_path) |
Given the following code snippet before the placeholder: <|code_start|>
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
TEST_DATA_DIR = os.path.join(TEST_DIR, 'test_data')
TEST_CONFIG_PATH = os.path.join(TEST_DIR, 'test_config.yml')
logging.basicConfig(level=logging.INFO)
_flag_names = ["pretrained_dir",
"config",
"debug",
"model",
"model_params",
"dataset",
"dataset_params"]
Flags = namedtuple('Flags', _flag_names)
TEST_FLAGS = Flags(pretrained_dir=None,
config=TEST_CONFIG_PATH,
debug=True,
model='{}',
dataset='{}',
model_params={'ckpt_dir': os.path.join(TEST_DIR, 'out')},
dataset_params={'data_dir': TEST_DATA_DIR})
def create_bot(flags=TEST_FLAGS, return_dataset=False):
"""Chatbot factory: Creates and returns a fresh bot. Nice for
testing specific methods quickly.
"""
# Wipe the graph and update config if needed.
tf.reset_default_graph()
<|code_end|>
, predict the next line using imports from the current file:
import logging
import data
import chatbot
import os
import pdb
import tensorflow as tf
from pydoc import locate
from utils import io_utils
from chatbot.globals import DEFAULT_FULL_CONFIG
from collections import namedtuple
and context including class names, function names, and sometimes code from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
. Output only the next line. | config = io_utils.parse_config(flags=flags) |
Given snippet: <|code_start|>
def create_bot(flags=TEST_FLAGS, return_dataset=False):
"""Chatbot factory: Creates and returns a fresh bot. Nice for
testing specific methods quickly.
"""
# Wipe the graph and update config if needed.
tf.reset_default_graph()
config = io_utils.parse_config(flags=flags)
io_utils.print_non_defaults(config)
# Instantiate a new dataset.
print("Setting up", config['dataset'], "dataset.")
dataset_class = locate(config['dataset']) \
or getattr(data, config['dataset'])
dataset = dataset_class(config['dataset_params'])
# Instantiate a new chatbot.
print("Creating", config['model'], ". . . ")
bot_class = locate(config['model']) or getattr(chatbot, config['model'])
bot = bot_class(dataset, config)
if return_dataset:
return bot, dataset
else:
return bot
def update_config(config, **kwargs):
new_config = {}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import data
import chatbot
import os
import pdb
import tensorflow as tf
from pydoc import locate
from utils import io_utils
from chatbot.globals import DEFAULT_FULL_CONFIG
from collections import namedtuple
and context:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
which might include code, classes, or functions. Output only the next line. | for key in DEFAULT_FULL_CONFIG: |
Given the code snippet: <|code_start|> # ================================================
flags = TEST_FLAGS
flags = flags._replace(model_params=dict(
ckpt_dir=os.path.join(TEST_DIR, 'out'),
reset_model=True,
steps_per_ckpt=20,
max_steps=40))
bot = create_bot(flags)
self.assertEqual(bot.reset_model, True)
# Simulate small train sesh on bot.
bot.train()
# ================================================
# 2. Recreate a chattable bot.
# ================================================
# Recreate bot from scratch with decode set to true.
logging.info("Resetting default graph . . . ")
tf.reset_default_graph()
flags = flags._replace(model_params={
**flags.model_params,
'reset_model': False,
'decode': True,
'max_steps': 100,
'steps_per_ckpt': 50})
self.assertTrue(flags.model_params.get('decode'))
bot = create_bot(flags)
self.assertTrue(bot.is_chatting)
self.assertTrue(bot.decode)
print("Testing quick chat sesh . . . ")
<|code_end|>
, generate the next line using the imports in this file:
import time
import logging
import unittest
import numpy as np
import tensorflow as tf
import pydoc
import data
import chatbot
from pydoc import locate
from utils import io_utils, bot_freezer
from tests.utils import *
and context (functions, classes, or occasionally code) from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: utils/bot_freezer.py
# def load_graph(frozen_model_dir):
# def unfreeze_bot(frozen_model_path):
# def unfreeze_and_chat(frozen_model_path):
# def as_words(sentence):
# def respond_to(sentence):
# def get_frozen_vocab(config):
# def __init__(self, frozen_model_dir, vocab_size):
# def as_words(self, sentence):
# def __call__(self, sentence):
# class FrozenBot:
. Output only the next line. | config = io_utils.parse_config(flags=flags) |
Next line prediction: <|code_start|>
print("Testing quick chat sesh . . . ")
config = io_utils.parse_config(flags=flags)
dataset_class = pydoc.locate(config['dataset']) \
or getattr(data, config['dataset'])
dataset = dataset_class(config['dataset_params'])
test_input = "How's it going?"
encoder_inputs = io_utils.sentence_to_token_ids(
tf.compat.as_bytes(test_input),
dataset.word_to_idx)
encoder_inputs = np.array([encoder_inputs[::-1]])
bot.pipeline._feed_dict = {
bot.pipeline.user_input: encoder_inputs}
# Get output sentence from the chatbot.
_, _, response = bot.step(forward_only=True)
print("Robot:", dataset.as_words(response[0][:-1]))
# ================================================
# 3. Freeze the chattable bot.
# ================================================
logging.info("Calling bot.freeze() . . . ")
bot.freeze()
# ================================================
# 4. Try to unfreeze and use it.
# ================================================
logging.info("Resetting default graph . . . ")
tf.reset_default_graph()
logging.info("Importing frozen graph into default . . . ")
<|code_end|>
. Use current file imports:
(import time
import logging
import unittest
import numpy as np
import tensorflow as tf
import pydoc
import data
import chatbot
from pydoc import locate
from utils import io_utils, bot_freezer
from tests.utils import *)
and context including class names, function names, or small code snippets from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: utils/bot_freezer.py
# def load_graph(frozen_model_dir):
# def unfreeze_bot(frozen_model_path):
# def unfreeze_and_chat(frozen_model_path):
# def as_words(sentence):
# def respond_to(sentence):
# def get_frozen_vocab(config):
# def __init__(self, frozen_model_dir, vocab_size):
# def as_words(self, sentence):
# def __call__(self, sentence):
# class FrozenBot:
. Output only the next line. | frozen_graph = bot_freezer.load_graph(bot.ckpt_dir) |
Using the snippet: <|code_start|> def test_basic(self):
"""Instantiate all supported datasets and check they satisfy basic conditions.
THIS MAY TAKE A LONG TIME TO COMPLETE. Since we are testing that the
supported datasets can be instantiated successfully, it necessarily
means that the data must exist in proper format. Since the program
will generate the proper format(s) if not found, this will take
about 15 minutes if run from a completely fresh setup.
Otherwise, a few seconds. :)
"""
if os.getenv('DATA') is None \
and not os.path.exists('/home/brandon/Datasets'):
print('To run this test, please enter the path to your datasets: ')
data_dir = input()
else:
data_dir = '/home/brandon/Datasets'
for dataset_name in self.supported_datasets:
logging.info('Testing %s', dataset_name)
incomplete_params = {
'vocab_size': 40000,
'max_seq_len': 10}
self.assertIsNotNone(incomplete_params)
dataset_class = getattr(data, dataset_name)
# User must specify data_dir, which we have not done yet.
self.assertRaises(ValueError, dataset_class, incomplete_params)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import pdb
import sys
import os
import unittest
import tensorflow as tf
import chatbot
import data
from pydoc import locate
from utils import io_utils
from chatbot.globals import DEFAULT_FULL_CONFIG
from tests.utils import *
and context (class names, function names, or code) available:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
. Output only the next line. | config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> Otherwise, a few seconds. :)
"""
if os.getenv('DATA') is None \
and not os.path.exists('/home/brandon/Datasets'):
print('To run this test, please enter the path to your datasets: ')
data_dir = input()
else:
data_dir = '/home/brandon/Datasets'
for dataset_name in self.supported_datasets:
logging.info('Testing %s', dataset_name)
incomplete_params = {
'vocab_size': 40000,
'max_seq_len': 10}
self.assertIsNotNone(incomplete_params)
dataset_class = getattr(data, dataset_name)
# User must specify data_dir, which we have not done yet.
self.assertRaises(ValueError, dataset_class, incomplete_params)
config = io_utils.parse_config(flags=TEST_FLAGS)
dataset_params = config.get('dataset_params')
dataset_params['data_dir'] = os.path.join(
data_dir,
dataset_name.lower())
dataset = dataset_class(dataset_params)
# Ensure all params from DEFAULT_FULL_CONFIG['dataset_params']
# are set to a value in our dataset object.
<|code_end|>
. Use current file imports:
(import logging
import pdb
import sys
import os
import unittest
import tensorflow as tf
import chatbot
import data
from pydoc import locate
from utils import io_utils
from chatbot.globals import DEFAULT_FULL_CONFIG
from tests.utils import *)
and context including class names, function names, or small code snippets from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
. Output only the next line. | for default_key in DEFAULT_FULL_CONFIG['dataset_params']: |
Using the snippet: <|code_start|>
class TestLegacyModels(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
self.seq_len = 20
<|code_end|>
, determine the next line of code. You have imports:
import os
import tensorflow as tf
import unittest
import logging
import sys
import data
import chatbot
from utils import io_utils
from tests.utils import TEST_FLAGS
and context (class names, function names, or code) available:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: tests/utils.py
# TEST_FLAGS = Flags(pretrained_dir=None,
# config=TEST_CONFIG_PATH,
# debug=True,
# model='{}',
# dataset='{}',
# model_params={'ckpt_dir': os.path.join(TEST_DIR, 'out')},
# dataset_params={'data_dir': TEST_DATA_DIR})
. Output only the next line. | self.config = io_utils.parse_config(flags=TEST_FLAGS) |
Using the snippet: <|code_start|>
class TestLegacyModels(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
self.seq_len = 20
<|code_end|>
, determine the next line of code. You have imports:
import os
import tensorflow as tf
import unittest
import logging
import sys
import data
import chatbot
from utils import io_utils
from tests.utils import TEST_FLAGS
and context (class names, function names, or code) available:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: tests/utils.py
# TEST_FLAGS = Flags(pretrained_dir=None,
# config=TEST_CONFIG_PATH,
# debug=True,
# model='{}',
# dataset='{}',
# model_params={'ckpt_dir': os.path.join(TEST_DIR, 'out')},
# dataset_params={'data_dir': TEST_DATA_DIR})
. Output only the next line. | self.config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> time=tf.TensorShape(None),
alignments=tf.TensorShape([None, None]),
alignment_history=())
class BasicRNNCell(RNNCell):
"""Same as tf.contrib.rnn.BasicRNNCell, rewritten for clarity.
For example, many TF implementations have leftover code debt from past
versions, so I wanted to show what is actually going on, with the fluff
removed. Also, I've removed generally accepted values from parameters/args
in favor of just setting them.
"""
def __init__(self, num_units, reuse=None):
self._num_units = num_units
self._reuse = reuse
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
def __call__(self, inputs, state, scope=None):
"""Most basic RNN. Define as:
output = new_state = act(W * input + U * state + B).
"""
<|code_end|>
. Use current file imports:
(import tensorflow as tf
from tensorflow.python.util import nest
from tensorflow.python.ops import rnn_cell_impl
from chatbot.components import bot_ops
from tensorflow.contrib.rnn import RNNCell
from tensorflow.contrib.rnn import GRUCell, MultiRNNCell, LSTMStateTuple
from tensorflow.python.layers import core as layers_core
from tensorflow.contrib.seq2seq import DynamicAttentionWrapper \
as AttentionWrapper
from tensorflow.contrib.seq2seq import DynamicAttentionWrapperState \
as AttentionWrapperState
from tensorflow.contrib.seq2seq import AttentionWrapper
from tensorflow.contrib.seq2seq import AttentionWrapperState)
and context including class names, function names, or small code snippets from other files:
# Path: chatbot/components/bot_ops.py
# def dynamic_sampled_softmax_loss(labels, logits, output_projection, vocab_size,
# from_scratch=False, num_samples=512, name=None):
# def _dynamic_sampled_map(labels, logits, output_projection, vocab_size,
# num_samples=512, name=None):
# def sampled_loss(elem):
# def _dynamic_sampled_from_scratch(labels, logits, output_projection, vocab_size,
# num_samples, name=None):
# def sampled_loss_single_timestep(args):
# def fn(s_i): return tf.where(targets == s_i, tf.ones_like(targets), tf.zeros_like(targets))
# def cross_entropy_sequence_loss(logits, labels, weights):
# def dot_prod(x, y):
# def bahdanau_score(attention_dim, h_j, s_i):
# def luong_score(attention_dim, h_j, s_i):
# def linear_map(args, output_size, biases=None):
# _W = tf.nn.embedding_lookup(weights, all_ids, partition_strategy='div')
# W = {'targets': tf.slice(_W, begin=[0, 0], size=[batch_size, state_size]),
# 'samples': tf.slice(_W, begin=[batch_size, 0], size=[num_samples, state_size])}
# F = tf.concat([true_logits, sampled_logits], 1)
. Output only the next line. | output = tf.tanh(bot_ops.linear_map( |
Predict the next line for this snippet: <|code_start|> config_path=None,
return_config=True,
**kwargs):
"""Update contents of a config file, overwriting any that
match those in kwargs.
Args:
config: (dict) subset of DEFAULT_FULL_CONFIG.
config_path: (str) location of a yaml config file.
return_config: (bool) whether or not to return the config dictionary.
kwargs: key-value pairs to update in the config dictionary and/or file.
At least one of {config, config_path} must be not None. If both are not
None, then we update the config dictionary with the kwargs, and then set
the file at config_path to match updated dictionary contents.
In other words, if config is not None, we do won't consider the contents
of config_path when doing the updates.
"""
if config is None and config_path is None:
raise ValueError("Configuration info not given to update_config.")
if config is None:
# Grab the current config file contents into a dictionary.
config = get_yaml_config(config_path)
logging.info("Updating config values %r for %s",
list(kwargs.keys()), config_path)
# Update its values with those in kwargs.
<|code_end|>
with the help of current file imports:
import os
import re
import sys
import yaml
import copy
import pandas as pd
import logging
import tensorflow as tf
from collections import Counter, namedtuple
from tensorflow.python.platform import gfile
from subprocess import Popen, PIPE
from chatbot.globals import DEFAULT_FULL_CONFIG
and context from other files:
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
, which may contain function names, class names, or code. Output only the next line. | for top_level_key in DEFAULT_FULL_CONFIG: |
Predict the next line after this snippet: <|code_start|>"""Used by legacy_models for decoding. Not needed by DynamicBot."""
def decode(bot, dataset, teacher_mode=True):
"""Runs a chat session between the given chatbot and user."""
# We decode one sentence at a time.
bot.batch_size = 1
# Decode from standard input.
print("Type \"exit\" to exit.")
print("Write stuff after the \">\" below and I, your robot friend, will respond.")
<|code_end|>
using the current file's imports:
import tensorflow as tf
import logging
import os
import sys
import numpy as np
from utils import io_utils
from utils.io_utils import sentence_to_token_ids, get_vocab_dicts
and any relevant context from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: utils/io_utils.py
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# """Convert a string to list of integers representing token-ids.
#
# For example, a sentence "I have a dog" may become tokenized into
# ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2,
# "a": 4, "dog": 7"} this function will return [1, 2, 4, 7].
#
# Args:
# sentence: the sentence in bytes format to convert to token-ids.
# vocabulary: a dictionary mapping tokens to integers.
# normalize_digits: Boolean; if true, all digits are replaced by 0s.
#
# Returns:
# a list of integers, the token-ids for the sentence.
# """
# words = basic_tokenizer(sentence)
#
# if not normalize_digits:
# return [vocabulary.get(w, UNK_ID) for w in words]
#
# # Normalize digits by 0 before looking words up in the vocabulary.
# return [vocabulary.get(_DIGIT_RE.sub(b"0", w), UNK_ID) for w in words]
#
# def get_vocab_dicts(vocabulary_path):
# """Returns word_to_idx, idx_to_word dictionaries given vocabulary.
#
# Args:
# vocabulary_path: path to the file containing the vocabulary.
#
# Returns:
# a pair: the vocabulary (a dictionary mapping string to integers), and
# the reversed vocabulary (a list, which reverses the vocabulary mapping).
#
# Raises:
# ValueError: if the provided vocabulary_path does not exist.
# """
# if gfile.Exists(vocabulary_path):
# rev_vocab = []
# with gfile.GFile(vocabulary_path, mode="rb") as f:
# rev_vocab.extend(f.readlines())
# rev_vocab = [tf.compat.as_bytes(line.strip()) for line in rev_vocab]
# vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
# return vocab, rev_vocab
# else:
# raise ValueError("Vocabulary file %s not found.", vocabulary_path)
. Output only the next line. | sentence = io_utils.get_sentence() |
Here is a snippet: <|code_start|>"""Used by legacy_models for decoding. Not needed by DynamicBot."""
def decode(bot, dataset, teacher_mode=True):
"""Runs a chat session between the given chatbot and user."""
# We decode one sentence at a time.
bot.batch_size = 1
# Decode from standard input.
print("Type \"exit\" to exit.")
print("Write stuff after the \">\" below and I, your robot friend, will respond.")
sentence = io_utils.get_sentence()
while sentence:
# Convert input sentence to token-ids.
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
import logging
import os
import sys
import numpy as np
from utils import io_utils
from utils.io_utils import sentence_to_token_ids, get_vocab_dicts
and context from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: utils/io_utils.py
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# """Convert a string to list of integers representing token-ids.
#
# For example, a sentence "I have a dog" may become tokenized into
# ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2,
# "a": 4, "dog": 7"} this function will return [1, 2, 4, 7].
#
# Args:
# sentence: the sentence in bytes format to convert to token-ids.
# vocabulary: a dictionary mapping tokens to integers.
# normalize_digits: Boolean; if true, all digits are replaced by 0s.
#
# Returns:
# a list of integers, the token-ids for the sentence.
# """
# words = basic_tokenizer(sentence)
#
# if not normalize_digits:
# return [vocabulary.get(w, UNK_ID) for w in words]
#
# # Normalize digits by 0 before looking words up in the vocabulary.
# return [vocabulary.get(_DIGIT_RE.sub(b"0", w), UNK_ID) for w in words]
#
# def get_vocab_dicts(vocabulary_path):
# """Returns word_to_idx, idx_to_word dictionaries given vocabulary.
#
# Args:
# vocabulary_path: path to the file containing the vocabulary.
#
# Returns:
# a pair: the vocabulary (a dictionary mapping string to integers), and
# the reversed vocabulary (a list, which reverses the vocabulary mapping).
#
# Raises:
# ValueError: if the provided vocabulary_path does not exist.
# """
# if gfile.Exists(vocabulary_path):
# rev_vocab = []
# with gfile.GFile(vocabulary_path, mode="rb") as f:
# rev_vocab.extend(f.readlines())
# rev_vocab = [tf.compat.as_bytes(line.strip()) for line in rev_vocab]
# vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
# return vocab, rev_vocab
# else:
# raise ValueError("Vocabulary file %s not found.", vocabulary_path)
, which may include functions, classes, or code. Output only the next line. | token_ids = sentence_to_token_ids(tf.compat.as_bytes(sentence), dataset.word_to_idx) |
Continue the code snippet: <|code_start|>"""Tests for various operations done on config (yaml) dictionaries in project."""
dir = os.path.dirname(os.path.realpath(__file__))
class TestConfig(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
with open(TEST_CONFIG_PATH) as f:
# So we can always reference default vals.
self.test_config = yaml.load(f)
def test_merge_params(self):
"""Checks how parameters passed to TEST_FLAGS interact with
parameters from yaml files. Expected behavior is that any
params in TEST_FLAGS will override those from files, but that
all values from file will be used if not explicitly passed to
TEST_FLAGS.
"""
<|code_end|>
. Use current file imports:
import os
import pydoc
import yaml
import logging
import unittest
import tensorflow as tf
import chatbot
import data
from utils import io_utils
from tests.utils import *
and context (classes, functions, or code) from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
. Output only the next line. | config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> def check_input_lengths(self, inputs, expected_lengths):
"""
Raises:
ValueError: if length of encoder_inputs, decoder_inputs, or
target_weights disagrees with bucket size for the specified bucket_id.
"""
for input, length in zip(inputs, expected_lengths):
if len(input) != length:
raise ValueError("Input length doesn't match bucket size:"
" %d != %d." % (len(input), length))
def get_batch(self, data, bucket_id):
"""Get a random batch of data from the specified bucket, prepare for step.
Args:
data: tuple of len(self.buckets). data[bucket_id] == [source_ids, target_ids]
bucket_id: integer, which bucket to get the batch for.
Returns:
The triple (encoder_inputs, decoder_inputs, target_weights) for
the constructed batch that has the proper format to call step(...) later.
"""
encoder_size, decoder_size = self.buckets[bucket_id]
encoder_inputs, decoder_inputs = [], []
# Get a random batch of encoder and decoder inputs from data,
# pad them if needed, reverse encoder inputs and add GO to decoder.
for _ in range(self.batch_size):
encoder_input, decoder_input = random.choice(data[bucket_id])
# BasicEncoder inputs are padded and then reversed.
<|code_end|>
. Use current file imports:
(import os
import copy
import yaml
import random
import subprocess
import numpy as np
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.python.client import device_lib
from utils import io_utils
from chatbot.components import *
from chatbot.globals import DEFAULT_FULL_CONFIG, OPTIMIZERS
from chatbot.legacy._train import train
from chatbot.legacy._decode import decode)
and context including class names, function names, or small code snippets from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
#
# OPTIMIZERS = {
# 'Adagrad': tf.train.AdagradOptimizer,
# 'Adam': tf.train.AdamOptimizer,
# 'SGD': tf.train.GradientDescentOptimizer,
# 'RMSProp': tf.train.RMSPropOptimizer,
# }
. Output only the next line. | encoder_pad = [io_utils.PAD_ID] * (encoder_size - len(encoder_input)) |
Here is a snippet: <|code_start|> """Useful for e.g. deploying model on website.
Args: directory containing model ckpt files we'd like to freeze.
"""
if not tf.get_collection('freezer'):
self.log.warning('No freezer found. Not saving a frozen model.')
return
# Note: output_node_names is only used to tell tensorflow what is can
# throw away in the frozen graph (e.g. training ops).
output_node_names = ",".join(
[t.name.rstrip(':0') for t in tf.get_collection('freezer')])
self.log.info('Output node names: %r', output_node_names)
# Save a graph with only the bare necessities for chat sessions.
output_graph_def = tf.graph_util.convert_variables_to_constants(
self.sess, self.graph.as_graph_def(), output_node_names.split(','))
output_fname = os.path.join(self.ckpt_dir, "frozen_model.pb")
with tf.gfile.GFile(output_fname, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print("%d ops in the final graph." % len(output_graph_def.node))
subprocess.call(['cp', self.dataset.paths['vocab'], self.ckpt_dir])
def __getattr__(self, name):
if name == 'params':
camel_case = self.data_name.title().replace('_', '')
replace_dict = {'dataset': "data."+camel_case}
return {**self.__dict__['__params'], **replace_dict}
<|code_end|>
. Write the next line using the current file imports:
import os
import copy
import yaml
import random
import subprocess
import numpy as np
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.python.client import device_lib
from utils import io_utils
from chatbot.components import *
from chatbot.globals import DEFAULT_FULL_CONFIG, OPTIMIZERS
from chatbot.legacy._train import train
from chatbot.legacy._decode import decode
and context from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
#
# OPTIMIZERS = {
# 'Adagrad': tf.train.AdagradOptimizer,
# 'Adam': tf.train.AdamOptimizer,
# 'SGD': tf.train.GradientDescentOptimizer,
# 'RMSProp': tf.train.RMSPropOptimizer,
# }
, which may include functions, classes, or code. Output only the next line. | elif name in DEFAULT_FULL_CONFIG: # Requesting a top-level key. |
Given the following code snippet before the placeholder: <|code_start|> dir_name = kwargs[key]
new_ckpt_dir = os.path.join(new_ckpt_dir, dir_name)
return new_ckpt_dir
class BucketModel(Model):
"""Abstract class. Any classes that extend BucketModel just need to customize their
graph structure in __init__ and implement the step(...) function.
The real motivation for making this was to be able to use the true Model
abstract class for all classes in this directory, bucketed or not, r1.0 or r0.12.
"""
def __init__(self, logger, buckets, dataset, params):
self.buckets = buckets
super(BucketModel, self).__init__(
logger=logger,
dataset=dataset,
params=params)
def compile(self):
""" Configure training process. Name was inspired by Keras. <3 """
if self.losses is None:
raise ValueError("Tried compiling model before defining losses.")
print("Configuring training operations. This may take some time . . . ")
# Note: variables are trainable=True by default.
params = tf.trainable_variables()
# train_op will store the parameter (S)GD train_op.
self.apply_gradients = []
<|code_end|>
, predict the next line using imports from the current file:
import os
import copy
import yaml
import random
import subprocess
import numpy as np
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.python.client import device_lib
from utils import io_utils
from chatbot.components import *
from chatbot.globals import DEFAULT_FULL_CONFIG, OPTIMIZERS
from chatbot.legacy._train import train
from chatbot.legacy._decode import decode
and context including class names, function names, and sometimes code from other files:
# Path: utils/io_utils.py
# _PAD = b"_PAD" # Append to unused space for both encoder/decoder.
# _GO = b"_GO" # Prepend to each decoder input.
# _EOS = b"_EOS" # Append to outputs only. Stopping signal when decoding.
# _UNK = b"_UNK" # For any symbols not in our vocabulary.
# _START_VOCAB = [_PAD, _GO, _EOS, _UNK]
# PAD_ID = 0
# GO_ID = 1
# EOS_ID = 2
# UNK_ID = 3
# _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
# _DIGIT_RE = re.compile(br"\d")
# _FLAGS = Flags(pretrained_dir=None,
# config=None,
# debug=None,
# model='{}',
# dataset='{}',
# model_params='{}',
# dataset_params='{}')
# def save_hyper_params(hyper_params, fname):
# def get_sentence(lower=True):
# def update_config(config=None,
# config_path=None,
# return_config=True,
# **kwargs):
# def get_yaml_config(path, save_path=True):
# def load_pretrained_config(pretrained_dir):
# def print_non_defaults(config):
# def flags_to_dict(flags):
# def merge_dicts(default_dict, preference_dict):
# def parse_config(flags=None, pretrained_dir=None, config_path=None):
# def basic_tokenizer(sentence):
# def num_lines(file_path):
# def get_word_freqs(path, counter, norm_digits=True):
# def create_vocabulary(vocab_path, from_path, to_path, max_vocab_size, norm_digits=True):
# def get_vocab_dicts(vocabulary_path):
# def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True):
# def data_to_token_ids(data_path, target_path, vocabulary_path, normalize_digits=True):
# def prepare_data(data_dir,
# vocab_size,
# from_train_path=None,
# to_train_path=None,
# from_valid_path=None,
# to_valid_path=None,
# optimize=True,
# config_path=None):
# def maybe_set_param(param, file_name):
# def get_vocab_path(vocab_size):
# def append_to_paths(s, **paths):
#
# Path: chatbot/globals.py
# DEFAULT_FULL_CONFIG = {
# "model": "DynamicBot",
# "dataset": "Cornell",
# "model_params": {
# "base_cell": "GRUCell",
# "ckpt_dir": "out", # Directory to store training checkpoints.
# "decode": False,
# "batch_size": 256,
# "dropout_prob": 0.2, # Drop rate applied at encoder/decoders output.
# "decoder.class": "BasicDecoder",
# "encoder.class": "BasicEncoder",
# "embed_size": 128,
# "learning_rate": 0.002,
# "l1_reg": 1.0e-6, # L1 regularization applied to word embeddings.
# "lr_decay": 0.98,
# "max_gradient": 5.0,
# "max_steps": int(1e6), # Max number of training iterations.
# "num_layers": 1, # Num layers for each of encoder, decoder.
# "num_samples": 512, # IF sampled_loss is true, default sample size.
# "optimizer": "Adam", # Options are those in OPTIMIZERS above.
# "reset_model": True,
# "sampled_loss": False, # Whether to do sampled softmax.
# "state_size": 512,
# "steps_per_ckpt": 200,
# "temperature": 0.0, # Response temp for chat sessions. (default argmax)
# },
# "dataset_params": {
# "data_dir": None, # Require user to specify.
# "vocab_size": 40000,
# "max_seq_len": 10, # Maximum length of sentence used to train bot.
# "optimize_params": True # Reduce vocab size if exceeds num unique words
# },
# }
#
# OPTIMIZERS = {
# 'Adagrad': tf.train.AdagradOptimizer,
# 'Adam': tf.train.AdamOptimizer,
# 'SGD': tf.train.GradientDescentOptimizer,
# 'RMSProp': tf.train.RMSPropOptimizer,
# }
. Output only the next line. | optimizer = OPTIMIZERS[self.optimizer](self.learning_rate) |
Next line prediction: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class DesbloquearSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.desbloquear_sat()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "DesbloquearSAT" (numero_caixa=%s)\n%s',
<|code_end|>
. Use current file imports:
(import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser)
and context including class names, function names, or small code snippets from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class DesbloquearSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Based on the snippet: <|code_start|>
class TrocarCodigoDeAtivacao(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
opcao = args['opcao']
novo_codigo = args['novo_codigo']
novo_codigo_confirmacao = args['novo_codigo_confirmacao']
abort(501) # FIXME: consultar número de sessão não implementado
# 501 - Server does not recognise method or lacks ability to fulfill
# NOTE: https://github.com/base4sistemas/satcfe
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.trocar_codigo_ativacao(
opcao,
novo_codigo,
novo_codigo_confirmacao)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "TrocarCodigoDeAtivacao" ('
'numero_caixa={!r}, opcao={!r}, novo_codigo={!r}, '
'novo_codigo_confirmacao={!r})\n{}'.format(
numero_caixa,
opcao,
novo_codigo,
novo_codigo_confirmacao,
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from flask import abort
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, sometimes code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | hexdump(retorno))) |
Based on the snippet: <|code_start|> type=opcao_codigo,
required=True,
help=u'Identifica a que se refere o código de ativação usado '
u'para realizar a troca')
parser.add_argument('novo_codigo',
type=str,
required=True,
help=u'Novo código de ativação')
parser.add_argument('novo_codigo_confirmacao',
type=str,
required=True,
help=u'Confirmação do novo código de ativação')
class TrocarCodigoDeAtivacao(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
opcao = args['opcao']
novo_codigo = args['novo_codigo']
novo_codigo_confirmacao = args['novo_codigo_confirmacao']
abort(501) # FIXME: consultar número de sessão não implementado
# 501 - Server does not recognise method or lacks ability to fulfill
# NOTE: https://github.com/base4sistemas/satcfe
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from flask import abort
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, sometimes code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Next line prediction: <|code_start|>
Se o código de ativação original tiver sido perdido, então o código de
ativação de emergência deverá ser escrito no arquivo de configurações e
deverá ser usada a opção ``2`` para que seja reconhecido pelo equipamento
SAT como o código de ativação de emergência.
Será muito mais prático usar o software de gerenciamento do fabricante para
efetuar a troca do código de ativação, a menos que o estabelecimento siga
uma política de troca frequente do código de ativação devido a questões de
segurança. Neste caso, seria muito mais interessante implementar esta
funcionalidade na aplicação de retaguarda, já que é uma operação puramente
administrativa. Mas isso é apenas uma sugestão.
"""
logger = logging.getLogger('sathub.resource')
def opcao_codigo(value, name):
# 1 - codigo de ativação normal
# 2 - código de ativação de emergência
opcao = int(value)
if opcao not in [1, 2]: # FIXME: deveriam ser constantes em `satcomum`
raise ValueError('Parametro {} invalido: {}'.format(name, value))
return opcao
<|code_end|>
. Use current file imports:
(import logging
from flask import abort
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser)
and context including class names, function names, or small code snippets from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | parser = request_parser() |
Continue the code snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('certificado',
type=str,
required=True,
help=u'Conteúdo do certificado digital ICP-Brasil')
class ComunicarCertificadoICPBRASIL(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
certificado = args['certificado']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.comunicar_certificado_icpbrasil(certificado)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ComunicarCertificadoICPBRASIL" '
<|code_end|>
. Use current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, or code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Next line prediction: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('certificado',
type=str,
required=True,
help=u'Conteúdo do certificado digital ICP-Brasil')
class ComunicarCertificadoICPBRASIL(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
certificado = args['certificado']
<|code_end|>
. Use current file imports:
(import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser)
and context including class names, function names, or small code snippets from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the code snippet: <|code_start|> type=str,
required=True,
help=u'Sequencia contendo CNPJ da AC e do estabelecimento comercial')
parser.add_argument('assinatura_ac',
type=str,
required=True,
help=u'Assinatura da sequencia pela AC codificada em base64')
class AssociarAssinatura(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
sequencia_cnpj = args['sequencia_cnpj']
assinatura_ac = args['assinatura_ac']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.associar_assinatura(sequencia_cnpj, assinatura_ac)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "AssociarAssinatura" ('
'numero_caixa=%s, '
'sequencia_cnpj="%s", '
'assinatura_ac="%s")\n%s',
numero_caixa,
sequencia_cnpj,
assinatura_ac,
<|code_end|>
, generate the next line using the imports in this file:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (functions, classes, or occasionally code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | hexdump(retorno)) |
Continue the code snippet: <|code_start|>#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('sequencia_cnpj',
type=str,
required=True,
help=u'Sequencia contendo CNPJ da AC e do estabelecimento comercial')
parser.add_argument('assinatura_ac',
type=str,
required=True,
help=u'Assinatura da sequencia pela AC codificada em base64')
class AssociarAssinatura(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
sequencia_cnpj = args['sequencia_cnpj']
assinatura_ac = args['assinatura_ac']
<|code_end|>
. Use current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, or code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the following code snippet before the placeholder: <|code_start|> Assim, cada caixa terá a sua própria faixa de numeração de sessão, o que
torna impossível conflitos de número de sessão. Além disso, cada caixa
terá um arquivo próprio, onde os números gerados serão persistidos,
garantindo que os últimos 100 números gerados para aquele caixa não serão
repetidos.
+-------+-----------------------------+
| Caixa | Faixa de Números de Sessão |
+=======+=============================+
| 0 | 100000 a 100899 |
+-------+-----------------------------+
| 1 | 100900 a 101798 |
+-------+-----------------------------+
| ... |
+-------+-----------------------------+
| 999 | 998102 a 999000 |
+-------+-----------------------------+
"""
def __init__(self, tamanho=100, numero_caixa=1):
super(NumeradorSessaoPorCaixa, self).__init__()
self._memoria = []
self._tamanho = tamanho
self._numero_caixa = numero_caixa
assert NUM_CAIXA_MIN <= self._numero_caixa <= NUM_CAIXA_MAX, \
'Numero do caixa fora da faixa (0..999): {}'.format(
self._numero_caixa)
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
import random
import sys
from satcfe import BibliotecaSAT
from satcfe import ClienteSATLocal
from satcfe.base import FuncoesSAT
from .config import PROJECT_ROOT
from .config import conf
and context including class names, function names, and sometimes code from other files:
# Path: sathub/comum/config.py
# PROJECT_ROOT = os.path.join(
# os.path.abspath(os.path.dirname(__file__)), '..', '..')
#
# Path: sathub/comum/config.py
# PROJECT_ROOT = os.path.join(
# os.path.abspath(os.path.dirname(__file__)), '..', '..')
# DEFAULT_LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': True,
# 'formatters': {
# 'verbose': {
# 'format': '%(asctime)s %(levelname)-8s [%(name)s] '\
# '(%(module)s:%(lineno)d) %(message)s'
# },
# 'simple': {
# 'format': '%(levelname)-8s [%(name)s] %(message)s'
# }
# },
# 'filters': {},
# 'handlers': {
# 'null': {
# 'level':'DEBUG',
# 'class':'logging.NullHandler',
# },
# 'console':{
# 'level':'DEBUG',
# 'class':'logging.StreamHandler',
# 'formatter': 'simple'
# },
# 'socket': {
# 'level': 'WARNING',
# 'class': 'logging.handlers.SocketHandler',
# 'host': '10.0.0.1',
# 'port': 7007
# }
# },
# 'loggers': {
# 'flask': {
# 'handlers': ['null'],
# 'propagate': True,
# 'level':'INFO'
# },
# 'satcfe': {
# 'handlers': ['socket'],
# 'propagate': True,
# 'level': 'WARNING'
# },
# 'sathub': {
# 'handlers': ['socket'],
# 'level': 'WARNING',
# 'propagate': False
# }
# }
# }
# DEFAULT_CONFIG = {
# 'debug': True,
# 'usuario': 'sathub',
# 'senha': 'sathub',
# 'descricao': 'Equipamento SAT 1',
# 'codigo_ativacao': '12345678',
# 'caminho_biblioteca': '/opt/fabricante/libsat.so',
# 'convencao_chamada': satcomum.constantes.STANDARD_C,
# }
# class Configuracoes(object):
# def __init__(self, origem=None):
# def origem(self):
# def is_debug(self):
# def usuario(self):
# def senha(self):
# def descricao(self):
# def codigo_ativacao(self):
# def caminho_biblioteca(self):
# def convencao_chamada(self):
# def is_biblioteca_disponivel(self):
# def nome_convencao_chamada(self):
# def descrever(self):
# def _configure_logging(config_path=None):
# def _verbose(message, *args):
. Output only the next line. | self._arquivo_json = os.path.join(PROJECT_ROOT, |
Next line prediction: <|code_start|>
def _escrever_memoria(self):
with open(self._arquivo_json, 'w') as f:
json.dump(self._memoria, f)
def memoize(fn):
# Implementação de memoize obtida de "Thumbtack Engineering"
# https://www.thumbtack.com/engineering/a-primer-on-python-decorators/
stored_results = {}
def memoized(*args):
try:
# try to get the cached result
return stored_results[args]
except KeyError:
# nothing was cached for those args. let's fix that.
result = stored_results[args] = fn(*args)
return result
return memoized
@memoize
def instanciar_numerador_sessao(numero_caixa):
return NumeradorSessaoPorCaixa(numero_caixa=numero_caixa)
@memoize
def instanciar_funcoes_sat(numero_caixa):
<|code_end|>
. Use current file imports:
(import json
import os
import random
import sys
from satcfe import BibliotecaSAT
from satcfe import ClienteSATLocal
from satcfe.base import FuncoesSAT
from .config import PROJECT_ROOT
from .config import conf)
and context including class names, function names, or small code snippets from other files:
# Path: sathub/comum/config.py
# PROJECT_ROOT = os.path.join(
# os.path.abspath(os.path.dirname(__file__)), '..', '..')
#
# Path: sathub/comum/config.py
# PROJECT_ROOT = os.path.join(
# os.path.abspath(os.path.dirname(__file__)), '..', '..')
# DEFAULT_LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': True,
# 'formatters': {
# 'verbose': {
# 'format': '%(asctime)s %(levelname)-8s [%(name)s] '\
# '(%(module)s:%(lineno)d) %(message)s'
# },
# 'simple': {
# 'format': '%(levelname)-8s [%(name)s] %(message)s'
# }
# },
# 'filters': {},
# 'handlers': {
# 'null': {
# 'level':'DEBUG',
# 'class':'logging.NullHandler',
# },
# 'console':{
# 'level':'DEBUG',
# 'class':'logging.StreamHandler',
# 'formatter': 'simple'
# },
# 'socket': {
# 'level': 'WARNING',
# 'class': 'logging.handlers.SocketHandler',
# 'host': '10.0.0.1',
# 'port': 7007
# }
# },
# 'loggers': {
# 'flask': {
# 'handlers': ['null'],
# 'propagate': True,
# 'level':'INFO'
# },
# 'satcfe': {
# 'handlers': ['socket'],
# 'propagate': True,
# 'level': 'WARNING'
# },
# 'sathub': {
# 'handlers': ['socket'],
# 'level': 'WARNING',
# 'propagate': False
# }
# }
# }
# DEFAULT_CONFIG = {
# 'debug': True,
# 'usuario': 'sathub',
# 'senha': 'sathub',
# 'descricao': 'Equipamento SAT 1',
# 'codigo_ativacao': '12345678',
# 'caminho_biblioteca': '/opt/fabricante/libsat.so',
# 'convencao_chamada': satcomum.constantes.STANDARD_C,
# }
# class Configuracoes(object):
# def __init__(self, origem=None):
# def origem(self):
# def is_debug(self):
# def usuario(self):
# def senha(self):
# def descricao(self):
# def codigo_ativacao(self):
# def caminho_biblioteca(self):
# def convencao_chamada(self):
# def is_biblioteca_disponivel(self):
# def nome_convencao_chamada(self):
# def descrever(self):
# def _configure_logging(config_path=None):
# def _verbose(message, *args):
. Output only the next line. | funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca, |
Predict the next line after this snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('configuracao',
type=str,
required=True,
help=u'XML contendo as configurações da interface de rede')
class ConfigurarInterfaceDeRede(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
configuracao = args['configuracao']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.configurar_interface_de_rede(configuracao)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ConfigurarInterfaceDeRede" '
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('configuracao',
type=str,
required=True,
help=u'XML contendo as configurações da interface de rede')
class ConfigurarInterfaceDeRede(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
configuracao = args['configuracao']
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the following code snippet before the placeholder: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda para o teste fim-a-fim')
class TesteFimAFim(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
dados_venda = args['dados_venda']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.teste_fim_a_fim(dados_venda)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "TesteFimAFim" '
<|code_end|>
, predict the next line using imports from the current file:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context including class names, function names, and sometimes code from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda para o teste fim-a-fim')
class TesteFimAFim(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
dados_venda = args['dados_venda']
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Based on the snippet: <|code_start|>
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('chave_cfe',
type=str,
required=True,
help=u'Chave do CF-e a ser cancelado (prefixada "CFe...")')
parser.add_argument('dados_cancelamento',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de cancelamento')
class CancelarUltimaVenda(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
chave_cfe = args['chave_cfe']
dados_cancelamento = args['dados_cancelamento']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.cancelar_ultima_venda(chave_cfe, dados_cancelamento)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "CancelarUltimaVenda" '
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, sometimes code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Next line prediction: <|code_start|>#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('chave_cfe',
type=str,
required=True,
help=u'Chave do CF-e a ser cancelado (prefixada "CFe...")')
parser.add_argument('dados_cancelamento',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de cancelamento')
class CancelarUltimaVenda(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
chave_cfe = args['chave_cfe']
dados_cancelamento = args['dados_cancelamento']
<|code_end|>
. Use current file imports:
(import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser)
and context including class names, function names, or small code snippets from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class BloquearSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.bloquear_sat()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "BloquearSAT" (numero_caixa=%s)\n%s',
<|code_end|>
, generate the next line using the imports in this file:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (functions, classes, or occasionally code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | numero_caixa, hexdump(retorno)) |
Predict the next line for this snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class BloquearSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
with the help of current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
, which may contain function names, class names, or code. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Predict the next line for this snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ConsultarSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.consultar_sat()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ConsultarSAT" (numero_caixa=%s)\n%s',
<|code_end|>
with the help of current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
, which may contain function names, class names, or code. Output only the next line. | numero_caixa, hexdump(retorno)) |
Given the code snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ConsultarSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
, generate the next line using the imports in this file:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (functions, classes, or occasionally code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('numero_sessao',
type=str,
required=True,
help=u'Número da sessão a ser consultada')
class ConsultarNumeroSessao(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
numero_sessao = args['numero_sessao']
abort(501) # FIXME: consultar número de sessão não implementado
# 501 - Server does not recognise method or lacks ability to fulfill
# NOTE: https://github.com/base4sistemas/satcfe
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.consultar_numero_sessao(numero_sessao)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ConsultarNumeroSessao" '
'(numero_caixa=%s, numero_sessao=%s)\n%s',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from flask import abort
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
which might include code, classes, or functions. Output only the next line. | numero_caixa, numero_sessao, hexdump(retorno)) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('numero_sessao',
type=str,
required=True,
help=u'Número da sessão a ser consultada')
class ConsultarNumeroSessao(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
numero_sessao = args['numero_sessao']
abort(501) # FIXME: consultar número de sessão não implementado
# 501 - Server does not recognise method or lacks ability to fulfill
# NOTE: https://github.com/base4sistemas/satcfe
<|code_end|>
with the help of current file imports:
import logging
from flask import abort
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
, which may contain function names, class names, or code. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class AtualizarSoftwareSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.atualizar_software_sat()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "AtualizarSoftwareSAT" (numero_caixa=%s)\n%s',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
which might include code, classes, or functions. Output only the next line. | numero_caixa, hexdump(retorno)) |
Continue the code snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class AtualizarSoftwareSAT(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
. Use current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, or code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Continue the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ConsultarStatusOperacional(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.consultar_status_operacional()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ConsultarStatusOperacional" '
<|code_end|>
. Use current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (classes, functions, or code) from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Using the snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ConsultarStatusOperacional(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
, determine the next line of code. You have imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context (class names, function names, or code) available:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Predict the next line after this snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda')
class EnviarDadosVenda(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
dados_venda = args['dados_venda']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.enviar_dados_venda(dados_venda)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "EnviarDadosVenda" '
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda')
class EnviarDadosVenda(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
dados_venda = args['dados_venda']
<|code_end|>
using the current file's imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and any relevant context from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ExtrairLogs(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
fsat = instanciar_funcoes_sat(numero_caixa)
retorno = fsat.extrair_logs()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Retorno "ExtrairLogs" (numero_caixa=%s)\n%s',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
which might include code, classes, or functions. Output only the next line. | numero_caixa, hexdump(retorno)) |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
class ExtrairLogs(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
<|code_end|>
, predict the next line using imports from the current file:
import logging
from flask.ext import restful
from ..comum.util import hexdump
from ..comum.util import instanciar_funcoes_sat
from ..custom import request_parser
and context including class names, function names, and sometimes code from other files:
# Path: sathub/comum/util.py
# def hexdump(data):
# def _cut(sequence, size):
# for i in xrange(0, len(sequence), size):
# yield sequence[i:i+size]
# _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]
# _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]
# raw_data = map(ord, data)
# hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]
# chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]
# hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))
# chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))
# return '\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))
#
# Path: sathub/comum/util.py
# @memoize
# def instanciar_funcoes_sat(numero_caixa):
# funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca,
# convencao=conf.convencao_chamada),
# codigo_ativacao=conf.codigo_ativacao,
# numerador_sessao=instanciar_numerador_sessao(numero_caixa))
# return funcoes_sat
#
# Path: sathub/custom.py
# def request_parser():
# global parser
# return parser.copy()
. Output only the next line. | fsat = instanciar_funcoes_sat(numero_caixa) |
Next line prediction: <|code_start|>
:param meta_string: Raw meta-inf content as a string
"""
super(PageMetaInf, self).__init__(meta_string)
self.nav_name = self.title if self.nav_name is None else self.nav_name
def load_page(content_path, page_path):
"""Load the page file and return the path, URL and contents"""
# Extract the part of the page_path that will be used as the URL path
pattern = URL_PATH_REGEX % content_path
matches = re.match(pattern, page_path)
if matches:
url_path = matches.group('path').rstrip('/').lstrip('/')
else:
raise PageParseException("Unable to parse page path [%s]" %
content_path)
if not os.path.exists(page_path):
raise ContentException('Could not find file for content page "%s"' %
page_path)
# Read the page file
with codecs.open(page_path, 'r', encoding='utf8') as f:
file_string = f.read()
return page_path, url_path, file_string
<|code_end|>
. Use current file imports:
(import codecs
import os
import re
import markdown
from mdweb.BaseObjects import NavigationBaseItem, MetaInfParser
from mdweb.Exceptions import (
ContentException,
PageParseException,
))
and context including class names, function names, or small code snippets from other files:
# Path: mdweb/BaseObjects.py
# class NavigationBaseItem(object): # pylint: disable=R0903
# """Base object for navigation items such as nav-levels or pages."""
#
# #: Type of navigation item
# @property
# def nav_type(self):
# """Return the type of this nav item (the class name)."""
# return self.__class__.__name__
#
# class MetaInfParser(object): # pylint: disable=R0903
# """Base Meta Inf Parser."""
#
# #: Registered meta fields, can be overridden by inheriting class.
# META_FIELDS = MDW_META_FIELDS
#
# #: Regular expression to extract meta field key-value pairs.
# # can be overridden by inheriting class.
# FIELD_VALUE_REGEX = r"^(?P<key>[a-zA-Z0-9 ]+):(?P<value>.+)$"
#
# def __init__(self, meta_string):
# """Initialize the parser using attributes defined in FIELD_TYPES"""
# for attribute, attribute_details in self.META_FIELDS.items():
# setattr(self, attribute, attribute_details[1])
#
# self._parse_meta_inf(meta_string)
#
# def _parse_meta_inf(self, meta_inf_string):
# """Parse given meta information string into a dictionary.
#
# Metainf fields now support multi-line values. New lines must be
# indented with at least one whitespace character.
#
# :param meta_inf_string: Raw meta content
# """
#
# # NOTE: This regex leaves blank lines and comments in but that will
# # be handled in the line processing loop
# line_regex = '(?P<line>[a-zA-Z0-9 ]+:(?:(?![\n]+\w)[\w\W\r\n])+)'
# line_matches = re.findall(line_regex, meta_inf_string)
# line_blocks = line_matches
#
# for line_block in line_blocks:
# # Split the line block into seperate lines and process each line
# lines = line_block.split('\n')
# processed_line = ''
# for line in lines:
# # Remove blank lines and comments
# if line.strip(' ') == '' or re.match(r'^ *#', line):
# continue
# # Strip beginning and trailing whitespace and newlines
# line = line.strip(' \t\n\r')
#
# processed_line += ' ' + line
#
# match = re.search(self.FIELD_VALUE_REGEX, processed_line)
# if match is None:
# raise PageMetaInfFieldException(
# "Improperly formated metainf line '%s'" % processed_line)
#
# key = match.group('key').strip().lower().replace(' ', '_')
# value = match.group('value').strip()
#
# if '' == value:
# raise PageMetaInfFieldException(
# "Empty value for meta-inf field '%s'" % key)
#
# # Cast field value to appropriate type
# if key not in self.META_FIELDS.keys():
# key = 'custom_' + key
# # We have to add the new attribute to the class before we
# # set the value to the instance below
# setattr(MetaInfParser, key, None)
# try:
# value = unicode(value)
# except NameError:
# pass
# elif 'int' == self.META_FIELDS[key][0]:
# value = int(value)
# elif 'date' == self.META_FIELDS[key][0]:
# value = dateparser.parse(value)
# elif 'bool' == self.META_FIELDS[key][0]:
# if isinstance(value, string_types):
# value = value.lower() == 'true'
# elif isinstance(value, bool):
# value = value
# else:
# value = self.META_FIELDS[key][1]
# else:
# try:
# value = unicode(value)
# except NameError:
# pass
#
# setattr(self, key, value)
#
# Path: mdweb/Exceptions.py
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
. Output only the next line. | class Page(NavigationBaseItem): |
Given the following code snippet before the placeholder: <|code_start|>META_INF_REGEX = r'(^```metainf(?P<metainf>.*?)```)?(?P<content>.*)'
class PageMetaInf(MetaInfParser): # pylint: disable=R0903
"""MDWeb Page Meta Information."""
def __init__(self, meta_string):
"""Content page meta-information.
If a page defines a non-standard meta value it is blindly included.
:param meta_string: Raw meta-inf content as a string
"""
super(PageMetaInf, self).__init__(meta_string)
self.nav_name = self.title if self.nav_name is None else self.nav_name
def load_page(content_path, page_path):
"""Load the page file and return the path, URL and contents"""
# Extract the part of the page_path that will be used as the URL path
pattern = URL_PATH_REGEX % content_path
matches = re.match(pattern, page_path)
if matches:
url_path = matches.group('path').rstrip('/').lstrip('/')
else:
raise PageParseException("Unable to parse page path [%s]" %
content_path)
if not os.path.exists(page_path):
<|code_end|>
, predict the next line using imports from the current file:
import codecs
import os
import re
import markdown
from mdweb.BaseObjects import NavigationBaseItem, MetaInfParser
from mdweb.Exceptions import (
ContentException,
PageParseException,
)
and context including class names, function names, and sometimes code from other files:
# Path: mdweb/BaseObjects.py
# class NavigationBaseItem(object): # pylint: disable=R0903
# """Base object for navigation items such as nav-levels or pages."""
#
# #: Type of navigation item
# @property
# def nav_type(self):
# """Return the type of this nav item (the class name)."""
# return self.__class__.__name__
#
# class MetaInfParser(object): # pylint: disable=R0903
# """Base Meta Inf Parser."""
#
# #: Registered meta fields, can be overridden by inheriting class.
# META_FIELDS = MDW_META_FIELDS
#
# #: Regular expression to extract meta field key-value pairs.
# # can be overridden by inheriting class.
# FIELD_VALUE_REGEX = r"^(?P<key>[a-zA-Z0-9 ]+):(?P<value>.+)$"
#
# def __init__(self, meta_string):
# """Initialize the parser using attributes defined in FIELD_TYPES"""
# for attribute, attribute_details in self.META_FIELDS.items():
# setattr(self, attribute, attribute_details[1])
#
# self._parse_meta_inf(meta_string)
#
# def _parse_meta_inf(self, meta_inf_string):
# """Parse given meta information string into a dictionary.
#
# Metainf fields now support multi-line values. New lines must be
# indented with at least one whitespace character.
#
# :param meta_inf_string: Raw meta content
# """
#
# # NOTE: This regex leaves blank lines and comments in but that will
# # be handled in the line processing loop
# line_regex = '(?P<line>[a-zA-Z0-9 ]+:(?:(?![\n]+\w)[\w\W\r\n])+)'
# line_matches = re.findall(line_regex, meta_inf_string)
# line_blocks = line_matches
#
# for line_block in line_blocks:
# # Split the line block into seperate lines and process each line
# lines = line_block.split('\n')
# processed_line = ''
# for line in lines:
# # Remove blank lines and comments
# if line.strip(' ') == '' or re.match(r'^ *#', line):
# continue
# # Strip beginning and trailing whitespace and newlines
# line = line.strip(' \t\n\r')
#
# processed_line += ' ' + line
#
# match = re.search(self.FIELD_VALUE_REGEX, processed_line)
# if match is None:
# raise PageMetaInfFieldException(
# "Improperly formated metainf line '%s'" % processed_line)
#
# key = match.group('key').strip().lower().replace(' ', '_')
# value = match.group('value').strip()
#
# if '' == value:
# raise PageMetaInfFieldException(
# "Empty value for meta-inf field '%s'" % key)
#
# # Cast field value to appropriate type
# if key not in self.META_FIELDS.keys():
# key = 'custom_' + key
# # We have to add the new attribute to the class before we
# # set the value to the instance below
# setattr(MetaInfParser, key, None)
# try:
# value = unicode(value)
# except NameError:
# pass
# elif 'int' == self.META_FIELDS[key][0]:
# value = int(value)
# elif 'date' == self.META_FIELDS[key][0]:
# value = dateparser.parse(value)
# elif 'bool' == self.META_FIELDS[key][0]:
# if isinstance(value, string_types):
# value = value.lower() == 'true'
# elif isinstance(value, bool):
# value = value
# else:
# value = self.META_FIELDS[key][1]
# else:
# try:
# value = unicode(value)
# except NameError:
# pass
#
# setattr(self, key, value)
#
# Path: mdweb/Exceptions.py
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
. Output only the next line. | raise ContentException('Could not find file for content page "%s"' % |
Next line prediction: <|code_start|>#: A regex to extract the url path from the file path
URL_PATH_REGEX = r'^%s(?P<path>[^\0]*?)(index)?(\.md)'
#: A regex for extracting meta information (and comments).
META_INF_REGEX = r'(^```metainf(?P<metainf>.*?)```)?(?P<content>.*)'
class PageMetaInf(MetaInfParser): # pylint: disable=R0903
"""MDWeb Page Meta Information."""
def __init__(self, meta_string):
"""Content page meta-information.
If a page defines a non-standard meta value it is blindly included.
:param meta_string: Raw meta-inf content as a string
"""
super(PageMetaInf, self).__init__(meta_string)
self.nav_name = self.title if self.nav_name is None else self.nav_name
def load_page(content_path, page_path):
"""Load the page file and return the path, URL and contents"""
# Extract the part of the page_path that will be used as the URL path
pattern = URL_PATH_REGEX % content_path
matches = re.match(pattern, page_path)
if matches:
url_path = matches.group('path').rstrip('/').lstrip('/')
else:
<|code_end|>
. Use current file imports:
(import codecs
import os
import re
import markdown
from mdweb.BaseObjects import NavigationBaseItem, MetaInfParser
from mdweb.Exceptions import (
ContentException,
PageParseException,
))
and context including class names, function names, or small code snippets from other files:
# Path: mdweb/BaseObjects.py
# class NavigationBaseItem(object): # pylint: disable=R0903
# """Base object for navigation items such as nav-levels or pages."""
#
# #: Type of navigation item
# @property
# def nav_type(self):
# """Return the type of this nav item (the class name)."""
# return self.__class__.__name__
#
# class MetaInfParser(object): # pylint: disable=R0903
# """Base Meta Inf Parser."""
#
# #: Registered meta fields, can be overridden by inheriting class.
# META_FIELDS = MDW_META_FIELDS
#
# #: Regular expression to extract meta field key-value pairs.
# # can be overridden by inheriting class.
# FIELD_VALUE_REGEX = r"^(?P<key>[a-zA-Z0-9 ]+):(?P<value>.+)$"
#
# def __init__(self, meta_string):
# """Initialize the parser using attributes defined in FIELD_TYPES"""
# for attribute, attribute_details in self.META_FIELDS.items():
# setattr(self, attribute, attribute_details[1])
#
# self._parse_meta_inf(meta_string)
#
# def _parse_meta_inf(self, meta_inf_string):
# """Parse given meta information string into a dictionary.
#
# Metainf fields now support multi-line values. New lines must be
# indented with at least one whitespace character.
#
# :param meta_inf_string: Raw meta content
# """
#
# # NOTE: This regex leaves blank lines and comments in but that will
# # be handled in the line processing loop
# line_regex = '(?P<line>[a-zA-Z0-9 ]+:(?:(?![\n]+\w)[\w\W\r\n])+)'
# line_matches = re.findall(line_regex, meta_inf_string)
# line_blocks = line_matches
#
# for line_block in line_blocks:
# # Split the line block into seperate lines and process each line
# lines = line_block.split('\n')
# processed_line = ''
# for line in lines:
# # Remove blank lines and comments
# if line.strip(' ') == '' or re.match(r'^ *#', line):
# continue
# # Strip beginning and trailing whitespace and newlines
# line = line.strip(' \t\n\r')
#
# processed_line += ' ' + line
#
# match = re.search(self.FIELD_VALUE_REGEX, processed_line)
# if match is None:
# raise PageMetaInfFieldException(
# "Improperly formated metainf line '%s'" % processed_line)
#
# key = match.group('key').strip().lower().replace(' ', '_')
# value = match.group('value').strip()
#
# if '' == value:
# raise PageMetaInfFieldException(
# "Empty value for meta-inf field '%s'" % key)
#
# # Cast field value to appropriate type
# if key not in self.META_FIELDS.keys():
# key = 'custom_' + key
# # We have to add the new attribute to the class before we
# # set the value to the instance below
# setattr(MetaInfParser, key, None)
# try:
# value = unicode(value)
# except NameError:
# pass
# elif 'int' == self.META_FIELDS[key][0]:
# value = int(value)
# elif 'date' == self.META_FIELDS[key][0]:
# value = dateparser.parse(value)
# elif 'bool' == self.META_FIELDS[key][0]:
# if isinstance(value, string_types):
# value = value.lower() == 'true'
# elif isinstance(value, bool):
# value = value
# else:
# value = self.META_FIELDS[key][1]
# else:
# try:
# value = unicode(value)
# except NameError:
# pass
#
# setattr(self, key, value)
#
# Path: mdweb/Exceptions.py
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
. Output only the next line. | raise PageParseException("Unable to parse page path [%s]" % |
Given snippet: <|code_start|>
Tests to write
* Handle symlinks
* File already open
* Non supported extension (.xls)
* Permissions
Maybe test?
* atime, mtime
* large file
"""
try:
# Python >= 3.3
except ImportError:
# Python < 3.3
class TestPageMeta(fake_filesystem_unittest.TestCase):
"""PageMetaInf object tests."""
def setUp(self):
"""Create fake filesystem."""
self.setUpPyfakefs()
def test_parse_empty_string(self):
"""Empty string should parse successfully."""
file_string = u""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import mock
from pyfakefs import fake_filesystem_unittest
from unittest import skip
from unittest import mock
from mdweb.Page import PageMetaInf, Page, load_page
from mdweb.Exceptions import (
PageMetaInfFieldException,
PageParseException,
ContentException,
)
and context:
# Path: mdweb/Page.py
# class PageMetaInf(MetaInfParser): # pylint: disable=R0903
# """MDWeb Page Meta Information."""
#
# def __init__(self, meta_string):
# """Content page meta-information.
#
# If a page defines a non-standard meta value it is blindly included.
#
# :param meta_string: Raw meta-inf content as a string
# """
# super(PageMetaInf, self).__init__(meta_string)
# self.nav_name = self.title if self.nav_name is None else self.nav_name
#
# class Page(NavigationBaseItem):
# """MDWeb Page View."""
#
# def __init__(self, page_path, url_path, file_string):
# """Initialize Page object."""
#
# self.page_path = page_path
# self.url_path = url_path
#
# # Separate the meta information and the page content
# meta_inf_regex = re.compile(META_INF_REGEX, flags=re.DOTALL)
# match = meta_inf_regex.search(file_string)
# meta_inf_string = match.group('metainf') if match.group('metainf') \
# else ''
# content_string = match.group('content')
#
# self.meta_inf = PageMetaInf(meta_inf_string)
#
# # Strip the meta information and comments
# self.markdown_str = content_string
#
# # The page will be rendered on first view
# self.page_html = self.parse_markdown(self.markdown_str)
#
# self.abstract = self.page_html[0:100]
#
# @property
# def is_published(self):
# return self.meta_inf.published
#
# @staticmethod
# def parse_markdown(page_markdown):
# """Parse given markdown string into rendered html.
#
# :param page_markdown: Markdown to be parsed
# :return: Rendered page HTML
# """
# page_html = markdown.markdown(page_markdown)
#
# return page_html
#
# def __repr__(self):
# return '{0}'.format(self.page_path)
#
# def load_page(content_path, page_path):
# """Load the page file and return the path, URL and contents"""
#
# # Extract the part of the page_path that will be used as the URL path
# pattern = URL_PATH_REGEX % content_path
# matches = re.match(pattern, page_path)
# if matches:
# url_path = matches.group('path').rstrip('/').lstrip('/')
# else:
# raise PageParseException("Unable to parse page path [%s]" %
# content_path)
#
# if not os.path.exists(page_path):
# raise ContentException('Could not find file for content page "%s"' %
# page_path)
#
# # Read the page file
# with codecs.open(page_path, 'r', encoding='utf8') as f:
# file_string = f.read()
#
# return page_path, url_path, file_string
#
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
#
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
which might include code, classes, or functions. Output only the next line. | meta_inf = PageMetaInf(file_string) |
Predict the next line after this snippet: <|code_start|> def test_parse_custom_field(self):
"""Multiline fields should parse successfully."""
file_string = u"""Title: MDWeb
Description: The minimalistic markdown NaCMS
Author: Chad Rempp
Summary Image: blah.jpg
"""
meta_inf = PageMetaInf(file_string)
self.assertEqual(meta_inf.custom_summary_image, u'blah.jpg')
@skip
def test_unpublished_page(self):
"""Unpublished pages should have the correct attr value."""
self.assertEqual(1, 2)
class TestPage(fake_filesystem_unittest.TestCase):
"""Page object tests."""
def setUp(self):
"""Create fake filesystem."""
self.setUpPyfakefs()
def test_page_instantiation(self):
"""A page should be instantiated with appropriate attributes."""
file_string = u"This is a page"
self.fs.create_file('/my/content/about/history.md',
contents=file_string)
<|code_end|>
using the current file's imports:
import datetime
import mock
from pyfakefs import fake_filesystem_unittest
from unittest import skip
from unittest import mock
from mdweb.Page import PageMetaInf, Page, load_page
from mdweb.Exceptions import (
PageMetaInfFieldException,
PageParseException,
ContentException,
)
and any relevant context from other files:
# Path: mdweb/Page.py
# class PageMetaInf(MetaInfParser): # pylint: disable=R0903
# """MDWeb Page Meta Information."""
#
# def __init__(self, meta_string):
# """Content page meta-information.
#
# If a page defines a non-standard meta value it is blindly included.
#
# :param meta_string: Raw meta-inf content as a string
# """
# super(PageMetaInf, self).__init__(meta_string)
# self.nav_name = self.title if self.nav_name is None else self.nav_name
#
# class Page(NavigationBaseItem):
# """MDWeb Page View."""
#
# def __init__(self, page_path, url_path, file_string):
# """Initialize Page object."""
#
# self.page_path = page_path
# self.url_path = url_path
#
# # Separate the meta information and the page content
# meta_inf_regex = re.compile(META_INF_REGEX, flags=re.DOTALL)
# match = meta_inf_regex.search(file_string)
# meta_inf_string = match.group('metainf') if match.group('metainf') \
# else ''
# content_string = match.group('content')
#
# self.meta_inf = PageMetaInf(meta_inf_string)
#
# # Strip the meta information and comments
# self.markdown_str = content_string
#
# # The page will be rendered on first view
# self.page_html = self.parse_markdown(self.markdown_str)
#
# self.abstract = self.page_html[0:100]
#
# @property
# def is_published(self):
# return self.meta_inf.published
#
# @staticmethod
# def parse_markdown(page_markdown):
# """Parse given markdown string into rendered html.
#
# :param page_markdown: Markdown to be parsed
# :return: Rendered page HTML
# """
# page_html = markdown.markdown(page_markdown)
#
# return page_html
#
# def __repr__(self):
# return '{0}'.format(self.page_path)
#
# def load_page(content_path, page_path):
# """Load the page file and return the path, URL and contents"""
#
# # Extract the part of the page_path that will be used as the URL path
# pattern = URL_PATH_REGEX % content_path
# matches = re.match(pattern, page_path)
# if matches:
# url_path = matches.group('path').rstrip('/').lstrip('/')
# else:
# raise PageParseException("Unable to parse page path [%s]" %
# content_path)
#
# if not os.path.exists(page_path):
# raise ContentException('Could not find file for content page "%s"' %
# page_path)
#
# # Read the page file
# with codecs.open(page_path, 'r', encoding='utf8') as f:
# file_string = f.read()
#
# return page_path, url_path, file_string
#
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
#
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
. Output only the next line. | page = Page(*load_page('/my/content', '/my/content/about/history.md')) |
Based on the snippet: <|code_start|> def test_parse_custom_field(self):
"""Multiline fields should parse successfully."""
file_string = u"""Title: MDWeb
Description: The minimalistic markdown NaCMS
Author: Chad Rempp
Summary Image: blah.jpg
"""
meta_inf = PageMetaInf(file_string)
self.assertEqual(meta_inf.custom_summary_image, u'blah.jpg')
@skip
def test_unpublished_page(self):
"""Unpublished pages should have the correct attr value."""
self.assertEqual(1, 2)
class TestPage(fake_filesystem_unittest.TestCase):
"""Page object tests."""
def setUp(self):
"""Create fake filesystem."""
self.setUpPyfakefs()
def test_page_instantiation(self):
"""A page should be instantiated with appropriate attributes."""
file_string = u"This is a page"
self.fs.create_file('/my/content/about/history.md',
contents=file_string)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import mock
from pyfakefs import fake_filesystem_unittest
from unittest import skip
from unittest import mock
from mdweb.Page import PageMetaInf, Page, load_page
from mdweb.Exceptions import (
PageMetaInfFieldException,
PageParseException,
ContentException,
)
and context (classes, functions, sometimes code) from other files:
# Path: mdweb/Page.py
# class PageMetaInf(MetaInfParser): # pylint: disable=R0903
# """MDWeb Page Meta Information."""
#
# def __init__(self, meta_string):
# """Content page meta-information.
#
# If a page defines a non-standard meta value it is blindly included.
#
# :param meta_string: Raw meta-inf content as a string
# """
# super(PageMetaInf, self).__init__(meta_string)
# self.nav_name = self.title if self.nav_name is None else self.nav_name
#
# class Page(NavigationBaseItem):
# """MDWeb Page View."""
#
# def __init__(self, page_path, url_path, file_string):
# """Initialize Page object."""
#
# self.page_path = page_path
# self.url_path = url_path
#
# # Separate the meta information and the page content
# meta_inf_regex = re.compile(META_INF_REGEX, flags=re.DOTALL)
# match = meta_inf_regex.search(file_string)
# meta_inf_string = match.group('metainf') if match.group('metainf') \
# else ''
# content_string = match.group('content')
#
# self.meta_inf = PageMetaInf(meta_inf_string)
#
# # Strip the meta information and comments
# self.markdown_str = content_string
#
# # The page will be rendered on first view
# self.page_html = self.parse_markdown(self.markdown_str)
#
# self.abstract = self.page_html[0:100]
#
# @property
# def is_published(self):
# return self.meta_inf.published
#
# @staticmethod
# def parse_markdown(page_markdown):
# """Parse given markdown string into rendered html.
#
# :param page_markdown: Markdown to be parsed
# :return: Rendered page HTML
# """
# page_html = markdown.markdown(page_markdown)
#
# return page_html
#
# def __repr__(self):
# return '{0}'.format(self.page_path)
#
# def load_page(content_path, page_path):
# """Load the page file and return the path, URL and contents"""
#
# # Extract the part of the page_path that will be used as the URL path
# pattern = URL_PATH_REGEX % content_path
# matches = re.match(pattern, page_path)
# if matches:
# url_path = matches.group('path').rstrip('/').lstrip('/')
# else:
# raise PageParseException("Unable to parse page path [%s]" %
# content_path)
#
# if not os.path.exists(page_path):
# raise ContentException('Could not find file for content page "%s"' %
# page_path)
#
# # Read the page file
# with codecs.open(page_path, 'r', encoding='utf8') as f:
# file_string = f.read()
#
# return page_path, url_path, file_string
#
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
#
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
. Output only the next line. | page = Page(*load_page('/my/content', '/my/content/about/history.md')) |
Using the snippet: <|code_start|> self.setUpPyfakefs()
def test_page_instantiation(self):
"""A page should be instantiated with appropriate attributes."""
file_string = u"This is a page"
self.fs.create_file('/my/content/about/history.md',
contents=file_string)
page = Page(*load_page('/my/content', '/my/content/about/history.md'))
self.assertEqual(page.page_path, '/my/content/about/history.md')
self.assertEqual(page.url_path, 'about/history')
self.fs.create_file('/my/content/super/deep/url/path/index.md',
contents=file_string)
page = Page(*load_page('/my/content',
'/my/content/super/deep/url/path/index.md'))
self.assertEqual(page.page_path,
'/my/content/super/deep/url/path/index.md')
self.assertEqual(page.url_path, 'super/deep/url/path')
def test_unparsable_path(self):
"""An unparsable page path should raise PageParseException."""
file_string = u""
self.fs.create_file('/my/content/index',
contents=file_string)
# Not an MD file
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import mock
from pyfakefs import fake_filesystem_unittest
from unittest import skip
from unittest import mock
from mdweb.Page import PageMetaInf, Page, load_page
from mdweb.Exceptions import (
PageMetaInfFieldException,
PageParseException,
ContentException,
)
and context (class names, function names, or code) available:
# Path: mdweb/Page.py
# class PageMetaInf(MetaInfParser): # pylint: disable=R0903
# """MDWeb Page Meta Information."""
#
# def __init__(self, meta_string):
# """Content page meta-information.
#
# If a page defines a non-standard meta value it is blindly included.
#
# :param meta_string: Raw meta-inf content as a string
# """
# super(PageMetaInf, self).__init__(meta_string)
# self.nav_name = self.title if self.nav_name is None else self.nav_name
#
# class Page(NavigationBaseItem):
# """MDWeb Page View."""
#
# def __init__(self, page_path, url_path, file_string):
# """Initialize Page object."""
#
# self.page_path = page_path
# self.url_path = url_path
#
# # Separate the meta information and the page content
# meta_inf_regex = re.compile(META_INF_REGEX, flags=re.DOTALL)
# match = meta_inf_regex.search(file_string)
# meta_inf_string = match.group('metainf') if match.group('metainf') \
# else ''
# content_string = match.group('content')
#
# self.meta_inf = PageMetaInf(meta_inf_string)
#
# # Strip the meta information and comments
# self.markdown_str = content_string
#
# # The page will be rendered on first view
# self.page_html = self.parse_markdown(self.markdown_str)
#
# self.abstract = self.page_html[0:100]
#
# @property
# def is_published(self):
# return self.meta_inf.published
#
# @staticmethod
# def parse_markdown(page_markdown):
# """Parse given markdown string into rendered html.
#
# :param page_markdown: Markdown to be parsed
# :return: Rendered page HTML
# """
# page_html = markdown.markdown(page_markdown)
#
# return page_html
#
# def __repr__(self):
# return '{0}'.format(self.page_path)
#
# def load_page(content_path, page_path):
# """Load the page file and return the path, URL and contents"""
#
# # Extract the part of the page_path that will be used as the URL path
# pattern = URL_PATH_REGEX % content_path
# matches = re.match(pattern, page_path)
# if matches:
# url_path = matches.group('path').rstrip('/').lstrip('/')
# else:
# raise PageParseException("Unable to parse page path [%s]" %
# content_path)
#
# if not os.path.exists(page_path):
# raise ContentException('Could not find file for content page "%s"' %
# page_path)
#
# # Read the page file
# with codecs.open(page_path, 'r', encoding='utf8') as f:
# file_string = f.read()
#
# return page_path, url_path, file_string
#
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
#
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
. Output only the next line. | self.assertRaises(PageParseException, load_page, '/my/content', |
Next line prediction: <|code_start|> # Not an MD file
self.assertRaises(PageParseException, load_page, '/my/content',
'/my/content/index')
@mock.patch('mdweb.Page.PageMetaInf')
def test_repr(self, mock_page_meta_inf):
"""A Page object should return the proper repr."""
file_string = u""
self.fs.create_file('/my/content/index.md',
contents=file_string)
page = Page(*load_page('/my/content', '/my/content/index.md'))
self.assertEqual(str(page), '/my/content/index.md')
@mock.patch('mdweb.Page.PageMetaInf')
def test_parse_empty_file(self, mock_page_meta_inf):
"""An empty file should parse properly."""
file_string = u""
self.fs.create_file('/my/content/index.md',
contents=file_string)
page = Page(*load_page('/my/content', '/my/content/index.md'))
mock_page_meta_inf.assert_called_once_with('')
self.assertEqual(page.markdown_str, '')
self.assertEqual(page.page_html, '')
def test_no_file(self):
"""If the path has no file a ContentException should be raised."""
<|code_end|>
. Use current file imports:
(import datetime
import mock
from pyfakefs import fake_filesystem_unittest
from unittest import skip
from unittest import mock
from mdweb.Page import PageMetaInf, Page, load_page
from mdweb.Exceptions import (
PageMetaInfFieldException,
PageParseException,
ContentException,
))
and context including class names, function names, or small code snippets from other files:
# Path: mdweb/Page.py
# class PageMetaInf(MetaInfParser): # pylint: disable=R0903
# """MDWeb Page Meta Information."""
#
# def __init__(self, meta_string):
# """Content page meta-information.
#
# If a page defines a non-standard meta value it is blindly included.
#
# :param meta_string: Raw meta-inf content as a string
# """
# super(PageMetaInf, self).__init__(meta_string)
# self.nav_name = self.title if self.nav_name is None else self.nav_name
#
# class Page(NavigationBaseItem):
# """MDWeb Page View."""
#
# def __init__(self, page_path, url_path, file_string):
# """Initialize Page object."""
#
# self.page_path = page_path
# self.url_path = url_path
#
# # Separate the meta information and the page content
# meta_inf_regex = re.compile(META_INF_REGEX, flags=re.DOTALL)
# match = meta_inf_regex.search(file_string)
# meta_inf_string = match.group('metainf') if match.group('metainf') \
# else ''
# content_string = match.group('content')
#
# self.meta_inf = PageMetaInf(meta_inf_string)
#
# # Strip the meta information and comments
# self.markdown_str = content_string
#
# # The page will be rendered on first view
# self.page_html = self.parse_markdown(self.markdown_str)
#
# self.abstract = self.page_html[0:100]
#
# @property
# def is_published(self):
# return self.meta_inf.published
#
# @staticmethod
# def parse_markdown(page_markdown):
# """Parse given markdown string into rendered html.
#
# :param page_markdown: Markdown to be parsed
# :return: Rendered page HTML
# """
# page_html = markdown.markdown(page_markdown)
#
# return page_html
#
# def __repr__(self):
# return '{0}'.format(self.page_path)
#
# def load_page(content_path, page_path):
# """Load the page file and return the path, URL and contents"""
#
# # Extract the part of the page_path that will be used as the URL path
# pattern = URL_PATH_REGEX % content_path
# matches = re.match(pattern, page_path)
# if matches:
# url_path = matches.group('path').rstrip('/').lstrip('/')
# else:
# raise PageParseException("Unable to parse page path [%s]" %
# content_path)
#
# if not os.path.exists(page_path):
# raise ContentException('Could not find file for content page "%s"' %
# page_path)
#
# # Read the page file
# with codecs.open(page_path, 'r', encoding='utf8') as f:
# file_string = f.read()
#
# return page_path, url_path, file_string
#
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# class PageParseException(Exception):
# """Error parsing page markdown."""
#
# pass
#
# class ContentException(Exception):
# """Markdown content exception."""
#
# pass
. Output only the next line. | self.assertRaises(ContentException, load_page, '/my/content', |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""Tests for the Debug Helper."""
class TestDebugHelperOn(TestCase):
"""Debug helper tests.
Can't use pyfakefs for this or partials won't load"""
def create_app(self):
<|code_end|>
. Use current file imports:
(from flask_testing import TestCase
from tests.sites import MDTestSiteDebugHelper, MDTestSite)
and context including class names, function names, or small code snippets from other files:
# Path: tests/sites.py
# class MDTestSiteDebugHelper(MDSite):
# """Test site for use with fake FS and debug helper enabled."""
#
# class MDConfig: # pylint: disable=R0903
# """Config class for testing."""
#
# DEBUG = False
# SECRET_KEY = 'create_a_secret_key_for_use_in_production'
# CONTENT_PATH = 'demo-content/'
# THEME = 'bootstrap'
# TESTING = True
# GA_TRACKING_ID = 'UA-00000000-1'
# DEBUG_HELPER = True
#
# class MDTestSite(MDSite):
# """Test site for use with real FS"""
#
# class MDConfig: # pylint: disable=R0903
# """Config class for testing."""
#
# DEBUG = False
# SECRET_KEY = 'create_a_secret_key_for_use_in_production'
# CONTENT_PATH = 'demo-content/'
# THEME = 'basic'
# TESTING = True
# GA_TRACKING_ID = 'UA-00000000-1'
# DEBUG_HELPER = False
. Output only the next line. | app = MDTestSiteDebugHelper( |
Given snippet: <|code_start|>
class TestDebugHelperOn(TestCase):
"""Debug helper tests.
Can't use pyfakefs for this or partials won't load"""
def create_app(self):
app = MDTestSiteDebugHelper(
"MDWeb",
app_options={}
)
app.start()
return app
def test_debug_helper_loads(self):
# self.app.DEBUG_HELPER
with self.app.test_client() as client:
response = client.get('/')
response_data = response.get_data(as_text=True)
self.assertTrue('<div id="md_debug_display">' in response_data)
class TestDebugHelperOff(TestCase):
"""Debug helper tests.
Can't use pyfakefs for this or partials won't load"""
def create_app(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask_testing import TestCase
from tests.sites import MDTestSiteDebugHelper, MDTestSite
and context:
# Path: tests/sites.py
# class MDTestSiteDebugHelper(MDSite):
# """Test site for use with fake FS and debug helper enabled."""
#
# class MDConfig: # pylint: disable=R0903
# """Config class for testing."""
#
# DEBUG = False
# SECRET_KEY = 'create_a_secret_key_for_use_in_production'
# CONTENT_PATH = 'demo-content/'
# THEME = 'bootstrap'
# TESTING = True
# GA_TRACKING_ID = 'UA-00000000-1'
# DEBUG_HELPER = True
#
# class MDTestSite(MDSite):
# """Test site for use with real FS"""
#
# class MDConfig: # pylint: disable=R0903
# """Config class for testing."""
#
# DEBUG = False
# SECRET_KEY = 'create_a_secret_key_for_use_in_production'
# CONTENT_PATH = 'demo-content/'
# THEME = 'basic'
# TESTING = True
# GA_TRACKING_ID = 'UA-00000000-1'
# DEBUG_HELPER = False
which might include code, classes, or functions. Output only the next line. | app = MDTestSite( |
Here is a snippet: <|code_start|> def _parse_meta_inf(self, meta_inf_string):
"""Parse given meta information string into a dictionary.
Metainf fields now support multi-line values. New lines must be
indented with at least one whitespace character.
:param meta_inf_string: Raw meta content
"""
# NOTE: This regex leaves blank lines and comments in but that will
# be handled in the line processing loop
line_regex = '(?P<line>[a-zA-Z0-9 ]+:(?:(?![\n]+\w)[\w\W\r\n])+)'
line_matches = re.findall(line_regex, meta_inf_string)
line_blocks = line_matches
for line_block in line_blocks:
# Split the line block into seperate lines and process each line
lines = line_block.split('\n')
processed_line = ''
for line in lines:
# Remove blank lines and comments
if line.strip(' ') == '' or re.match(r'^ *#', line):
continue
# Strip beginning and trailing whitespace and newlines
line = line.strip(' \t\n\r')
processed_line += ' ' + line
match = re.search(self.FIELD_VALUE_REGEX, processed_line)
if match is None:
<|code_end|>
. Write the next line using the current file imports:
import re
import dateparser
from six import string_types
from mdweb.Exceptions import PageMetaInfFieldException
from mdweb.metafields import META_FIELDS as MDW_META_FIELDS
and context from other files:
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# Path: mdweb/metafields.py
# META_FIELDS = {
# 'title': ('unicode', None),
# 'nav_name': ('unicode', None),
# 'description': ('unicode', None),
# 'author': ('unicode', None),
# 'date': ('date', None),
# 'order': ('int', 0),
# 'template': ('unicode', None),
# 'teaser': ('unicode', None),
# 'teaser_image': ('unicode', None),
# 'sitemap_priority': ('unicode', None),
# 'sitemap_changefreq': ('unicode', None),
# 'published': ('bool', True),
# }
, which may include functions, classes, or code. Output only the next line. | raise PageMetaInfFieldException( |
Next line prediction: <|code_start|>"""MDWeb Base Navigation Item.
This is broken out into a separate file to avoid circular imports.
"""
class NavigationBaseItem(object): # pylint: disable=R0903
"""Base object for navigation items such as nav-levels or pages."""
#: Type of navigation item
@property
def nav_type(self):
"""Return the type of this nav item (the class name)."""
return self.__class__.__name__
class MetaInfParser(object): # pylint: disable=R0903
"""Base Meta Inf Parser."""
#: Registered meta fields, can be overridden by inheriting class.
<|code_end|>
. Use current file imports:
(import re
import dateparser
from six import string_types
from mdweb.Exceptions import PageMetaInfFieldException
from mdweb.metafields import META_FIELDS as MDW_META_FIELDS)
and context including class names, function names, or small code snippets from other files:
# Path: mdweb/Exceptions.py
# class PageMetaInfFieldException(Exception):
# """Invalid field in page metadata."""
#
# pass
#
# Path: mdweb/metafields.py
# META_FIELDS = {
# 'title': ('unicode', None),
# 'nav_name': ('unicode', None),
# 'description': ('unicode', None),
# 'author': ('unicode', None),
# 'date': ('date', None),
# 'order': ('int', 0),
# 'template': ('unicode', None),
# 'teaser': ('unicode', None),
# 'teaser_image': ('unicode', None),
# 'sitemap_priority': ('unicode', None),
# 'sitemap_changefreq': ('unicode', None),
# 'published': ('bool', True),
# }
. Output only the next line. | META_FIELDS = MDW_META_FIELDS |
Continue the code snippet: <|code_start|>
class Files(object):
"""
Keeps track of the files TSS uses (currently?).
Keeps references like this /// <reference path="lib/mocha/mocha.d.ts" />
up to date. For this it parses unsaved views after each keystroke.
"""
@max_calls(name='Files.init')
def init(self, root, callback):
self.update_indexed_files(root, callback)
@max_calls(name='Files.update_indexed_files')
def update_indexed_files(self, root, callback=None):
""" add the files in current project (=root) determined by tss>files command to LISTE """
def async_react(files):
""" callback for async tss>files response. Add files"""
for f in files:
self.add(root, f)
if callback is not None:
callback()
Debug('files', "GETTING FILE LIST from TSS")
TSS.get_tss_indexed_files(root, async_react)
@max_calls(name='Files.add')
def add(self, root, filename):
""" Adds/updates filename in LISTE, keeping track of belonging project (=root) and references """
Debug('files', "ADD FILE to LISTE, parse references: %s" % filename)
<|code_end|>
. Use current file imports:
from threading import Thread
from ..Utils import read_file, file_exists, fn2l, Debug, max_calls
from ..Tss import TSS
from .Liste import LISTE
import sublime
import re
import os
and context (classes, functions, or code) from other files:
# Path: lib/system/busted/Liste.py
# LISTE = Liste()
. Output only the next line. | LISTE.add(filename, |
Using the snippet: <|code_start|># coding=utf8
#from .Project import ProjectSettings, ProjectError, errorSetting
# ----------------------------------------- CONSTANT ---------------------------------------- #
SUBLIME_PROJECT = 'sublime_project'
SUBLIME_TS = 'sublime_ts'
NO_PROJECT = 'no_project'
# ----------------------------------------- SETTINGS ---------------------------------------- #
class Settings(object):
projects_type = {}
def __init__(self):
super(Settings, self).__init__()
def get(self, token, root):
return self.projects_type[root].get(get_any_view_with_root(root),token)
<|code_end|>
, determine the next line of code. You have imports:
import sublime
import sys
import os
from .Liste import get_root
from ..Utils import read_and_decode_json_file, read_file, get_any_ts_view, fn2l, get_any_view_with_root
and context (class names, function names, or code) available:
# Path: lib/system/busted/Liste.py
# def get_root(self,filename):
# """ return <root filename> of file <filename> or None """
# if not filename or not self.has(filename):
# return None
# return self.liste[fn2k(filename)]['root']
. Output only the next line. | def get_root(self, view): |
Given the following code snippet before the placeholder: <|code_start|># coding=utf8
class Message(object):
messages =[]
def show(self, message, hide=False, with_panel=True):
self.messages = []
self.messages.append(message)
if with_panel:
window = sublime.active_window()
window.run_command("hide_overlay")
window.show_quick_panel(self.messages, self.hide)
sublime.status_message(message)
if hide:
<|code_end|>
, predict the next line using imports from the current file:
import sublime
from ..utils.debounce import debounce
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debounce.py
# def debounce(fn, delay=DEFAULT_DEBOUNCE_DELAY, uid=None, *args):
# uid = uid if uid else fn
#
# if uid in debounced_timers:
# debounced_timers[uid].cancel()
#
# timer = threading.Timer(delay, fn, args)
# timer.start()
#
# debounced_timers[uid] = timer
. Output only the next line. | debounce(self.hide, 1, 'message' + str(id(MESSAGE))) |
Continue the code snippet: <|code_start|>
# has a global variable in globals.py
def is_plugin_globally_disabled():
return "*global" in plugin_disabled_for_folders
def is_plugin_temporarily_disabled(folder=None):
""" Returns True if the plugin is disabled globally or for folder.
Folder can be a view """
if is_plugin_globally_disabled() or folder is None:
return is_plugin_globally_disabled()
if folder is not None and isinstance(folder, sublime.View):
if folder.file_name() is None:
return is_plugin_globally_disabled()
folder = os.path.dirname(folder.file_name())
folder = os.path.normcase(folder)
return folder in plugin_disabled_for_folders
def set_plugin_temporarily_enabled(folder=None):
""" Disables the plugin globally or for folder.
Folder can be a view """
if folder is None:
if is_plugin_globally_disabled():
plugin_disabled_for_folders.remove("*global")
else:
if isinstance(folder, sublime.View):
folder = os.path.dirname(folder.file_name())
folder = os.path.normcase(folder)
<|code_end|>
. Use current file imports:
import sublime
import os
from .debug import Debug
from ..system.globals import plugin_disabled_for_folders
and context (classes, functions, or code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/system/globals.py
# OPENED_PROJECTS = {}
. Output only the next line. | Debug('project', 'Enable ArcticTypescript for %s' % folder) |
Continue the code snippet: <|code_start|># coding=utf8
try:
except ImportError:
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel, triggered_for_file):
self.triggered_for_file = triggered_for_file
self.window_for_panel = window_for_panel
self.project = project
self.p = None
self.cancel_build = False
Thread.__init__(self)
def run(self):
if self.p is not None:
<|code_end|>
. Use current file imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and context (classes, functions, or code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
. Output only the next line. | Debug('error', "Only use Compiler Object once!") |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel, triggered_for_file):
self.triggered_for_file = triggered_for_file
self.window_for_panel = window_for_panel
self.project = project
self.p = None
self.cancel_build = False
Thread.__init__(self)
def run(self):
if self.p is not None:
Debug('error', "Only use Compiler Object once!")
self.cwd = os.path.abspath(self.project.tsconfigdir)
node_path, compile_cmd = self._make_commandline()
<|code_end|>
using the current file's imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
. Output only the next line. | self.kwargs = get_kwargs() |
Given the following code snippet before the placeholder: <|code_start|> Debug('build', '> Cancel Build')
self.cancel_build = True
self.answer_pending.put("")
Debug('build', 'Ask for authoritation of post/pre commands')
sublime.active_window().show_quick_panel(messages, on_done)
# Wait until user has choosen
self.answer_pending.get() # blocking until answered
Debug('build', 'Continue with Compiler Thread')
self._authorize_shell_execution() # check again, this time it should not ask
def _run_command(self, cmd, shell=False):
if self.cancel_build:
return
Debug('build', 'BUILD EXECUTE: %s' % str(cmd))
if isinstance(cmd, str):
self._show_output(">>> %s\n" % cmd.replace("\n", "\\n"))
else:
self._show_output(">>> %s\n" % cmd)
self.p = Popen(cmd, stdin=PIPE, stdout=PIPE, cwd=self.cwd, shell=shell, **self.kwargs)
self._run_forward_compiler_output()
def _make_commandline(self):
""" generates the commandline to start either tss.js or tsserver.js,
depending on the project settings """
node_path = default_node_path(self.project.get_setting('node_path'))
<|code_end|>
, predict the next line using imports from the current file:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
. Output only the next line. | tsc_path = default_tsc_path(self.project.get_setting('tsc_path'), |
Predict the next line after this snippet: <|code_start|> else:
Debug('build', '> Cancel Build')
self.cancel_build = True
self.answer_pending.put("")
Debug('build', 'Ask for authoritation of post/pre commands')
sublime.active_window().show_quick_panel(messages, on_done)
# Wait until user has choosen
self.answer_pending.get() # blocking until answered
Debug('build', 'Continue with Compiler Thread')
self._authorize_shell_execution() # check again, this time it should not ask
def _run_command(self, cmd, shell=False):
if self.cancel_build:
return
Debug('build', 'BUILD EXECUTE: %s' % str(cmd))
if isinstance(cmd, str):
self._show_output(">>> %s\n" % cmd.replace("\n", "\\n"))
else:
self._show_output(">>> %s\n" % cmd)
self.p = Popen(cmd, stdin=PIPE, stdout=PIPE, cwd=self.cwd, shell=shell, **self.kwargs)
self._run_forward_compiler_output()
def _make_commandline(self):
""" generates the commandline to start either tss.js or tsserver.js,
depending on the project settings """
<|code_end|>
using the current file's imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
. Output only the next line. | node_path = default_node_path(self.project.get_setting('node_path')) |
Given the following code snippet before the placeholder: <|code_start|>
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel, triggered_for_file):
self.triggered_for_file = triggered_for_file
self.window_for_panel = window_for_panel
self.project = project
self.p = None
self.cancel_build = False
Thread.__init__(self)
def run(self):
if self.p is not None:
Debug('error', "Only use Compiler Object once!")
self.cwd = os.path.abspath(self.project.tsconfigdir)
node_path, compile_cmd = self._make_commandline()
self.kwargs = get_kwargs()
self._prepare_pre_and_post_commands()
PANEL.clear(self.window_for_panel)
if self.post_pre_authorized:
for pre_cmd in self.pre_processing_commands:
<|code_end|>
, predict the next line using imports from the current file:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
. Output only the next line. | pre_cmd = expand_variables(str(pre_cmd), self.project, use_cache=True) |
Predict the next line for this snippet: <|code_start|>
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel, triggered_for_file):
self.triggered_for_file = triggered_for_file
self.window_for_panel = window_for_panel
self.project = project
self.p = None
self.cancel_build = False
Thread.__init__(self)
def run(self):
if self.p is not None:
Debug('error', "Only use Compiler Object once!")
self.cwd = os.path.abspath(self.project.tsconfigdir)
node_path, compile_cmd = self._make_commandline()
self.kwargs = get_kwargs()
self._prepare_pre_and_post_commands()
<|code_end|>
with the help of current file imports:
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue
from Queue import Queue
from ..utils import package_path, Debug
from ..utils.osutils import get_kwargs
from ..utils.pathutils import default_tsc_path, default_node_path, expand_variables
from ..display.Panel import PANEL
import sublime
import os
import json
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/pathutils.py
# def default_tsc_path(tsc_path=None, project=None):
# if tsc_path is not None and tsc_path:
# tsc_path = expand_variables(tsc_path, project)
# return tsc_path
#
# # search node_modules
# if project:
# node_modules_dir = search_node_modules(project.tsconfigdir)
# if node_modules_dir:
# tsc_path = os.path.join(node_modules_dir, ".bin", "tsc")
# if file_exists(tsc_path):
# return os.path.normcase(tsc_path)
#
# # use ArcticTypescript's tsc
# return os.path.join(package_path, 'bin', 'node_modules', 'typescript', 'bin', 'tsc')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# def expand_variables(path, project=None, use_cache=False):
# variables = {}
# if project is not None:
# variables.update(project.extract_variables(use_cache))
# return replace_variables(path, variables)
#
# Path: lib/display/Panel.py
# PANEL = Panel()
, which may contain function names, class names, or code. Output only the next line. | PANEL.clear(self.window_for_panel) |
Predict the next line for this snippet: <|code_start|># coding=utf8
empty_tsconfig = {
"compilerOptions": {},
}
# ##########################################################################
# ################### MAIN: lints entry point ##########
# ##########################################################################
@catch_CancelCommand
def check_tsconfig(view):
""" Tests view for being a tsconfig.json.
Reads the tsconfig.json and checks for errors.
Show Errors using Regions.
Set a error map [<(a,b), msg>] into views settings. """
if not _is_valid_and_enabled(view):
return
<|code_end|>
with the help of current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
, which may contain function names, class names, or code. Output only the next line. | Debug('tsconfig', 'tsconfig modified, check') |
Predict the next line after this snippet: <|code_start|># coding=utf8
empty_tsconfig = {
"compilerOptions": {},
}
# ##########################################################################
# ################### MAIN: lints entry point ##########
# ##########################################################################
<|code_end|>
using the current file's imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | @catch_CancelCommand |
Given the code snippet: <|code_start|>
def _add_regions(self):
""" Display all found Errors """
if self.view:
self.view.add_regions('tsconfig-error', self.error_regions,
'invalid', 'dot', sublime.DRAW_NO_FILL)
# ######################################################################
# ############### READ CONTENT ##########
# ######################################################################
def _read_file_and_set_paths(self):
""" Reads content from view into self.content and self.len """
if self.view:
self.file_name = self.view.file_name()
self.content = get_content(self.view)
self.len = len(self.content)
elif self.file_name:
self.content = read_file(self.file_name)
self.len = len(self.content)
else:
Debug('error', "Tsconfiglinter: either view or filename is required");
self.tsconfigdir = os.path.abspath(os.path.dirname(self.file_name))
if self.content is None:
self.numerrors += 1
Debug('tsconfig', 'Could not read content from view.')
<|code_end|>
, generate the next line using the imports in this file:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context (functions, classes, or occasionally code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | raise CancelCommand() |
Based on the snippet: <|code_start|> error_locations = []
error_locations.extend(self.harderrors)
error_locations.extend(self.softerrors)
self.view.settings().set('tsconfig-lints', error_locations)
# ######################################################################
# ############### DISPLAY ##########
# ######################################################################
def _add_regions(self):
""" Display all found Errors """
if self.view:
self.view.add_regions('tsconfig-error', self.error_regions,
'invalid', 'dot', sublime.DRAW_NO_FILL)
# ######################################################################
# ############### READ CONTENT ##########
# ######################################################################
def _read_file_and_set_paths(self):
""" Reads content from view into self.content and self.len """
if self.view:
self.file_name = self.view.file_name()
self.content = get_content(self.view)
self.len = len(self.content)
elif self.file_name:
<|code_end|>
, predict the immediate next line with the help of imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context (classes, functions, sometimes code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | self.content = read_file(self.file_name) |
Given the code snippet: <|code_start|> """ Stores the errors in view.settings()
Format: [<((a,b), msg)>] """
if self.view:
error_locations = []
error_locations.extend(self.harderrors)
error_locations.extend(self.softerrors)
self.view.settings().set('tsconfig-lints', error_locations)
# ######################################################################
# ############### DISPLAY ##########
# ######################################################################
def _add_regions(self):
""" Display all found Errors """
if self.view:
self.view.add_regions('tsconfig-error', self.error_regions,
'invalid', 'dot', sublime.DRAW_NO_FILL)
# ######################################################################
# ############### READ CONTENT ##########
# ######################################################################
def _read_file_and_set_paths(self):
""" Reads content from view into self.content and self.len """
if self.view:
self.file_name = self.view.file_name()
<|code_end|>
, generate the next line using the imports in this file:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context (functions, classes, or occasionally code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | self.content = get_content(self.view) |
Continue the code snippet: <|code_start|> return
self._soft_error("key '%s' is spelled wrong" % k,
self._lint_key(k))
return key_found
def _check_root_dicts(self):
""" Check Type of root dicts == dict.
Returns True if everything is ok. """
# root
if type(self.tsconfig) != dict:
self._hard_error("root structure must be an object: { }",
self._lint_range(0, self.len - 1))
return False
# first layer
valid = self._execute_validator(dict, self.tsconfig, 'compilerOptions'), \
self._execute_validator(list, self.tsconfig, 'files'), \
self._execute_validator(list, self.tsconfig, 'filesGlob'), \
self._execute_validator(dict, self.tsconfig, 'ArcticTypescript')
return all(valid)
def _check_unknown_keys(self):
""" Check for unknown keys in compilerOptions and ArcticTypescript """
if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
<|code_end|>
. Use current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context (classes, functions, or code) from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | if option not in allowed_compileroptions: |
Here is a snippet: <|code_start|> def _check_root_dicts(self):
""" Check Type of root dicts == dict.
Returns True if everything is ok. """
# root
if type(self.tsconfig) != dict:
self._hard_error("root structure must be an object: { }",
self._lint_range(0, self.len - 1))
return False
# first layer
valid = self._execute_validator(dict, self.tsconfig, 'compilerOptions'), \
self._execute_validator(list, self.tsconfig, 'files'), \
self._execute_validator(list, self.tsconfig, 'filesGlob'), \
self._execute_validator(dict, self.tsconfig, 'ArcticTypescript')
return all(valid)
def _check_unknown_keys(self):
""" Check for unknown keys in compilerOptions and ArcticTypescript """
if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
if option not in allowed_compileroptions:
self._soft_error("unknown key '%s' in compilerOptions"
% option,
self._lint_key(option))
if "ArcticTypescript" in self.tsconfig:
for option in self.tsconfig["ArcticTypescript"].keys():
<|code_end|>
. Write the next line using the current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
, which may include functions, classes, or code. Output only the next line. | if option not in allowed_settings: |
Here is a snippet: <|code_start|> return all(valid)
def _check_unknown_keys(self):
""" Check for unknown keys in compilerOptions and ArcticTypescript """
if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
if option not in allowed_compileroptions:
self._soft_error("unknown key '%s' in compilerOptions"
% option,
self._lint_key(option))
if "ArcticTypescript" in self.tsconfig:
for option in self.tsconfig["ArcticTypescript"].keys():
if option not in allowed_settings:
self._soft_error("unknown key '%s' in ArcticTypescript"
% option,
self._lint_key(option))
# ######################################################################
# ############### LINT VALUES ##########
# ######################################################################
def _validate_values(self):
""" Validate compilerOptions and ArcticTypescript using the validators
from utils.options """
if "compilerOptions" in self.tsconfig:
<|code_end|>
. Write the next line using the current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
, which may include functions, classes, or code. Output only the next line. | for key, validator in compileroptions_validations.items(): |
Predict the next line for this snippet: <|code_start|> if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
if option not in allowed_compileroptions:
self._soft_error("unknown key '%s' in compilerOptions"
% option,
self._lint_key(option))
if "ArcticTypescript" in self.tsconfig:
for option in self.tsconfig["ArcticTypescript"].keys():
if option not in allowed_settings:
self._soft_error("unknown key '%s' in ArcticTypescript"
% option,
self._lint_key(option))
# ######################################################################
# ############### LINT VALUES ##########
# ######################################################################
def _validate_values(self):
""" Validate compilerOptions and ArcticTypescript using the validators
from utils.options """
if "compilerOptions" in self.tsconfig:
for key, validator in compileroptions_validations.items():
self._execute_validator(validator,
self.tsconfig["compilerOptions"], key)
if "ArcticTypescript" in self.tsconfig:
<|code_end|>
with the help of current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
, which may contain function names, class names, or code. Output only the next line. | for key, validator in settings_validations.items(): |
Given snippet: <|code_start|> if view.settings().has('tsconfig-lints'):
error_locations = view.settings().get('tsconfig-lints', [])
current_errors = []
current_selection = view.sel()[0]
for pos, error in error_locations:
error_region = sublime.Region(pos[0], pos[1])
if current_selection.intersects(error_region):
current_errors.append(error)
if len(current_errors):
view.set_status('tsconfig-errors', ' | '.join(current_errors))
else:
view.erase_status('tsconfig-errors')
# ######################################################################
# ############### HELPERS ##########
# ######################################################################
def _is_valid_and_enabled(view):
""" Returns True if tslint should be activated """
if not view.is_valid() or view.is_loading():
return False
if not _is_tsconfig(view):
return False
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sublime
import json
import os
import re
from ..utils.debug import Debug
from ..utils.CancelCommand import catch_CancelCommand, CancelCommand
from ..utils.fileutils import read_file
from ..utils.pathutils import package_path
from ..utils.viewutils import get_content
from ..utils.options import allowed_compileroptions, \
allowed_settings, \
compileroptions_validations, \
settings_validations
from ..utils.disabling import set_tsglobexpansion_disabled, \
set_tsglobexpansion_enabled, \
is_tsglobexpansion_disabled
and context:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/CancelCommand.py
# def catch_CancelCommand(func):
# """ Decorate every command with this one. It will check for
# the plugin disabled flag and catch CancelCommand exceptins. """
#
# def catcher(*kargs, **kwargs):
# if is_plugin_temporarily_disabled():
# return # do not execute command
# try:
# return func(*kargs, **kwargs)
# except CancelCommand:
# Debug('command', "A COMMAND WAS CANCELED")
# return False
# return catcher
#
# class CancelCommand(Exception):
# """ Throw this exception in a command. The decorator
# catch_CancelCommand will catch it and cancel silently """
# pass
#
# Path: lib/utils/fileutils.py
# def read_file(filename):
# """ returns None or file contents if available """
# filename = os.path.normcase(filename) # back to \\ in nt
# if os.path.isfile(filename):
# try:
# if os.name == 'nt':
# return open(filename, 'r', encoding='utf8').read()
# else:
# return codecs.open(filename, 'r', 'utf-8').read()
# except IOError:
# pass
# return None
#
# Path: lib/utils/pathutils.py
# def add_usr_local_bin_to_path_on_osx():
# def find_tsconfigdir(rootdir):
# def expand_variables(path, project=None, use_cache=False):
# def get_tss_path():
# def get_expandglob_path():
# def default_node_path(node_path, project=None):
# def default_tsc_path(tsc_path=None, project=None):
# def search_node_modules(rootdir):
#
# Path: lib/utils/viewutils.py
# def get_content(view):
# return view.substr(sublime.Region(0, view.size()))
#
# Path: lib/utils/options.py
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
which might include code, classes, or functions. Output only the next line. | if is_tsglobexpansion_disabled(): |
Continue the code snippet: <|code_start|># coding=utf8
# PACKAGE PATH
package_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
def add_usr_local_bin_to_path_on_osx():
""" OBSOLETE
Adds /usr/local/bin to path on mac osx, because that is
where nodejs lives.
This function has not worked out its intension. Popen does not
use this PATH as a search base for the executable.
default_node_path() is back to it's previous state."""
if os.environ.get('PATH') and sys.platform == 'darwin':
if '/usr/local/bin' in os.environ.get('PATH').split(':'):
os.environ['PATH'] = os.environ.get('PATH') + ":'/usr/local/bin'"
def find_tsconfigdir(rootdir):
""" Returns the normalized dir, in which the tsconfig.json file is located"""
rootdir = os.path.abspath(rootdir)
try:
<|code_end|>
. Use current file imports:
import os
import sys
from .fileutils import file_exists
from .utils import replace_variables
from .debug import Debug
and context (classes, functions, or code) from other files:
# Path: lib/utils/fileutils.py
# def file_exists(filename):
# """ returns weather the file exists """
# return os.path.isfile(os.path.normcase(filename))
#
# Path: lib/utils/utils.py
# def replace_variables(value, variables):
# if hasattr(sublime, 'expand_variables'): # ST3, Build 3068
# # stringify dict
# for k in variables.keys():
# variables[k] = str(variables[k]);
# return sublime.expand_variables(value, variables)
# else:
# # sort keys after length, to get $file_path before $file
# keys = list(variables.keys())
# keys.sort(key=len, reverse=True)
# for k in keys:
# key = "${%s}" % k
# if key in value:
# value = value.replace(key, str(variables[k]))
# return value
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
. Output only the next line. | if file_exists(os.path.join(rootdir, "tsconfig.json")): |
Given the code snippet: <|code_start|> """ OBSOLETE
Adds /usr/local/bin to path on mac osx, because that is
where nodejs lives.
This function has not worked out its intension. Popen does not
use this PATH as a search base for the executable.
default_node_path() is back to it's previous state."""
if os.environ.get('PATH') and sys.platform == 'darwin':
if '/usr/local/bin' in os.environ.get('PATH').split(':'):
os.environ['PATH'] = os.environ.get('PATH') + ":'/usr/local/bin'"
def find_tsconfigdir(rootdir):
""" Returns the normalized dir, in which the tsconfig.json file is located"""
rootdir = os.path.abspath(rootdir)
try:
if file_exists(os.path.join(rootdir, "tsconfig.json")):
return os.path.normcase(rootdir)
except FileNotFoundError:
pass
parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
if parentdir == rootdir:
return None
else:
return find_tsconfigdir(parentdir)
def expand_variables(path, project=None, use_cache=False):
variables = {}
if project is not None:
variables.update(project.extract_variables(use_cache))
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
from .fileutils import file_exists
from .utils import replace_variables
from .debug import Debug
and context (functions, classes, or occasionally code) from other files:
# Path: lib/utils/fileutils.py
# def file_exists(filename):
# """ returns weather the file exists """
# return os.path.isfile(os.path.normcase(filename))
#
# Path: lib/utils/utils.py
# def replace_variables(value, variables):
# if hasattr(sublime, 'expand_variables'): # ST3, Build 3068
# # stringify dict
# for k in variables.keys():
# variables[k] = str(variables[k]);
# return sublime.expand_variables(value, variables)
# else:
# # sort keys after length, to get $file_path before $file
# keys = list(variables.keys())
# keys.sort(key=len, reverse=True)
# for k in keys:
# key = "${%s}" % k
# if key in value:
# value = value.replace(key, str(variables[k]))
# return value
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
. Output only the next line. | return replace_variables(path, variables) |
Predict the next line for this snippet: <|code_start|> except FileNotFoundError:
pass
parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
if parentdir == rootdir:
return None
else:
return find_tsconfigdir(parentdir)
def expand_variables(path, project=None, use_cache=False):
variables = {}
if project is not None:
variables.update(project.extract_variables(use_cache))
return replace_variables(path, variables)
# GET TSS PATH
def get_tss_path():
""" Return path to tss.js """
return os.path.join(package_path, 'bin', 'tss.js')
# GET TSS PATH
def get_expandglob_path():
""" Return path to expandglob.js """
return os.path.join(package_path, 'bin', 'expandglob.js')
def default_node_path(node_path, project=None):
if node_path == 'none':
<|code_end|>
with the help of current file imports:
import os
import sys
from .fileutils import file_exists
from .utils import replace_variables
from .debug import Debug
and context from other files:
# Path: lib/utils/fileutils.py
# def file_exists(filename):
# """ returns weather the file exists """
# return os.path.isfile(os.path.normcase(filename))
#
# Path: lib/utils/utils.py
# def replace_variables(value, variables):
# if hasattr(sublime, 'expand_variables'): # ST3, Build 3068
# # stringify dict
# for k in variables.keys():
# variables[k] = str(variables[k]);
# return sublime.expand_variables(value, variables)
# else:
# # sort keys after length, to get $file_path before $file
# keys = list(variables.keys())
# keys.sort(key=len, reverse=True)
# for k in keys:
# key = "${%s}" % k
# if key in value:
# value = value.replace(key, str(variables[k]))
# return value
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
, which may contain function names, class names, or code. Output only the next line. | Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.') |
Using the snippet: <|code_start|>
# Expanding?
if is_tsglobexpansion_disabled():
return False
if linter is None or not linter or not linter.linted:
return False
if len(linter.harderrors) > 0:
return False
if len(linter.softerrors) != linter.numerrors:
return False
if linter.content == "":
return False
if "filesGlob" not in linter.tsconfig:
return True # Should reopen project, so return True here
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
Debug("tsconfig.json", "fileGlobs expaned")
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are still displayed
<|code_end|>
, determine the next line of code. You have imports:
import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled
and context (class names, function names, or code) available:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | check_tsconfig(linter.view) |
Based on the snippet: <|code_start|> This operates on the file contents, so the file should have been saved
before.
Returns immediately if not linted or linter is None
Returns True if the filesGlob has been expanded
Returns False if there was a linter error, so no expansion has been done
"""
# Expanding?
if is_tsglobexpansion_disabled():
return False
if linter is None or not linter or not linter.linted:
return False
if len(linter.harderrors) > 0:
return False
if len(linter.softerrors) != linter.numerrors:
return False
if linter.content == "":
return False
if "filesGlob" not in linter.tsconfig:
return True # Should reopen project, so return True here
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled
and context (classes, functions, sometimes code) from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | Debug("tsconfig.json", "fileGlobs expaned") |
Here is a snippet: <|code_start|>
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
Debug("tsconfig.json", "fileGlobs expaned")
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are still displayed
check_tsconfig(linter.view)
return True
def _expand_globs_with_javascript(project_dir, linter):
""" use the nodejs script bin/expandglob.js to expand the glob entries in
the already saved file tsconfig.json in project_dir.
Returns the files list, but also CHANGES THE DISK CONTENTS.
We use javascript here, because python shuffles the dicts keys in each
iteration """
try:
node_path = None
if "ArcticTypescript" in linter.tsconfig:
if "node_path" in linter.tsconfig["ArcticTypescript"]:
node_path = linter.tsconfig["ArcticTypescript"]["node_path"]
node_path = default_node_path(node_path)
<|code_end|>
. Write the next line using the current file imports:
import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled
and context from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
, which may include functions, classes, or code. Output only the next line. | expandglob_path = get_expandglob_path() |
Next line prediction: <|code_start|> if "filesGlob" not in linter.tsconfig:
return True # Should reopen project, so return True here
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
Debug("tsconfig.json", "fileGlobs expaned")
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are still displayed
check_tsconfig(linter.view)
return True
def _expand_globs_with_javascript(project_dir, linter):
""" use the nodejs script bin/expandglob.js to expand the glob entries in
the already saved file tsconfig.json in project_dir.
Returns the files list, but also CHANGES THE DISK CONTENTS.
We use javascript here, because python shuffles the dicts keys in each
iteration """
try:
node_path = None
if "ArcticTypescript" in linter.tsconfig:
if "node_path" in linter.tsconfig["ArcticTypescript"]:
node_path = linter.tsconfig["ArcticTypescript"]["node_path"]
<|code_end|>
. Use current file imports:
(import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled)
and context including class names, function names, or small code snippets from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | node_path = default_node_path(node_path) |
Predict the next line after this snippet: <|code_start|>
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are still displayed
check_tsconfig(linter.view)
return True
def _expand_globs_with_javascript(project_dir, linter):
""" use the nodejs script bin/expandglob.js to expand the glob entries in
the already saved file tsconfig.json in project_dir.
Returns the files list, but also CHANGES THE DISK CONTENTS.
We use javascript here, because python shuffles the dicts keys in each
iteration """
try:
node_path = None
if "ArcticTypescript" in linter.tsconfig:
if "node_path" in linter.tsconfig["ArcticTypescript"]:
node_path = linter.tsconfig["ArcticTypescript"]["node_path"]
node_path = default_node_path(node_path)
expandglob_path = get_expandglob_path()
cwd = os.path.abspath(project_dir)
cmdline = [node_path, expandglob_path]
<|code_end|>
using the current file's imports:
import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled
and any relevant context from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | kwargs = get_kwargs() |
Continue the code snippet: <|code_start|>
# from pathlib import Path # not avalilable in python 3.3 (only 3.4)
# Expanding is now done via javascript expandglob.js
# There are too many differences between the glob implementations, and pathutils
# are not available for now
# Second reason for pure js solution: python shuffles the dicts keys in each iteration
#
# [1] https://github.com/TypeStrong/atom-typescript/issues/172
# [2] https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md
# [3] https://github.com/TypeStrong/atom-typescript/blob/master/lib/main/tsconfig/tsconfig.ts
# [4] https://github.com/anodynos/node-glob-expand/blob/master/source/code/expand.coffee
def expand_filesglob(linter):
"""
This mimics the filesGlob behaviour of atom-typescript [2]
If tsconfig.json has no HardErrors, it executes bin/expandglob.js
and reloads linter.view from disk.
This operates on the file contents, so the file should have been saved
before.
Returns immediately if not linted or linter is None
Returns True if the filesGlob has been expanded
Returns False if there was a linter error, so no expansion has been done
"""
# Expanding?
<|code_end|>
. Use current file imports:
import os
import glob
import json
from subprocess import Popen, PIPE, TimeoutExpired
from .TsconfigLinter import check_tsconfig
from ..utils.debug import Debug
from ..utils.pathutils import get_expandglob_path, default_node_path
from ..utils.osutils import get_kwargs
from ..utils.disabling import set_tsglobexpansion_disabled, set_tsglobexpansion_enabled, is_tsglobexpansion_disabled
and context (classes, functions, or code) from other files:
# Path: lib/tsconfiglint/TsconfigLinter.py
# @catch_CancelCommand
# def check_tsconfig(view):
# """ Tests view for being a tsconfig.json.
# Reads the tsconfig.json and checks for errors.
# Show Errors using Regions.
# Set a error map [<(a,b), msg>] into views settings. """
#
# if not _is_valid_and_enabled(view):
# return
#
# Debug('tsconfig', 'tsconfig modified, check')
#
# linter = TsconfigLinter(view)
#
# return linter
#
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/pathutils.py
# def get_expandglob_path():
# """ Return path to expandglob.js """
# return os.path.join(package_path, 'bin', 'expandglob.js')
#
# def default_node_path(node_path, project=None):
# if node_path == 'none':
# Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.')
# node_path = None
#
# if node_path == "" or node_path is None:
# if sys.platform == "linux":
# return "nodejs"
# elif sys.platform == "nt":
# return "node"
# elif sys.platform == "darwin":
# return "/usr/local/bin/node"
# else:
# return "node"
# else:
# return expand_variables(node_path, project)
#
# Path: lib/utils/osutils.py
# def get_kwargs(stderr=True):
# if os.name == 'nt':
# startupinfo = subprocess.STARTUPINFO()
# startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# if stderr:
# #errorlog = open(os.devnull, 'w')
# return {'stderr':subprocess.DEVNULL, 'startupinfo': startupinfo}
# return {'startupinfo': startupinfo}
# else:
# return {}
#
# Path: lib/utils/disabling.py
# def set_tsglobexpansion_disabled():
# """ Sets the disabled flag for tsglobexpansion """
# if "*tsglob" not in plugin_disabled_for_folders:
# plugin_disabled_for_folders.append("*tsglob")
#
# def set_tsglobexpansion_enabled():
# """ Clears the disabled flag for tsglobexpansion """
# if "*tsglob" in plugin_disabled_for_folders:
# plugin_disabled_for_folders.remove("*tsglob")
#
# def is_tsglobexpansion_disabled():
# """ Checks the disabled flag for tsglobexpansion """
# return "*tsglob" in plugin_disabled_for_folders
. Output only the next line. | if is_tsglobexpansion_disabled(): |
Predict the next line after this snippet: <|code_start|># coding=utf8
# CANCEL COMMAND EXCEPTION
class CancelCommand(Exception):
""" Throw this exception in a command. The decorator
catch_CancelCommand will catch it and cancel silently """
pass
# CANCEL COMMAND EXCEPTION CATCHER DECORATOR
def catch_CancelCommand(func):
""" Decorate every command with this one. It will check for
the plugin disabled flag and catch CancelCommand exceptins. """
def catcher(*kargs, **kwargs):
if is_plugin_temporarily_disabled():
return # do not execute command
try:
return func(*kargs, **kwargs)
except CancelCommand:
<|code_end|>
using the current file's imports:
from .debug import Debug
from .disabling import is_plugin_temporarily_disabled
and any relevant context from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/disabling.py
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | Debug('command', "A COMMAND WAS CANCELED") |
Given the following code snippet before the placeholder: <|code_start|># coding=utf8
# CANCEL COMMAND EXCEPTION
class CancelCommand(Exception):
""" Throw this exception in a command. The decorator
catch_CancelCommand will catch it and cancel silently """
pass
# CANCEL COMMAND EXCEPTION CATCHER DECORATOR
def catch_CancelCommand(func):
""" Decorate every command with this one. It will check for
the plugin disabled flag and catch CancelCommand exceptins. """
def catcher(*kargs, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
from .debug import Debug
from .disabling import is_plugin_temporarily_disabled
and context including class names, function names, and sometimes code from other files:
# Path: lib/utils/debug.py
# def Debug(classification, text):
# if 'all' in print_classifications or classification in print_classifications:
# print("ArcticTypescript: %s: %s" % (classification.ljust(8), text))
# if classification not in possible_classifications:
# print("ArcticTypescript: debug: got unknown debug message classification: %s. " \
# "Consider adding this to possible_classifications" % classification)
# sys.stdout.flush()
#
# Path: lib/utils/disabling.py
# def is_plugin_temporarily_disabled(folder=None):
# """ Returns True if the plugin is disabled globally or for folder.
# Folder can be a view """
# if is_plugin_globally_disabled() or folder is None:
# return is_plugin_globally_disabled()
# if folder is not None and isinstance(folder, sublime.View):
# if folder.file_name() is None:
# return is_plugin_globally_disabled()
# folder = os.path.dirname(folder.file_name())
# folder = os.path.normcase(folder)
# return folder in plugin_disabled_for_folders
. Output only the next line. | if is_plugin_temporarily_disabled(): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.