Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|>from __future__ import division def cast_float(variable): return Variable(torch.from_numpy(variable).float(), requires_grad=True) <|code_end|> . Write the next line using the current file imports: import numpy as np import torch from torch.autograd import Variable from lxmls.deep_learning.mlp import MLP and context from other files: # Path: lxmls/deep_learning/mlp.py # class MLP(Model): # def __init__(self, **config): # # # CHECK THE PARAMETERS ARE VALID # self.sanity_checks(config) # # # OPTIONAL MODEL LOADING # model_folder = config.get('model_folder', None) # if model_folder is not None: # saved_config, loaded_parameters = self.load(model_folder) # # Note that if a config is given this is used instead of the saved # # one (must be consistent) # if config is None: # config = saved_config # else: # loaded_parameters = None # # # MEMBER VARIABLES # self.num_layers = len(config['geometry']) - 1 # self.config = config # self.parameters = initialize_mlp_parameters( # config['geometry'], # loaded_parameters # ) # # def sanity_checks(self, config): # # model_folder = config.get('model_folder', None) # # assert bool(config is None) or bool(model_folder is None), \ # "Need to specify config, model_folder or both" # # if model_folder is not None: # model_file = "%s/config.yml" % model_folder # assert os.path.isfile(model_file), "Need to provide %s" % model_file # # def load(self, model_folder): # """ # Load model # """ # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # config = load_config(config_file) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # loaded_parameters = load_parameters(parameter_file) # # return config, loaded_parameters # # def save(self, model_folder): # """ # Save model # """ # # # Create folder if it does not exist # if not os.path.isdir(model_folder): # os.mkdir(model_folder) # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # save_config(config_file, self.config) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # with open(parameter_file, 'wb') as fid: # cPickle.dump(self.parameters, fid, cPickle.HIGHEST_PROTOCOL) # # def plot_weights(self, show=True, aspect='auto'): # """ # Plots the weights of the newtwork # # Use show = False to plot various models one after the other # """ # import matplotlib.pyplot as plt # plt.figure() # for n in range(self.n_layers): # # # Get weights and bias # weight, bias = self.parameters[n] # # # Plot them # plt.subplot(2, self.n_layers, n+1) # plt.imshow(weight, aspect=aspect, interpolation='nearest') # plt.title('Layer %d Weight' % n) # plt.colorbar() # plt.subplot(2, self.n_layers, self.n_layers+(n+1)) # plt.plot(bias) # plt.title('Layer %d Bias' % n) # plt.colorbar() # # if show: # plt.show() , which may include functions, classes, or code. Output only the next line.
class PytorchMLP(MLP):
Predict the next line after this snippet: <|code_start|> # coding: utf-8 # ### Amazon Sentiment Data # In[ ]: corpus = srs.SentimentCorpus("books") data = AmazonData(corpus=corpus) # ### Train Log Linear in Pytorch # In order to learn the differences between a numpy and a Pytorch implementation, explore the reimplementation of Ex. 3.1 in Pytorch. Compare the content of each of the functions, in particular the `forward()` and `update()` methods. The comments indicated as IMPORTANT will highlight common sources of errors. # In[ ]: class PytorchLogLinear(Model): def __init__(self, **config): # Initialize parameters weight_shape = (config['input_size'], config['num_classes']) # after Xavier Glorot et al <|code_end|> using the current file's imports: import lxmls.readers.sentiment_reader as srs import numpy as np import torch from lxmls.deep_learning.utils import AmazonData from lxmls.deep_learning.utils import Model, glorot_weight_init from torch.autograd import Variable and any relevant context from other files: # Path: lxmls/deep_learning/utils.py # class AmazonData(object): # """ # Template # """ # def __init__(self, **config): # # # Data-sets # self.datasets = { # 'train': { # 'input': config['corpus'].train_X, # 'output': config['corpus'].train_y[:, 0] # }, # # 'dev': (config['corpus'].dev_X, config['corpus'].dev_y[:, 0]), # 'test': { # 'input': config['corpus'].test_X, # 'output': config['corpus'].test_y[:, 0] # } # } # # Config # self.config = config # # Number of samples # self.nr_samples = { # sset: content['output'].shape[0] # for sset, content in self.datasets.items() # } # # def size(self, set_name): # return self.nr_samples[set_name] # # def batches(self, set_name, batch_size=None): # # dset = self.datasets[set_name] # nr_examples = self.nr_samples[set_name] # if batch_size is None: # nr_batch = 1 # batch_size = nr_examples # else: # nr_batch = int(np.ceil(nr_examples*1./batch_size)) # # data = [] # for batch_n in range(nr_batch): # # Colect data for this batch # data_batch = {} # for side in ['input', 'output']: # data_batch[side] = dset[side][ # batch_n * batch_size:(batch_n + 1) * batch_size # ] # data.append(data_batch) # # return DataIterator(data, nr_samples=self.nr_samples[set_name]) # # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight . Output only the next line.
self.weight = glorot_weight_init(weight_shape, 'softmax')
Next line prediction: <|code_start|> # Softmax is computed in log-domain to prevent underflow/overflow log_tilde_z = z - logsumexp(z, axis=1, keepdims=True) return log_tilde_z, layer_inputs def cross_entropy_loss(self, input, output): """Cross entropy loss""" num_examples = input.shape[0] log_probability, _ = self.log_forward(input) return -log_probability[range(num_examples), output].mean() def backpropagation(self, input, output): """Gradients for sigmoid hidden layers and output softmax""" # Run forward and store activations for each layer log_prob_y, layer_inputs = self.log_forward(input) prob_y = np.exp(log_prob_y) num_examples, num_clases = prob_y.shape num_hidden_layers = len(self.parameters) - 1 # For each layer in reverse store the backpropagated error, then # compute the gradients from the errors and the layer inputs errors = [] # ---------- # Solution to Exercise 3.2 # Initial error is the cost derivative at the last layer (for cross # entropy cost) <|code_end|> . Use current file imports: (import numpy as np from lxmls.deep_learning.mlp import MLP from lxmls.deep_learning.utils import index2onehot, logsumexp) and context including class names, function names, or small code snippets from other files: # Path: lxmls/deep_learning/mlp.py # class MLP(Model): # def __init__(self, **config): # # # CHECK THE PARAMETERS ARE VALID # self.sanity_checks(config) # # # OPTIONAL MODEL LOADING # model_folder = config.get('model_folder', None) # if model_folder is not None: # saved_config, loaded_parameters = self.load(model_folder) # # Note that if a config is given this is used instead of the saved # # one (must be consistent) # if config is None: # config = saved_config # else: # loaded_parameters = None # # # MEMBER VARIABLES # self.num_layers = len(config['geometry']) - 1 # self.config = config # self.parameters = initialize_mlp_parameters( # config['geometry'], # loaded_parameters # ) # # def sanity_checks(self, config): # # model_folder = config.get('model_folder', None) # # assert bool(config is None) or bool(model_folder is None), \ # "Need to specify config, model_folder or both" # # if model_folder is not None: # model_file = "%s/config.yml" % model_folder # assert os.path.isfile(model_file), "Need to provide %s" % model_file # # def load(self, model_folder): # """ # Load model # """ # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # config = load_config(config_file) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # loaded_parameters = load_parameters(parameter_file) # # return config, loaded_parameters # # def save(self, model_folder): # """ # Save model # """ # # # Create folder if it does not exist # if not os.path.isdir(model_folder): # os.mkdir(model_folder) # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # save_config(config_file, self.config) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # with open(parameter_file, 'wb') as fid: # cPickle.dump(self.parameters, fid, cPickle.HIGHEST_PROTOCOL) # # def plot_weights(self, show=True, aspect='auto'): # """ # Plots the weights of the newtwork # # Use show = False to plot various models one after the other # """ # import matplotlib.pyplot as plt # plt.figure() # for n in range(self.n_layers): # # # Get weights and bias # weight, bias = self.parameters[n] # # # Plot them # plt.subplot(2, self.n_layers, n+1) # plt.imshow(weight, aspect=aspect, interpolation='nearest') # plt.title('Layer %d Weight' % n) # plt.colorbar() # plt.subplot(2, self.n_layers, self.n_layers+(n+1)) # plt.plot(bias) # plt.title('Layer %d Bias' % n) # plt.colorbar() # # if show: # plt.show() # # Path: lxmls/deep_learning/utils.py # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot # # def logsumexp(a, axis=None, keepdims=False): # """ # This is an improvement over the original logsumexp of # scipy/maxentropy/maxentutils.py that allows specifying an axis to sum # It also allows keepdims=True. # """ # if axis is None: # a = np.asarray(a) # a_max = a.max() # return a_max + np.log(np.exp(a-a_max).sum()) # else: # a_max = np.amax(a, axis=axis, keepdims=keepdims) # return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims)) . Output only the next line.
I = index2onehot(output, num_clases)
Based on the snippet: <|code_start|> def log_forward(self, input): """Forward pass for sigmoid hidden layers and output softmax""" # Input tilde_z = input layer_inputs = [] # Hidden layers num_hidden_layers = len(self.parameters) - 1 for n in range(num_hidden_layers): # Store input to this layer (needed for backpropagation) layer_inputs.append(tilde_z) # Linear transformation weight, bias = self.parameters[n] z = np.dot(tilde_z, weight.T) + bias # Non-linear transformation (sigmoid) tilde_z = 1.0 / (1 + np.exp(-z)) # Store input to last layer layer_inputs.append(tilde_z) # Output linear transformation weight, bias = self.parameters[num_hidden_layers] z = np.dot(tilde_z, weight.T) + bias # Softmax is computed in log-domain to prevent underflow/overflow <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from lxmls.deep_learning.mlp import MLP from lxmls.deep_learning.utils import index2onehot, logsumexp and context (classes, functions, sometimes code) from other files: # Path: lxmls/deep_learning/mlp.py # class MLP(Model): # def __init__(self, **config): # # # CHECK THE PARAMETERS ARE VALID # self.sanity_checks(config) # # # OPTIONAL MODEL LOADING # model_folder = config.get('model_folder', None) # if model_folder is not None: # saved_config, loaded_parameters = self.load(model_folder) # # Note that if a config is given this is used instead of the saved # # one (must be consistent) # if config is None: # config = saved_config # else: # loaded_parameters = None # # # MEMBER VARIABLES # self.num_layers = len(config['geometry']) - 1 # self.config = config # self.parameters = initialize_mlp_parameters( # config['geometry'], # loaded_parameters # ) # # def sanity_checks(self, config): # # model_folder = config.get('model_folder', None) # # assert bool(config is None) or bool(model_folder is None), \ # "Need to specify config, model_folder or both" # # if model_folder is not None: # model_file = "%s/config.yml" % model_folder # assert os.path.isfile(model_file), "Need to provide %s" % model_file # # def load(self, model_folder): # """ # Load model # """ # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # config = load_config(config_file) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # loaded_parameters = load_parameters(parameter_file) # # return config, loaded_parameters # # def save(self, model_folder): # """ # Save model # """ # # # Create folder if it does not exist # if not os.path.isdir(model_folder): # os.mkdir(model_folder) # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # save_config(config_file, self.config) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # with open(parameter_file, 'wb') as fid: # cPickle.dump(self.parameters, fid, cPickle.HIGHEST_PROTOCOL) # # def plot_weights(self, show=True, aspect='auto'): # """ # Plots the weights of the newtwork # # Use show = False to plot various models one after the other # """ # import matplotlib.pyplot as plt # plt.figure() # for n in range(self.n_layers): # # # Get weights and bias # weight, bias = self.parameters[n] # # # Plot them # plt.subplot(2, self.n_layers, n+1) # plt.imshow(weight, aspect=aspect, interpolation='nearest') # plt.title('Layer %d Weight' % n) # plt.colorbar() # plt.subplot(2, self.n_layers, self.n_layers+(n+1)) # plt.plot(bias) # plt.title('Layer %d Bias' % n) # plt.colorbar() # # if show: # plt.show() # # Path: lxmls/deep_learning/utils.py # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot # # def logsumexp(a, axis=None, keepdims=False): # """ # This is an improvement over the original logsumexp of # scipy/maxentropy/maxentutils.py that allows specifying an axis to sum # It also allows keepdims=True. # """ # if axis is None: # a = np.asarray(a) # a_max = a.max() # return a_max + np.log(np.exp(a-a_max).sum()) # else: # a_max = np.amax(a, axis=axis, keepdims=keepdims) # return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims)) . Output only the next line.
log_tilde_z = z - logsumexp(z, axis=1, keepdims=True)
Next line prediction: <|code_start|> def backpropagation(self, input, output): ''' Compute gradientes, with the back-propagation method inputs: x: vector with the (embedding) indicies of the words of a sentence outputs: vector with the indicies of the tags for each word of the sentence outputs: gradient_parameters: vector with parameters gradientes ''' # Get parameters and sizes W_e, W_x, W_h, W_y = self.parameters nr_steps = input.shape[0] log_p_y, y, h, z_e, x = self.log_forward(input) p_y = np.exp(log_p_y) # Initialize gradients with zero entrances gradient_W_e = np.zeros(W_e.shape) gradient_W_x = np.zeros(W_x.shape) gradient_W_h = np.zeros(W_h.shape) gradient_W_y = np.zeros(W_y.shape) # ---------- # Solution to Exercise 6.1 # Gradient of the cost with respect to the last linear model <|code_end|> . Use current file imports: (import numpy as np from lxmls.deep_learning.rnn import RNN from lxmls.deep_learning.utils import index2onehot, logsumexp) and context including class names, function names, or small code snippets from other files: # Path: lxmls/deep_learning/rnn.py # class RNN(Model): # def __init__(self, **config): # # # CHECK THE PARAMETERS ARE VALID # self.sanity_checks(config) # # # OPTIONAL MODEL LOADING # model_folder = config.get('model_folder', None) # if model_folder is not None: # saved_config, loaded_parameters = self.load(model_folder) # # Note that if a config is given this is used instead of the saved # # one (must be consistent) # if config is None: # config = saved_config # else: # loaded_parameters = None # # # Class variables # self.config = config # self.parameters = initialize_rnn_parameters( # config['input_size'], # config['embedding_size'], # config['hidden_size'], # config['output_size'], # loaded_parameters=loaded_parameters # ) # # def sanity_checks(self, config): # # model_folder = config.get('model_folder', None) # # assert bool(config is None) or bool(model_folder is None), \ # "Need to specify config, model_folder or both" # # if config is not None: # pass # # if model_folder is not None: # model_file = "%s/config.yml" % model_folder # assert os.path.isfile(model_file), "Need to provide %s" % model_file # # def load(self, model_folder): # """ # Load model # """ # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # config = load_config(config_file) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # loaded_parameters = load_parameters(parameter_file) # # return config, loaded_parameters # # def save(self, model_folder): # """ # Save model # """ # # # Create folder if it does not exist # if not os.path.isdir(model_folder): # os.mkdir(model_folder) # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # save_config(config_file, self.config) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # with open(parameter_file, 'wb') as fid: # pickle.dump(self.parameters, fid, pickle.HIGHEST_PROTOCOL) # # def plot_weights(self, show=True, aspect='auto'): # """ # Plots the weights of the newtwork # # Use show = False to plot various models one after the other # """ # import matplotlib.pyplot as plt # plt.figure() # for n in range(self.n_layers): # # # Get weights and bias # weight, bias = self.parameters[n] # # # Plot them # plt.subplot(2, self.n_layers, n+1) # plt.imshow(weight, aspect=aspect, interpolation='nearest') # plt.title('Layer %d Weight' % n) # plt.colorbar() # plt.subplot(2, self.n_layers, self.n_layers+(n+1)) # plt.plot(bias) # plt.title('Layer %d Bias' % n) # plt.colorbar() # # if show: # plt.show() # # Path: lxmls/deep_learning/utils.py # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot # # def logsumexp(a, axis=None, keepdims=False): # """ # This is an improvement over the original logsumexp of # scipy/maxentropy/maxentutils.py that allows specifying an axis to sum # It also allows keepdims=True. # """ # if axis is None: # a = np.asarray(a) # a_max = a.max() # return a_max + np.log(np.exp(a-a_max).sum()) # else: # a_max = np.amax(a, axis=axis, keepdims=keepdims) # return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims)) . Output only the next line.
I = index2onehot(output, W_y.shape[0])
Using the snippet: <|code_start|> # Update each parameter with SGD rule num_parameters = len(self.parameters) for m in range(num_parameters): # Update weight self.parameters[m] -= learning_rate * gradients[m] def log_forward(self, input): # Get parameters and sizes W_e, W_x, W_h, W_y = self.parameters hidden_size = W_h.shape[0] nr_steps = input.shape[0] # Embedding layer z_e = W_e[input, :] # Recurrent layer h = np.zeros((nr_steps + 1, hidden_size)) for t in range(nr_steps): # Linear z_t = W_x.dot(z_e[t, :]) + W_h.dot(h[t, :]) # Non-linear h[t+1, :] = 1.0 / (1 + np.exp(-z_t)) # Output layer y = h[1:, :].dot(W_y.T) # Softmax <|code_end|> , determine the next line of code. You have imports: import numpy as np from lxmls.deep_learning.rnn import RNN from lxmls.deep_learning.utils import index2onehot, logsumexp and context (class names, function names, or code) available: # Path: lxmls/deep_learning/rnn.py # class RNN(Model): # def __init__(self, **config): # # # CHECK THE PARAMETERS ARE VALID # self.sanity_checks(config) # # # OPTIONAL MODEL LOADING # model_folder = config.get('model_folder', None) # if model_folder is not None: # saved_config, loaded_parameters = self.load(model_folder) # # Note that if a config is given this is used instead of the saved # # one (must be consistent) # if config is None: # config = saved_config # else: # loaded_parameters = None # # # Class variables # self.config = config # self.parameters = initialize_rnn_parameters( # config['input_size'], # config['embedding_size'], # config['hidden_size'], # config['output_size'], # loaded_parameters=loaded_parameters # ) # # def sanity_checks(self, config): # # model_folder = config.get('model_folder', None) # # assert bool(config is None) or bool(model_folder is None), \ # "Need to specify config, model_folder or both" # # if config is not None: # pass # # if model_folder is not None: # model_file = "%s/config.yml" % model_folder # assert os.path.isfile(model_file), "Need to provide %s" % model_file # # def load(self, model_folder): # """ # Load model # """ # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # config = load_config(config_file) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # loaded_parameters = load_parameters(parameter_file) # # return config, loaded_parameters # # def save(self, model_folder): # """ # Save model # """ # # # Create folder if it does not exist # if not os.path.isdir(model_folder): # os.mkdir(model_folder) # # # Configuration un yaml format # config_file = "%s/config.yml" % model_folder # save_config(config_file, self.config) # # # Computation graph parameters as pickle file # parameter_file = "%s/parameters.pkl" % model_folder # with open(parameter_file, 'wb') as fid: # pickle.dump(self.parameters, fid, pickle.HIGHEST_PROTOCOL) # # def plot_weights(self, show=True, aspect='auto'): # """ # Plots the weights of the newtwork # # Use show = False to plot various models one after the other # """ # import matplotlib.pyplot as plt # plt.figure() # for n in range(self.n_layers): # # # Get weights and bias # weight, bias = self.parameters[n] # # # Plot them # plt.subplot(2, self.n_layers, n+1) # plt.imshow(weight, aspect=aspect, interpolation='nearest') # plt.title('Layer %d Weight' % n) # plt.colorbar() # plt.subplot(2, self.n_layers, self.n_layers+(n+1)) # plt.plot(bias) # plt.title('Layer %d Bias' % n) # plt.colorbar() # # if show: # plt.show() # # Path: lxmls/deep_learning/utils.py # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot # # def logsumexp(a, axis=None, keepdims=False): # """ # This is an improvement over the original logsumexp of # scipy/maxentropy/maxentutils.py that allows specifying an axis to sum # It also allows keepdims=True. # """ # if axis is None: # a = np.asarray(a) # a_max = a.max() # return a_max + np.log(np.exp(a-a_max).sum()) # else: # a_max = np.amax(a, axis=axis, keepdims=keepdims) # return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims)) . Output only the next line.
log_p_y = y - logsumexp(y, axis=1, keepdims=True)
Next line prediction: <|code_start|> y_pred = hmm.posterior_decode(simple.test.seq_list[0]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['rainy', 'rainy', 'sunny', 'sunny'] y_pred = hmm.posterior_decode(simple.test.seq_list[1]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['rainy', 'rainy', 'rainy', 'rainy'] hmm.train_supervised(simple.train, smoothing=0.1) y_pred = hmm.posterior_decode(simple.test.seq_list[0]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['rainy', 'rainy', 'sunny', 'sunny'] y_pred = hmm.posterior_decode(simple.test.seq_list[1]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['sunny', 'sunny', 'sunny', 'sunny'] def test_exercise_8(hmm, simple): with warnings.catch_warnings(): warnings.simplefilter("ignore") y_pred, score = hmm.viterbi_decode(simple.test.seq_list[0]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['rainy', 'rainy', 'sunny', 'sunny'] assert abs(score - -6.02050124698) < 0.5 # Check why in pytest this gives a different result from the notebook execution y_pred, score = hmm.viterbi_decode(simple.test.seq_list[1]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['sunny', 'sunny', 'sunny', 'sunny'] assert abs(score - -11.713974074) < tolerance @pytest.fixture(scope='module') def corpus_and_sequences(): corpus = pcc.PostagCorpus() <|code_end|> . Use current file imports: (import sys import os import numpy as np import pytest import warnings import lxmls.readers.pos_corpus as pcc import lxmls.readers.simple_sequence as ssr import lxmls.sequences.hmm as hmmc from lxmls import data from lxmls.sequences.log_domain import logsum) and context including class names, function names, or small code snippets from other files: # Path: lxmls/data.py # def find(filename): . Output only the next line.
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'), max_sent_len=15, max_nr_sent=1000)
Here is a snippet: <|code_start|> # perturbation of weight values perturbations = np.linspace(-span, span, 200) # Compute the loss when varying the study weight parameters = deepcopy(model.parameters) current_weight = float(get_parameter(parameters)) loss_range = [] old_parameters = list(model.parameters) for perturbation in perturbations: # Chage parameters model.parameters = set_parameter( parameters, current_weight + perturbation ) # Compute loss perturbated_loss = model.cross_entropy_loss( batch['input'], batch['output'] ) loss_range.append(perturbated_loss) # Return to old parameters model.parameters = old_parameters weight_range = current_weight + perturbations return weight_range, loss_range <|code_end|> . Write the next line using the current file imports: import os import yaml import numpy as np import matplotlib.pyplot as plt from six.moves import cPickle from copy import deepcopy from lxmls.deep_learning.utils import Model, glorot_weight_init and context from other files: # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight , which may include functions, classes, or code. Output only the next line.
class MLP(Model):
Here is a snippet: <|code_start|>def initialize_mlp_parameters(geometry, loaded_parameters=None, random_seed=None): """ Initialize parameters from geometry or existing weights """ num_layers = len(geometry) - 1 num_hidden_layers = num_layers - 1 activation_functions = ['sigmoid']*num_hidden_layers + ['softmax'] # Initialize random seed if not given if random_seed is None: random_seed = np.random.RandomState(1234) if loaded_parameters is not None: assert len(loaded_parameters) == num_layers, \ "New geometry not matching model saved" parameters = [] for n in range(num_layers): # Weights if loaded_parameters is not None: weight, bias = loaded_parameters[n] assert weight.shape == (geometry[n+1], geometry[n]), \ "New geometry does not match for weigths in layer %d" % n assert bias.shape == (1, geometry[n+1]), \ "New geometry does not match for bias in layer %d" % n else: <|code_end|> . Write the next line using the current file imports: import os import yaml import numpy as np import matplotlib.pyplot as plt from six.moves import cPickle from copy import deepcopy from lxmls.deep_learning.utils import Model, glorot_weight_init and context from other files: # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight , which may include functions, classes, or code. Output only the next line.
weight = glorot_weight_init(
Next line prediction: <|code_start|> tolerance = 1e-5 @pytest.fixture(scope='module') def scr(): return srs.SentimentCorpus("books") # Exercise 1.1 def test_naive_bayes(scr): <|code_end|> . Use current file imports: (import sys import os import pytest import warnings import lxmls.classifiers.gaussian_naive_bayes as gnbc import lxmls.classifiers.max_ent_batch as mebc import lxmls.classifiers.max_ent_online as meoc import lxmls.classifiers.mira as mirac import lxmls.classifiers.perceptron as percc import lxmls.classifiers.svm as svmc import lxmls.readers.sentiment_reader as srs import lxmls.readers.simple_data_set as sds from numpy import allclose from lxmls.classifiers import multinomial_naive_bayes as mnbb) and context including class names, function names, or small code snippets from other files: # Path: lxmls/classifiers/multinomial_naive_bayes.py # class MultinomialNaiveBayes(lc.LinearClassifier): # def __init__(self, xtype="gaussian"): # def train(self, x, y): . Output only the next line.
mnb = mnbb.MultinomialNaiveBayes()
Here is a snippet: <|code_start|> tolerance = 1e-5 @pytest.fixture(scope='module') def corpus_and_sequences(): corpus = pcc.PostagCorpus() <|code_end|> . Write the next line using the current file imports: import sys import os import numpy as np import pytest import lxmls.readers.pos_corpus as pcc import lxmls.sequences.crf_online as crfo import lxmls.sequences.extended_feature as exfc import lxmls.sequences.id_feature as idfc import lxmls.sequences.structured_perceptron as spc from lxmls import data and context from other files: # Path: lxmls/data.py # def find(filename): , which may include functions, classes, or code. Output only the next line.
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'), max_sent_len=10, max_nr_sent=1000)
Predict the next line after this snippet: <|code_start|> # coding: utf-8 # ### Amazon Sentiment Data # To ease-up the upcoming implementation exercise, examine and comment the following implementation of a log-linear model and its gradient update rule. Start by loading Amazon sentiment corpus used in day 1 # In[ ]: corpus = srs.SentimentCorpus("books") data = AmazonData(corpus=corpus) # In[ ]: data.datasets['train'] # ### A Shallow Model: Log-Linear in Numpy # Compare the following numpy implementation of a log-linear model with the derivations seen in the previous sections. Introduce comments on the blocks marked with # relating them to the corresponding algorithm steps. # In[ ]: <|code_end|> using the current file's imports: import lxmls.readers.sentiment_reader as srs import numpy as np from lxmls.deep_learning.utils import AmazonData from lxmls.deep_learning.utils import Model, glorot_weight_init, index2onehot from scipy.special import logsumexp and any relevant context from other files: # Path: lxmls/deep_learning/utils.py # class AmazonData(object): # """ # Template # """ # def __init__(self, **config): # # # Data-sets # self.datasets = { # 'train': { # 'input': config['corpus'].train_X, # 'output': config['corpus'].train_y[:, 0] # }, # # 'dev': (config['corpus'].dev_X, config['corpus'].dev_y[:, 0]), # 'test': { # 'input': config['corpus'].test_X, # 'output': config['corpus'].test_y[:, 0] # } # } # # Config # self.config = config # # Number of samples # self.nr_samples = { # sset: content['output'].shape[0] # for sset, content in self.datasets.items() # } # # def size(self, set_name): # return self.nr_samples[set_name] # # def batches(self, set_name, batch_size=None): # # dset = self.datasets[set_name] # nr_examples = self.nr_samples[set_name] # if batch_size is None: # nr_batch = 1 # batch_size = nr_examples # else: # nr_batch = int(np.ceil(nr_examples*1./batch_size)) # # data = [] # for batch_n in range(nr_batch): # # Colect data for this batch # data_batch = {} # for side in ['input', 'output']: # data_batch[side] = dset[side][ # batch_n * batch_size:(batch_n + 1) * batch_size # ] # data.append(data_batch) # # return DataIterator(data, nr_samples=self.nr_samples[set_name]) # # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight # # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot . Output only the next line.
class NumpyLogLinear(Model):
Predict the next line after this snippet: <|code_start|># To ease-up the upcoming implementation exercise, examine and comment the following implementation of a log-linear model and its gradient update rule. Start by loading Amazon sentiment corpus used in day 1 # In[ ]: corpus = srs.SentimentCorpus("books") data = AmazonData(corpus=corpus) # In[ ]: data.datasets['train'] # ### A Shallow Model: Log-Linear in Numpy # Compare the following numpy implementation of a log-linear model with the derivations seen in the previous sections. Introduce comments on the blocks marked with # relating them to the corresponding algorithm steps. # In[ ]: class NumpyLogLinear(Model): def __init__(self, **config): # Initialize parameters weight_shape = (config['input_size'], config['num_classes']) # after Xavier Glorot et al <|code_end|> using the current file's imports: import lxmls.readers.sentiment_reader as srs import numpy as np from lxmls.deep_learning.utils import AmazonData from lxmls.deep_learning.utils import Model, glorot_weight_init, index2onehot from scipy.special import logsumexp and any relevant context from other files: # Path: lxmls/deep_learning/utils.py # class AmazonData(object): # """ # Template # """ # def __init__(self, **config): # # # Data-sets # self.datasets = { # 'train': { # 'input': config['corpus'].train_X, # 'output': config['corpus'].train_y[:, 0] # }, # # 'dev': (config['corpus'].dev_X, config['corpus'].dev_y[:, 0]), # 'test': { # 'input': config['corpus'].test_X, # 'output': config['corpus'].test_y[:, 0] # } # } # # Config # self.config = config # # Number of samples # self.nr_samples = { # sset: content['output'].shape[0] # for sset, content in self.datasets.items() # } # # def size(self, set_name): # return self.nr_samples[set_name] # # def batches(self, set_name, batch_size=None): # # dset = self.datasets[set_name] # nr_examples = self.nr_samples[set_name] # if batch_size is None: # nr_batch = 1 # batch_size = nr_examples # else: # nr_batch = int(np.ceil(nr_examples*1./batch_size)) # # data = [] # for batch_n in range(nr_batch): # # Colect data for this batch # data_batch = {} # for side in ['input', 'output']: # data_batch[side] = dset[side][ # batch_n * batch_size:(batch_n + 1) * batch_size # ] # data.append(data_batch) # # return DataIterator(data, nr_samples=self.nr_samples[set_name]) # # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight # # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot . Output only the next line.
self.weight = glorot_weight_init(weight_shape, 'softmax')
Given the following code snippet before the placeholder: <|code_start|> # Initialize parameters weight_shape = (config['input_size'], config['num_classes']) # after Xavier Glorot et al self.weight = glorot_weight_init(weight_shape, 'softmax') self.bias = np.zeros((1, config['num_classes'])) self.learning_rate = config['learning_rate'] def log_forward(self, input=None): """Forward pass of the computation graph""" # Linear transformation z = np.dot(input, self.weight.T) + self.bias # Softmax implemented in log domain log_tilde_z = z - logsumexp(z, axis=1)[:, None] return log_tilde_z def predict(self, input=None): """Prediction: most probable class index""" return np.argmax(np.exp(self.log_forward(input)), axis=1) def update(self, input=None, output=None): """Stochastic Gradient Descent update""" # Probabilities of each class class_probabilities = np.exp(self.log_forward(input)) batch_size, num_classes = class_probabilities.shape # Error derivative at softmax layer <|code_end|> , predict the next line using imports from the current file: import lxmls.readers.sentiment_reader as srs import numpy as np from lxmls.deep_learning.utils import AmazonData from lxmls.deep_learning.utils import Model, glorot_weight_init, index2onehot from scipy.special import logsumexp and context including class names, function names, and sometimes code from other files: # Path: lxmls/deep_learning/utils.py # class AmazonData(object): # """ # Template # """ # def __init__(self, **config): # # # Data-sets # self.datasets = { # 'train': { # 'input': config['corpus'].train_X, # 'output': config['corpus'].train_y[:, 0] # }, # # 'dev': (config['corpus'].dev_X, config['corpus'].dev_y[:, 0]), # 'test': { # 'input': config['corpus'].test_X, # 'output': config['corpus'].test_y[:, 0] # } # } # # Config # self.config = config # # Number of samples # self.nr_samples = { # sset: content['output'].shape[0] # for sset, content in self.datasets.items() # } # # def size(self, set_name): # return self.nr_samples[set_name] # # def batches(self, set_name, batch_size=None): # # dset = self.datasets[set_name] # nr_examples = self.nr_samples[set_name] # if batch_size is None: # nr_batch = 1 # batch_size = nr_examples # else: # nr_batch = int(np.ceil(nr_examples*1./batch_size)) # # data = [] # for batch_n in range(nr_batch): # # Colect data for this batch # data_batch = {} # for side in ['input', 'output']: # data_batch[side] = dset[side][ # batch_n * batch_size:(batch_n + 1) * batch_size # ] # data.append(data_batch) # # return DataIterator(data, nr_samples=self.nr_samples[set_name]) # # Path: lxmls/deep_learning/utils.py # class Model(object): # def __init__(self, **config): # self.initialized = False # # def initialize_features(self, *args): # self.initialized = True # raise NotImplementedError( # "Need to implement initialize_features method" # ) # # def get_features(self, input=None, output=None): # """ # Default feature extraction is do nothing # """ # return {'input': input, 'output': output} # # def predict(self, *args): # raise NotImplementedError("Need to implement predict method") # # def update(self, *args): # # This needs to return at least {'cost' : 0} # raise NotImplementedError("Need to implement update method") # return {'cost': None} # # def set(self, **kwargs): # raise NotImplementedError("Need to implement set method") # # def get(self, name): # raise NotImplementedError("Need to implement get method") # # def save(self): # raise NotImplementedError("Need to implement save method") # # def load(self, model_folder): # raise NotImplementedError("Need to implement load method") # # def glorot_weight_init(shape, activation_function, random_seed=None): # """Layer weight initialization after Xavier Glorot et. al""" # # if random_seed is None: # random_seed = np.random.RandomState(1234) # # # Weights are uniform distributed with span depending on input and output # # sizes # num_inputs, num_outputs = shape # weight = random_seed.uniform( # low=-np.sqrt(6. / (num_inputs + num_outputs)), # high=np.sqrt(6. / (num_inputs + num_outputs)), # size=(num_outputs, num_inputs) # ) # # # Scaling factor depending on non-linearity # if activation_function == 'sigmoid': # weight *= 4 # elif activation_function == 'softmax': # weight *= 4 # # return weight # # def index2onehot(index, N): # """ # Transforms index to one-hot representation, for example # # Input: e.g. index = [1, 2, 0], N = 4 # Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] # """ # L = index.shape[0] # onehot = np.zeros((L, N)) # for l in np.arange(L): # onehot[l, index[l]] = 1 # return onehot . Output only the next line.
I = index2onehot(output, num_classes)
Given the code snippet: <|code_start|> MAX_SENT_SIZE = 1000 MAX_NR_SENTENCES = 100000 MODEL_DIR = "../models/wsj_postag/" def build_corpus_features(): corpus = pcc.PostagCorpus() <|code_end|> , generate the next line using the imports in this file: from lxmls import data import readers.pos_corpus as pcc import sequences.extended_feature as exfc import sequences.structured_perceptron as spc and context (functions, classes, or occasionally code) from other files: # Path: lxmls/data.py # def find(filename): . Output only the next line.
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'),
Given the following code snippet before the placeholder: <|code_start|>''' Utilities to handle embeddings ''' def download_embeddings(embbeding_name, target_file): ''' Downloads file through http with progress report Obtained in stack overflow: http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http -using-python ''' # Embedding download URLs if embbeding_name == 'senna_50': # senna_50 embeddings source_url = 'http://lxmls.it.pt/2015/wp-content/uploads/2015/senna_50' else: raise ValueError("I do not have embeddings %s for download" % embbeding_name) <|code_end|> , predict the next line using imports from the current file: import os import numpy as np from six.moves import urllib from lxmls import data and context including class names, function names, and sometimes code from other files: # Path: lxmls/data.py # def find(filename): . Output only the next line.
target_file_name = os.path.basename(data.find('senna_50'))
Given the following code snippet before the placeholder: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' """Utility handlers used for monitoring the server.""" class RequestQueueHandler(tornado.web.RequestHandler): """Responds with number of items in RequestProcessor.""" def get(self): try: <|code_end|> , predict the next line using imports from the current file: import tornado.web from pushkin import context and context including class names, function names, and sometimes code from other files: # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): . Output only the next line.
queue_size = context.request_processor.queue_size()
Using the snippet: <|code_start|> APN = 'pushkin.sender.senders.ApnNotificationSender' GCM = 'pushkin.sender.senders.GcmNotificationSender' @mock.patch('pushkin.sender.sender_manager.config') def test_sender_manager_init_no_senders_given(mock_config): mock_config.enabled_senders.split.return_value=[] with pytest.raises(SystemExit) as ex: <|code_end|> , determine the next line of code. You have imports: import mock import pytest from pushkin.sender.nordifier import constants from pushkin.sender import sender_manager and context (class names, function names, or code) available: # Path: pushkin/sender/nordifier/constants.py # SN_GUEST = 0 # SN_FACEBOOK = 1 # SN_GOOGLE = 2 # PLATFORM_ANDROID = 1 # PLATFORM_IPHONE = 2 # PLATFORM_IPAD = 5 # PLATFORM_ANDROID_TABLET = 6 # PLATFORM_BY_PROVIDER = { # PLATFORM_ANDROID: 1, # PLATFORM_ANDROID_TABLET: 1, # PLATFORM_IPHONE: 2, # PLATFORM_IPAD: 2, # } # NOTIFICATION_CONTROL_GROUP = -2 # NOTIFICATION_READY = -1 # NOTIFICATION_SUCCESS = 0 # NOTIFICATION_UNKNOWN_ERROR = 1 # NOTIFICATION_CONNECTION_ERROR = 2 # NOTIFICATION_EXPIRED = 3 # NOTIFICATION_UNKNOWN_PLATFORM = 4 # NOTIFICATION_SENDER_QUEUE_LIMIT = 5 # NOTIFICATION_GCM_FATAL_ERROR = 100 # NOTIFICATION_GCM_UNAVAILABLE = 101 # NOTIFICATION_GCM_INVALID_REGISTRATION_ID = 102 # NOTIFICATION_GCM_DEVICE_UNREGISTERED = 103 # NOTIFICATION_APNS_MALFORMED_ERROR = 200 # NOTIFICATION_APNS_DEVICE_UNREGISTERED = 201 # TIME_TO_LIVE_HOURS = 6 # # Path: pushkin/sender/sender_manager.py # class NotificationSenderManager(): # def __init__(self): # def submit(self, notification): # def start(self): . Output only the next line.
sender_manager.NotificationSenderManager()
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' request_processor = None event_handler_manager = None log_queue = None PERSIST_LOGGER_PREFFIX = 'persist_' main_logger = None notification_logger = None message_blacklist = None """This module is used as a holder for global state in server process""" def setup_loggers(): """Should be called before using loggers""" global log_queue global PERSIST_LOGGER_PREFFIX global main_logger global notification_logger # setup folders <|code_end|> using the current file's imports: import logging import os from pushkin import config from util.multiprocesslogging import LogCollector, create_multiprocess_logger and any relevant context from other files: # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): . Output only the next line.
if not os.path.exists(os.path.dirname(config.main_log_path)):
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' @pytest.fixture def mock_log(mocker): mocker.patch("pushkin.context.main_logger") def test_valid_notification_proto(mock_log): '''Test that a valid notification proto is validated correctly.''' <|code_end|> using the current file's imports: import pytest from pushkin.request.requests import NotificationRequestSingle from pushkin.request.requests import NotificationRequestBatch from pushkin.context import config from pushkin.database import database and any relevant context from other files: # Path: pushkin/request/requests.py # class NotificationRequestSingle(AbstractRequest): # def __init__(self, login_id, title, content, screen=''): # self.login_id = login_id # self.title = title # self.content = content # self.screen = screen # # Path: pushkin/request/requests.py # class NotificationRequestBatch(): # """Encapsulates a batch of notifications ready for processing.""" # # def __init__(self, notifications): # self.notifications = notifications # # def process(self): # for notification in self.notifications: # try: # if self.validate_single(notification): # self.process_single(notification) # else: # context.main_logger.error("Notification proto is not valid: {}".format(notification)) # except: # context.main_logger.exception("Error while processing notification proto: {}".format(notification)) # # def process_single(self, notification): # raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content, # notification.screen, config.game, config.world_id, config.dry_run) # if len(raw_messages) > 0: # for raw_message in raw_messages: # context.main_logger.debug("Submitting to NotificationSender: {}".format(raw_message)) # context.request_processor.sender_manager.submit(raw_message) # else: # context.main_logger.debug("No device for user {login_id}, notification not sent".format(login_id=notification.login_id)) # # def validate_single(self, notification): # """Validate a single notification proto.""" # result = True # result = result and notification.has_field('login_id') # result = result and notification.has_field('title') # result = result and notification.has_field('content') # return result # # def __repr__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # def __str__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.", "some_screen_id")
Given snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' @pytest.fixture def mock_log(mocker): mocker.patch("pushkin.context.main_logger") def test_valid_notification_proto(mock_log): '''Test that a valid notification proto is validated correctly.''' notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.", "some_screen_id") <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pushkin.request.requests import NotificationRequestSingle from pushkin.request.requests import NotificationRequestBatch from pushkin.context import config from pushkin.database import database and context: # Path: pushkin/request/requests.py # class NotificationRequestSingle(AbstractRequest): # def __init__(self, login_id, title, content, screen=''): # self.login_id = login_id # self.title = title # self.content = content # self.screen = screen # # Path: pushkin/request/requests.py # class NotificationRequestBatch(): # """Encapsulates a batch of notifications ready for processing.""" # # def __init__(self, notifications): # self.notifications = notifications # # def process(self): # for notification in self.notifications: # try: # if self.validate_single(notification): # self.process_single(notification) # else: # context.main_logger.error("Notification proto is not valid: {}".format(notification)) # except: # context.main_logger.exception("Error while processing notification proto: {}".format(notification)) # # def process_single(self, notification): # raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content, # notification.screen, config.game, config.world_id, config.dry_run) # if len(raw_messages) > 0: # for raw_message in raw_messages: # context.main_logger.debug("Submitting to NotificationSender: {}".format(raw_message)) # context.request_processor.sender_manager.submit(raw_message) # else: # context.main_logger.debug("No device for user {login_id}, notification not sent".format(login_id=notification.login_id)) # # def validate_single(self, notification): # """Validate a single notification proto.""" # result = True # result = result and notification.has_field('login_id') # result = result and notification.has_field('title') # result = result and notification.has_field('content') # return result # # def __repr__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # def __str__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): which might include code, classes, or functions. Output only the next line.
assert NotificationRequestBatch([notification]).validate_single(notification)
Next line prediction: <|code_start|> def test_notification_proto_without_content(mock_log): '''Test that a notification proto without content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", None, "some_screen_id") assert not NotificationRequestBatch([notification]).validate_single(notification) def test_notification_proto_empty_content(mock_log): '''Test that a notification proto with empty content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", "", "some_screen_id") assert not NotificationRequestBatch([notification]).validate_single(notification) def test_valid_notification_proto_without_screen(mock_log): '''Test that a valid notification proto without screen is validated correctly.''' notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.") assert NotificationRequestBatch([notification]).validate_single(notification) def test_valid_notification_proto_empty_screen(mock_log): '''Test that a valid notification proto with empty screen is validated correctly.''' notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.", "") assert NotificationRequestBatch([notification]).validate_single(notification) def test_notification_proto_empty_screen_process(mocker, mock_log): '''Test that a valid notification proto without screen can be processed.''' mocker.patch('pushkin.database.database.get_raw_messages') notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.") NotificationRequestBatch([notification]).process_single(notification) <|code_end|> . Use current file imports: (import pytest from pushkin.request.requests import NotificationRequestSingle from pushkin.request.requests import NotificationRequestBatch from pushkin.context import config from pushkin.database import database) and context including class names, function names, or small code snippets from other files: # Path: pushkin/request/requests.py # class NotificationRequestSingle(AbstractRequest): # def __init__(self, login_id, title, content, screen=''): # self.login_id = login_id # self.title = title # self.content = content # self.screen = screen # # Path: pushkin/request/requests.py # class NotificationRequestBatch(): # """Encapsulates a batch of notifications ready for processing.""" # # def __init__(self, notifications): # self.notifications = notifications # # def process(self): # for notification in self.notifications: # try: # if self.validate_single(notification): # self.process_single(notification) # else: # context.main_logger.error("Notification proto is not valid: {}".format(notification)) # except: # context.main_logger.exception("Error while processing notification proto: {}".format(notification)) # # def process_single(self, notification): # raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content, # notification.screen, config.game, config.world_id, config.dry_run) # if len(raw_messages) > 0: # for raw_message in raw_messages: # context.main_logger.debug("Submitting to NotificationSender: {}".format(raw_message)) # context.request_processor.sender_manager.submit(raw_message) # else: # context.main_logger.debug("No device for user {login_id}, notification not sent".format(login_id=notification.login_id)) # # def validate_single(self, notification): # """Validate a single notification proto.""" # result = True # result = result and notification.has_field('login_id') # result = result and notification.has_field('title') # result = result and notification.has_field('content') # return result # # def __repr__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # def __str__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
database.get_raw_messages.assert_called_with(1338, "Msg title", "Text of a message.", "", config.game,
Given snippet: <|code_start|> def test_notification_proto_without_content(mock_log): '''Test that a notification proto without content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", None, "some_screen_id") assert not NotificationRequestBatch([notification]).validate_single(notification) def test_notification_proto_empty_content(mock_log): '''Test that a notification proto with empty content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", "", "some_screen_id") assert not NotificationRequestBatch([notification]).validate_single(notification) def test_valid_notification_proto_without_screen(mock_log): '''Test that a valid notification proto without screen is validated correctly.''' notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.") assert NotificationRequestBatch([notification]).validate_single(notification) def test_valid_notification_proto_empty_screen(mock_log): '''Test that a valid notification proto with empty screen is validated correctly.''' notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.", "") assert NotificationRequestBatch([notification]).validate_single(notification) def test_notification_proto_empty_screen_process(mocker, mock_log): '''Test that a valid notification proto without screen can be processed.''' mocker.patch('pushkin.database.database.get_raw_messages') notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.") NotificationRequestBatch([notification]).process_single(notification) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pushkin.request.requests import NotificationRequestSingle from pushkin.request.requests import NotificationRequestBatch from pushkin.context import config from pushkin.database import database and context: # Path: pushkin/request/requests.py # class NotificationRequestSingle(AbstractRequest): # def __init__(self, login_id, title, content, screen=''): # self.login_id = login_id # self.title = title # self.content = content # self.screen = screen # # Path: pushkin/request/requests.py # class NotificationRequestBatch(): # """Encapsulates a batch of notifications ready for processing.""" # # def __init__(self, notifications): # self.notifications = notifications # # def process(self): # for notification in self.notifications: # try: # if self.validate_single(notification): # self.process_single(notification) # else: # context.main_logger.error("Notification proto is not valid: {}".format(notification)) # except: # context.main_logger.exception("Error while processing notification proto: {}".format(notification)) # # def process_single(self, notification): # raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content, # notification.screen, config.game, config.world_id, config.dry_run) # if len(raw_messages) > 0: # for raw_message in raw_messages: # context.main_logger.debug("Submitting to NotificationSender: {}".format(raw_message)) # context.request_processor.sender_manager.submit(raw_message) # else: # context.main_logger.debug("No device for user {login_id}, notification not sent".format(login_id=notification.login_id)) # # def validate_single(self, notification): # """Validate a single notification proto.""" # result = True # result = result and notification.has_field('login_id') # result = result and notification.has_field('title') # result = result and notification.has_field('content') # return result # # def __repr__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # def __str__(self): # return "NotificationsRequests({})".format(len(self.notifications)) # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): which might include code, classes, or functions. Output only the next line.
database.get_raw_messages.assert_called_with(1338, "Msg title", "Text of a message.", "", config.game,
Continue the code snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' class BatchHandler(tornado.web.RequestHandler): """Abstract handler for receiving request batches.""" __metaclass__ = abc.ABCMeta def parse_request(self, body): # discard invalid requests if not body: <|code_end|> . Use current file imports: import tornado.web import httplib import abc from pushkin import context and context (classes, functions, or code) from other files: # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): . Output only the next line.
context.main_logger.error("Request was empty in batch handler {}!".format(self.__class__.__name__))
Given snippet: <|code_start|> class NotificationSenderManager(): def __init__(self): self.sender_by_name = {} self.sender_name_by_platform = {} values = [v.strip() for v in config.enabled_senders.split('\n')] values = filter(bool, values) if not values: sys.exit(u"Nothing to start. At least one sender class must " u"be specified in config [Sender]enabled_senders") for value in values: cfg = value.split('{', 1) sender_name = cfg[0].strip() if not sender_name: sys.exit(u"Error: bad sender configuration: {}".format(cfg)) try: kwargs = json.loads('{' + cfg[1]) except IndexError: kwargs = {} except ValueError: sys.exit(u"Error: failed to parse JSON kwargs " u"from sender configuration: {}".format(s)) try: module, cls_name = sender_name.rsplit('.', 1) sender_cls = getattr(__import__(module, fromlist=[cls_name]), cls_name) <|code_end|> , continue by predicting the next line. Consider current file imports: import json import sys from pushkin.sender.nordifier import constants from pushkin.sender import senders from pushkin import context from pushkin import config and context: # Path: pushkin/sender/nordifier/constants.py # SN_GUEST = 0 # SN_FACEBOOK = 1 # SN_GOOGLE = 2 # PLATFORM_ANDROID = 1 # PLATFORM_IPHONE = 2 # PLATFORM_IPAD = 5 # PLATFORM_ANDROID_TABLET = 6 # PLATFORM_BY_PROVIDER = { # PLATFORM_ANDROID: 1, # PLATFORM_ANDROID_TABLET: 1, # PLATFORM_IPHONE: 2, # PLATFORM_IPAD: 2, # } # NOTIFICATION_CONTROL_GROUP = -2 # NOTIFICATION_READY = -1 # NOTIFICATION_SUCCESS = 0 # NOTIFICATION_UNKNOWN_ERROR = 1 # NOTIFICATION_CONNECTION_ERROR = 2 # NOTIFICATION_EXPIRED = 3 # NOTIFICATION_UNKNOWN_PLATFORM = 4 # NOTIFICATION_SENDER_QUEUE_LIMIT = 5 # NOTIFICATION_GCM_FATAL_ERROR = 100 # NOTIFICATION_GCM_UNAVAILABLE = 101 # NOTIFICATION_GCM_INVALID_REGISTRATION_ID = 102 # NOTIFICATION_GCM_DEVICE_UNREGISTERED = 103 # NOTIFICATION_APNS_MALFORMED_ERROR = 200 # NOTIFICATION_APNS_DEVICE_UNREGISTERED = 201 # TIME_TO_LIVE_HOURS = 6 # # Path: pushkin/sender/senders.py # class NotificationSender(ProcessPool): # class NotificationOperation(): # class NotificationPostProcessor(Thread): # class NotificationStatistics: # class ApnNotificationSender(NotificationSender): # class GcmNotificationSender(NotificationSender): # NUM_WORKERS_DEFAULT = 50 # UPDATE_CANONICALS = 1 # UPDATE_UNREGISTERED_DEVICES = 2 # OPERATION_QUEUE = multiprocessing.Queue() # PLATFORMS = (constants.PLATFORM_IPHONE, # constants.PLATFORM_IPAD) # PLATFORMS = (constants.PLATFORM_ANDROID, # constants.PLATFORM_ANDROID_TABLET) # def __init__(self, **kwargs): # def limit_exceeded(self, notification): # def queue_size(self): # def log_notifications(self, notifications): # def __init__(self, operation, data): # def __init__(self): # def queue_size(self): # def update_canonicals(self, canonical_ids): # def update_unregistered_devices(self, unregistered_devices): # def run(self): # def __init__(self, name, logger, last_averages=100, log_time_seconds=30): # def start(self): # def stop(self): # def process(self): # def process(self): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): which might include code, classes, or functions. Output only the next line.
if not issubclass(sender_cls, senders.NotificationSender):
Given snippet: <|code_start|> cls_name) if not issubclass(sender_cls, senders.NotificationSender): raise AttributeError( u"{} must be a subclass of senders.NotificationSender" u"".format(sender_cls)) except (ImportError, AttributeError, TypeError) as e: err = u"Failed to load sender '{}': {}: {}" sys.exit(err.format(sender_name, type(e).__name__, e)) try: platforms = sender_cls.PLATFORMS except AttributeError: err = u"Failed to load sender: missed property {}.PLATFORMS" sys.exit(err.format(sender_name)) if not platforms: err = u"Failed to load sender: empty {}.PLATFORMS" sys.exit(err.format(sender_name)) sender_ins = sender_cls(**kwargs) for platform in map(int, platforms): if platform in self.sender_name_by_platform: rival_name = self.sender_name_by_platform[platform] err = (u"Failed to load sender '{}': platform '{}' " u"is already registered by another sender '{}'") sys.exit(err.format(sender_name, platform, rival_name)) self.sender_name_by_platform[platform] = sender_name <|code_end|> , continue by predicting the next line. Consider current file imports: import json import sys from pushkin.sender.nordifier import constants from pushkin.sender import senders from pushkin import context from pushkin import config and context: # Path: pushkin/sender/nordifier/constants.py # SN_GUEST = 0 # SN_FACEBOOK = 1 # SN_GOOGLE = 2 # PLATFORM_ANDROID = 1 # PLATFORM_IPHONE = 2 # PLATFORM_IPAD = 5 # PLATFORM_ANDROID_TABLET = 6 # PLATFORM_BY_PROVIDER = { # PLATFORM_ANDROID: 1, # PLATFORM_ANDROID_TABLET: 1, # PLATFORM_IPHONE: 2, # PLATFORM_IPAD: 2, # } # NOTIFICATION_CONTROL_GROUP = -2 # NOTIFICATION_READY = -1 # NOTIFICATION_SUCCESS = 0 # NOTIFICATION_UNKNOWN_ERROR = 1 # NOTIFICATION_CONNECTION_ERROR = 2 # NOTIFICATION_EXPIRED = 3 # NOTIFICATION_UNKNOWN_PLATFORM = 4 # NOTIFICATION_SENDER_QUEUE_LIMIT = 5 # NOTIFICATION_GCM_FATAL_ERROR = 100 # NOTIFICATION_GCM_UNAVAILABLE = 101 # NOTIFICATION_GCM_INVALID_REGISTRATION_ID = 102 # NOTIFICATION_GCM_DEVICE_UNREGISTERED = 103 # NOTIFICATION_APNS_MALFORMED_ERROR = 200 # NOTIFICATION_APNS_DEVICE_UNREGISTERED = 201 # TIME_TO_LIVE_HOURS = 6 # # Path: pushkin/sender/senders.py # class NotificationSender(ProcessPool): # class NotificationOperation(): # class NotificationPostProcessor(Thread): # class NotificationStatistics: # class ApnNotificationSender(NotificationSender): # class GcmNotificationSender(NotificationSender): # NUM_WORKERS_DEFAULT = 50 # UPDATE_CANONICALS = 1 # UPDATE_UNREGISTERED_DEVICES = 2 # OPERATION_QUEUE = multiprocessing.Queue() # PLATFORMS = (constants.PLATFORM_IPHONE, # constants.PLATFORM_IPAD) # PLATFORMS = (constants.PLATFORM_ANDROID, # constants.PLATFORM_ANDROID_TABLET) # def __init__(self, **kwargs): # def limit_exceeded(self, notification): # def queue_size(self): # def log_notifications(self, notifications): # def __init__(self, operation, data): # def __init__(self): # def queue_size(self): # def update_canonicals(self, canonical_ids): # def update_unregistered_devices(self, unregistered_devices): # def run(self): # def __init__(self, name, logger, last_averages=100, log_time_seconds=30): # def start(self): # def stop(self): # def process(self): # def process(self): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): which might include code, classes, or functions. Output only the next line.
if config.main_log_level == context.logging.DEBUG:
Predict the next line for this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' class NotificationSenderManager(): def __init__(self): self.sender_by_name = {} self.sender_name_by_platform = {} <|code_end|> with the help of current file imports: import json import sys from pushkin.sender.nordifier import constants from pushkin.sender import senders from pushkin import context from pushkin import config and context from other files: # Path: pushkin/sender/nordifier/constants.py # SN_GUEST = 0 # SN_FACEBOOK = 1 # SN_GOOGLE = 2 # PLATFORM_ANDROID = 1 # PLATFORM_IPHONE = 2 # PLATFORM_IPAD = 5 # PLATFORM_ANDROID_TABLET = 6 # PLATFORM_BY_PROVIDER = { # PLATFORM_ANDROID: 1, # PLATFORM_ANDROID_TABLET: 1, # PLATFORM_IPHONE: 2, # PLATFORM_IPAD: 2, # } # NOTIFICATION_CONTROL_GROUP = -2 # NOTIFICATION_READY = -1 # NOTIFICATION_SUCCESS = 0 # NOTIFICATION_UNKNOWN_ERROR = 1 # NOTIFICATION_CONNECTION_ERROR = 2 # NOTIFICATION_EXPIRED = 3 # NOTIFICATION_UNKNOWN_PLATFORM = 4 # NOTIFICATION_SENDER_QUEUE_LIMIT = 5 # NOTIFICATION_GCM_FATAL_ERROR = 100 # NOTIFICATION_GCM_UNAVAILABLE = 101 # NOTIFICATION_GCM_INVALID_REGISTRATION_ID = 102 # NOTIFICATION_GCM_DEVICE_UNREGISTERED = 103 # NOTIFICATION_APNS_MALFORMED_ERROR = 200 # NOTIFICATION_APNS_DEVICE_UNREGISTERED = 201 # TIME_TO_LIVE_HOURS = 6 # # Path: pushkin/sender/senders.py # class NotificationSender(ProcessPool): # class NotificationOperation(): # class NotificationPostProcessor(Thread): # class NotificationStatistics: # class ApnNotificationSender(NotificationSender): # class GcmNotificationSender(NotificationSender): # NUM_WORKERS_DEFAULT = 50 # UPDATE_CANONICALS = 1 # UPDATE_UNREGISTERED_DEVICES = 2 # OPERATION_QUEUE = multiprocessing.Queue() # PLATFORMS = (constants.PLATFORM_IPHONE, # constants.PLATFORM_IPAD) # PLATFORMS = (constants.PLATFORM_ANDROID, # constants.PLATFORM_ANDROID_TABLET) # def __init__(self, **kwargs): # def limit_exceeded(self, notification): # def queue_size(self): # def log_notifications(self, notifications): # def __init__(self, operation, data): # def __init__(self): # def queue_size(self): # def update_canonicals(self, canonical_ids): # def update_unregistered_devices(self, unregistered_devices): # def run(self): # def __init__(self, name, logger, last_averages=100, log_time_seconds=30): # def start(self): # def stop(self): # def process(self): # def process(self): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): , which may contain function names, class names, or code. Output only the next line.
values = [v.strip() for v in config.enabled_senders.split('\n')]
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' <|code_end|> using the current file's imports: import pytest from pushkin.request.event_handlers import EventHandler, EventHandlerManager from pushkin.database import database and any relevant context from other files: # Path: pushkin/request/event_handlers.py # class EventHandler(): # def __init__(self, event_id): # self.event_id = event_id # # def handle_event(self, event, event_params): # raise Exception("Not implemented!") # # def validate(self, event, event_params): # return event.has_field('user_id') and event.has_field('timestamp') # # class EventHandlerManager(): # """Responsible for invoking event handlers for given events.""" # # def __init__(self): # self._event_handler_map = defaultdict(list) # self._build() # # def _add_event_handler(self, handler): # self._event_handler_map[handler.event_id].append(handler) # # def _build(self): # self._add_event_handler(LoginEventHandler()) # self._add_event_handler(TurnOffNotificationEventHandler()) # event_to_message_mapping = database.get_event_to_message_mapping() # for event_id, message_ids in event_to_message_mapping.iteritems(): # self._add_event_handler(EventToMessagesHandler(event_id, message_ids)) # # def get_handlers(self, event_id): # return self._event_handler_map[event_id] # # def get_event_ids(self): # return self._event_handler_map.keys() # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
class EventHandlerA1(EventHandler):
Here is a snippet: <|code_start|>@pytest.fixture def mock_log(mocker): mocker.patch("pushkin.context.main_logger") @pytest.fixture def setup(mock_log): ''' Runs setup before and clean up after a test which use this fixture ''' # prepare database for test database.create_database() prepare_demodata() def prepare_demodata(): # add some test users database.process_user_login(login_id=1, language_id=1, platform_id=2, device_token='dtoken1', application_version=200) database.process_user_login(login_id=2, language_id=1, platform_id=2, device_token='dtoken2', application_version=200) database.process_user_login(login_id=3, language_id=1, platform_id=2, device_token='dtoken3', application_version=200) # insert messages database.add_message('msg1', 1, 'title', 'text', 1) database.add_message('msg2', 1, 'title', 'text', 1) database.add_message('msg3', 1, 'title', 'text', 2) @pytest.fixture def manager(): # mock event handlers <|code_end|> . Write the next line using the current file imports: import pytest from pushkin.request.event_handlers import EventHandler, EventHandlerManager from pushkin.database import database and context from other files: # Path: pushkin/request/event_handlers.py # class EventHandler(): # def __init__(self, event_id): # self.event_id = event_id # # def handle_event(self, event, event_params): # raise Exception("Not implemented!") # # def validate(self, event, event_params): # return event.has_field('user_id') and event.has_field('timestamp') # # class EventHandlerManager(): # """Responsible for invoking event handlers for given events.""" # # def __init__(self): # self._event_handler_map = defaultdict(list) # self._build() # # def _add_event_handler(self, handler): # self._event_handler_map[handler.event_id].append(handler) # # def _build(self): # self._add_event_handler(LoginEventHandler()) # self._add_event_handler(TurnOffNotificationEventHandler()) # event_to_message_mapping = database.get_event_to_message_mapping() # for event_id, message_ids in event_to_message_mapping.iteritems(): # self._add_event_handler(EventToMessagesHandler(event_id, message_ids)) # # def get_handlers(self, event_id): # return self._event_handler_map[event_id] # # def get_event_ids(self): # return self._event_handler_map.keys() # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): , which may include functions, classes, or code. Output only the next line.
manager = EventHandlerManager()
Using the snippet: <|code_start|> pass class EventHandlerB1(EventHandler): def __init__(self): EventHandler.__init__(self, 1) def handle_event(self, event_request): pass class EventHandlerA2(EventHandler): def __init__(self): EventHandler.__init__(self, 2) def handle_event(self, event_request): pass @pytest.fixture def mock_log(mocker): mocker.patch("pushkin.context.main_logger") @pytest.fixture def setup(mock_log): ''' Runs setup before and clean up after a test which use this fixture ''' # prepare database for test <|code_end|> , determine the next line of code. You have imports: import pytest from pushkin.request.event_handlers import EventHandler, EventHandlerManager from pushkin.database import database and context (class names, function names, or code) available: # Path: pushkin/request/event_handlers.py # class EventHandler(): # def __init__(self, event_id): # self.event_id = event_id # # def handle_event(self, event, event_params): # raise Exception("Not implemented!") # # def validate(self, event, event_params): # return event.has_field('user_id') and event.has_field('timestamp') # # class EventHandlerManager(): # """Responsible for invoking event handlers for given events.""" # # def __init__(self): # self._event_handler_map = defaultdict(list) # self._build() # # def _add_event_handler(self, handler): # self._event_handler_map[handler.event_id].append(handler) # # def _build(self): # self._add_event_handler(LoginEventHandler()) # self._add_event_handler(TurnOffNotificationEventHandler()) # event_to_message_mapping = database.get_event_to_message_mapping() # for event_id, message_ids in event_to_message_mapping.iteritems(): # self._add_event_handler(EventToMessagesHandler(event_id, message_ids)) # # def get_handlers(self, event_id): # return self._event_handler_map[event_id] # # def get_event_ids(self): # return self._event_handler_map.keys() # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
database.create_database()
Using the snippet: <|code_start|> class AbstractRequest(): def has_field(self, field): if self.__dict__.get(field) is not None and self.__dict__.get(field) != '': return True else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_id, title, content, screen=''): self.login_id = login_id self.title = title self.content = content self.screen = screen class NotificationRequestBatch(): """Encapsulates a batch of notifications ready for processing.""" def __init__(self, notifications): self.notifications = notifications def process(self): for notification in self.notifications: try: if self.validate_single(notification): self.process_single(notification) else: <|code_end|> , determine the next line of code. You have imports: from pushkin import context from pushkin import config from pushkin.database import database and context (class names, function names, or code) available: # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
context.main_logger.error("Notification proto is not valid: {}".format(notification))
Here is a snippet: <|code_start|> else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_id, title, content, screen=''): self.login_id = login_id self.title = title self.content = content self.screen = screen class NotificationRequestBatch(): """Encapsulates a batch of notifications ready for processing.""" def __init__(self, notifications): self.notifications = notifications def process(self): for notification in self.notifications: try: if self.validate_single(notification): self.process_single(notification) else: context.main_logger.error("Notification proto is not valid: {}".format(notification)) except: context.main_logger.exception("Error while processing notification proto: {}".format(notification)) def process_single(self, notification): raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content, <|code_end|> . Write the next line using the current file imports: from pushkin import context from pushkin import config from pushkin.database import database and context from other files: # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): , which may include functions, classes, or code. Output only the next line.
notification.screen, config.game, config.world_id, config.dry_run)
Based on the snippet: <|code_start|> return True else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_id, title, content, screen=''): self.login_id = login_id self.title = title self.content = content self.screen = screen class NotificationRequestBatch(): """Encapsulates a batch of notifications ready for processing.""" def __init__(self, notifications): self.notifications = notifications def process(self): for notification in self.notifications: try: if self.validate_single(notification): self.process_single(notification) else: context.main_logger.error("Notification proto is not valid: {}".format(notification)) except: context.main_logger.exception("Error while processing notification proto: {}".format(notification)) def process_single(self, notification): <|code_end|> , predict the immediate next line with the help of imports: from pushkin import context from pushkin import config from pushkin.database import database and context (classes, functions, sometimes code) from other files: # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): . Output only the next line.
raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content,
Using the snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' """A place for handling events. Currently only login event is handled, this should be dinamycally configured in future.""" class EventHandlerManager(): """Responsible for invoking event handlers for given events.""" def __init__(self): self._event_handler_map = defaultdict(list) self._build() def _add_event_handler(self, handler): self._event_handler_map[handler.event_id].append(handler) def _build(self): self._add_event_handler(LoginEventHandler()) self._add_event_handler(TurnOffNotificationEventHandler()) <|code_end|> , determine the next line of code. You have imports: from collections import defaultdict from pushkin.database import database from pushkin import context from pushkin import config from pushkin.util.tools import is_integer import re and context (class names, function names, or code) available: # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/util/tools.py # def is_integer(value): # """ # Checks if a value is of integer type # # :param value: # :return: True if value is integer, False otherwise # """ # try: # int(value) # return True # except ValueError: # return False . Output only the next line.
event_to_message_mapping = database.get_event_to_message_mapping()
Given snippet: <|code_start|> def __init__(self): EventHandler.__init__(self, config.login_event_id) def handle_event(self, event, event_params): database.process_user_login(login_id=event.user_id, language_id=event_params.get('languageId'), platform_id=event_params['platformId'], device_token=event_params.get('deviceToken'), application_version=event_params['applicationVersion']) return [] def validate(self, event, event_params): result = EventHandler.validate(self, event, event_params) result &= is_integer(event_params.get('platformId', '')) result &= is_integer(event_params.get('applicationVersion', '')) return result class TurnOffNotificationEventHandler(EventHandler): """ Writes data about notifications that user doesn't want to receive into database """ def __init__(self): EventHandler.__init__(self, config.turn_off_notification_event_id) def handle_event(self, event, event_params): blacklist = set() for _, value in event_params.iteritems(): blacklist.add(value) database.upsert_message_blacklist(event.user_id, list(blacklist)) <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import defaultdict from pushkin.database import database from pushkin import context from pushkin import config from pushkin.util.tools import is_integer import re and context: # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/util/tools.py # def is_integer(value): # """ # Checks if a value is of integer type # # :param value: # :return: True if value is integer, False otherwise # """ # try: # int(value) # return True # except ValueError: # return False which might include code, classes, or functions. Output only the next line.
context.message_blacklist[event.user_id] = blacklist
Predict the next line after this snippet: <|code_start|> def _build(self): self._add_event_handler(LoginEventHandler()) self._add_event_handler(TurnOffNotificationEventHandler()) event_to_message_mapping = database.get_event_to_message_mapping() for event_id, message_ids in event_to_message_mapping.iteritems(): self._add_event_handler(EventToMessagesHandler(event_id, message_ids)) def get_handlers(self, event_id): return self._event_handler_map[event_id] def get_event_ids(self): return self._event_handler_map.keys() class EventHandler(): def __init__(self, event_id): self.event_id = event_id def handle_event(self, event, event_params): raise Exception("Not implemented!") def validate(self, event, event_params): return event.has_field('user_id') and event.has_field('timestamp') class LoginEventHandler(EventHandler): """Writes user data to database on login event.""" def __init__(self): <|code_end|> using the current file's imports: from collections import defaultdict from pushkin.database import database from pushkin import context from pushkin import config from pushkin.util.tools import is_integer import re and any relevant context from other files: # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/util/tools.py # def is_integer(value): # """ # Checks if a value is of integer type # # :param value: # :return: True if value is integer, False otherwise # """ # try: # int(value) # return True # except ValueError: # return False . Output only the next line.
EventHandler.__init__(self, config.login_event_id)
Next line prediction: <|code_start|> def get_event_ids(self): return self._event_handler_map.keys() class EventHandler(): def __init__(self, event_id): self.event_id = event_id def handle_event(self, event, event_params): raise Exception("Not implemented!") def validate(self, event, event_params): return event.has_field('user_id') and event.has_field('timestamp') class LoginEventHandler(EventHandler): """Writes user data to database on login event.""" def __init__(self): EventHandler.__init__(self, config.login_event_id) def handle_event(self, event, event_params): database.process_user_login(login_id=event.user_id, language_id=event_params.get('languageId'), platform_id=event_params['platformId'], device_token=event_params.get('deviceToken'), application_version=event_params['applicationVersion']) return [] def validate(self, event, event_params): result = EventHandler.validate(self, event, event_params) <|code_end|> . Use current file imports: (from collections import defaultdict from pushkin.database import database from pushkin import context from pushkin import config from pushkin.util.tools import is_integer import re) and context including class names, function names, or small code snippets from other files: # Path: pushkin/database/database.py # ENGINE = None # SESSION = None # ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini') # ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool) # SESSION = sessionmaker(bind=ENGINE) # def init_db(): # def create_database(): # def upgrade_database(): # def get_head_revision(): # def get_current_revision(): # def execute_query(query): # def execute_query_with_results(query): # def session_scope(): # def get_device_tokens(login_id): # def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None, # expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None): # def update_canonicals(canonicals): # def update_unregistered_devices(unregistered): # def process_user_login(login_id, language_id, platform_id, device_token, application_version): # def upsert_login(login_id, language_id): # def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): # def get_all_logins(): # def get_all_message_blacklist(): # def upsert_message_blacklist(login_id, blacklist): # def get_login(login_id): # def get_devices(login): # def delete_login(login): # def delete_device(device): # def get_localized_message(login_id, message_id): # def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): # def upsert_message_localization(message_name, language_id, message_title, message_text): # def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, # screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): # def get_all_messages(): # def get_message(message_name): # def get_message_localizations(message): # def delete_message(message): # def delete_message_localization(message_localization): # def get_event_to_message_mapping(): # def get_and_update_messages_to_send(user_message_set): # # Path: pushkin/context.py # PERSIST_LOGGER_PREFFIX = 'persist_' # def setup_loggers(): # def setup_configuration(configuration_filename): # def start_processors(): # # Path: pushkin/config.py # DATABASE_CONFIG_SECTION = 'Database' # SERVER_SPECIFIC_CONFIG_SECTION = 'ServerSpecific' # EVENT_CONFIG_SECTION = 'Event' # LOG_CONFIG_SECTION = 'Log' # SERVER_CONFIG_SECTION = 'Server' # MESSENGER_CONFIG_SECTION = 'Messenger' # REQUEST_PROCESSOR_CONFIG_SECTION = 'RequestProcessor' # SENDER_CONFIG_SECTION = 'Sender' # REQUEST_HANDLER_SECTION = 'RequestHandler' # def init(configuration_file): # # Path: pushkin/util/tools.py # def is_integer(value): # """ # Checks if a value is of integer type # # :param value: # :return: True if value is integer, False otherwise # """ # try: # int(value) # return True # except ValueError: # return False . Output only the next line.
result &= is_integer(event_params.get('platformId', ''))
Given the following code snippet before the placeholder: <|code_start|># Returns # ------- # An approximation to the spectral radius of A # # """ # if symmetric: # method = eigen_symmetric # else: # method = eigen # # return norm( method(A, k=1, tol=0.1, which='LM', maxiter=maxiter, # return_eigenvectors=False) ) def _approximate_eigenvalues(A, maxiter, symmetric=None, initial_guess=None): """Apprixmate eigenvalues. Used by approximate_spectral_radius and condest. Returns [W, E, H, V, breakdown_flag], where W and E are the eigenvectors and eigenvalues of the Hessenberg matrix H, respectively, and V is the Krylov space. breakdown_flag denotes whether Lanczos/Arnoldi suffered breakdown. E is therefore the approximate eigenvalues of A. To obtain approximate eigenvectors of A, compute V*W. """ A = aslinearoperator(A) # A could be dense or sparse, or something weird # Choose tolerance for deciding if break-down has occurred <|code_end|> , predict the next line using imports from the current file: from warnings import warn from scipy import sparse from scipy.sparse.linalg import aslinearoperator from scipy.linalg import lapack, get_blas_funcs, eig, svd from .params import set_tol import numpy as np and context including class names, function names, and sometimes code from other files: # Path: pyamg/util/params.py # def set_tol(dtype): # """Set a tolerance based on a numpy dtype char. # # Parameters # ---------- # dtype : np.dtype # numpy dtype # # Returns # ------- # tol : float # A smallish value based on precision # # Notes # ----- # Handles both real and complex (through the .lower() case) # # See Also # -------- # numpy.typecodes, numpy.sctypes # """ # if dtype.char.lower() == 'f': # tol = 1e3 * np.finfo(np.single).eps # elif dtype.char.lower() == 'd': # tol = 1e6 * np.finfo(np.double).eps # elif dtype.char.lower() == 'g': # tol = 1e6 * np.finfo(np.longdouble).eps # else: # raise ValueError('Attempting to set a tolerance for an unsupported precision.') # # return tol . Output only the next line.
breakdown = set_tol(A.dtype)
Continue the code snippet: <|code_start|> coords = list(zip(V[[i,j1], 0], V[[i,j1],1])) newobj = sg.LineString(coords) # add a line object to the list todraw.append(newobj) todraw = cascaded_union(todraw) # union all objects in the aggregate todraw = todraw.buffer(0.1) # expand to smooth todraw = todraw.buffer(-0.05) # then contract try: xs, ys = todraw.exterior.xy # get all of the exterior points ax.fill(xs, ys, color=color, clip_on=False) # fill with a color except: print('uh oh') pass # when does this happen # aggregate edges Edges = np.vstack((A.tocoo().row,A.tocoo().col)).T # edges of the matrix graph inner_edges = AggOp.indices[Edges[:,0]] == AggOp.indices[Edges[:,1]] aggs = V[Edges[inner_edges].ravel(),:].reshape((-1, 2, 2)) col = mplt.collections.LineCollection(aggs, color=edgecolor, linewidth=lw) ax.add_collection(col, autolim=True) ax.set_aspect('equal') X = loadmat('pyamg.mat') V = X['vertices'] E = X['elements'] <|code_end|> . Use current file imports: import sys import numpy as np import matplotlib as mplt import matplotlib.pyplot as plt import shapely.geometry as sg import pyamg from scipy.io import loadmat from shapely.ops import cascaded_union from pyamg.gallery.fem import mesh, gradgradform and context (classes, functions, or code) from other files: # Path: pyamg/gallery/fem.py # def check_mesh(V, E): # def generate_quadratic(V, E, return_edges=False): # def diameter(V, E): # def refine2dtri(V, E, marked_elements=None): # def l2norm(u, mesh): # def basis1(x, y): # def basis2(x, y): # def __init__(self, V, E, degree=1): # def generate_quadratic(self): # def refine(self, levels): # def smooth(self, maxit=10, tol=0.01): # def _compute_diffusion_matrix(kappa_lmbda, x, y): # def gradgradform(mesh, kappa=None, f=None, degree=1): # def f(_x, _y): # def kappa(_x, _y): # def divform(mesh): # def applybc(A, b, mesh, bc): # def stokes(mesh, fu, fv): # def model(num=0): # E01 = np.vstack((V[E[:, 1], 0] - V[E[:, 0], 0], # V[E[:, 1], 1] - V[E[:, 0], 1], # np.zeros(E.shape[0]))).T # E12 = np.vstack((V[E[:, 2], 0] - V[E[:, 1], 0], # V[E[:, 2], 1] - V[E[:, 1], 1], # np.zeros(E.shape[0]))).T # ID = np.kron(np.arange(0, ne), np.ones((3,), dtype=int)) # G = sparse.coo_matrix((np.ones((ne*3,), dtype=int), (E.ravel(), ID,))) # V2V = G * G.T # V = np.vstack((V, Vmid)) # E = np.hstack((E, np.zeros((E.shape[0], 3), dtype=int))) # E[:, 3] = V2Vmid[E[:, 0], E[:, 1]] # E[:, 4] = V2Vmid[E[:, 1], E[:, 2]] # E[:, 5] = V2Vmid[E[:, 2], E[:, 0]] # I = [0, 1, 2, 0] # V2V = sparse.coo_matrix((data, (row, col)), shape=(Nel, Nv)) # V2V = V2V.T * V2V # V = np.vstack((V, V_new)) # V = mesh.V # E = mesh.E # V = mesh.V2 # E = mesh.E2 # I = np.arange(3) # I = np.arange(6) # I = np.where(ids)[0] # J = np.arange(E.max()+1) # J[I] = np.arange(nv) # E = J[E] # V = V[I, :] # G = sparse.coo_matrix((data, (edge0, edge1)), shape=(nv, nv)) # W = np.array(G.sum(axis=1)).flatten() # E = mesh.E # X = mesh.X # Y = mesh.Y # E = mesh.E2 # X = mesh.X2 # Y = mesh.Y2 # AA = np.zeros((ne, m**2)) # IA = np.zeros((ne, m**2), dtype=int) # JA = np.zeros((ne, m**2), dtype=int) # K = E[ei, :] # J = np.array([[x1 - x0, x2 - x0], # [y1 - y0, y2 - y0]]) # A = sparse.coo_matrix((AA.ravel(), (IA.ravel(), JA.ravel()))) # X, Y = mesh.X, mesh.Y # E = mesh.E2 # DX = np.zeros((ne, m1*m2)) # DXI = np.zeros((ne, m1*m2), dtype=int) # DXJ = np.zeros((ne, m1*m2), dtype=int) # DY = np.zeros((ne, m1*m2)) # DYI = np.zeros((ne, m1*m2), dtype=int) # DYJ = np.zeros((ne, m1*m2), dtype=int) # K = E[ei, :] # J = np.array([[x1 - x0, x2 - x0], # [y1 - y0, y2 - y0]]) # BX = sparse.coo_matrix((DX.ravel(), (DXI.ravel(), DXJ.ravel()))) # BY = sparse.coo_matrix((DY.ravel(), (DYI.ravel(), DYJ.ravel()))) # X = mesh.X # Y = mesh.Y # X = mesh.X2 # Y = mesh.Y2 # BX, BY = divform(mesh) # C = sparse.bmat([[Au, None, BX.T], # [None, Av, BY.T], # [BX, BY, None]]) # class Mesh: . Output only the next line.
mesh = mesh(V, E)
Predict the next line after this snippet: <|code_start|> newobj = sg.LineString(coords) # add a line object to the list todraw.append(newobj) todraw = cascaded_union(todraw) # union all objects in the aggregate todraw = todraw.buffer(0.1) # expand to smooth todraw = todraw.buffer(-0.05) # then contract try: xs, ys = todraw.exterior.xy # get all of the exterior points ax.fill(xs, ys, color=color, clip_on=False) # fill with a color except: print('uh oh') pass # when does this happen # aggregate edges Edges = np.vstack((A.tocoo().row,A.tocoo().col)).T # edges of the matrix graph inner_edges = AggOp.indices[Edges[:,0]] == AggOp.indices[Edges[:,1]] aggs = V[Edges[inner_edges].ravel(),:].reshape((-1, 2, 2)) col = mplt.collections.LineCollection(aggs, color=edgecolor, linewidth=lw) ax.add_collection(col, autolim=True) ax.set_aspect('equal') X = loadmat('pyamg.mat') V = X['vertices'] E = X['elements'] mesh = mesh(V, E) <|code_end|> using the current file's imports: import sys import numpy as np import matplotlib as mplt import matplotlib.pyplot as plt import shapely.geometry as sg import pyamg from scipy.io import loadmat from shapely.ops import cascaded_union from pyamg.gallery.fem import mesh, gradgradform and any relevant context from other files: # Path: pyamg/gallery/fem.py # def check_mesh(V, E): # def generate_quadratic(V, E, return_edges=False): # def diameter(V, E): # def refine2dtri(V, E, marked_elements=None): # def l2norm(u, mesh): # def basis1(x, y): # def basis2(x, y): # def __init__(self, V, E, degree=1): # def generate_quadratic(self): # def refine(self, levels): # def smooth(self, maxit=10, tol=0.01): # def _compute_diffusion_matrix(kappa_lmbda, x, y): # def gradgradform(mesh, kappa=None, f=None, degree=1): # def f(_x, _y): # def kappa(_x, _y): # def divform(mesh): # def applybc(A, b, mesh, bc): # def stokes(mesh, fu, fv): # def model(num=0): # E01 = np.vstack((V[E[:, 1], 0] - V[E[:, 0], 0], # V[E[:, 1], 1] - V[E[:, 0], 1], # np.zeros(E.shape[0]))).T # E12 = np.vstack((V[E[:, 2], 0] - V[E[:, 1], 0], # V[E[:, 2], 1] - V[E[:, 1], 1], # np.zeros(E.shape[0]))).T # ID = np.kron(np.arange(0, ne), np.ones((3,), dtype=int)) # G = sparse.coo_matrix((np.ones((ne*3,), dtype=int), (E.ravel(), ID,))) # V2V = G * G.T # V = np.vstack((V, Vmid)) # E = np.hstack((E, np.zeros((E.shape[0], 3), dtype=int))) # E[:, 3] = V2Vmid[E[:, 0], E[:, 1]] # E[:, 4] = V2Vmid[E[:, 1], E[:, 2]] # E[:, 5] = V2Vmid[E[:, 2], E[:, 0]] # I = [0, 1, 2, 0] # V2V = sparse.coo_matrix((data, (row, col)), shape=(Nel, Nv)) # V2V = V2V.T * V2V # V = np.vstack((V, V_new)) # V = mesh.V # E = mesh.E # V = mesh.V2 # E = mesh.E2 # I = np.arange(3) # I = np.arange(6) # I = np.where(ids)[0] # J = np.arange(E.max()+1) # J[I] = np.arange(nv) # E = J[E] # V = V[I, :] # G = sparse.coo_matrix((data, (edge0, edge1)), shape=(nv, nv)) # W = np.array(G.sum(axis=1)).flatten() # E = mesh.E # X = mesh.X # Y = mesh.Y # E = mesh.E2 # X = mesh.X2 # Y = mesh.Y2 # AA = np.zeros((ne, m**2)) # IA = np.zeros((ne, m**2), dtype=int) # JA = np.zeros((ne, m**2), dtype=int) # K = E[ei, :] # J = np.array([[x1 - x0, x2 - x0], # [y1 - y0, y2 - y0]]) # A = sparse.coo_matrix((AA.ravel(), (IA.ravel(), JA.ravel()))) # X, Y = mesh.X, mesh.Y # E = mesh.E2 # DX = np.zeros((ne, m1*m2)) # DXI = np.zeros((ne, m1*m2), dtype=int) # DXJ = np.zeros((ne, m1*m2), dtype=int) # DY = np.zeros((ne, m1*m2)) # DYI = np.zeros((ne, m1*m2), dtype=int) # DYJ = np.zeros((ne, m1*m2), dtype=int) # K = E[ei, :] # J = np.array([[x1 - x0, x2 - x0], # [y1 - y0, y2 - y0]]) # BX = sparse.coo_matrix((DX.ravel(), (DXI.ravel(), DXJ.ravel()))) # BY = sparse.coo_matrix((DY.ravel(), (DYI.ravel(), DYJ.ravel()))) # X = mesh.X # Y = mesh.Y # X = mesh.X2 # Y = mesh.Y2 # BX, BY = divform(mesh) # C = sparse.bmat([[Au, None, BX.T], # [None, Av, BY.T], # [BX, BY, None]]) # class Mesh: . Output only the next line.
A, _ = gradgradform(mesh)
Based on the snippet: <|code_start|>"""Test basic mesh construction.""" class TestRegularTriangleMesh(TestCase): def test_1x1(self): try: <|code_end|> , predict the immediate next line with the help of imports: from pyamg.gallery.mesh import regular_triangle_mesh from numpy.testing import TestCase, assert_equal and context (classes, functions, sometimes code) from other files: # Path: pyamg/gallery/mesh.py # def regular_triangle_mesh(nx, ny): # """Construct a regular triangular mesh in the unit square. # # Parameters # ---------- # nx : int # Number of nodes in the x-direction # ny : int # Number of nodes in the y-direction # # Returns # ------- # Vert : array # nx*ny x 2 vertex list # E2V : array # Nex x 3 element list # # Examples # -------- # >>> from pyamg.gallery import regular_triangle_mesh # >>> E2V,Vert = regular_triangle_mesh(3, 2) # # """ # nx, ny = int(nx), int(ny) # # if nx < 2 or ny < 2: # raise ValueError(f'minimum mesh dimension is 2: {(nx, ny)}') # # Vert1 = np.tile(np.arange(0, nx-1), ny - 1) +\ # np.repeat(np.arange(0, nx * (ny - 1), nx), nx - 1) # Vert3 = np.tile(np.arange(0, nx-1), ny - 1) +\ # np.repeat(np.arange(0, nx * (ny - 1), nx), nx - 1) + nx # Vert2 = Vert3 + 1 # Vert4 = Vert1 + 1 # # Verttmp = np.meshgrid(np.arange(0, nx, dtype='float'), # np.arange(0, ny, dtype='float')) # Verttmp = (Verttmp[0].ravel(), Verttmp[1].ravel()) # Vert = np.vstack(Verttmp).transpose() # Vert[:, 0] = (1.0 / (nx - 1)) * Vert[:, 0] # Vert[:, 1] = (1.0 / (ny - 1)) * Vert[:, 1] # # E2V1 = np.vstack((Vert1, Vert2, Vert3)).transpose() # E2V2 = np.vstack((Vert1, Vert4, Vert2)).transpose() # E2V = np.vstack((E2V1, E2V2)) # # return Vert, E2V . Output only the next line.
regular_triangle_mesh(1, 0)
Based on the snippet: <|code_start|>"""Test stencil construction.""" class TestStencil(TestCase): def test_1d(self): stencil = np.array([1, 2, 3]) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from pyamg.gallery.stencil import stencil_grid from numpy.testing import TestCase, assert_equal and context (classes, functions, sometimes code) from other files: # Path: pyamg/gallery/stencil.py # def stencil_grid(S, grid, dtype=None, format=None): # """Construct a sparse matrix form a local matrix stencil. # # Parameters # ---------- # S : ndarray # matrix stencil stored in N-d array # grid : tuple # tuple containing the N grid dimensions # dtype : # data type of the result # format : string # sparse matrix format to return, e.g. "csr", "coo", etc. # # Returns # ------- # A : sparse matrix # Sparse matrix which represents the operator given by applying # stencil S at each vertex of a regular grid with given dimensions. # # Notes # ----- # The grid vertices are enumerated as arange(prod(grid)).reshape(grid). # This implies that the last grid dimension cycles fastest, while the # first dimension cycles slowest. For example, if grid=(2,3) then the # grid vertices are ordered as (0,0), (0,1), (0,2), (1,0), (1,1), (1,2). # # This coincides with the ordering used by the NumPy functions # ndenumerate() and mgrid(). # # Examples # -------- # >>> from pyamg.gallery import stencil_grid # >>> stencil = [-1,2,-1] # 1D Poisson stencil # >>> grid = (5,) # 1D grid with 5 vertices # >>> A = stencil_grid(stencil, grid, dtype=float, format='csr') # >>> A.toarray() # array([[ 2., -1., 0., 0., 0.], # [-1., 2., -1., 0., 0.], # [ 0., -1., 2., -1., 0.], # [ 0., 0., -1., 2., -1.], # [ 0., 0., 0., -1., 2.]]) # # >>> stencil = [[0,-1,0],[-1,4,-1],[0,-1,0]] # 2D Poisson stencil # >>> grid = (3,3) # 2D grid with shape 3x3 # >>> A = stencil_grid(stencil, grid, dtype=float, format='csr') # >>> A.toarray() # array([[ 4., -1., 0., -1., 0., 0., 0., 0., 0.], # [-1., 4., -1., 0., -1., 0., 0., 0., 0.], # [ 0., -1., 4., 0., 0., -1., 0., 0., 0.], # [-1., 0., 0., 4., -1., 0., -1., 0., 0.], # [ 0., -1., 0., -1., 4., -1., 0., -1., 0.], # [ 0., 0., -1., 0., -1., 4., 0., 0., -1.], # [ 0., 0., 0., -1., 0., 0., 4., -1., 0.], # [ 0., 0., 0., 0., -1., 0., -1., 4., -1.], # [ 0., 0., 0., 0., 0., -1., 0., -1., 4.]]) # # """ # S = np.asarray(S, dtype=dtype) # grid = tuple(grid) # # if not (np.asarray(S.shape) % 2 == 1).all(): # raise ValueError('all stencil dimensions must be odd') # # if len(grid) != np.ndim(S): # raise ValueError('stencil dimension must equal number of grid\ # dimensions') # # if min(grid) < 1: # raise ValueError('grid dimensions must be positive') # # N_v = np.prod(grid) # number of vertices in the mesh # N_s = (S != 0).sum() # number of nonzero stencil entries # # # diagonal offsets # diags = np.zeros(N_s, dtype=int) # # # compute index offset of each dof within the stencil # strides = np.cumprod([1] + list(reversed(grid)))[:-1] # indices = tuple(i.copy() for i in S.nonzero()) # for i, s in zip(indices, S.shape): # i -= s // 2 # # i = (i - s) // 2 # # i = i // 2 # # i = i - (s // 2) # for stride, coords in zip(strides, reversed(indices)): # diags += stride * coords # # data = S[S != 0].repeat(N_v).reshape(N_s, N_v) # # indices = np.vstack(indices).T # # # zero boundary connections # for index, diag in zip(indices, data): # diag = diag.reshape(grid) # for n, i in enumerate(index): # if i > 0: # s = [slice(None)] * len(grid) # s[n] = slice(0, i) # s = tuple(s) # diag[s] = 0 # elif i < 0: # s = [slice(None)]*len(grid) # s[n] = slice(i, None) # s = tuple(s) # diag[s] = 0 # # # remove diagonals that lie outside matrix # mask = abs(diags) < N_v # if not mask.all(): # diags = diags[mask] # data = data[mask] # # # sum duplicate diagonals # if len(np.unique(diags)) != len(diags): # new_diags = np.unique(diags) # new_data = np.zeros((len(new_diags), data.shape[1]), # dtype=data.dtype) # # for dia, dat in zip(diags, data): # n = np.searchsorted(new_diags, dia) # new_data[n, :] += dat # # diags = new_diags # data = new_data # # return sparse.dia_matrix((data, diags), # shape=(N_v, N_v)).asformat(format) . Output only the next line.
result = stencil_grid(stencil, (3,)).toarray()
Next line prediction: <|code_start|> self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), (1 + 3j) * np.arange(4).reshape(4, 1))) # two aggregates two candidates self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), (1 + 0j) * np.vstack((np.ones(4), np.arange(4))).T)) self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), (0 + 3j) * np.vstack((np.ones(4), np.arange(4))).T)) self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), (1 + 3j) * np.vstack((np.ones(4), np.arange(4))).T)) self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), np.array([[-1 + 4j, 1 + 3j], [0 + 5j, 6 + 0j], [5 - 2j, 7 + 1j], [9 - 8j, 7 + 2j]]))) def test_all_cases(self): def mask_candidate(AggOp, candidates): # mask out all dofs that are not included in the aggregation candidates[np.where(np.diff(AggOp.indptr) == 0)[0], :] = 0 for AggOp, fine_candidates in self.cases: mask_candidate(AggOp, fine_candidates) <|code_end|> . Use current file imports: (import numpy as np from scipy.sparse import csr_matrix from pyamg.aggregation.aggregation import fit_candidates from numpy.testing import TestCase, assert_almost_equal) and context including class names, function names, or small code snippets from other files: # Path: pyamg/aggregation/aggregation.py # def smoothed_aggregation_solver(A, B=None, BH=None, # symmetry='hermitian', strength='symmetric', # aggregate='standard', # smooth=('jacobi', {'omega': 4.0/3.0}), # presmoother=('block_gauss_seidel', # {'sweep': 'symmetric'}), # postsmoother=('block_gauss_seidel', # {'sweep': 'symmetric'}), # improve_candidates=(('block_gauss_seidel', # {'sweep': 'symmetric', # 'iterations': 4}), # None), # max_levels=10, max_coarse=10, # diagonal_dominance=False, # keep=False, **kwargs): # def _extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, # diagonal_dominance=False, keep=True): # def unpack_arg(v): # A = csr_matrix(A) # A = A.asfptype() # B = np.kron(np.ones((int(A.shape[0]/get_blocksize(A)), 1), dtype=A.dtype), # np.eye(get_blocksize(A), dtype=A.dtype)) # B = np.asarray(B, dtype=A.dtype) # B = B.reshape(-1, 1) # BH = B.copy() # BH = np.asarray(BH, dtype=A.dtype) # BH = BH.reshape(-1, 1) # A = levels[-1].A # B = levels[-1].B # AH = A.H.asformat(A.format) # BH = levels[-1].BH # C = symmetric_strength_of_connection(A, **kwargs) # C = classical_strength_of_connection(A, **kwargs) # C = distance_strength_of_connection(A, **kwargs) # C = evolution_strength_of_connection(A, **kwargs) # C = evolution_strength_of_connection(A, B, **kwargs) # C = energy_based_strength_of_connection(A, **kwargs) # C = kwargs['C'].tocsr() # C = algebraic_distance(A, **kwargs) # C = affinity_distance(A, **kwargs) # C = A.tocsr() # C = eliminate_diag_dom_nodes(A, C, **kwargs) # B = relaxation_as_linear_operator((fn, kwargs), A, b) * B # BH = relaxation_as_linear_operator((fn, kwargs), AH, b) * BH # T, B = fit_candidates(AggOp, B) # TH, BH = fit_candidates(AggOp, BH) # P = jacobi_prolongation_smoother(A, T, C, B, **kwargs) # P = richardson_prolongation_smoother(A, T, **kwargs) # P = energy_prolongation_smoother(A, T, C, B, None, (False, {}), # **kwargs) # P = T # R = P.H # R = P.T # R = jacobi_prolongation_smoother(AH, TH, C, BH, **kwargs).H # R = richardson_prolongation_smoother(AH, TH, **kwargs).H # R = energy_prolongation_smoother(AH, TH, C, BH, None, (False, {}), # **kwargs) # R = R.H # R = T.H # A = R * A * P # Galerkin operator . Output only the next line.
Q, coarse_candidates = fit_candidates(AggOp, fine_candidates)
Predict the next line for this snippet: <|code_start|> [1, 2], [1, 1], [2, 0], [2, 1], [2, 2], [2, 3], [3, 2], [3, 1], [3, 0], [4, 0]]) del xy G = np.zeros((12, 12)) G[0, [1]] = 1 G[1, [2, 7]] = 1 G[2, [0, 3]] = 1 G[3, [5]] = 1 G[4, [10]] = 1 G[5, [4, 6]] = 1 G[6, [2]] = 1 G[7, [6]] = 1 G[8, [6]] = 1 G[9, [5, 8]] = 1 G[10, [9, 11]] = 1 G[11, [9]] = 1 G = sparse.csr_matrix(G) np.random.seed(1664236979) G.data[:] = np.random.rand(len(G.data)) * 2 cases.append(G) # (4) 191 node unstructured finite element matrix <|code_end|> with the help of current file imports: import numpy as np import pyamg.amg_core as amg_core import scipy.sparse as sparse from pyamg.gallery import load_example from numpy.testing import TestCase, assert_equal, assert_array_equal and context from other files: # Path: pyamg/gallery/example.py # def load_example(name): # """Load an example problem by name. # # Parameters # ---------- # name : string (e.g. 'airfoil') # Name of the example to load # # Notes # ----- # Each example is stored in a dictionary with the following keys: # - 'A' : sparse matrix # - 'B' : near-nullspace candidates # - 'vertices' : dense array of nodal coordinates # - 'elements' : dense array of element indices # # Current example names are:%s # # Examples # -------- # >>> from pyamg.gallery import load_example # >>> ex = load_example('knot') # # """ # if name not in example_names: # raise ValueError(f'No example with name {name}') # # return loadmat(os.path.join(example_dir, name + '.mat'), struct_as_record=True) , which may contain function names, class names, or code. Output only the next line.
cases.append(load_example('unit_square')['A'])
Given the code snippet: <|code_start|> return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2) def z_slice(self,ind=-1): if len(self.array.shape)==2: raise RuntimeError('z_slice() only works for 3d wavefunctions') return Wavefunction(self.array[:,:,ind],self.energy,self.sampling[:2],self.offset) def apply_ctf(self,ctf): return ctf.apply(self) def resample(self,sampling): if len(self.array.shape)==3: raise RuntimeError('resample() only works for 2d wavefunctions') if not isinstance(sampling, (list, tuple)): sampling=(sampling,)*2 zoom=(self.sampling[0]/sampling[0],self.sampling[1]/sampling[1]) real = scipy.ndimage.interpolation.zoom(np.real(self.array), zoom) imag = scipy.ndimage.interpolation.zoom(np.imag(self.array), zoom) sampling=(self.array.shape[0]*self.sampling[0]/real.shape[0], self.array.shape[1]*self.sampling[1]/real.shape[1]) return Wavefunction(real+1.j*imag,self.energy,sampling,self.offset) <|code_end|> , generate the next line using the imports in this file: import matplotlib.pyplot as plt import scipy import scipy.ndimage import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.widgets import Slider from .detection import detect and context (functions, classes, or occasionally code) from other files: # Path: pyqstem/detection.py # def detect(img,sampling,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): # # if resample is not None: # if not isinstance(resample, (list, tuple)): # resample=(resample,)*2 # zoom=(sampling[0]/resample[0],sampling[1]/resample[1]) # sampling=resample # warnings.filterwarnings('ignore') # img = scipy.ndimage.interpolation.zoom(img, zoom) # warnings.filterwarnings('always') # # # if blur is not None: # img=gaussian(img,blur) # # if dose is not None: # img = img/np.sum(img)*dose*np.product(sampling)*np.product(img.shape) # # img[img<0]=0 # #vals = len(np.unique(img)) # #vals = 2**np.ceil(np.log2(vals)) # #img = np.random.poisson(img * vals) / float(vals) # # img = np.random.poisson(img).astype(np.int64) # # if MTF_param is not None: # if MTF_func is None: # MTF_func=MTF_a # # kx,ky,k2=spatial_frequencies(img.shape,sampling) # k=np.sqrt(k2) # mtf=MTF_func(k,*MTF_param) # img=np.fft.ifft2(np.fft.fft2(img)*np.sqrt(mtf)) # img=(img.real+img.imag)/2 # # return img . Output only the next line.
def detect(self,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None):
Given the code snippet: <|code_start|> V=1/0.07957747154594767*V # 1/epsilon0 elif units=='SI': e=1.60217662*10**(-19) epsilon0=8.854187817*10**(-12) V=e/epsilon0*V else: raise RuntimeError('Unit convention {0} not recognized.'.format(units)) return V def create_potential_slices(V,n,box,nonneg=True): Nz=V.shape[2] if n<1: raise RuntimeError('n should be a positive integer') if Nz%n!=0: raise RuntimeError('V.shape[2] is not divisible by n ({0} % {1} != 0)'.format(Nz,n)) V_slices=np.zeros(V.shape[:2]+(n,)) dz=box[2]/float(Nz) nz=int(Nz/n) for i in range(n): V_slices[:,:,i]=np.trapz(V[:,:,i*nz:(i+1)*nz+1],dx=dz,axis=2) if nonneg: V_slices=V_slices-V_slices.min() sampling = (box[0]/V_slices.shape[0],box[1]/V_slices.shape[1],box[2]/n) <|code_end|> , generate the next line using the imports in this file: import numpy as np import numpy.linalg from .wave import Potential from skimage.filters import gaussian and context (functions, classes, or occasionally code) from other files: # Path: pyqstem/wave.py # class Potential(BaseArray): # # def __init__(self, array, sampling, periodic_xy=True, periodic_z=False): # BaseArray.__init__(self, array, sampling) # # self.periodic_xy=periodic_xy # self.periodic_z=periodic_z # # def view(self,method='intensity',nav_axis=2,ind=-1,slider=False,ax=None,**kwargs): # projected = np.sum(self.array,axis=2) # self.refs += view(self,method=method,nav_axis=nav_axis,ind=ind,slider=slider,ax=ax,**kwargs) . Output only the next line.
potential = Potential(V_slices,sampling)
Based on the snippet: <|code_start|> self.convergence_angle,self.focal_spread,self.aberrations) def check_recalculate(self,shape,sampling,wavelength,tol=1e-12): if np.any([None is i for i in [self.array,self.sampling,self.wavelength]]): return True elif ((not np.isclose(self.wavelength,wavelength,rtol=tol))| (not np.isclose(self.sampling,sampling,rtol=tol).all())| (not (self.array.shape == shape))): return True else: return False def apply(self,wave,keep=True): shape=wave.array.shape sampling=wave.sampling wavelength=wave.wavelength if self.check_recalculate(shape,sampling,wavelength): ctf = self.calculate(shape,sampling,wavelength) new_wave_array=np.fft.ifft2(np.fft.fft2(wave.array)*ctf) if keep: self.sampling=sampling self.wavelength=wavelength self.array=ctf if len(new_wave_array.shape) > 2: <|code_end|> , predict the immediate next line with the help of imports: from .wave import Wave from .util import energy2wavelength, spatial_frequencies from scipy.interpolate import spline,interp1d import matplotlib.pyplot as plt import numpy as np and context (classes, functions, sometimes code) from other files: # Path: pyqstem/wave.py # class Wave(BaseArray): # # def __init__(self, array, energy, sampling=None, periodic_xy=True): # BaseArray.__init__(self, array, sampling) # self.energy = energy # # @property # def shape(self): # return self.array.shape # # @property # def wavelength(self): # return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2) # # def z_slice(self,ind=-1): # # if len(self.array.shape)==2: # raise RuntimeError('z_slice() only works for 3d wavefunctions') # # return Wavefunction(self.array[:,:,ind],self.energy,self.sampling[:2],self.offset) # # def apply_ctf(self,ctf): # return ctf.apply(self) # # def resample(self,sampling): # # if len(self.array.shape)==3: # raise RuntimeError('resample() only works for 2d wavefunctions') # # if not isinstance(sampling, (list, tuple)): # sampling=(sampling,)*2 # # zoom=(self.sampling[0]/sampling[0],self.sampling[1]/sampling[1]) # # real = scipy.ndimage.interpolation.zoom(np.real(self.array), zoom) # imag = scipy.ndimage.interpolation.zoom(np.imag(self.array), zoom) # # sampling=(self.array.shape[0]*self.sampling[0]/real.shape[0], # self.array.shape[1]*self.sampling[1]/real.shape[1]) # # return Wavefunction(real+1.j*imag,self.energy,sampling,self.offset) # # def detect(self,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): # sampling=self.sampling # img=np.abs(self.array)**2 # return detect(img,sampling,dose=dose,MTF_param=MTF_param,MTF_func=MTF_func,blur=blur,resample=resample) # # def save(self,name): # np.savez(name,self.array,self.energy,self.sampling) # # def view(self,method='intensity',nav_axis=2,ind=-1,slider=False,ax=None,**kwargs): # # self.refs += view(self,method=method,nav_axis=nav_axis,ind=ind,slider=slider,ax=ax,**kwargs) # # Path: pyqstem/util.py # def energy2wavelength(v0): # m0=0.5109989461*10**3 # keV / c**2 # h=4.135667662*10**(-15)*10**(-3) # eV * s # c=2.99792458*10**8 # m / s # return h*c/np.sqrt(v0*(2*m0+v0))*10**10 # # def spatial_frequencies(shape,sampling,return_polar=False,return_nyquist=False,wavelength=None): # # if not isinstance(shape, collections.Iterable): # shape = (shape,)*2 # # if not isinstance(sampling, collections.Iterable): # sampling = (sampling,)*2 # # dkx=1/(shape[0]*sampling[0]) # dky=1/(shape[1]*sampling[1]) # # if shape[0]%2==0: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2,shape[0]/2,1)) # else: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2-.5,shape[0]/2-.5,1)) # # if shape[1]%2==0: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2,shape[1]/2,1)) # else: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2-.5,shape[1]/2-.5,1)) # # ky,kx = np.meshgrid(ky,kx) # # k2 = kx**2+ky**2 # # ret = (kx,ky,k2) # if return_nyquist: # knx = 1/(2*sampling[0]) # kny = 1/(2*sampling[1]) # Kx=kx/knx # Ky=ky/knx # K2 = Kx**2+Ky**2 # ret += (Kx,Ky,K2) # if return_polar: # theta = np.sqrt(k2*wavelength**2) # phi = np.arctan2(ky,kx) # ret += (theta,phi) # # return ret . Output only the next line.
return [Wave(a,wave.energy,wave.sampling) for a in new_wave_array]
Given snippet: <|code_start|> self.sampling=sampling self.wavelength=wavelength self.array=ctf if len(new_wave_array.shape) > 2: return [Wave(a,wave.energy,wave.sampling) for a in new_wave_array] else: return Wave(new_wave_array,wave.energy,wave.sampling) def parse_wave_params(self, shape, sampling, energy, wavelength): if shape is None: if self.array is None: raise RuntimeError('Shape not set') else: shape = self.array.shape if sampling is None: if self.sampling is None: raise RuntimeError('Sampling not set') else: sampling = self.sampling if (wavelength is None)&(energy is None): if self.wavelength is None: raise RuntimeError('Wavelength not set. Provide energy or wavelength.') else: wavelength = self.wavelength if wavelength is None: <|code_end|> , continue by predicting the next line. Consider current file imports: from .wave import Wave from .util import energy2wavelength, spatial_frequencies from scipy.interpolate import spline,interp1d import matplotlib.pyplot as plt import numpy as np and context: # Path: pyqstem/wave.py # class Wave(BaseArray): # # def __init__(self, array, energy, sampling=None, periodic_xy=True): # BaseArray.__init__(self, array, sampling) # self.energy = energy # # @property # def shape(self): # return self.array.shape # # @property # def wavelength(self): # return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2) # # def z_slice(self,ind=-1): # # if len(self.array.shape)==2: # raise RuntimeError('z_slice() only works for 3d wavefunctions') # # return Wavefunction(self.array[:,:,ind],self.energy,self.sampling[:2],self.offset) # # def apply_ctf(self,ctf): # return ctf.apply(self) # # def resample(self,sampling): # # if len(self.array.shape)==3: # raise RuntimeError('resample() only works for 2d wavefunctions') # # if not isinstance(sampling, (list, tuple)): # sampling=(sampling,)*2 # # zoom=(self.sampling[0]/sampling[0],self.sampling[1]/sampling[1]) # # real = scipy.ndimage.interpolation.zoom(np.real(self.array), zoom) # imag = scipy.ndimage.interpolation.zoom(np.imag(self.array), zoom) # # sampling=(self.array.shape[0]*self.sampling[0]/real.shape[0], # self.array.shape[1]*self.sampling[1]/real.shape[1]) # # return Wavefunction(real+1.j*imag,self.energy,sampling,self.offset) # # def detect(self,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): # sampling=self.sampling # img=np.abs(self.array)**2 # return detect(img,sampling,dose=dose,MTF_param=MTF_param,MTF_func=MTF_func,blur=blur,resample=resample) # # def save(self,name): # np.savez(name,self.array,self.energy,self.sampling) # # def view(self,method='intensity',nav_axis=2,ind=-1,slider=False,ax=None,**kwargs): # # self.refs += view(self,method=method,nav_axis=nav_axis,ind=ind,slider=slider,ax=ax,**kwargs) # # Path: pyqstem/util.py # def energy2wavelength(v0): # m0=0.5109989461*10**3 # keV / c**2 # h=4.135667662*10**(-15)*10**(-3) # eV * s # c=2.99792458*10**8 # m / s # return h*c/np.sqrt(v0*(2*m0+v0))*10**10 # # def spatial_frequencies(shape,sampling,return_polar=False,return_nyquist=False,wavelength=None): # # if not isinstance(shape, collections.Iterable): # shape = (shape,)*2 # # if not isinstance(sampling, collections.Iterable): # sampling = (sampling,)*2 # # dkx=1/(shape[0]*sampling[0]) # dky=1/(shape[1]*sampling[1]) # # if shape[0]%2==0: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2,shape[0]/2,1)) # else: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2-.5,shape[0]/2-.5,1)) # # if shape[1]%2==0: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2,shape[1]/2,1)) # else: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2-.5,shape[1]/2-.5,1)) # # ky,kx = np.meshgrid(ky,kx) # # k2 = kx**2+ky**2 # # ret = (kx,ky,k2) # if return_nyquist: # knx = 1/(2*sampling[0]) # kny = 1/(2*sampling[1]) # Kx=kx/knx # Ky=ky/knx # K2 = Kx**2+Ky**2 # ret += (Kx,Ky,K2) # if return_polar: # theta = np.sqrt(k2*wavelength**2) # phi = np.arctan2(ky,kx) # ret += (theta,phi) # # return ret which might include code, classes, or functions. Output only the next line.
wavelength=energy2wavelength(energy)
Given the following code snippet before the placeholder: <|code_start|> shape = self.array.shape if sampling is None: if self.sampling is None: raise RuntimeError('Sampling not set') else: sampling = self.sampling if (wavelength is None)&(energy is None): if self.wavelength is None: raise RuntimeError('Wavelength not set. Provide energy or wavelength.') else: wavelength = self.wavelength if wavelength is None: wavelength=energy2wavelength(energy) return shape, sampling, wavelength def as_array(self,shape=None,sampling=None,energy=None,wavelength=None): shape, sampling, wavelength = self.parse_wave_params(shape, sampling, energy, wavelength) if self.check_recalculate(shape,sampling,wavelength): return self.calculate(shape,sampling,wavelength) else: return self.array def calculate(self,shape,sampling,wavelength,return_envelopes=False): <|code_end|> , predict the next line using imports from the current file: from .wave import Wave from .util import energy2wavelength, spatial_frequencies from scipy.interpolate import spline,interp1d import matplotlib.pyplot as plt import numpy as np and context including class names, function names, and sometimes code from other files: # Path: pyqstem/wave.py # class Wave(BaseArray): # # def __init__(self, array, energy, sampling=None, periodic_xy=True): # BaseArray.__init__(self, array, sampling) # self.energy = energy # # @property # def shape(self): # return self.array.shape # # @property # def wavelength(self): # return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2) # # def z_slice(self,ind=-1): # # if len(self.array.shape)==2: # raise RuntimeError('z_slice() only works for 3d wavefunctions') # # return Wavefunction(self.array[:,:,ind],self.energy,self.sampling[:2],self.offset) # # def apply_ctf(self,ctf): # return ctf.apply(self) # # def resample(self,sampling): # # if len(self.array.shape)==3: # raise RuntimeError('resample() only works for 2d wavefunctions') # # if not isinstance(sampling, (list, tuple)): # sampling=(sampling,)*2 # # zoom=(self.sampling[0]/sampling[0],self.sampling[1]/sampling[1]) # # real = scipy.ndimage.interpolation.zoom(np.real(self.array), zoom) # imag = scipy.ndimage.interpolation.zoom(np.imag(self.array), zoom) # # sampling=(self.array.shape[0]*self.sampling[0]/real.shape[0], # self.array.shape[1]*self.sampling[1]/real.shape[1]) # # return Wavefunction(real+1.j*imag,self.energy,sampling,self.offset) # # def detect(self,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): # sampling=self.sampling # img=np.abs(self.array)**2 # return detect(img,sampling,dose=dose,MTF_param=MTF_param,MTF_func=MTF_func,blur=blur,resample=resample) # # def save(self,name): # np.savez(name,self.array,self.energy,self.sampling) # # def view(self,method='intensity',nav_axis=2,ind=-1,slider=False,ax=None,**kwargs): # # self.refs += view(self,method=method,nav_axis=nav_axis,ind=ind,slider=slider,ax=ax,**kwargs) # # Path: pyqstem/util.py # def energy2wavelength(v0): # m0=0.5109989461*10**3 # keV / c**2 # h=4.135667662*10**(-15)*10**(-3) # eV * s # c=2.99792458*10**8 # m / s # return h*c/np.sqrt(v0*(2*m0+v0))*10**10 # # def spatial_frequencies(shape,sampling,return_polar=False,return_nyquist=False,wavelength=None): # # if not isinstance(shape, collections.Iterable): # shape = (shape,)*2 # # if not isinstance(sampling, collections.Iterable): # sampling = (sampling,)*2 # # dkx=1/(shape[0]*sampling[0]) # dky=1/(shape[1]*sampling[1]) # # if shape[0]%2==0: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2,shape[0]/2,1)) # else: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2-.5,shape[0]/2-.5,1)) # # if shape[1]%2==0: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2,shape[1]/2,1)) # else: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2-.5,shape[1]/2-.5,1)) # # ky,kx = np.meshgrid(ky,kx) # # k2 = kx**2+ky**2 # # ret = (kx,ky,k2) # if return_nyquist: # knx = 1/(2*sampling[0]) # kny = 1/(2*sampling[1]) # Kx=kx/knx # Ky=ky/knx # K2 = Kx**2+Ky**2 # ret += (Kx,Ky,K2) # if return_polar: # theta = np.sqrt(k2*wavelength**2) # phi = np.arctan2(ky,kx) # ret += (theta,phi) # # return ret . Output only the next line.
kx,ky,k2,theta,phi=spatial_frequencies(shape,sampling,wavelength=wavelength,return_polar=True)
Using the snippet: <|code_start|> def detect(img,sampling,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): if resample is not None: if not isinstance(resample, (list, tuple)): resample=(resample,)*2 zoom=(sampling[0]/resample[0],sampling[1]/resample[1]) sampling=resample warnings.filterwarnings('ignore') img = scipy.ndimage.interpolation.zoom(img, zoom) warnings.filterwarnings('always') if blur is not None: img=gaussian(img,blur) if dose is not None: img = img/np.sum(img)*dose*np.product(sampling)*np.product(img.shape) img[img<0]=0 #vals = len(np.unique(img)) #vals = 2**np.ceil(np.log2(vals)) #img = np.random.poisson(img * vals) / float(vals) img = np.random.poisson(img).astype(np.int64) if MTF_param is not None: if MTF_func is None: MTF_func=MTF_a <|code_end|> , determine the next line of code. You have imports: import numpy as np import scipy.ndimage import matplotlib.pyplot as plt import warnings from .util import spatial_frequencies from skimage.filters import gaussian and context (class names, function names, or code) available: # Path: pyqstem/util.py # def spatial_frequencies(shape,sampling,return_polar=False,return_nyquist=False,wavelength=None): # # if not isinstance(shape, collections.Iterable): # shape = (shape,)*2 # # if not isinstance(sampling, collections.Iterable): # sampling = (sampling,)*2 # # dkx=1/(shape[0]*sampling[0]) # dky=1/(shape[1]*sampling[1]) # # if shape[0]%2==0: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2,shape[0]/2,1)) # else: # kx = np.fft.fftshift(dkx*np.arange(-shape[0]/2-.5,shape[0]/2-.5,1)) # # if shape[1]%2==0: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2,shape[1]/2,1)) # else: # ky = np.fft.fftshift(dky*np.arange(-shape[1]/2-.5,shape[1]/2-.5,1)) # # ky,kx = np.meshgrid(ky,kx) # # k2 = kx**2+ky**2 # # ret = (kx,ky,k2) # if return_nyquist: # knx = 1/(2*sampling[0]) # kny = 1/(2*sampling[1]) # Kx=kx/knx # Ky=ky/knx # K2 = Kx**2+Ky**2 # ret += (Kx,Ky,K2) # if return_polar: # theta = np.sqrt(k2*wavelength**2) # phi = np.arctan2(ky,kx) # ret += (theta,phi) # # return ret . Output only the next line.
kx,ky,k2=spatial_frequencies(img.shape,sampling)
Given the code snippet: <|code_start|> def __init__(self, cursor): self.cursor = cursor def execute(self, sql, params=()): return defer.maybeDeferred(self.cursor.execute, sql, params) def fetchone(self): return defer.maybeDeferred(self.cursor.fetchone) def fetchall(self): return defer.maybeDeferred(self.cursor.fetchall) def lastRowId(self): return defer.succeed(self.cursor.lastrowid) def close(self): return defer.maybeDeferred(self.cursor.close) class BlockingRunner(object): """ I wrap a single DB-API2 db connection in an asynchronous api. """ <|code_end|> , generate the next line using the imports in this file: from zope.interface import implements from twisted.internet import defer from functools import partial from collections import deque, defaultdict from norm.interface import IAsyncCursor, IRunner, IPool and context (functions, classes, or occasionally code) from other files: # Path: norm/interface.py # class IAsyncCursor(Interface): # # # def execute(query, params=None): # """ # Execute the given sql and params. # # Return a C{Deferred} which will fire with the DB-API results. # """ # # # def fetchone(): # pass # # # def fetchall(): # pass # # # def lastRowId(): # """ # Return a C{Deferred} id of the most recently inserted row. # """ # # # def close(): # pass # # class IRunner(Interface): # """ # I translate and run operations. # """ # # # def runQuery(sql, params=None): # """ # Run a query in a one-off transaction, returning the deferred result. # """ # # # def runOperation(sql, params=()): # """ # Run a query with no results # """ # # # def runInteraction(function, *args, **kwargs): # """ # Run a function within a database transaction. The function will be # passed an L{IAsyncCursor} as the first arg. # """ # # # def close(): # """ # Close the connections # """ # # class IPool(Interface): # # # def add(option): # """ # Add a ready option to the pool # """ # # # def remove(option): # """ # Remove an option from the pool # """ # # # def get(): # """ # Choose the next option; this will fire with a Deferred when the next # thing is ready for use. # """ # # # def done(option): # """ # Accept an option as ready # """ # # # def list(): # """ # List all the things # """ . Output only the next line.
implements(IRunner)
Given snippet: <|code_start|> """ The connection is bad, try the query again. """ retval = original_failure try: new_conn = yield self.makeConnection() m = getattr(new_conn, name) retval = yield m(*args, **kwargs) self.pool.remove(bad_conn) self.pool.add(new_conn) except: pass defer.returnValue(retval) def close(self): dlist = [] for item in self.pool.list(): dlist.append(defer.maybeDeferred(item.close)) return defer.gatherResults(dlist) class NextAvailablePool(object): """ I give you the next available object in the pool. """ <|code_end|> , continue by predicting the next line. Consider current file imports: from zope.interface import implements from twisted.internet import defer from functools import partial from collections import deque, defaultdict from norm.interface import IAsyncCursor, IRunner, IPool and context: # Path: norm/interface.py # class IAsyncCursor(Interface): # # # def execute(query, params=None): # """ # Execute the given sql and params. # # Return a C{Deferred} which will fire with the DB-API results. # """ # # # def fetchone(): # pass # # # def fetchall(): # pass # # # def lastRowId(): # """ # Return a C{Deferred} id of the most recently inserted row. # """ # # # def close(): # pass # # class IRunner(Interface): # """ # I translate and run operations. # """ # # # def runQuery(sql, params=None): # """ # Run a query in a one-off transaction, returning the deferred result. # """ # # # def runOperation(sql, params=()): # """ # Run a query with no results # """ # # # def runInteraction(function, *args, **kwargs): # """ # Run a function within a database transaction. The function will be # passed an L{IAsyncCursor} as the first arg. # """ # # # def close(): # """ # Close the connections # """ # # class IPool(Interface): # # # def add(option): # """ # Add a ready option to the pool # """ # # # def remove(option): # """ # Remove an option from the pool # """ # # # def get(): # """ # Choose the next option; this will fire with a Deferred when the next # thing is ready for use. # """ # # # def done(option): # """ # Accept an option as ready # """ # # # def list(): # """ # List all the things # """ which might include code, classes, or functions. Output only the next line.
implements(IPool)
Given the code snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class PatcherTest(TestCase): def getPool(self): return makePool('sqlite:') @defer.inlineCallbacks def test_add(self): """ You can add patches to a patcher and apply them to a database. """ called = [] <|code_end|> , generate the next line using the imports in this file: from twisted.trial.unittest import TestCase from twisted.internet import defer from norm import makePool from norm.patch import Patcher, SQLPatch and context (functions, classes, or occasionally code) from other files: # Path: norm/porcelain.py # def makePool(uri, connections=1): # parsed = parseURI(uri) # if parsed['scheme'] == 'sqlite': # return _makeSqlite(parsed) # elif parsed['scheme'] == 'postgres': # return _makePostgres(parsed, connections) # else: # raise Exception('%s is not supported' % (parsed['scheme'],)) # # Path: norm/patch.py # class Patcher(object): # """ # I hold patch functions for a database. # """ # # def __init__(self, patch_table_name='_patch'): # self.patch_table_name = patch_table_name # self.patches = [] # self._patchnames = set() # # # def add(self, name, func): # """ # Add a patch function. # # @param name: Name describing the patch. # @param func: A function to be called with an asynchronous cursor # as the only argument. A string, list or tuple of strings may also # be provided, in which case C{func} will be wrapped in L{SQLPatch}. # # @raise ValueError: If a patch name is reused. # """ # if name in self._patchnames: # raise ValueError('There is already a patch named %r' % (name,)) # if type(func) in (str, unicode): # func = SQLPatch(func) # elif type(func) in (tuple, list): # func = SQLPatch(*func) # self.patches.append((name, func)) # self._patchnames.add(name) # # # def upgrade(self, runner, stop_at_patch=None): # """ # Upgrade a database through the given runner. # # @param runner: An L{IRunner}. # @param stop_at_patch: The name of the patch to stop at. This will # correspond to the name supplied to L{add}. # # @return: A list of the patches applied # """ # already = self._appliedPatches(runner) # return already.addCallback(self._applyMissing, runner, stop_at_patch) # # # def _applyMissing(self, already, runner, stop_at_patch=None): # applied = [] # sem = defer.DeferredSemaphore(1) # stop = False # for name,func in self.patches: # if stop: # break # if stop_at_patch is not None and stop_at_patch == name: # # stopping after this one # stop = True # if name in already: # # patch already applied # continue # applied.append(name) # # apply the patch # sem.run(runner.runInteraction, func) # # record the application # sem.run(runner.runInteraction, self._recordPatch, name) # return applied # # # def _recordPatch(self, cursor, name): # return cursor.execute('insert into %s (name) values (?)' % ( # self.patch_table_name,), (name,)) # # # def _appliedPatches(self, runner): # d = runner.runQuery('select name from ' + self.patch_table_name) # d.addErrback(lambda x: self._createPatchTable(runner)) # d.addCallback(lambda a: [x[0] for x in a]) # return d # # # def _createPatchTable(self, runner): # d = runner.runOperation( # '''create table ''' + self.patch_table_name + '''( # name text, # created timestamp default current_timestamp # )''') # return d.addCallback(lambda x: []) # # class SQLPatch(object): # # # def __init__(self, *sqls): # self.sqls = sqls # # # def __call__(self, cursor): # sem = defer.DeferredSemaphore(1) # dlist = [] # for sql in self.sqls: # d = sem.run(cursor.execute, sql) # dlist.append(d) # return defer.gatherResults(dlist) . Output only the next line.
patcher = Patcher('_patch')
Next line prediction: <|code_start|> You can use a single string or a list/tuple of strings, instead of using SQLPatch directly. """ patcher = Patcher('_patch') patcher.add('something', [ 'create table bar (name text)', 'create table bar2 (name text)', ]) patcher.add('another', 'create table bar3 (name text)') pool = yield self.getPool() applied = yield patcher.upgrade(pool) self.assertEqual(applied, ['something', 'another'], "Should return the" " names of the patches applied") yield pool.runOperation('insert into bar (name) values (?)', ('hey',)) yield pool.runOperation('insert into bar2 (name) values (?)', ('hey',)) yield pool.runOperation('insert into bar3 (name) values (?)', ('hey',)) @defer.inlineCallbacks def test_commit(self): """ There should be a commit after applying patches """ patcher = Patcher() <|code_end|> . Use current file imports: (from twisted.trial.unittest import TestCase from twisted.internet import defer from norm import makePool from norm.patch import Patcher, SQLPatch) and context including class names, function names, or small code snippets from other files: # Path: norm/porcelain.py # def makePool(uri, connections=1): # parsed = parseURI(uri) # if parsed['scheme'] == 'sqlite': # return _makeSqlite(parsed) # elif parsed['scheme'] == 'postgres': # return _makePostgres(parsed, connections) # else: # raise Exception('%s is not supported' % (parsed['scheme'],)) # # Path: norm/patch.py # class Patcher(object): # """ # I hold patch functions for a database. # """ # # def __init__(self, patch_table_name='_patch'): # self.patch_table_name = patch_table_name # self.patches = [] # self._patchnames = set() # # # def add(self, name, func): # """ # Add a patch function. # # @param name: Name describing the patch. # @param func: A function to be called with an asynchronous cursor # as the only argument. A string, list or tuple of strings may also # be provided, in which case C{func} will be wrapped in L{SQLPatch}. # # @raise ValueError: If a patch name is reused. # """ # if name in self._patchnames: # raise ValueError('There is already a patch named %r' % (name,)) # if type(func) in (str, unicode): # func = SQLPatch(func) # elif type(func) in (tuple, list): # func = SQLPatch(*func) # self.patches.append((name, func)) # self._patchnames.add(name) # # # def upgrade(self, runner, stop_at_patch=None): # """ # Upgrade a database through the given runner. # # @param runner: An L{IRunner}. # @param stop_at_patch: The name of the patch to stop at. This will # correspond to the name supplied to L{add}. # # @return: A list of the patches applied # """ # already = self._appliedPatches(runner) # return already.addCallback(self._applyMissing, runner, stop_at_patch) # # # def _applyMissing(self, already, runner, stop_at_patch=None): # applied = [] # sem = defer.DeferredSemaphore(1) # stop = False # for name,func in self.patches: # if stop: # break # if stop_at_patch is not None and stop_at_patch == name: # # stopping after this one # stop = True # if name in already: # # patch already applied # continue # applied.append(name) # # apply the patch # sem.run(runner.runInteraction, func) # # record the application # sem.run(runner.runInteraction, self._recordPatch, name) # return applied # # # def _recordPatch(self, cursor, name): # return cursor.execute('insert into %s (name) values (?)' % ( # self.patch_table_name,), (name,)) # # # def _appliedPatches(self, runner): # d = runner.runQuery('select name from ' + self.patch_table_name) # d.addErrback(lambda x: self._createPatchTable(runner)) # d.addCallback(lambda a: [x[0] for x in a]) # return d # # # def _createPatchTable(self, runner): # d = runner.runOperation( # '''create table ''' + self.patch_table_name + '''( # name text, # created timestamp default current_timestamp # )''') # return d.addCallback(lambda x: []) # # class SQLPatch(object): # # # def __init__(self, *sqls): # self.sqls = sqls # # # def __call__(self, cursor): # sem = defer.DeferredSemaphore(1) # dlist = [] # for sql in self.sqls: # d = sem.run(cursor.execute, sql) # dlist.append(d) # return defer.gatherResults(dlist) . Output only the next line.
patcher.add('hello', SQLPatch(
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None) skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this ' 'postgres test') if postgres_url: skip_postgres = '' def postgresConnStr(): if not postgres_url: raise SkipTest(skip_postgres) <|code_end|> with the help of current file imports: from twisted.trial.unittest import SkipTest from norm.uri import mkConnStr, parseURI import os and context from other files: # Path: norm/uri.py # def mkConnStr(parsed_uri): # """ # Turn a parsed uri into a connection string suitable for the db module # """ # if parsed_uri['scheme'] == 'sqlite': # return parsed_uri['file'] or ':memory:' # # # postgres # parts = ['dbname=%s' % parsed_uri['db']] # for attr in ['host', 'port', 'user', 'password', 'sslmode']: # if attr in parsed_uri: # parts.append('%s=%s' % (attr, parsed_uri[attr])) # return ' '.join(parts) # # def parseURI(uri): # """ # Parse a database uri into component parts. # """ # ret = {} # r = urlparse(uri) # ret['scheme'] = r.scheme # if r.scheme == 'sqlite': # # sqlite # ret['file'] = uri.split(':')[1] # else: # # postgres # parts = r.path.lstrip('/').split('?') # ret['db'] = parts[0] # if r.username: # ret['user'] = r.username # if r.hostname: # ret['host'] = r.hostname # if r.port: # ret['port'] = r.port # if r.password: # ret['password'] = r.password # if len(parts) == 2: # query = parts[1] # for k,v in parse_qs(query).items(): # ret[k] = v[-1] # return ret , which may contain function names, class names, or code. Output only the next line.
return mkConnStr(parseURI(postgres_url))
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None) skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this ' 'postgres test') if postgres_url: skip_postgres = '' def postgresConnStr(): if not postgres_url: raise SkipTest(skip_postgres) <|code_end|> , predict the next line using imports from the current file: from twisted.trial.unittest import SkipTest from norm.uri import mkConnStr, parseURI import os and context including class names, function names, and sometimes code from other files: # Path: norm/uri.py # def mkConnStr(parsed_uri): # """ # Turn a parsed uri into a connection string suitable for the db module # """ # if parsed_uri['scheme'] == 'sqlite': # return parsed_uri['file'] or ':memory:' # # # postgres # parts = ['dbname=%s' % parsed_uri['db']] # for attr in ['host', 'port', 'user', 'password', 'sslmode']: # if attr in parsed_uri: # parts.append('%s=%s' % (attr, parsed_uri[attr])) # return ' '.join(parts) # # def parseURI(uri): # """ # Parse a database uri into component parts. # """ # ret = {} # r = urlparse(uri) # ret['scheme'] = r.scheme # if r.scheme == 'sqlite': # # sqlite # ret['file'] = uri.split(':')[1] # else: # # postgres # parts = r.path.lstrip('/').split('?') # ret['db'] = parts[0] # if r.username: # ret['user'] = r.username # if r.hostname: # ret['host'] = r.hostname # if r.port: # ret['port'] = r.port # if r.password: # ret['password'] = r.password # if len(parts) == 2: # query = parts[1] # for k,v in parse_qs(query).items(): # ret[k] = v[-1] # return ret . Output only the next line.
return mkConnStr(parseURI(postgres_url))
Next line prediction: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class parseURITest(TestCase): def test_sqlite(self): """ sqlite URIs should be supported """ <|code_end|> . Use current file imports: (from twisted.trial.unittest import TestCase from norm.uri import parseURI, mkConnStr) and context including class names, function names, or small code snippets from other files: # Path: norm/uri.py # def parseURI(uri): # """ # Parse a database uri into component parts. # """ # ret = {} # r = urlparse(uri) # ret['scheme'] = r.scheme # if r.scheme == 'sqlite': # # sqlite # ret['file'] = uri.split(':')[1] # else: # # postgres # parts = r.path.lstrip('/').split('?') # ret['db'] = parts[0] # if r.username: # ret['user'] = r.username # if r.hostname: # ret['host'] = r.hostname # if r.port: # ret['port'] = r.port # if r.password: # ret['password'] = r.password # if len(parts) == 2: # query = parts[1] # for k,v in parse_qs(query).items(): # ret[k] = v[-1] # return ret # # def mkConnStr(parsed_uri): # """ # Turn a parsed uri into a connection string suitable for the db module # """ # if parsed_uri['scheme'] == 'sqlite': # return parsed_uri['file'] or ':memory:' # # # postgres # parts = ['dbname=%s' % parsed_uri['db']] # for attr in ['host', 'port', 'user', 'password', 'sslmode']: # if attr in parsed_uri: # parts.append('%s=%s' % (attr, parsed_uri[attr])) # return ' '.join(parts) . Output only the next line.
parsed = parseURI('sqlite:')
Given the following code snippet before the placeholder: <|code_start|> p = parseURI('postgres:///postgres') self.assertEqual(p['db'], 'postgres') self.assertFalse('user' in p) self.assertFalse('host' in p) self.assertFalse('port' in p) self.assertFalse('password' in p) self.assertFalse('sslmode' in p) p = parseURI('postgres://user@host:1234/postgres') self.assertEqual(p['db'], 'postgres') self.assertEqual(p['user'], 'user') self.assertEqual(p['host'], 'host') self.assertEqual(p['port'], 1234) p = parseURI('postgres://user:password@') self.assertEqual(p['user'], 'user') self.assertEqual(p['password'], 'password') p = parseURI('postgres:///postgres?sslmode=require') self.assertEqual(p['db'], 'postgres') self.assertEqual(p['sslmode'], 'require') class makeConnStrTest(TestCase): def t(self, i, expected): parsed = parseURI(i) <|code_end|> , predict the next line using imports from the current file: from twisted.trial.unittest import TestCase from norm.uri import parseURI, mkConnStr and context including class names, function names, and sometimes code from other files: # Path: norm/uri.py # def parseURI(uri): # """ # Parse a database uri into component parts. # """ # ret = {} # r = urlparse(uri) # ret['scheme'] = r.scheme # if r.scheme == 'sqlite': # # sqlite # ret['file'] = uri.split(':')[1] # else: # # postgres # parts = r.path.lstrip('/').split('?') # ret['db'] = parts[0] # if r.username: # ret['user'] = r.username # if r.hostname: # ret['host'] = r.hostname # if r.port: # ret['port'] = r.port # if r.password: # ret['password'] = r.password # if len(parts) == 2: # query = parts[1] # for k,v in parse_qs(query).items(): # ret[k] = v[-1] # return ret # # def mkConnStr(parsed_uri): # """ # Turn a parsed uri into a connection string suitable for the db module # """ # if parsed_uri['scheme'] == 'sqlite': # return parsed_uri['file'] or ':memory:' # # # postgres # parts = ['dbname=%s' % parsed_uri['db']] # for attr in ['host', 'port', 'user', 'password', 'sslmode']: # if attr in parsed_uri: # parts.append('%s=%s' % (attr, parsed_uri[attr])) # return ' '.join(parts) . Output only the next line.
output = mkConnStr(parsed)
Next line prediction: <|code_start|> for cls in classes: obj = cls.__new__(cls) empty_obj = True for prop, value in class_data[cls]: if empty_obj and value is not None: empty_obj = False prop.fromDatabase(obj, value) if empty_obj: # No values, None (from a Left Join or the like) ret.append(None) else: ret.append(obj) if len(ret) == 1: return ret[0] return ret def updateObjectFromDatabase(data, obj, converter): """ Update an existing object's attributes from a database response row. @param data: A tuple-dict thing as returned by IAsyncCursor.fetchOne @param obj: An ORM'd object @param converter: A L{Converter} instance that knows how to convert from database-land to python-land. @return: The same C{obj} with updated attributes. """ if data is None: <|code_end|> . Use current file imports: (from collections import defaultdict, MutableMapping from zope.interface import implements from norm.orm.error import NotFound from norm.interface import IOperator from norm.orm.expr import Eq from norm.orm.expr import Neq from norm.orm.expr import Gt from norm.orm.expr import Gte from norm.orm.expr import Lt from norm.orm.expr import Lte import inspect import weakref) and context including class names, function names, or small code snippets from other files: # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ . Output only the next line.
raise NotFound(obj)
Given snippet: <|code_start|> """ def __init__(self): self.converters = defaultdict(lambda: []) def when(self, key): """ """ def deco(f): self.converters[key].append(f) return f return deco def convert(self, key, value): """ XXX """ for conv in self.converters[key]: value = conv(value) return value class BaseOperator(object): """ I provide asynchronous CRUD database access with objects. """ <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import defaultdict, MutableMapping from zope.interface import implements from norm.orm.error import NotFound from norm.interface import IOperator from norm.orm.expr import Eq from norm.orm.expr import Neq from norm.orm.expr import Gt from norm.orm.expr import Gte from norm.orm.expr import Lt from norm.orm.expr import Lte import inspect import weakref and context: # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ which might include code, classes, or functions. Output only the next line.
implements(IOperator)
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class TxPostgresCursor(txpostgres.Cursor): implements(IAsyncCursor) def execute(self, sql, params=()): <|code_end|> , continue by predicting the next line. Consider current file imports: from zope.interface import implements from txpostgres import txpostgres from norm.interface import IAsyncCursor from norm.postgres import translateSQL import psycopg2.extras and context: # Path: norm/interface.py # class IAsyncCursor(Interface): # # # def execute(query, params=None): # """ # Execute the given sql and params. # # Return a C{Deferred} which will fire with the DB-API results. # """ # # # def fetchone(): # pass # # # def fetchall(): # pass # # # def lastRowId(): # """ # Return a C{Deferred} id of the most recently inserted row. # """ # # # def close(): # pass # # Path: norm/postgres.py # def translateSQL(sql): # # this is naive # return sql.replace('?', '%s') which might include code, classes, or functions. Output only the next line.
sql = translateSQL(sql)
Here is a snippet: <|code_start|> __sql_table__ = 'book' id = Int(primary=True) name = Unicode() def __init__(self, name=None): self.name = name class FunctionalIOperatorTestsMixin(object): """ I am a mixin for functionally testing different database IOperators. To use me, you'll need to create a connection pool (runner) and create some database tables. See L{norm.orm.test.test_sqlite} for an example. """ def getOperator(self): raise NotImplementedError("You must implement getOperator to use this " "mixin") def getPool(self): raise NotImplementedError("You must implement getPool to use this " "mixin") @defer.inlineCallbacks def test_IOperator(self): oper = yield self.getOperator() <|code_end|> . Write the next line using the current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) , which may include functions, classes, or code. Output only the next line.
verifyObject(IOperator, oper)
Using the snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) <|code_end|> , determine the next line of code. You have imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context (class names, function names, or code) available: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) . Output only the next line.
name = String()
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) which might include code, classes, or functions. Output only the next line.
uni = Unicode()
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) which might include code, classes, or functions. Output only the next line.
date = Date()
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() date = Date() <|code_end|> with the help of current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) , which may contain function names, class names, or code. Output only the next line.
dtime = DateTime()
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() date = Date() dtime = DateTime() <|code_end|> with the help of current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) , which may contain function names, class names, or code. Output only the next line.
mybool = Bool()
Given snippet: <|code_start|> @defer.inlineCallbacks def test_insert_binary(self): """ Should handle binary data okay """ oper = yield self.getOperator() pool = yield self.getPool() empty = Empty() empty.name = '\x00\x01\x02hey\x00' yield pool.runInteraction(oper.insert, empty) self.assertEqual(empty.name, '\x00\x01\x02hey\x00') @defer.inlineCallbacks def test_query_basic(self): """ A basic query should work """ oper = yield self.getOperator() pool = yield self.getPool() e1 = Empty() e1.name = '1' yield pool.runInteraction(oper.insert, e1) e2 = Empty() e2.name = '2' yield pool.runInteraction(oper.insert, e2) <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) which might include code, classes, or functions. Output only the next line.
items = yield pool.runInteraction(oper.query, Query(Empty))
Using the snippet: <|code_start|> e2 = Empty() e2.name = '2' yield pool.runInteraction(oper.insert, e2) items = yield pool.runInteraction(oper.query, Query(Empty)) self.assertEqual(len(items), 2) items = sorted(items, key=lambda x:x.name) self.assertTrue(isinstance(items[0], Empty)) self.assertEqual(items[0].name, '1') self.assertTrue(isinstance(items[1], Empty)) self.assertEqual(items[1].name, '2') @defer.inlineCallbacks def test_query_Eq(self): oper = yield self.getOperator() pool = yield self.getPool() e1 = Empty() e1.name = '1' yield pool.runInteraction(oper.insert, e1) e2 = Empty() e2.name = '2' yield pool.runInteraction(oper.insert, e2) items = yield pool.runInteraction(oper.query, <|code_end|> , determine the next line of code. You have imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context (class names, function names, or code) available: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) . Output only the next line.
Query(Empty, Eq(Empty.id, e1.id)))
Next line prediction: <|code_start|> e1 = Empty() e1.name = '1' yield pool.runInteraction(oper.insert, e1) items = yield pool.runInteraction(oper.query, Query(Empty, Eq(Empty.name, '1'))) self.assertEqual(len(items), 1) @defer.inlineCallbacks def test_query_autoJoin(self): """ You can query across two tables with the default SQL join """ oper = yield self.getOperator() pool = yield self.getPool() p1 = Parent() p1.id = 1 p2 = Parent() p2.id = 2 c1 = Child(u'child1') c1.parent_id = 1 c2 = Child(u'child2') c2.parent_id = 2 for obj in [p1, p2, c1, c2]: yield pool.runInteraction(oper.insert, obj) items = yield pool.runInteraction(oper.query, <|code_end|> . Use current file imports: (from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle) and context including class names, function names, or small code snippets from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) . Output only the next line.
Query(Child, And(
Here is a snippet: <|code_start|> yield pool.runInteraction(oper.insert, obj) items = yield pool.runInteraction(oper.query, Query(Child, And( Eq(Child.parent_id, Parent.id), Eq(Parent.id,1)))) self.assertEqual(len(items), 1) self.assertEqual(items[0].name, 'child1', "Should return the one child") @defer.inlineCallbacks def test_query_LeftJoin(self): """ You can query across two tables with the a LEFT JOIN """ oper = yield self.getOperator() pool = yield self.getPool() p1 = Parent() p1.id = 1 p2 = Parent() p2.id = 2 c1 = Child(u'child1') c1.parent_id = 1 for obj in [p1, p2, c1]: yield pool.runInteraction(oper.insert, obj) items = yield pool.runInteraction(oper.query, Query((Parent,Child), joins=[ <|code_end|> . Write the next line using the current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) , which may include functions, classes, or code. Output only the next line.
LeftJoin(Child, Child.parent_id == Parent.id)]))
Predict the next line for this snippet: <|code_start|> obj = Empty() yield pool.runInteraction(oper.insert, obj) obj.name = 'new name' obj.uni = u'unicycle' obj.date = date(2000, 1, 1) yield pool.runInteraction(oper.update, obj) obj2 = Empty() obj2.id = obj.id yield pool.runInteraction(oper.refresh, obj2) self.assertEqual(obj2.name, 'new name') self.assertEqual(obj2.uni, u'unicycle') self.assertEqual(obj2.date, date(2000, 1, 1)) @defer.inlineCallbacks def test_delete(self): """ You can delete single objects """ oper = yield self.getOperator() pool = yield self.getPool() obj = yield pool.runInteraction(oper.insert, Empty()) yield pool.runInteraction(oper.delete, obj) obj2 = Empty() obj2.id = obj.id <|code_end|> with the help of current file imports: from twisted.internet import defer from zope.interface.verify import verifyObject from datetime import datetime, date from norm.interface import IOperator from norm.orm.props import Int, String, Unicode, Date, DateTime, Bool from norm.orm.expr import Query, Eq, And, LeftJoin from norm.orm.error import NotFound from norm import ormHandle and context from other files: # Path: norm/interface.py # class IOperator(Interface): # """ # I provide functions for doing operations. My methods are suitable for # use as the function in L{IRunner.runInteraction}. # """ # # # def insert(cursor, obj): # """ # Insert the ORM object into the database, update the object's attributes # and return the object. # """ # # # def query(cursor, query): # """ # XXX # """ # # # def refresh(cursor, obj): # """ # XXX # """ # # # def update(cursor, obj): # """ # XXX # """ # # # def delete(cursor, obj): # """ # XXX # """ # # Path: norm/orm/props.py # class Int(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return value # if type(value) not in (int, long): # raise TypeError('%r must be an integer, not %r' % (prop, value)) # return value # # class String(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), str): # raise TypeError('%r must be a str, not %r' % (prop, value)) # return value # # class Unicode(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), unicode): # raise TypeError('%r must be a unicode, not %r' % (prop, value)) # return value # # class Date(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), date): # raise TypeError('%r must be a date, not %r' % (prop, value)) # return value # # class DateTime(Property): # # # def _validate(self, prop, obj, value): # if type(value) not in (type(None), datetime): # raise TypeError('%r must be a datetime, not %r' % (prop, value)) # return value # # class Bool(Property): # # # def _validate(self, prop, obj, value): # if value is None: # return None # if type(value) not in (bool, int): # raise TypeError('%r must be a boolean, not %r' % (prop, value)) # return bool(value) # # Path: norm/orm/expr.py # class Query(object): # """ # I am a query for a set of objects. Pass me to L{IOperator.query}. # """ # # # def __init__(self, select, *constraints, **kwargs): # """ # @param select: Class(es) to return in the result. This may either be # a single class or a list/tuple of classes. # @param constraints: A L{Comparison} or other compileable expression. # # @param kwargs: # joins # """ # if type(select) not in (list, tuple): # select = (select,) # self.select = select # if constraints: # self.constraints = And(*constraints) # else: # self.constraints = None # self.joins = kwargs.pop('joins', None) or [] # self._classes = [] # self._props = [] # self._process() # # # def _process(self): # self._classes = [] # self._props = [] # for item in self.select: # info = classInfo(item) # keys = sorted(info.attributes.values()) # self._props.extend(keys) # self._classes.append(item) # # # def properties(self): # """ # Get a tuple of the Properties that will be returned by the query. # """ # return tuple(self._props) # # # def classes(self): # """ # Return a list of classes involved in the query. # """ # return self._classes # # # def find(self, select, constraints=None, joins=None): # """ # Search for another kind of object with additional constraints. # """ # all_constraints = [x for x in [self.constraints, constraints] if x] # joins = joins or [] # return Query(select, *all_constraints, joins=self.joins + joins) # # class Eq(Comparison): # op = '=' # # class And(LogicalBinaryOp): # join = ' AND ' # # class LeftJoin(Join): # # oper = 'LEFT JOIN' # # Path: norm/orm/error.py # class NotFound(Error): # pass # # Path: norm/porcelain.py # def ormHandle(pool): # operator = None # if pool.db_scheme == 'sqlite': # from norm.sqlite import SqliteOperator # operator = SqliteOperator() # elif pool.db_scheme == 'postgres': # from norm.postgres import PostgresOperator # operator = PostgresOperator() # return ORMHandle(pool, operator) , which may contain function names, class names, or code. Output only the next line.
self.assertFailure(pool.runInteraction(oper.refresh, obj2), NotFound)
Based on the snippet: <|code_start|> cursor = PostgresCursorWrapper(mock) result = getattr(cursor, name)(*args, **kwargs) getattr(mock, name).assert_called_once_with(*args, **kwargs) self.assertEqual(self.successResultOf(result), 'foo') def test_fetchone(self): self.assertCallThrough('fetchone') def test_fetchall(self): self.assertCallThrough('fetchall') def test_close(self): self.assertCallThrough('close') class PostgresCursorWrapperFunctionalTest(TestCase): timeout = 2 def test_works(self): connstr = postgresConnStr() db = psycopg2.connect(connstr) c = db.cursor() <|code_end|> , predict the immediate next line with the help of imports: from twisted.trial.unittest import TestCase from twisted.internet import defer from zope.interface.verify import verifyObject from mock import MagicMock from norm.interface import IAsyncCursor from norm.common import BlockingCursor from norm.postgres import PostgresCursorWrapper from norm.test.util import postgresConnStr import psycopg2 and context (classes, functions, sometimes code) from other files: # Path: norm/interface.py # class IAsyncCursor(Interface): # # # def execute(query, params=None): # """ # Execute the given sql and params. # # Return a C{Deferred} which will fire with the DB-API results. # """ # # # def fetchone(): # pass # # # def fetchall(): # pass # # # def lastRowId(): # """ # Return a C{Deferred} id of the most recently inserted row. # """ # # # def close(): # pass # # Path: norm/common.py # class BlockingCursor(object): # """ # I wrap a single DB-API2 db cursor in an asynchronous api. # """ # # implements(IAsyncCursor) # # # def __init__(self, cursor): # self.cursor = cursor # # # def execute(self, sql, params=()): # return defer.maybeDeferred(self.cursor.execute, sql, params) # # # def fetchone(self): # return defer.maybeDeferred(self.cursor.fetchone) # # # def fetchall(self): # return defer.maybeDeferred(self.cursor.fetchall) # # # def lastRowId(self): # return defer.succeed(self.cursor.lastrowid) # # # def close(self): # return defer.maybeDeferred(self.cursor.close) # # Path: norm/postgres.py # class PostgresCursorWrapper(object): # # # implements(IAsyncCursor) # # # def __init__(self, cursor): # self.cursor = cursor # # # def execute(self, sql, params=()): # sql = translateSQL(sql) # ret = self.cursor.execute(sql, params) # return ret # # # def lastRowId(self): # d = self.cursor.execute('select lastval()') # d.addCallback(lambda _: self.cursor.fetchone()) # return d.addCallback(lambda row: row[0]) # # # def fetchone(self): # return self.cursor.fetchone() # # # def fetchall(self): # return self.cursor.fetchall() # # # def close(self): # return self.cursor.close() # # Path: norm/test/util.py # def postgresConnStr(): # if not postgres_url: # raise SkipTest(skip_postgres) # return mkConnStr(parseURI(postgres_url)) . Output only the next line.
wrapped = PostgresCursorWrapper(BlockingCursor(c))
Given the code snippet: <|code_start|> def assertCallThrough(self, name, *args, **kwargs): mock = MagicMock() setattr(mock, name, MagicMock(return_value=defer.succeed('foo'))) cursor = PostgresCursorWrapper(mock) result = getattr(cursor, name)(*args, **kwargs) getattr(mock, name).assert_called_once_with(*args, **kwargs) self.assertEqual(self.successResultOf(result), 'foo') def test_fetchone(self): self.assertCallThrough('fetchone') def test_fetchall(self): self.assertCallThrough('fetchall') def test_close(self): self.assertCallThrough('close') class PostgresCursorWrapperFunctionalTest(TestCase): timeout = 2 def test_works(self): <|code_end|> , generate the next line using the imports in this file: from twisted.trial.unittest import TestCase from twisted.internet import defer from zope.interface.verify import verifyObject from mock import MagicMock from norm.interface import IAsyncCursor from norm.common import BlockingCursor from norm.postgres import PostgresCursorWrapper from norm.test.util import postgresConnStr import psycopg2 and context (functions, classes, or occasionally code) from other files: # Path: norm/interface.py # class IAsyncCursor(Interface): # # # def execute(query, params=None): # """ # Execute the given sql and params. # # Return a C{Deferred} which will fire with the DB-API results. # """ # # # def fetchone(): # pass # # # def fetchall(): # pass # # # def lastRowId(): # """ # Return a C{Deferred} id of the most recently inserted row. # """ # # # def close(): # pass # # Path: norm/common.py # class BlockingCursor(object): # """ # I wrap a single DB-API2 db cursor in an asynchronous api. # """ # # implements(IAsyncCursor) # # # def __init__(self, cursor): # self.cursor = cursor # # # def execute(self, sql, params=()): # return defer.maybeDeferred(self.cursor.execute, sql, params) # # # def fetchone(self): # return defer.maybeDeferred(self.cursor.fetchone) # # # def fetchall(self): # return defer.maybeDeferred(self.cursor.fetchall) # # # def lastRowId(self): # return defer.succeed(self.cursor.lastrowid) # # # def close(self): # return defer.maybeDeferred(self.cursor.close) # # Path: norm/postgres.py # class PostgresCursorWrapper(object): # # # implements(IAsyncCursor) # # # def __init__(self, cursor): # self.cursor = cursor # # # def execute(self, sql, params=()): # sql = translateSQL(sql) # ret = self.cursor.execute(sql, params) # return ret # # # def lastRowId(self): # d = self.cursor.execute('select lastval()') # d.addCallback(lambda _: self.cursor.fetchone()) # return d.addCallback(lambda row: row[0]) # # # def fetchone(self): # return self.cursor.fetchone() # # # def fetchall(self): # return self.cursor.fetchall() # # # def close(self): # return self.cursor.close() # # Path: norm/test/util.py # def postgresConnStr(): # if not postgres_url: # raise SkipTest(skip_postgres) # return mkConnStr(parseURI(postgres_url)) . Output only the next line.
connstr = postgresConnStr()
Given the following code snippet before the placeholder: <|code_start|>""" BORIS Behavioral Observation Research Interactive Software Copyright 2012-2020 Olivier Friard module for testing db_functions.py pytest -vv test_db_functions.py """ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) class Test_load_events_in_db(object): def test_1(self): pj = json.loads(open("files/test.boris").read()) <|code_end|> , predict the next line using imports from the current file: import os import sys import json from boris import db_functions and context including class names, function names, and sometimes code from other files: # Path: boris/db_functions.py # def load_events_in_db(pj: dict, # selected_subjects: list, # selected_observations: list, # selected_behaviors: list, # time_interval: str = TIME_FULL_OBS): # def load_aggregated_events_in_db(pj: dict, selected_subjects: list, selected_observations: list, # selected_behaviors: list): # def load_aggregated_events_in_intervals(pj: dict, selected_subjects: list, selected_observations: list, # selected_behaviors: list): . Output only the next line.
cursor = db_functions.load_events_in_db(pj, ["subject1"], ["observation #1"], ["s"])
Predict the next line after this snippet: <|code_start|> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not see <http://www.gnu.org/licenses/>. """ class ModifiersList(QDialog): def __init__(self, code, modifiers_dict, currentModifier): super().__init__() self.setWindowTitle(programName) self.setWindowFlags(Qt.WindowStaysOnTopHint) self.modifiers_dict = dict(modifiers_dict) currentModifierList = currentModifier.split("|") V1layout = QVBoxLayout() label = QLabel() label.setText(f"Choose the modifier{'s' * (len(self.modifiers_dict) > 1)} for <b>{code}</b> behavior") V1layout.addWidget(label) Hlayout = QHBoxLayout() self.modifiersSetNumber = 0 <|code_end|> using the current file's imports: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from boris.config import * from boris.utilities import sorted_keys import re and any relevant context from other files: # Path: boris/utilities.py # def sorted_keys(d: dict) -> list: # """ # return list of sorted keys of provided dictionary # # Args: # d (dict): dictionary # # Returns: # list: dictionary keys sorted numerically # """ # return [str(x) for x in sorted([int(x) for x in d.keys()])] . Output only the next line.
for idx in sorted_keys(modifiers_dict):
Here is a snippet: <|code_start|> Args: pj (dict): project dictionary selected_observations (list): selected_subjects (list): selected_behaviors (list): Returns: bool: True if OK else False str: error message database connector: db connector if bool True else None """ logging.debug(f"function: load_aggregated_events_in_db") # if no observation selected select all if not selected_observations: selected_observations = sorted([x for x in pj[OBSERVATIONS]]) # if no subject selected select all if not selected_subjects: selected_subjects = sorted([pj[SUBJECTS][x][SUBJECT_NAME] for x in pj[SUBJECTS]] + [NO_FOCAL_SUBJECT]) # if no behavior selected select all if not selected_behaviors: selected_behaviors = sorted([pj[ETHOGRAM][x][BEHAVIOR_CODE] for x in pj[ETHOGRAM]]) # check if state events are paired out = "" for obsId in selected_observations: <|code_end|> . Write the next line using the current file imports: import sqlite3 import os import logging import time from boris.config import * from boris import project_functions and context from other files: # Path: boris/project_functions.py # def check_observation_exhaustivity(events: list, ethogram: list, state_events_list: list = []): # def interval_len(interval): # def interval_number(interval): # def behavior_category(ethogram: dict) -> dict: # def check_coded_behaviors(pj: dict) -> set: # def check_if_media_available(observation: dict, project_file_name: str) -> bool: # def check_state_events_obs(obsId: str, ethogram: dict, observation: dict, time_format: str = HHMMSS) -> tuple: # def check_project_integrity(pj: dict, # time_format: str, # project_file_name: str, # media_file_available: bool = True) -> str: # def create_subtitles(pj: dict, selected_observations: list, parameters: dict, export_dir: str) -> tuple: # def subject_color(subject): # def export_observations_list(pj: dict, selected_observations: list, file_name: str, output_format: str) -> bool: # def remove_media_files_path(pj): # def media_full_path(media_file: str, project_file_name: str) -> str: # def observed_interval(observation: dict): # def observation_total_length(observation: dict): # def observation_length(pj, selected_observations: list) -> tuple: # def events_start_stop(ethogram, events): # def extract_observed_subjects(pj: dict, selected_observations: list) -> list: # def open_project_json(projectFileName: str) -> tuple: # def event_type(code: str, ethogram: dict) -> str: # def fix_unpaired_state_events(obsId, ethogram, observation, fix_at_time): , which may include functions, classes, or code. Output only the next line.
r, msg = project_functions.check_state_events_obs(obsId, pj[ETHOGRAM], pj[OBSERVATIONS][obsId], HHMMSS)
Predict the next line after this snippet: <|code_start|> else: plugin_path = os.path.dirname(p) dll = ctypes.CDLL(p) elif sys.platform.startswith('darwin'): # FIXME: should find a means to configure path d = '/Applications/VLC.app/Contents/MacOS/' c = d + 'lib/libvlccore.dylib' p = d + 'lib/libvlc.dylib' if os.path.exists(p) and os.path.exists(c): # pre-load libvlccore VLC 2.2.8+ ctypes.CDLL(c) dll = ctypes.CDLL(p) for p in ('modules', 'plugins'): p = d + p if os.path.isdir(p): plugin_path = p break else: # hope, some [DY]LD_LIBRARY_PATH is set... # pre-load libvlccore VLC 2.2.8+ ctypes.CDLL('libvlccore.dylib') dll = ctypes.CDLL('libvlc.dylib') else: raise NotImplementedError('%s: %s not supported' % (sys.argv[0], sys.platform)) return (dll, plugin_path) # MODIFIED BY OF # <|code_end|> using the current file's imports: import ctypes import os import sys import functools import logging import winreg as w import _winreg as w import termios import tty from ctypes.util import find_library from inspect import getargspec from boris import vlc_local from msvcrt import getch and any relevant context from other files: # Path: boris/vlc_local.py # def find_local_libvlc(): . Output only the next line.
dll, plugin_path = vlc_local.find_local_libvlc()
Predict the next line after this snippet: <|code_start|> Atomic = namedtuple('Atomic', ['left', 'lower', 'upper', 'right']) def mergeable(a, b): """ Tester whether two atomic intervals can be merged (i.e. they overlap or are adjacent). :param a: an atomic interval. :param b: an atomic interval. :return: True if mergeable, False otherwise. """ <|code_end|> using the current file's imports: from collections import namedtuple from .const import Bound, inf and any relevant context from other files: # Path: boris/portion/const.py # class Bound(enum.Enum): # class _Singleton(): # class _PInf(_Singleton): # class _NInf(_Singleton): # CLOSED = True # OPEN = False # def __bool__(self): # def __invert__(self): # def __str__(self): # def __repr__(self): # def __new__(cls, *args, **kwargs): # def __neg__(self): return _NInf() # def __lt__(self, o): return False # def __le__(self, o): return isinstance(o, _PInf) # def __gt__(self, o): return not isinstance(o, _PInf) # def __ge__(self, o): return True # def __eq__(self, o): return isinstance(o, _PInf) # def __repr__(self): return '+inf' # def __hash__(self): return hash(float('+inf')) # def __neg__(self): return _PInf() # def __lt__(self, o): return not isinstance(o, _NInf) # def __le__(self, o): return True # def __gt__(self, o): return False # def __ge__(self, o): return isinstance(o, _NInf) # def __eq__(self, o): return isinstance(o, _NInf) # def __repr__(self): return '-inf' # def __hash__(self): return hash(float('-inf')) . Output only the next line.
if a.lower < b.lower or (a.lower == b.lower and a.left == Bound.CLOSED):
Continue the code snippet: <|code_start|> return Interval.from_atomic(Bound.OPEN, lower, upper, Bound.CLOSED) def closedopen(lower, upper): """ Create a right-open interval with given bounds. :param lower: value of the lower bound. :param upper: value of the upper bound. :return: an interval. """ return Interval.from_atomic(Bound.CLOSED, lower, upper, Bound.OPEN) def singleton(value): """ Create a singleton interval. :param value: value of the lower and upper bounds. :return: an interval. """ return Interval.from_atomic(Bound.CLOSED, value, value, Bound.CLOSED) def empty(): """ Create an empty interval. :return: an interval. """ <|code_end|> . Use current file imports: from collections import namedtuple from .const import Bound, inf and context (classes, functions, or code) from other files: # Path: boris/portion/const.py # class Bound(enum.Enum): # class _Singleton(): # class _PInf(_Singleton): # class _NInf(_Singleton): # CLOSED = True # OPEN = False # def __bool__(self): # def __invert__(self): # def __str__(self): # def __repr__(self): # def __new__(cls, *args, **kwargs): # def __neg__(self): return _NInf() # def __lt__(self, o): return False # def __le__(self, o): return isinstance(o, _PInf) # def __gt__(self, o): return not isinstance(o, _PInf) # def __ge__(self, o): return True # def __eq__(self, o): return isinstance(o, _PInf) # def __repr__(self): return '+inf' # def __hash__(self): return hash(float('+inf')) # def __neg__(self): return _PInf() # def __lt__(self, o): return not isinstance(o, _NInf) # def __le__(self, o): return True # def __gt__(self, o): return False # def __ge__(self, o): return isinstance(o, _NInf) # def __eq__(self, o): return isinstance(o, _NInf) # def __repr__(self): return '-inf' # def __hash__(self): return hash(float('-inf')) . Output only the next line.
return Interval.from_atomic(Bound.OPEN, inf, -inf, Bound.OPEN)
Given snippet: <|code_start|> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not see <http://www.gnu.org/licenses/>. """ def check_text_file_type(rows): """ check text file returns separator and number of fields (if unique) """ separators = "\t,;" for separator in separators: cs = [] for row in rows: cs.append(row.count(separator)) if len(set(cs)) == 1: return separator, cs[0] + 1 return None, None def import_from_text_file(self): if self.twBehaviors.rowCount(): <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import logging import boris.utilities as utilities from boris import dialog from boris import project_functions from boris.config import * from boris import param_panel from PyQt5.QtWidgets import (QFileDialog, QTableWidgetItem, QApplication, QMessageBox, QListWidgetItem) from PyQt5.QtCore import (Qt) from PyQt5.QtGui import (QColor, QFont) and context: # Path: boris/dialog.py # def MessageDialog(title, text, buttons): # def error_message_box(task, error_type, error_file_name, # error_lineno): # do NOT use this function directly, use error_message function # def error_message(task: str, exc_info: tuple) -> None: # def __init__(self, parent=None): # def __init__(self): # def browse(self): # def ok(self): # def __init__(self, label_caption, elements_list): # def __init__(self, text, codes_list): # def getCode(self): # def pbOK_clicked(self): # def __init__(self, text, observations_list): # def get_selected_observations(self): # def __init__(self, time_format): # def __init__(self): # def rb_changed(self): # def pbOK_clicked(self): # def pbCancel_clicked(self): # def __init__(self): # def click(self, msg): # def __init__(self): # def click(self, msg): # def __init__(self): # def __init__(self): # def save_results(self): # def __init__(self): # def save_results(self): # def __init__(self): # def __init__(self): # def tw_cellDoubleClicked(self, r, c): # def choose_obs_subj_behav_category(pj: dict, # selected_observations: list, # maxTime=0, # flagShowIncludeModifiers: bool = True, # flagShowExcludeBehaviorsWoEvents: bool = True, # by_category: bool = False, # show_time: bool = False, # timeFormat: str = HHMMSS): # class Info_widget(QWidget): # class Video_overlay_dialog(QDialog): # class Input_dialog(QDialog): # class DuplicateBehaviorCode(QDialog): # class ChooseObservationsToImport(QDialog): # class Ask_time(QDialog): # class EditSelectedEvents(QDialog): # class FindInEvents(QWidget): # class FindReplaceEvents(QWidget): # class explore_project_dialog(QDialog): # class Results_dialog(QDialog): # class ResultsWidget(QWidget): # class View_data_head(QDialog): # class View_explore_project_results(QWidget): # # Path: boris/project_functions.py # def check_observation_exhaustivity(events: list, ethogram: list, state_events_list: list = []): # def interval_len(interval): # def interval_number(interval): # def behavior_category(ethogram: dict) -> dict: # def check_coded_behaviors(pj: dict) -> set: # def check_if_media_available(observation: dict, project_file_name: str) -> bool: # def check_state_events_obs(obsId: str, ethogram: dict, observation: dict, time_format: str = HHMMSS) -> tuple: # def check_project_integrity(pj: dict, # time_format: str, # project_file_name: str, # media_file_available: bool = True) -> str: # def create_subtitles(pj: dict, selected_observations: list, parameters: dict, export_dir: str) -> tuple: # def subject_color(subject): # def export_observations_list(pj: dict, selected_observations: list, file_name: str, output_format: str) -> bool: # def remove_media_files_path(pj): # def media_full_path(media_file: str, project_file_name: str) -> str: # def observed_interval(observation: dict): # def observation_total_length(observation: dict): # def observation_length(pj, selected_observations: list) -> tuple: # def events_start_stop(ethogram, events): # def extract_observed_subjects(pj: dict, selected_observations: list) -> list: # def open_project_json(projectFileName: str) -> tuple: # def event_type(code: str, ethogram: dict) -> str: # def fix_unpaired_state_events(obsId, ethogram, observation, fix_at_time): # # Path: boris/param_panel.py # class Param_panel(QDialog, Ui_Dialog): # def __init__(self, parent=None): # def rb_time(self, button): # def subjects_button_clicked(self, command): # def behaviors_button_clicked(self, command): # def ok(self): # def behavior_item_clicked(self, item): # def extract_observed_behaviors(self, selected_observations, selected_subjects): # def cb_changed(self): which might include code, classes, or functions. Output only the next line.
response = dialog.MessageDialog(
Given the following code snippet before the placeholder: <|code_start|> paramPanelWindow.item = QListWidgetItem(behavior) paramPanelWindow.item.setCheckState(Qt.Unchecked) if category != "###no category###": paramPanelWindow.item.setData(33, "behavior") if category == "": paramPanelWindow.item.setData(34, "No category") else: paramPanelWindow.item.setData(34, category) paramPanelWindow.lwBehaviors.addItem(paramPanelWindow.item) if paramPanelWindow.exec_(): return paramPanelWindow.selectedBehaviors return [] except Exception: dialog.error_message(sys._getframe().f_code.co_name, sys.exc_info()) def import_behaviors_from_project(self): try: fn = QFileDialog().getOpenFileName(self, "Import behaviors from project file", "", ("Project files (*.boris *.boris.gz);;" "All files (*)")) file_name = fn[0] if type(fn) is tuple else fn if file_name: <|code_end|> , predict the next line using imports from the current file: import sys import logging import boris.utilities as utilities from boris import dialog from boris import project_functions from boris.config import * from boris import param_panel from PyQt5.QtWidgets import (QFileDialog, QTableWidgetItem, QApplication, QMessageBox, QListWidgetItem) from PyQt5.QtCore import (Qt) from PyQt5.QtGui import (QColor, QFont) and context including class names, function names, and sometimes code from other files: # Path: boris/dialog.py # def MessageDialog(title, text, buttons): # def error_message_box(task, error_type, error_file_name, # error_lineno): # do NOT use this function directly, use error_message function # def error_message(task: str, exc_info: tuple) -> None: # def __init__(self, parent=None): # def __init__(self): # def browse(self): # def ok(self): # def __init__(self, label_caption, elements_list): # def __init__(self, text, codes_list): # def getCode(self): # def pbOK_clicked(self): # def __init__(self, text, observations_list): # def get_selected_observations(self): # def __init__(self, time_format): # def __init__(self): # def rb_changed(self): # def pbOK_clicked(self): # def pbCancel_clicked(self): # def __init__(self): # def click(self, msg): # def __init__(self): # def click(self, msg): # def __init__(self): # def __init__(self): # def save_results(self): # def __init__(self): # def save_results(self): # def __init__(self): # def __init__(self): # def tw_cellDoubleClicked(self, r, c): # def choose_obs_subj_behav_category(pj: dict, # selected_observations: list, # maxTime=0, # flagShowIncludeModifiers: bool = True, # flagShowExcludeBehaviorsWoEvents: bool = True, # by_category: bool = False, # show_time: bool = False, # timeFormat: str = HHMMSS): # class Info_widget(QWidget): # class Video_overlay_dialog(QDialog): # class Input_dialog(QDialog): # class DuplicateBehaviorCode(QDialog): # class ChooseObservationsToImport(QDialog): # class Ask_time(QDialog): # class EditSelectedEvents(QDialog): # class FindInEvents(QWidget): # class FindReplaceEvents(QWidget): # class explore_project_dialog(QDialog): # class Results_dialog(QDialog): # class ResultsWidget(QWidget): # class View_data_head(QDialog): # class View_explore_project_results(QWidget): # # Path: boris/project_functions.py # def check_observation_exhaustivity(events: list, ethogram: list, state_events_list: list = []): # def interval_len(interval): # def interval_number(interval): # def behavior_category(ethogram: dict) -> dict: # def check_coded_behaviors(pj: dict) -> set: # def check_if_media_available(observation: dict, project_file_name: str) -> bool: # def check_state_events_obs(obsId: str, ethogram: dict, observation: dict, time_format: str = HHMMSS) -> tuple: # def check_project_integrity(pj: dict, # time_format: str, # project_file_name: str, # media_file_available: bool = True) -> str: # def create_subtitles(pj: dict, selected_observations: list, parameters: dict, export_dir: str) -> tuple: # def subject_color(subject): # def export_observations_list(pj: dict, selected_observations: list, file_name: str, output_format: str) -> bool: # def remove_media_files_path(pj): # def media_full_path(media_file: str, project_file_name: str) -> str: # def observed_interval(observation: dict): # def observation_total_length(observation: dict): # def observation_length(pj, selected_observations: list) -> tuple: # def events_start_stop(ethogram, events): # def extract_observed_subjects(pj: dict, selected_observations: list) -> list: # def open_project_json(projectFileName: str) -> tuple: # def event_type(code: str, ethogram: dict) -> str: # def fix_unpaired_state_events(obsId, ethogram, observation, fix_at_time): # # Path: boris/param_panel.py # class Param_panel(QDialog, Ui_Dialog): # def __init__(self, parent=None): # def rb_time(self, button): # def subjects_button_clicked(self, command): # def behaviors_button_clicked(self, command): # def ok(self): # def behavior_item_clicked(self, item): # def extract_observed_behaviors(self, selected_observations, selected_subjects): # def cb_changed(self): . Output only the next line.
_, _, project, _ = project_functions.open_project_json(file_name)
Given snippet: <|code_start|> subject[SUBJECT_NAME] = field.strip() if idx == 2: subject["description"] = field.strip() self.twSubjects.setRowCount(self.twSubjects.rowCount() + 1) for idx, field_name in enumerate(subjectsFields): item = QTableWidgetItem(subject.get(field_name, "")) self.twSubjects.setItem(self.twSubjects.rowCount() - 1, idx, item) except Exception: dialog.error_message(sys._getframe().f_code.co_name, sys.exc_info()) def select_behaviors(title="Record value from external data file", text="Behaviors", behavioral_categories=[], ethogram={}, behavior_type=[STATE_EVENT, POINT_EVENT]): """ allow user to select behaviors to import Args: title (str): title of dialog box text (str): text of dialog box behavioral_categories (list): behavioral categories ethogram (dict): ethogram """ try: <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import logging import boris.utilities as utilities from boris import dialog from boris import project_functions from boris.config import * from boris import param_panel from PyQt5.QtWidgets import (QFileDialog, QTableWidgetItem, QApplication, QMessageBox, QListWidgetItem) from PyQt5.QtCore import (Qt) from PyQt5.QtGui import (QColor, QFont) and context: # Path: boris/dialog.py # def MessageDialog(title, text, buttons): # def error_message_box(task, error_type, error_file_name, # error_lineno): # do NOT use this function directly, use error_message function # def error_message(task: str, exc_info: tuple) -> None: # def __init__(self, parent=None): # def __init__(self): # def browse(self): # def ok(self): # def __init__(self, label_caption, elements_list): # def __init__(self, text, codes_list): # def getCode(self): # def pbOK_clicked(self): # def __init__(self, text, observations_list): # def get_selected_observations(self): # def __init__(self, time_format): # def __init__(self): # def rb_changed(self): # def pbOK_clicked(self): # def pbCancel_clicked(self): # def __init__(self): # def click(self, msg): # def __init__(self): # def click(self, msg): # def __init__(self): # def __init__(self): # def save_results(self): # def __init__(self): # def save_results(self): # def __init__(self): # def __init__(self): # def tw_cellDoubleClicked(self, r, c): # def choose_obs_subj_behav_category(pj: dict, # selected_observations: list, # maxTime=0, # flagShowIncludeModifiers: bool = True, # flagShowExcludeBehaviorsWoEvents: bool = True, # by_category: bool = False, # show_time: bool = False, # timeFormat: str = HHMMSS): # class Info_widget(QWidget): # class Video_overlay_dialog(QDialog): # class Input_dialog(QDialog): # class DuplicateBehaviorCode(QDialog): # class ChooseObservationsToImport(QDialog): # class Ask_time(QDialog): # class EditSelectedEvents(QDialog): # class FindInEvents(QWidget): # class FindReplaceEvents(QWidget): # class explore_project_dialog(QDialog): # class Results_dialog(QDialog): # class ResultsWidget(QWidget): # class View_data_head(QDialog): # class View_explore_project_results(QWidget): # # Path: boris/project_functions.py # def check_observation_exhaustivity(events: list, ethogram: list, state_events_list: list = []): # def interval_len(interval): # def interval_number(interval): # def behavior_category(ethogram: dict) -> dict: # def check_coded_behaviors(pj: dict) -> set: # def check_if_media_available(observation: dict, project_file_name: str) -> bool: # def check_state_events_obs(obsId: str, ethogram: dict, observation: dict, time_format: str = HHMMSS) -> tuple: # def check_project_integrity(pj: dict, # time_format: str, # project_file_name: str, # media_file_available: bool = True) -> str: # def create_subtitles(pj: dict, selected_observations: list, parameters: dict, export_dir: str) -> tuple: # def subject_color(subject): # def export_observations_list(pj: dict, selected_observations: list, file_name: str, output_format: str) -> bool: # def remove_media_files_path(pj): # def media_full_path(media_file: str, project_file_name: str) -> str: # def observed_interval(observation: dict): # def observation_total_length(observation: dict): # def observation_length(pj, selected_observations: list) -> tuple: # def events_start_stop(ethogram, events): # def extract_observed_subjects(pj: dict, selected_observations: list) -> list: # def open_project_json(projectFileName: str) -> tuple: # def event_type(code: str, ethogram: dict) -> str: # def fix_unpaired_state_events(obsId, ethogram, observation, fix_at_time): # # Path: boris/param_panel.py # class Param_panel(QDialog, Ui_Dialog): # def __init__(self, parent=None): # def rb_time(self, button): # def subjects_button_clicked(self, command): # def behaviors_button_clicked(self, command): # def ok(self): # def behavior_item_clicked(self, item): # def extract_observed_behaviors(self, selected_observations, selected_subjects): # def cb_changed(self): which might include code, classes, or functions. Output only the next line.
paramPanelWindow = param_panel.Param_panel()
Based on the snippet: <|code_start|> This function returns a (lazy) iterator over the values of given interval, starting from its lower bound and ending on its upper bound (if interval is not open). Each returned value merely corresponds to lower + i * step, where "step" defines the step between consecutive values. It also accepts a callable that is used to compute the next possible value based on the current one. When a non-atomic interval is provided, this function chains the iterators obtained by calling itself on the underlying atomic intervals. The values returned by the iterator can be aligned with a base value with the "base" parameter. This parameter must be a callable that accepts the lower bound of the (atomic) interval as input, and returns the first value that needs to be considered for the iteration. By default, the identity function is used. If reverse=True, then the upper bound will be passed instead of the lower one. :param interval: an interval. :param step: step between values, or a callable that returns the next value. :param base: a callable that accepts a bound and returns an initial value to consider. :param reverse: set to True for descending order. :return: a lazy iterator. """ if base is None: base = (lambda x: x) exclude = operator.lt if not reverse else operator.gt include = operator.le if not reverse else operator.ge step = step if callable(step) else partial(operator.add, step) value = base(interval.lower if not reverse else interval.upper) <|code_end|> , predict the immediate next line with the help of imports: import operator from functools import partial from .const import inf and context (classes, functions, sometimes code) from other files: # Path: boris/portion/const.py # class Bound(enum.Enum): # class _Singleton(): # class _PInf(_Singleton): # class _NInf(_Singleton): # CLOSED = True # OPEN = False # def __bool__(self): # def __invert__(self): # def __str__(self): # def __repr__(self): # def __new__(cls, *args, **kwargs): # def __neg__(self): return _NInf() # def __lt__(self, o): return False # def __le__(self, o): return isinstance(o, _PInf) # def __gt__(self, o): return not isinstance(o, _PInf) # def __ge__(self, o): return True # def __eq__(self, o): return isinstance(o, _PInf) # def __repr__(self): return '+inf' # def __hash__(self): return hash(float('+inf')) # def __neg__(self): return _PInf() # def __lt__(self, o): return not isinstance(o, _NInf) # def __le__(self, o): return True # def __gt__(self, o): return False # def __ge__(self, o): return isinstance(o, _NInf) # def __eq__(self, o): return isinstance(o, _NInf) # def __repr__(self): return '-inf' # def __hash__(self): return hash(float('-inf')) . Output only the next line.
if (value == -inf and not reverse) or (value == inf and reverse):
Next line prediction: <|code_start|> self.hlayout1 = QHBoxLayout() self.hlayout1.addWidget(QLabel("Zoom")) self.hlayout1.addWidget(self.button_plus) self.hlayout1.addWidget(self.button_minus) self.hlayout1.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) self.hlayout2 = QHBoxLayout() self.hlayout2.addWidget(QLabel("Value")) self.lb_value = QLabel("") self.hlayout2.addWidget(self.lb_value) self.hlayout2.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) self.layout.addLayout(self.hlayout1) self.layout.addLayout(self.hlayout2) self.layout.addWidget(self.myplot) self.setLayout(self.layout) self.plot_style = plot_style self.plot_title = plot_title try: self.time_offset = Decimal(time_offset) except Exception: self.error_msg = "The offset value {} is not a decimal value".format(time_offset) return self.y_label = y_label self.error_msg = "" <|code_end|> . Use current file imports: (from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from decimal import Decimal from boris.utilities import txt2np_array import sys import numpy as np import time import logging) and context including class names, function names, or small code snippets from other files: # Path: boris/utilities.py # def txt2np_array(file_name: str, columns_str: str, substract_first_value: str, converters=None, column_converter=None): # """ # read a txt file (tsv or csv) and return np array with passed columns # # Args: # file_name (str): path of the file to load in numpy array # columns_str (str): indexes of columns to be loaded. First columns must be the timestamp. Example: "4,5" # substract_first_value (str): "True" or "False" # converters (dict): dictionary containing converters # column_converter (dict): dictionary key: column index, value: converter name # # Returns: # bool: True if data successfullly loaded, False if case of error # str: error message. Empty if success # numpy array: data. Empty if not data failed to be loaded # # """ # if converters is None: # converters = {} # if column_converter is None: # column_converter = {} # # # check columns # try: # columns = [int(x) - 1 for x in columns_str.split(",")] # except Exception: # return False, f"Problem with columns {columns_str}", np.array([]) # # # check converters # np_converters = {} # for column_idx in column_converter: # if column_converter[column_idx] in converters: # # conv_name = column_converter[column_idx] # # function = f"""def {conv_name}(INPUT):\n""" # function += """ INPUT = INPUT.decode("utf-8") if isinstance(INPUT, bytes) else INPUT""" # for line in converters[conv_name]["code"].split("\n"): # function += f" {line}\n" # function += """ return OUTPUT""" # # try: # exec(function) # except Exception: # return False, f"error in converter: {sys.exc_info()[1]}", np.array([]) # # np_converters[column_idx - 1] = locals()[conv_name] # # else: # return False, f"converter {converters_param[column_idx]} not found", np.array([]) # # # snif txt file # try: # with open(file_name) as csvfile: # buff = csvfile.read(1024) # snif = csv.Sniffer() # dialect = snif.sniff(buff) # has_header = snif.has_header(buff) # except Exception: # return False, f"{sys.exc_info()[1]}", np.array([]) # # try: # data = np.loadtxt(file_name, # delimiter=dialect.delimiter, # usecols=columns, # skiprows=has_header, # converters=np_converters) # except Exception: # return False, f"{sys.exc_info()[1]}", np.array([]) # # # check if first value must be substracted # if substract_first_value == "True": # data[:, 0] -= data[:, 0][0] # # return True, "", data . Output only the next line.
result, error_msg, data = txt2np_array(
Predict the next line after this snippet: <|code_start|>""" module for testing otx_parser.py https://realpython.com/python-continuous-integration/ pytest -s -vv test_otx_parser.py """ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) @pytest.fixture() def before(): os.system("rm -rf output") os.system("mkdir output") class Test_otx_to_boris(object): def test_otx(self): <|code_end|> using the current file's imports: import os import pytest import sys import json from boris import otx_parser and any relevant context from other files: # Path: boris/otx_parser.py # def otx_to_boris(file_path: str) -> dict: . Output only the next line.
boris_project = otx_parser.otx_to_boris("files/otx_parser_test.otx")
Given the following code snippet before the placeholder: <|code_start|> def chooseColor(self): """ area color button clicked """ cd = QColorDialog() col = cd.getColor() if col.isValid(): self.btColor.setStyleSheet("QWidget {background-color:%s}" % col.name()) self.areaColor = col self.areaColor.setAlpha(int(self.slAlpha.value() / 100 * 255)) if self.selectedPolygon: self.selectedPolygon.setBrush(self.areaColor) for idx, area in enumerate(self.polygonsList2): ac, pg = area if pg == self.selectedPolygon: pg.setBrush(self.areaColor) self.polygonsList2[idx] = [ac, pg] break if self.closedPolygon: self.closedPolygon.setBrush(self.areaColor) def closeEvent(self, event): if self.flagMapChanged: <|code_end|> , predict the next line using imports from the current file: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from decimal import getcontext from boris.config import * from boris import dialog import decimal import json import binascii import os import io import sys and context including class names, function names, and sometimes code from other files: # Path: boris/dialog.py # def MessageDialog(title, text, buttons): # def error_message_box(task, error_type, error_file_name, # error_lineno): # do NOT use this function directly, use error_message function # def error_message(task: str, exc_info: tuple) -> None: # def __init__(self, parent=None): # def __init__(self): # def browse(self): # def ok(self): # def __init__(self, label_caption, elements_list): # def __init__(self, text, codes_list): # def getCode(self): # def pbOK_clicked(self): # def __init__(self, text, observations_list): # def get_selected_observations(self): # def __init__(self, time_format): # def __init__(self): # def rb_changed(self): # def pbOK_clicked(self): # def pbCancel_clicked(self): # def __init__(self): # def click(self, msg): # def __init__(self): # def click(self, msg): # def __init__(self): # def __init__(self): # def save_results(self): # def __init__(self): # def save_results(self): # def __init__(self): # def __init__(self): # def tw_cellDoubleClicked(self, r, c): # def choose_obs_subj_behav_category(pj: dict, # selected_observations: list, # maxTime=0, # flagShowIncludeModifiers: bool = True, # flagShowExcludeBehaviorsWoEvents: bool = True, # by_category: bool = False, # show_time: bool = False, # timeFormat: str = HHMMSS): # class Info_widget(QWidget): # class Video_overlay_dialog(QDialog): # class Input_dialog(QDialog): # class DuplicateBehaviorCode(QDialog): # class ChooseObservationsToImport(QDialog): # class Ask_time(QDialog): # class EditSelectedEvents(QDialog): # class FindInEvents(QWidget): # class FindReplaceEvents(QWidget): # class explore_project_dialog(QDialog): # class Results_dialog(QDialog): # class ResultsWidget(QWidget): # class View_data_head(QDialog): # class View_explore_project_results(QWidget): . Output only the next line.
response = dialog.MessageDialog("BORIS - Modifiers map creator",
Here is a snippet: <|code_start|> self.selectedPolygon.setBrush(self.areaColor) self.areasList[self.leAreaCode.text()]["color"] = self.areaColor.rgba() if self.closedPolygon: self.closedPolygon.setBrush(self.areaColor) def chooseColor(self): """ area color button clocked """ cd = QColorDialog() cd.setOptions(QColorDialog.ShowAlphaChannel) col = cd.getColor() if col.isValid(): self.btColor.setStyleSheet("QWidget {background-color:%s}" % col.name()) self.areaColor = col if self.selectedPolygon: self.selectedPolygon.setBrush(self.areaColor) self.areasList[self.leAreaCode.text()]["color"] = self.areaColor.rgba() if self.closedPolygon: self.closedPolygon.setBrush(self.areaColor) def closeEvent(self, event): if self.flagMapChanged: <|code_end|> . Write the next line using the current file imports: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from decimal import getcontext from boris.config import * from boris import dialog import decimal import json import binascii import os import io import sys and context from other files: # Path: boris/dialog.py # def MessageDialog(title, text, buttons): # def error_message_box(task, error_type, error_file_name, # error_lineno): # do NOT use this function directly, use error_message function # def error_message(task: str, exc_info: tuple) -> None: # def __init__(self, parent=None): # def __init__(self): # def browse(self): # def ok(self): # def __init__(self, label_caption, elements_list): # def __init__(self, text, codes_list): # def getCode(self): # def pbOK_clicked(self): # def __init__(self, text, observations_list): # def get_selected_observations(self): # def __init__(self, time_format): # def __init__(self): # def rb_changed(self): # def pbOK_clicked(self): # def pbCancel_clicked(self): # def __init__(self): # def click(self, msg): # def __init__(self): # def click(self, msg): # def __init__(self): # def __init__(self): # def save_results(self): # def __init__(self): # def save_results(self): # def __init__(self): # def __init__(self): # def tw_cellDoubleClicked(self, r, c): # def choose_obs_subj_behav_category(pj: dict, # selected_observations: list, # maxTime=0, # flagShowIncludeModifiers: bool = True, # flagShowExcludeBehaviorsWoEvents: bool = True, # by_category: bool = False, # show_time: bool = False, # timeFormat: str = HHMMSS): # class Info_widget(QWidget): # class Video_overlay_dialog(QDialog): # class Input_dialog(QDialog): # class DuplicateBehaviorCode(QDialog): # class ChooseObservationsToImport(QDialog): # class Ask_time(QDialog): # class EditSelectedEvents(QDialog): # class FindInEvents(QWidget): # class FindReplaceEvents(QWidget): # class explore_project_dialog(QDialog): # class Results_dialog(QDialog): # class ResultsWidget(QWidget): # class View_data_head(QDialog): # class View_explore_project_results(QWidget): , which may include functions, classes, or code. Output only the next line.
response = dialog.MessageDialog("BORIS - Modifiers map creator",
Next line prediction: <|code_start|> pass def initialize_heuristic(self, src_sentence): """This is called after ``initialize()`` if the predictor is registered as heuristic predictor (i.e. ``estimate_future_cost()`` will be called in the future). Predictors can implement this function for initialization of their own heuristic mechanisms. Args: src_sentence (list): List of word IDs which form the source sentence without <S> or </S> """ pass def finalize_posterior(self, scores, use_weights, normalize_scores): """This method can be used to enforce the parameters use_weights normalize_scores in predictors with dict posteriors. Args: scores (dict): unnormalized log valued scores use_weights (bool): Set to false to replace all values in ``scores`` with 0 (= log 1) normalize_scores: Set to true to make the exp of elements in ``scores`` sum up to 1""" if not scores: # empty scores -> pass through return scores if not use_weights: scores = dict.fromkeys(scores, 0.0) if normalize_scores: <|code_end|> . Use current file imports: (from abc import abstractmethod from cam.sgnmt import utils from cam.sgnmt.utils import Observer, NEG_INF, MESSAGE_TYPE_DEFAULT) and context including class names, function names, or small code snippets from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/utils.py # class Observer(object): # """Super class for classes which observe (GoF design patten) other # classes. # """ # # @abstractmethod # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # """Get a notification from an observed object. # # Args: # message (object): the message sent by observed object # message_type (int): The type of the message. One of the # ``MESSAGE_TYPE_*`` variables # """ # raise NotImplementedError # # NEG_INF = float("-inf") # # MESSAGE_TYPE_DEFAULT = 1 . Output only the next line.
log_sum = utils.log_sum(scores.values())
Predict the next line after this snippet: <|code_start|> They are used in A* if the --heuristics parameter is set to predictor. This function should return the future log *cost* (i.e. the lower the better) given the current predictor state, assuming that the last word in the partial hypothesis 'hypo' is consumed next. This function must not change the internal predictor state. Args: hypo (PartialHypothesis): Hypothesis for which to estimate the future cost given the current predictor state Returns float. Future cost """ return 0.0 def get_unk_probability(self, posterior): """This function defines the probability of all words which are not in ``posterior``. This is usually used to combine open and closed vocabulary predictors. The argument ``posterior`` should have been produced with ``predict_next()`` Args: posterior (list,array,dict): Return value of the last call of ``predict_next`` Returns: float: Score to use for words outside ``posterior`` """ <|code_end|> using the current file's imports: from abc import abstractmethod from cam.sgnmt import utils from cam.sgnmt.utils import Observer, NEG_INF, MESSAGE_TYPE_DEFAULT and any relevant context from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/utils.py # class Observer(object): # """Super class for classes which observe (GoF design patten) other # classes. # """ # # @abstractmethod # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # """Get a notification from an observed object. # # Args: # message (object): the message sent by observed object # message_type (int): The type of the message. One of the # ``MESSAGE_TYPE_*`` variables # """ # raise NotImplementedError # # NEG_INF = float("-inf") # # MESSAGE_TYPE_DEFAULT = 1 . Output only the next line.
return NEG_INF
Given the following code snippet before the placeholder: <|code_start|> Args: scores (dict): unnormalized log valued scores use_weights (bool): Set to false to replace all values in ``scores`` with 0 (= log 1) normalize_scores: Set to true to make the exp of elements in ``scores`` sum up to 1""" if not scores: # empty scores -> pass through return scores if not use_weights: scores = dict.fromkeys(scores, 0.0) if normalize_scores: log_sum = utils.log_sum(scores.values()) ret = {k: v - log_sum for k, v in scores.items()} return ret return scores def is_equal(self, state1, state2): """Returns true if two predictor states are equal, i.e. both states will always result in the same scores. This is used for hypothesis recombination Args: state1 (object): First predictor state state2 (object): Second predictor state Returns: bool. True if both states are equal, false if not """ return False <|code_end|> , predict the next line using imports from the current file: from abc import abstractmethod from cam.sgnmt import utils from cam.sgnmt.utils import Observer, NEG_INF, MESSAGE_TYPE_DEFAULT and context including class names, function names, and sometimes code from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/utils.py # class Observer(object): # """Super class for classes which observe (GoF design patten) other # classes. # """ # # @abstractmethod # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # """Get a notification from an observed object. # # Args: # message (object): the message sent by observed object # message_type (int): The type of the message. One of the # ``MESSAGE_TYPE_*`` variables # """ # raise NotImplementedError # # NEG_INF = float("-inf") # # MESSAGE_TYPE_DEFAULT = 1 . Output only the next line.
def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT):
Given the code snippet: <|code_start|> """This class implements a predictor-level Mixture of Experts (MoE) model. In this scenario, we have a neural model which predicts predictor weights from the predictor outputs. See the sgnmt_moe project on how to train this gating network with TensorFlow. """ def __init__(self, num_experts, args): """Creates the computation graph of the MoE network and loads the checkpoint file. Following fields are fetched from ``args`` moe_config: Comma-separated <key>=<value> pairs specifying the MoE network. See the command line arguments of sgnmt_moe for a full description. Available keys: vocab_size, embed_size, activation, hidden_layer_size, preprocessing. moe_checkpoint_dir (string): Checkpoint directory n_cpu_threads (int): Number of CPU threads for TensorFlow Args: num_experts (int): Number of predictors under the MoE model args (object): SGNMT configuration object """ super(MoEInterpolationStrategy, self).__init__() config = dict(el.split("=", 1) for el in args.moe_config.split(";")) self._create_hparams(num_experts, config) self.model = MOEModel(self.params) logging.info("MoE HParams: %s" % self.params) moe_graph = tf.Graph() with moe_graph.as_default() as g: self.model.initialize() <|code_end|> , generate the next line using the imports in this file: from cam.sgnmt import utils, tf_utils from abc import abstractmethod from tensorflow.python.training import saver from tensorflow.python.training import training from tensorflow.contrib.training.python.training import hparam from sgnmt_moe.model import MOEModel import numpy as np import logging import tensorflow as tf and context (functions, classes, or occasionally code) from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/tf_utils.py # def session_config(n_cpu_threads=-1): # def create_session(checkpoint_path, n_cpu_threads=-1): . Output only the next line.
self.sess = tf_utils.create_session(args.moe_checkpoint_dir,
Predict the next line for this snippet: <|code_start|> """Converts the target sentence represented as sequence of token IDs to a string representation. Args: trg_sentence (list): A sequence of integers (token IDs) Returns: string. """ raise NotImplementedError class IDEncoder(Encoder): """Encoder for ID mapping.""" def encode(self, src_sentence): return [int(w) for w in src_sentence.split()] class IDDecoder(Decoder): """"Decoder for ID mapping.""" def decode(self, trg_sentence): return " ".join(map(str, trg_sentence)) class WordEncoder(Encoder): """Encoder for word based mapping.""" def encode(self, src_sentence): <|code_end|> with the help of current file imports: import logging import codecs import re from cam.sgnmt import utils and context from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): , which may contain function names, class names, or code. Output only the next line.
return [src_wmap.get(w, utils.UNK_ID)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # coding=utf-8 # Copyright 2019 The SGNMT Authors. # # 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. """This module contains predictors for n-gram (Kneser-Ney) language modeling. This is a ``UnboundedVocabularyPredictor`` as the vocabulary size ngram models normally do not permit complete enumeration of the posterior. """ try: # Requires kenlm except ImportError: pass # Deal with it in decode.py <|code_end|> . Use current file imports: from cam.sgnmt.predictors.core import UnboundedVocabularyPredictor from cam.sgnmt import utils import math import kenlm and context (classes, functions, or code) from other files: # Path: cam/sgnmt/predictors/core.py # class UnboundedVocabularyPredictor(Predictor): # """Predictors under this class implement models with very large # target vocabularies, for which it is too inefficient to list the # entire posterior. Instead, they are evaluated only for a given list # of target words. This list is usually created by taking all non-zero # probability words from the bounded vocabulary predictors. An # example of a unbounded vocabulary predictor is the ngram predictor: # Instead of listing the entire ngram vocabulary, we run srilm only # on the words which are possible according other predictor (e.g. fst # or nmt). This is realized by introducing the ``trgt_words`` # argument to ``predict_next``. """ # # def __init__(self): # """ Initializes ``current_sen_id`` with 0. """ # super(UnboundedVocabularyPredictor, self).__init__() # # @abstractmethod # def predict_next(self, trgt_words): # """Like in ``Predictor``, returns the predictive distribution # over target words given the predictor state. Note # that the prediction itself can change the state of the # predictor. For example, the neural predictor updates the # decoder network state and its attention to predict the next # word. Two calls of ``predict_next()`` must be separated by a # ``consume()`` call. # # Args: # trgt_words (list): List of target word ids. # # Returns: # dictionary,array,list. Word log probabilities for the next # target token. All ids which are not set are assumed to have # probability ``get_unk_probability()``. The returned set should # not contain any ids which are not in ``trgt_words``, but it # does not have to score all of them # """ # raise NotImplementedError # # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): . Output only the next line.
class KenLMPredictor(UnboundedVocabularyPredictor):
Given the following code snippet before the placeholder: <|code_start|> Args: path (string): Path to the ARPA language model file Raises: NameError. If KenLM is not installed """ super(KenLMPredictor, self).__init__() self.lm = kenlm.Model(path) self.lm_state2 = kenlm.State() def initialize(self, src_sentence): """Initializes the KenLM state. Args: src_sentence (list): Not used """ self.history = [] self._update_lm_state() def _update_lm_state(self): self.lm_state = kenlm.State() tmp_state = kenlm.State() self.lm.BeginSentenceWrite(self.lm_state) for w in self.history[-6:]: self.lm.BaseScore(self.lm_state, w, tmp_state) self.lm_state, tmp_state = tmp_state, self.lm_state def predict_next(self, words): return {w: self.lm.BaseScore(self.lm_state, <|code_end|> , predict the next line using imports from the current file: from cam.sgnmt.predictors.core import UnboundedVocabularyPredictor from cam.sgnmt import utils import math import kenlm and context including class names, function names, and sometimes code from other files: # Path: cam/sgnmt/predictors/core.py # class UnboundedVocabularyPredictor(Predictor): # """Predictors under this class implement models with very large # target vocabularies, for which it is too inefficient to list the # entire posterior. Instead, they are evaluated only for a given list # of target words. This list is usually created by taking all non-zero # probability words from the bounded vocabulary predictors. An # example of a unbounded vocabulary predictor is the ngram predictor: # Instead of listing the entire ngram vocabulary, we run srilm only # on the words which are possible according other predictor (e.g. fst # or nmt). This is realized by introducing the ``trgt_words`` # argument to ``predict_next``. """ # # def __init__(self): # """ Initializes ``current_sen_id`` with 0. """ # super(UnboundedVocabularyPredictor, self).__init__() # # @abstractmethod # def predict_next(self, trgt_words): # """Like in ``Predictor``, returns the predictive distribution # over target words given the predictor state. Note # that the prediction itself can change the state of the # predictor. For example, the neural predictor updates the # decoder network state and its attention to predict the next # word. Two calls of ``predict_next()`` must be separated by a # ``consume()`` call. # # Args: # trgt_words (list): List of target word ids. # # Returns: # dictionary,array,list. Word log probabilities for the next # target token. All ids which are not set are assumed to have # probability ``get_unk_probability()``. The returned set should # not contain any ids which are not in ``trgt_words``, but it # does not have to score all of them # """ # raise NotImplementedError # # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): . Output only the next line.
"</s>" if w == utils.EOS_ID else str(w),
Predict the next line after this snippet: <|code_start|> """ def __init__(self, path, min_order, max_order): """Creates an ngram output handler. Args: path (string): Path to the ngram directory to create min_order (int): Minimum order of extracted ngrams max_order (int): Maximum order of extracted ngrams """ super(NgramOutputHandler, self).__init__() self.path = path self.min_order = min_order self.max_order = max_order self.file_pattern = path + "/%d.txt" def write_hypos(self, all_hypos, sen_indices): """Writes ngram files for each sentence in ``all_hypos``. Args: all_hypos (list): list of nbest lists of hypotheses sen_indices (list): List of sentence indices (0-indexed) Raises: OSError. If the directory could not be created IOError. If something goes wrong while writing to the disk """ _mkdir(self.path, "ngram") for sen_idx, hypos in zip(sen_indices, all_hypos): sen_idx += 1 <|code_end|> using the current file's imports: from abc import abstractmethod from cam.sgnmt import utils from cam.sgnmt import io from collections import defaultdict import os import errno import logging import numpy as np import codecs import pywrapfst as fst import openfst_python as fst and any relevant context from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/io.py # def encode(src_sentence): # def decode(trg_sentence): # def initialize(args): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def __init__(self, codes_path, separator='@@', remove_eow=False): # def process_line(self, line): # def segment(self, sentence): # def segment_tokens(self, tokens): # def get_pairs(self, word): # def encode(self, orig): # def __init__(self, codes_path, separator='', remove_eow=False): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def decode(self, trg_sentence): # def load_src_wmap(path): # def load_trg_wmap(path): # class Encoder(object): # class Decoder(object): # class IDEncoder(Encoder): # class IDDecoder(Decoder): # class WordEncoder(Encoder): # class WordDecoder(Decoder): # class CharEncoder(Encoder): # class CharDecoder(Decoder): # class BPE(object): # class BPEEncoder(Encoder): # class BPEDecoder(Decoder): # class BPEAtAtDecoder(Decoder): . Output only the next line.
total = utils.log_sum([hypo.total_score for hypo in hypos])
Based on the snippet: <|code_start|> pass @abstractmethod def write_hypos(self, all_hypos, sen_indices=None): """This method writes output files to the file system. The configuration parameters such as output paths should already have been provided via constructor arguments. Args: all_hypos (list): list of nbest lists of hypotheses sen_indices (list): List of sentence indices (0-indexed) Raises: IOError. If something goes wrong while writing to the disk """ raise NotImplementedError class TextOutputHandler(OutputHandler): """Writes the first best hypotheses to a plain text file """ def __init__(self, path): """Creates a plain text output handler to write to ``path`` """ super(TextOutputHandler, self).__init__() self.path = path def write_hypos(self, all_hypos, sen_indices=None): """Writes the hypotheses in ``all_hypos`` to ``path`` """ if self.f is not None: for hypos in all_hypos: <|code_end|> , predict the immediate next line with the help of imports: from abc import abstractmethod from cam.sgnmt import utils from cam.sgnmt import io from collections import defaultdict import os import errno import logging import numpy as np import codecs import pywrapfst as fst import openfst_python as fst and context (classes, functions, sometimes code) from other files: # Path: cam/sgnmt/utils.py # GO_ID = 1 # EOS_ID = 2 # UNK_ID = 0 # NOTAPPLICABLE_ID = 3 # NEG_INF = float("-inf") # INF = float("inf") # EPS_P = 0.00001 # GO_ID = 0 # EOS_ID = 2 # UNK_ID = 3 # GO_ID = 2 # Usually not used # EOS_ID = 1 # UNK_ID = 3 # Don't rely on this: UNK not standardized in T2T # TMP_FILENAME = '/tmp/sgnmt.%s.fst' % os.getpid() # MESSAGE_TYPE_DEFAULT = 1 # MESSAGE_TYPE_POSTERIOR = 2 # MESSAGE_TYPE_FULL_HYPO = 3 # def switch_to_fairseq_indexing(): # def switch_to_t2t_indexing(): # def log_sum_tropical_semiring(vals): # def log_sum_log_semiring(vals): # def oov_to_unk(seq, vocab_size, unk_idx=None): # def argmax_n(arr, n): # def argmax(arr): # def common_viewkeys(obj): # def common_iterable(obj): # def common_get(obj, key, default): # def common_contains(obj, key): # def w2f(fstweight): # def load_fst(path): # def get_path(tmpl, sub = 1): # def split_comma(s, func=None): # def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT): # def __init__(self): # def add_observer(self, observer): # def notify_observers(self, message, message_type = MESSAGE_TYPE_DEFAULT): # class Observer(object): # class Observable(object): # # Path: cam/sgnmt/io.py # def encode(src_sentence): # def decode(trg_sentence): # def initialize(args): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def __init__(self, codes_path, separator='@@', remove_eow=False): # def process_line(self, line): # def segment(self, sentence): # def segment_tokens(self, tokens): # def get_pairs(self, word): # def encode(self, orig): # def __init__(self, codes_path, separator='', remove_eow=False): # def encode(self, src_sentence): # def decode(self, trg_sentence): # def decode(self, trg_sentence): # def load_src_wmap(path): # def load_trg_wmap(path): # class Encoder(object): # class Decoder(object): # class IDEncoder(Encoder): # class IDDecoder(Decoder): # class WordEncoder(Encoder): # class WordDecoder(Decoder): # class CharEncoder(Encoder): # class CharDecoder(Decoder): # class BPE(object): # class BPEEncoder(Encoder): # class BPEDecoder(Decoder): # class BPEAtAtDecoder(Decoder): . Output only the next line.
self.f.write(io.decode(hypos[0].trgt_sentence))
Here is a snippet: <|code_start|># Copyright © 2014 Bart Massey # StringTable class as a hash table. class StringTable(object): def __init__(self): self.table = [] for _ in range(65536): self.table += [[]] # Return the value at position k. def lookup(self, k): <|code_end|> . Write the next line using the current file imports: from djb2 import djb2 from stringtabletest import stringtabletest and context from other files: # Path: djb2.py # def djb2(s): # h = 5381 # for c in s: # h = (33 * ord(c) + h) % 65536 # return h , which may include functions, classes, or code. Output only the next line.
for kv in self.table[djb2(k)]:
Given the following code snippet before the placeholder: <|code_start|> def navbar(request): ''' Adds the needed data for the navbar context ''' return { 'navbar': { <|code_end|> , predict the next line using imports from the current file: from django.conf import settings from showing.models import Gallery and context including class names, function names, and sometimes code from other files: # Path: showing/models.py # class Gallery(SortableMixin, models.Model): # id = models.UUIDField(primary_key=True, # default=uuid4, # editable=False, # unique=True) # # title = models.CharField(max_length=150) # slug = models.SlugField(unique=True) # order = models.PositiveIntegerField(default=0, # editable=False, # db_index=True) # # def get_absolute_url(self): # return reverse('gallery-detail', # args=[str(self.slug)]) # # def __unicode__(self): # return self.title # # class Meta: # ordering = ['order'] # verbose_name_plural = 'Galleries' . Output only the next line.
'galleries': Gallery.objects.all()
Given the following code snippet before the placeholder: <|code_start|> def setup_attributes(self, tags): date = 0 time = 0 for code, value in super(Sun, self).setup_attributes(tags): if code == 40: self.intensity = value elif code == 63: self.sun_color = value elif code == 70: self.shadow_type = value elif code == 71: self.shadow_map_size = value elif code == 90: self.version = value elif code == 91: date = value elif code == 92: time = value elif code == 280: self.shadow_softness = value elif code == 290: self.status = bool(value) elif code == 291: self.shadows = bool(value) elif code == 292: self.daylight_savings_time = bool(value) else: yield code, value # chain of generators if date > 0: <|code_end|> , predict the next line using imports from the current file: from datetime import datetime from .juliandate import calendar_date and context including class names, function names, and sometimes code from other files: # Path: dxfgrabber/juliandate.py # def calendar_date(juliandate): # return CalendarDate(juliandate).result . Output only the next line.
date = calendar_date(date)