Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> Returns: Numpy array with shape [..., 3]. """ shape_in = arr.shape if are_points: hom = np.ones_like(arr[..., 0:1], dtype=np.float32) else: hom = np.zeros_like(arr[..., 0:1], dtype=np.float32) assert arr.shape[-1] == 3 + feature_count to_tx = np.concatenate([arr[..., :3], hom], axis=-1) to_tx = np.reshape(to_tx, [-1, 4]) transformed = np.matmul(to_tx, m.T)[:, :3] if feature_count: flat_samples = np.reshape(arr[..., 3:], [-1, feature_count]) transformed = np.concatenate([transformed, flat_samples], axis=1) return np.reshape(transformed, shape_in).astype(np.float32) def batch_apply_4x4(arrs, ms, are_points=True): """Applies a batch of 4x4 matrices to a batch of 3D points/vectors. Args: arrs: Numpy array with shape [bs, ..., 3]. ms: Matrix with shape [bs, 4, 4]. are_points: Boolean. Whether to treat arr as points or vectors. Returns: Numpy array with shape [bs, ..., 3]. """ <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from ldif.util import np_util from ldif.util.file_util import log and context (classes, functions, sometimes code) from other files: # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info('Input shapes to batch_apply_4x4: %s and %s' %
Next line prediction: <|code_start|> if not hasattr(self, '_depth_render'): depth_render = ensure_shape_and_resize_if_needed( tf.expand_dims( self._model_config.inputs['dataset'].depth_render, axis=1), self._model_config.hparams.bs, 1, 1, self._model_config.hparams.gh, self._model_config.hparams.gw, self._model_config.hparams.h, self._model_config.hparams.w) depth_render = tf.cast(depth_render, dtype=tf.float32) depth_render = apply_noise_to_depth(depth_render, self._model_config.hparams.dmn) self._depth_render = depth_render / 1000.0 return self._depth_render def apply_transformation(self, tx): """Applies a transformation to a shape.""" shape = tx.get_shape().as_list() if (len(shape) != 3 or shape[0] != self._model_config.hparams.bs or shape[1] != 4 or shape[2] != 4): raise ValueError(f'Unexpected shape for example transformation: {shape}') # TODO(kgenova) We assert no access has happened because it is safest. # This way it is guaranteed the untransformed points are never accessed. assert not hasattr(self, '_tx') self._tx = tx # There are currently 10K surface points. For now, let's just transform # the whole point cloud to the local frame. all_surface_points = self.all_surface_points all_surface_normals = self.all_normals all_surface_points, all_surface_normals = ( <|code_end|> . Use current file imports: (import collections import tensorflow as tf from ldif.util import geom_util from ldif.util import image_util) and context including class names, function names, or small code snippets from other files: # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/image_util.py # def rgba_to_rgb(model_config, rgba): # def downsample(images, exp=1): # def get_border_pixels(gt, threshold=0.1): # def hessian(sdf_im): # def summarize_image(gt, pred, name): # def get_pil_formatted_image(image): # def images_are_near(baseline_image, # result_image, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04): # def expect_images_are_near_and_save_comparison(test, # baseline_image, # result_image, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # save_format='.png'): # def expect_image_file_and_image_are_near(test, # baseline_path, # result_image_bytes_or_numpy, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # resize_baseline_image=None): . Output only the next line.
geom_util.transform_points_with_normals(
Continue the code snippet: <|code_start|> self._renders = ensure_shape_and_resize_if_needed( self._model_config.inputs['dataset'].mesh_renders, self._model_config.hparams.bs, 24, 4, 137, 137, self._model_config.hparams.h, self._model_config.hparams.w) return self._finite_wrapper(self._renders) @property def lum_renders(self): """Single-channel renders of the mesh.""" if not hasattr(self._model_config.inputs['dataset'], 'lum_renders'): raise ValueError("Trying to access lum images that aren't in the proto.") if self._lum_renders is None: self._lum_renders = tf.cast( ensure_shape_and_resize_if_needed( self._model_config.inputs['dataset'].lum_renders, self._model_config.hparams.bs, 20, 1, self._model_config.hparams.gh, self._model_config.hparams.gw, self._model_config.hparams.h, self._model_config.hparams.w), dtype=tf.float32) return self._finite_wrapper(self._lum_renders) @property def chosen_renders(self): """Subsampled renders seen this batch.""" if self._chosen_renders is None: chosen = self._subsample(self.renders, sample_count=1) chosen_rgba = tf.reshape(chosen, [ self._model_config.hparams.bs, 1, self._model_config.hparams.h, self._model_config.hparams.w, 4 ]) <|code_end|> . Use current file imports: import collections import tensorflow as tf from ldif.util import geom_util from ldif.util import image_util and context (classes, functions, or code) from other files: # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/image_util.py # def rgba_to_rgb(model_config, rgba): # def downsample(images, exp=1): # def get_border_pixels(gt, threshold=0.1): # def hessian(sdf_im): # def summarize_image(gt, pred, name): # def get_pil_formatted_image(image): # def images_are_near(baseline_image, # result_image, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04): # def expect_images_are_near_and_save_comparison(test, # baseline_image, # result_image, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # save_format='.png'): # def expect_image_file_and_image_are_near(test, # baseline_path, # result_image_bytes_or_numpy, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # resize_baseline_image=None): . Output only the next line.
chosen_rgb = image_util.rgba_to_rgb(self._model_config, chosen_rgba)
Continue the code snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for model.py.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order class ModelTest(tf.test.TestCase): def setUp(self): super(ModelTest, self).setUp() self.test_data_directory = os.path.join(path_util.get_path_to_ldif_root(), 'test_data') def test_render_centered_square(self): line_parameters = tf.constant([0.0, 64.0, 64.0, 32.0, 32.0], dtype=tf.float32) image = line_util.line_to_image( line_parameters, height=128, width=128, falloff=None) target_image_name = 'Centered_Square_0.png' baseline_image_path = os.path.join(self.test_data_directory, target_image_name) with self.test_session() as sess: <|code_end|> . Use current file imports: import os import tensorflow as tf from ldif.util import image_util from ldif.util import line_util from ldif.util import path_util and context (classes, functions, or code) from other files: # Path: ldif/util/image_util.py # def rgba_to_rgb(model_config, rgba): # def downsample(images, exp=1): # def get_border_pixels(gt, threshold=0.1): # def hessian(sdf_im): # def summarize_image(gt, pred, name): # def get_pil_formatted_image(image): # def images_are_near(baseline_image, # result_image, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04): # def expect_images_are_near_and_save_comparison(test, # baseline_image, # result_image, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # save_format='.png'): # def expect_image_file_and_image_are_near(test, # baseline_path, # result_image_bytes_or_numpy, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # resize_baseline_image=None): # # Path: ldif/util/line_util.py # def line_to_image(line_parameters, height, width, falloff=2.0): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def union_of_line_drawings(lines): # def network_line_parameters_to_line(line_parameters, height, width): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): . Output only the next line.
image = image_util.get_pil_formatted_image(sess.run(image))
Given snippet: <|code_start|># 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 # # https://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. # Lint as: python3 """Tests for model.py.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order class ModelTest(tf.test.TestCase): def setUp(self): super(ModelTest, self).setUp() self.test_data_directory = os.path.join(path_util.get_path_to_ldif_root(), 'test_data') def test_render_centered_square(self): line_parameters = tf.constant([0.0, 64.0, 64.0, 32.0, 32.0], dtype=tf.float32) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import tensorflow as tf from ldif.util import image_util from ldif.util import line_util from ldif.util import path_util and context: # Path: ldif/util/image_util.py # def rgba_to_rgb(model_config, rgba): # def downsample(images, exp=1): # def get_border_pixels(gt, threshold=0.1): # def hessian(sdf_im): # def summarize_image(gt, pred, name): # def get_pil_formatted_image(image): # def images_are_near(baseline_image, # result_image, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04): # def expect_images_are_near_and_save_comparison(test, # baseline_image, # result_image, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # save_format='.png'): # def expect_image_file_and_image_are_near(test, # baseline_path, # result_image_bytes_or_numpy, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # resize_baseline_image=None): # # Path: ldif/util/line_util.py # def line_to_image(line_parameters, height, width, falloff=2.0): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def union_of_line_drawings(lines): # def network_line_parameters_to_line(line_parameters, height, width): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): which might include code, classes, or functions. Output only the next line.
image = line_util.line_to_image(
Using the snippet: <|code_start|># Copyright 2020 Google LLC # # 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 # # https://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. # Lint as: python3 """Tests for model.py.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order class ModelTest(tf.test.TestCase): def setUp(self): super(ModelTest, self).setUp() <|code_end|> , determine the next line of code. You have imports: import os import tensorflow as tf from ldif.util import image_util from ldif.util import line_util from ldif.util import path_util and context (class names, function names, or code) available: # Path: ldif/util/image_util.py # def rgba_to_rgb(model_config, rgba): # def downsample(images, exp=1): # def get_border_pixels(gt, threshold=0.1): # def hessian(sdf_im): # def summarize_image(gt, pred, name): # def get_pil_formatted_image(image): # def images_are_near(baseline_image, # result_image, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04): # def expect_images_are_near_and_save_comparison(test, # baseline_image, # result_image, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # save_format='.png'): # def expect_image_file_and_image_are_near(test, # baseline_path, # result_image_bytes_or_numpy, # comparison_name, # images_differ_message, # max_outlier_fraction=0.005, # pixel_error_threshold=0.04, # resize_baseline_image=None): # # Path: ldif/util/line_util.py # def line_to_image(line_parameters, height, width, falloff=2.0): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def union_of_line_drawings(lines): # def network_line_parameters_to_line(line_parameters, height, width): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): . Output only the next line.
self.test_data_directory = os.path.join(path_util.get_path_to_ldif_root(),
Given the following code snippet before the placeholder: <|code_start|> # TODO(ldif-user) Set up the result path: base = FLAGS.input_dir + '/ROOT%i-*00000-*' % xid matches = file_util.glob(base) assert len(matches) >= 1 ckpts = [] for match in matches: # TODO(ldif-user) Set the file extension extension = None ckpt = int(match.split(extension)[0].split('-')[-1]) ckpts.append(ckpt) if len(ckpts) > 1 and not FLAGS.use_newest: log.info('Found multiple checkpoint matches for %s and --nouse_newest: %s' % (base, repr(ckpts))) if len(ckpts) == 1: ckpt = ckpts[0] elif len(ckpts) > 1: ckpts.sort() ckpt = ckpts[-1] log.info('Found multiple checkpoint matches %s, using %s' % (repr(ckpts), repr(ckpt))) # TODO(ldif-user) Set up the result path: path = FLAGS.input_dir + '/ROOT%i-%i.*' path = path % (xid, ckpt) return path def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') <|code_end|> , predict the next line using imports from the current file: import functools import apache_beam as beam import pandas as pd import tqdm from absl import app from absl import flags from ldif.inference import metrics from ldif.inference import util as inference_util from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log and context including class names, function names, and sometimes code from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
xids = inference_util.parse_xid_str(FLAGS.xids)
Given the following code snippet before the placeholder: <|code_start|>flags.mark_flag_as_required('input_dir') flags.DEFINE_string('xids', None, 'The XIDs to evaluate on.') flags.mark_flag_as_required('xids') flags.DEFINE_boolean('use_newest', None, 'Whether to use the newest checkpoint per XID.') flags.mark_flag_as_required('use_newest') flags.DEFINE_boolean('write_results', None, 'Whether to write a directory of the results.') flags.mark_flag_as_required('write_results') flags.DEFINE_boolean('write_metrics', None, 'Whether to write full metrics in the results.') flags.mark_flag_as_required('write_metrics') flags.DEFINE_boolean('write_metric_summaries', None, 'Whether to write summaries of metrics in the results.') flags.mark_flag_as_required('write_metric_summaries') def _write_results(proto, xid=None): """Writes the prediction, ground truth, and representation to disk.""" key, s = proto p = results_pb2.Results.FromString(s) if xid is None: dir_out = FLAGS.input_dir + '/extracted/' + key + '/' else: dir_out = FLAGS.input_dir + '/extracted/XID%i/%s/' % (xid, key) <|code_end|> , predict the next line using imports from the current file: import functools import apache_beam as beam import pandas as pd import tqdm from absl import app from absl import flags from ldif.inference import metrics from ldif.inference import util as inference_util from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log and context including class names, function names, and sometimes code from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
file_util.makedirs(dir_out)
Given snippet: <|code_start|>flags.mark_flag_as_required('use_newest') flags.DEFINE_boolean('write_results', None, 'Whether to write a directory of the results.') flags.mark_flag_as_required('write_results') flags.DEFINE_boolean('write_metrics', None, 'Whether to write full metrics in the results.') flags.mark_flag_as_required('write_metrics') flags.DEFINE_boolean('write_metric_summaries', None, 'Whether to write summaries of metrics in the results.') flags.mark_flag_as_required('write_metric_summaries') def _write_results(proto, xid=None): """Writes the prediction, ground truth, and representation to disk.""" key, s = proto p = results_pb2.Results.FromString(s) if xid is None: dir_out = FLAGS.input_dir + '/extracted/' + key + '/' else: dir_out = FLAGS.input_dir + '/extracted/XID%i/%s/' % (xid, key) file_util.makedirs(dir_out) file_util.write_mesh(f'{dir_out}/gt_mesh.ply', p.gt_mesh) file_util.write_mesh(f'{dir_out}/pred_mesh.ply', p.mesh) file_util.writetxt(f'{dir_out}/sif.txt', p.representation) # TODO(ldif-user) Set up the unnormalized2normalized path. path_to_tx = '/ROOT_DIR/%s/occnet_to_gaps.txt' % key occnet_to_gaps = file_util.read_txt_to_np(path_to_tx).reshape([4, 4]) <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import apache_beam as beam import pandas as pd import tqdm from absl import app from absl import flags from ldif.inference import metrics from ldif.inference import util as inference_util from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log and context: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
pm = mesh_util.deserialize(p.mesh)
Continue the code snippet: <|code_start|> nc, fst, fs2t, chamfer = metrics.all_mesh_metrics(mesh, gt_mesh) return { 'key': key, 'Normal Consistency': nc, 'F-Score (tau)': fst, 'F-Score (2*tau)': fs2t, 'Chamfer': chamfer, 'IoU': p.iou } def save_metrics(elts): elts = pd.DataFrame(elts) csv_str = elts.to_csv() return csv_str def get_result_path(xid): """Generates the result path associated with the requested XID.""" # TODO(ldif-user) Set up the result path: base = FLAGS.input_dir + '/ROOT%i-*00000-*' % xid matches = file_util.glob(base) assert len(matches) >= 1 ckpts = [] for match in matches: # TODO(ldif-user) Set the file extension extension = None ckpt = int(match.split(extension)[0].split('-')[-1]) ckpts.append(ckpt) if len(ckpts) > 1 and not FLAGS.use_newest: <|code_end|> . Use current file imports: import functools import apache_beam as beam import pandas as pd import tqdm from absl import app from absl import flags from ldif.inference import metrics from ldif.inference import util as inference_util from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info('Found multiple checkpoint matches for %s and --nouse_newest: %s' %
Predict the next line after this snippet: <|code_start|> height, width, is_screen_space=False, is_homogeneous=False) # Values should go from -1 -> 1, not from 0 -> 1: nic_x = np_util.batch_np(2 * pixel_coords[:, :, 0:1] - 1.0, batch_size) nic_y = np_util.batch_np(2 * pixel_coords[:, :, 1:2] - 1.0, batch_size) nic_d = -depth_image aspect = height / float(width) tan_xfov = tf.math.tan(xfov) yfov = tf.math.atan(aspect * tan_xfov) intrinsics_00 = tf.reshape(1.0 / tan_xfov, [batch_size, 1, 1, 1]) intrinsics_11 = tf.reshape(1.0 / tf.math.tan(yfov), [batch_size, 1, 1, 1]) cam_x = nic_x * -nic_d / intrinsics_00 cam_y = nic_y * nic_d / intrinsics_11 cam_z = nic_d return tf.concat([cam_x, cam_y, cam_z], axis=3) def gaps_depth_image_to_xyz_image(depth_image, xfov, cam2world, mask=None): """Converts a GAPS depth image to world space. Args: depth_image: Tensor with shape [batch_size, height, width, 1]. xfov: Scalar or Tensor with shape [1] or [batch_size]. cam2world: Transformation matrix Tensor with shape [batch_size, 4, 4]. mask: If provided, a Tensor with shape [batch_size, height, width, 1] that is of type bool and is true where the image is considered valid. Returns: Tensor with shape [batch_size, height, width, 3]. """ cam_images = gaps_depth_image_to_cam_image(depth_image, xfov) <|code_end|> using the current file's imports: import importlib import tensorflow as tf from ldif.util import geom_util from ldif.util import np_util from ldif.util import tf_util and any relevant context from other files: # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
xyz_images = geom_util.apply_4x4(cam_images, cam2world, are_points=True,
Based on the snippet: <|code_start|> # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order importlib.reload(tf_util) def gaps_depth_image_to_cam_image(depth_image, xfov): """Converts a GAPS depth image tensor to a camera-space image tensor. Args: depth_image: Tensor with shape [batch_size, height, width, 1]. xfov: Scalar or tensor with shape [1] or [batch_size]. Returns: cam_image: Tensor with shape [batch_size, height, width, 3]. """ batch_size, height, width = depth_image.get_shape().as_list()[:3] depth_image = tf.ensure_shape(depth_image, [batch_size, height, width, 1]) if isinstance(xfov, float): xfov = tf.constant([xfov], dtype=tf.float32) xfov = tf.tile(xfov, [batch_size]) else: xfov = tf.reshape(xfov, [batch_size]) # if xfov.get_shape().as_list()[0] == 1: # xfov = tf.tile(xfov, [batch_size]) # else: # assert xfov.get_shape().as_list()[0] == batch_size <|code_end|> , predict the immediate next line with the help of imports: import importlib import tensorflow as tf from ldif.util import geom_util from ldif.util import np_util from ldif.util import tf_util and context (classes, functions, sometimes code) from other files: # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
pixel_coords = np_util.make_coordinate_grid(
Based on the snippet: <|code_start|> specs = dict(feed=('feed', r'\d+'), tag=r'[^/]+', since=r'[^/]+', asc=None) specs_deprecated = dict(user=('feed', r'\d+'), tag=r'[^/]+') urljoin = lambda pieces: '/'.join(it.imap(op.methodcaller('strip', '/'), pieces)) def specs_sets(tpl, specs, make_redirects=False): if isinstance(specs, dict): specs = specs.items() for spec_set in it.chain.from_iterable( it.permutations(specs, n) for n in xrange(len(specs), 0, -1) ): url = list() for spec, pat in spec_set: if not isinstance(pat, (StringTypes, NoneType)): pat_spec, pat = pat else: pat_spec = spec pat = '{0}/(?P<{1}>{2})'.format(spec, pat_spec, pat)\ if pat is not None else '(?P<{0}>{1})'.format(pat_spec, spec) if make_redirects: pat = (pat, '{0}/%({1})s'.format(spec, pat_spec)) url.append(pat) yield tpl.format(urljoin(url)) if not make_redirects else\ ( tpl.format(urljoin(it.imap(op.itemgetter(0), url))), urljoin(it.imap(op.itemgetter(1), url)) ) urlpatterns = list() # Long-ago deprecated syndication links, now just a redirects urlpatterns.extend([ <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns from feedjack import views from types import StringTypes, NoneType import itertools as it, operator as op, functools as ft and context (classes, functions, sometimes code) from other files: # Path: feedjack/views.py # def ctx_get(ctx, k): # def cache_etag(request, *argz, **kwz): # def cache_last_modified(request, *argz, **kwz): # def initview(request, response_cache=True): # def get(self, request, *args, **kwz): # def blogroll(request, btype): # def foaf(request): # def opml(request): # def buildfeed(request, feedclass, **criterias): # def _buildfeed(request, feedclass, view_data, **criterias): # def rssfeed(request, **criterias): # def atomfeed(request, **criterias): # def mainview(request, **criterias): # def _mainview(request, view_data, **criterias): # class RedirectForSite(RedirectView): . Output only the next line.
(r'^rss20.xml$', views.RedirectForSite.as_view(url='/feed/rss/')),
Given snippet: <|code_start|># -*- coding: utf-8 -*- class SiteAdmin(admin.ModelAdmin): list_display = 'url', 'name' filter_vertical = 'links', <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from feedjack import models and context: # Path: feedjack/models.py # def get_by_string(cls, fields, query): # def __unicode__(self): return u'%s (%s)' % (self.name, self.link) # def get_by_string(self, query): # def feeds(self): # def active_subscribers(self): # def active_feeds(self): # def __unicode__(self): return self.name # def signal_updated_dispatch(self, sender=signal_sender_empty): # def save(self, *argz, **kwz): # def handler(self): # def handler_description(self): # def __unicode__(self): return u'{0.name} ({0.handler_name})'.format(self) # def handler(self): # def shortname(self): return self.__unicode__(short=True) # def __unicode__(self, short=False): # def __unicode__(self): # def apply_overlay_to_posts(self, posts): # def get_overlay_for_post(self, post, stored_check=True, stored_only=False): # def overlay(self): return self.overlay_decode(self.overlay_dump) # def overlay(self, data): self.overlay_dump = json.dumps(data) if data else None # def overlay_decode(self, data): # def timestamps(self): # def get_by_string(self, query): # def __unicode__(self): # def is_active_on_site(self, site): # def signal_updated_dispatch(self, sender=signal_sender_empty): # def calculate_check_interval( self, # max_interval, ewma_factor, max_days=None, # max_updates=None, ewma=0, ewma_ts=None, # add_partial=None ): # def processor_for_tags(self, tags=None, default_fallback=True): # def _filters_update_handler_check(sender, instance, **kwz): # def _filters_update_handler( sender, instance, force=False, # created=None, # post_save-specific # model=None, pk_set=list(), reverse=None, action=None, # m2m-specific # **kwz ): # def update_handler(feeds): # def __unicode__(self): return self.name # def similar(self, threshold, **criterias): # def with_criterias(self, site, feed=None, tag=None, since=None): # def sorted(self, site_ordering_id, force=None): # def filtered(self, site=None, for_display=True, **criterias): # def _enclosures_set(self, data): # def _enclosures_get(self): # def _get_ordering_attribute(site_ordering_id): # def date_on_site(self, site): # def _filtering_result(self, by_or): # def _filtering_result_checked(self, by_or): # def filtering_result_update(self): # def apply_overlay(self, overlay): # def __unicode__(self): return self.title # def get_absolute_url(self): return self.link # def save(self, *argz, **kwz): # def _update_handler(sender, instance, delete=False, **kwz): # def __unicode__(self): return u'%s in %s' % (self.feed, self.site) # def get_cloud(self): # def save(self, *argz, **kwz): # def _update_handler_check(sender, instance, **kwz): # def _update_handler(sender, instance, created, **kwz): # def transaction_signaled_commit(using=None): # def transaction_signaled_rollback(using=None): # def transaction_wrapper(func, logger=None, print_exc=None): # XXX: not needed anymore!!! # def _transaction_wrapper(*argz, **kwz): # def transaction_bulk_start(signal, sender, **kwz): # def transaction_bulk_process(signal, sender, **kwz): # def transaction_bulk_cancel(signal, sender, **kwz): # def transaction_bulk_finish(signal, sender, **kwz): # class Link(models.Model): # class Meta: # class Admin: pass # class Sites(models.Manager): # class Site(models.Model): # class Meta: # class ProcessingThingBase(models.Model): # class Meta: # class ProcessingThing(models.Model): # class Meta: # class FilterBase(ProcessingThingBase): # class Filter(ProcessingThing): # class FilterResult(models.Model): # class PostProcessorBase(ProcessingThingBase): # class PostProcessor(ProcessingThing): # class PostProcessorTag(models.Model): # class PostProcessorResult(models.Model): # class Meta: # class FeedQuerySet(models.query.QuerySet): # class Feeds(models.Manager): # class Feed(models.Model): # class Meta: # class Tag(models.Model): # class Meta: # class PostQuerySet(models.query.QuerySet): # class Posts(models.Manager): # class Post(models.Model): # class Meta: # class Subscriber(models.Model): # class Meta: # SITE_ORDERING = namedtuple( 'SiteOrdering', # 'modified created created_day' )(*xrange(1, 4)) # FILTER_CR_REBUILD = namedtuple( # 'CrossrefRebuild', 'new all' )(*xrange(2)) # FILTER_CR_TIMELINE_MAP = 'created', 'modified' # used to get column name # FILTER_CR_TIMELINE = namedtuple( 'CrossrefTimeline', # ' '.join(FILTER_CR_TIMELINE_MAP) )(*xrange(2)) # FEED_FILTERING_LOGIC = namedtuple('FilterLogic', 'all any')(*xrange(2)) which might include code, classes, or functions. Output only the next line.
admin.site.register(models.Site, SiteAdmin)
Given the code snippet: <|code_start|> class Command(BaseCommand): def usage(self, exe): return '%s [bucket1 ...]\n\nLists registered tags for the given buckets if any' % exe def handle(self, *buckets, **kwargs): <|code_end|> , generate the next line using the imports in this file: from django.core.management.base import BaseCommand from native_tags.registry import register and context (functions, classes, or occasionally code) from other files: # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func . Output only the next line.
for bucket,items in register.items():
Given the following code snippet before the placeholder: <|code_start|>eq = comparison(eq, doc=operator.eq.__doc__) def ne(a, b): return operator.ne(a, b) ne = comparison(ne, doc=operator.ne.__doc__) def ge(a, b): return operator.ge(a, b) ge = comparison(ge, doc=operator.ge.__doc__) def gt(a, b): return operator.gt(a, b) gt = comparison(gt, doc=operator.gt.__doc__) def not_(a): return operator.not_(a) not_ = comparison(not_, name='not', doc=operator.not_.__doc__) def is_(a): return operator.is_(a) is_ = comparison(is_, name='is', doc=operator.is_.__doc__) def is_not(a): return operator.is_not(a) is_not = comparison(is_not, doc=operator.is_not.__doc__) # Mathematical and bitwise operators def abs(a): return operator.abs(a) <|code_end|> , predict the next line using imports from the current file: import operator from native_tags.decorators import comparison, function and context including class names, function names, and sometimes code from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
abs = function(comparison(abs), doc=operator.abs.__doc__)
Predict the next line for this snippet: <|code_start|> def func_factory(method): try: func = getattr(math, method) except AttributeError: return def inner(arg1, arg2=None): try: return func(arg1, arg2) except TypeError: return func(arg1) inner.__name__ = method doc = func.__doc__.splitlines() if len(doc) > 1 and not doc[1]: doc = doc[2:] inner.__doc__ = '\n'.join(doc) if method.startswith('is'): return comparison(inner) <|code_end|> with the help of current file imports: import math from native_tags.decorators import function, filter, comparison and context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): , which may contain function names, class names, or code. Output only the next line.
return filter(function(inner))
Predict the next line for this snippet: <|code_start|> def func_factory(method): try: func = getattr(math, method) except AttributeError: return def inner(arg1, arg2=None): try: return func(arg1, arg2) except TypeError: return func(arg1) inner.__name__ = method doc = func.__doc__.splitlines() if len(doc) > 1 and not doc[1]: doc = doc[2:] inner.__doc__ = '\n'.join(doc) if method.startswith('is'): return comparison(inner) <|code_end|> with the help of current file imports: import math from native_tags.decorators import function, filter, comparison and context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): , which may contain function names, class names, or code. Output only the next line.
return filter(function(inner))
Next line prediction: <|code_start|> def func_factory(method): try: func = getattr(math, method) except AttributeError: return def inner(arg1, arg2=None): try: return func(arg1, arg2) except TypeError: return func(arg1) inner.__name__ = method doc = func.__doc__.splitlines() if len(doc) > 1 and not doc[1]: doc = doc[2:] inner.__doc__ = '\n'.join(doc) if method.startswith('is'): <|code_end|> . Use current file imports: (import math from native_tags.decorators import function, filter, comparison) and context including class names, function names, or small code snippets from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
return comparison(inner)
Predict the next line after this snippet: <|code_start|> def dynamic(*a, **kw): return list(a) + sorted(kw.items()) dynamic = function(dynamic) def no_render(*a, **kw): return list(a) + sorted(kw.items()) no_render = function(no_render, resolve=False) def myfilter(value, arg): return value + arg myfilter = filter(myfilter, test={'args':(1,1),'result':2}) def adder(x, y): return x + y adder = function(adder, name='add', test={'args':(1,1),'result':2}) def cmp_kwargs(**kw): return len(kw) <|code_end|> using the current file's imports: from native_tags.decorators import function, comparison, filter from datetime import datetime and any relevant context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
cmp_kwargs = comparison(cmp_kwargs)
Predict the next line after this snippet: <|code_start|> def dynamic(*a, **kw): return list(a) + sorted(kw.items()) dynamic = function(dynamic) def no_render(*a, **kw): return list(a) + sorted(kw.items()) no_render = function(no_render, resolve=False) def myfilter(value, arg): return value + arg <|code_end|> using the current file's imports: from native_tags.decorators import function, comparison, filter from datetime import datetime and any relevant context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
myfilter = filter(myfilter, test={'args':(1,1),'result':2})
Next line prediction: <|code_start|>""" Comparison tags """ try: set except NameError: def less(x,y): 'True if x is less than y' return x < y <|code_end|> . Use current file imports: ( from sets import Set as set from django.conf import settings from native_tags.decorators import comparison) and context including class names, function names, or small code snippets from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
less = comparison(less, test={'args':(0,1)})
Given the following code snippet before the placeholder: <|code_start|> register = Library() for tag_name in native_register['comparison']: if not tag_name.startswith('if'): tag_name = 'if_%s' % tag_name register.tags[tag_name] = do_comparison for tag_name in native_register['function']: <|code_end|> , predict the next line using imports from the current file: from django.template import Library from native_tags.nodes import do_function, do_comparison, do_block from native_tags.registry import register as native_register and context including class names, function names, and sometimes code from other files: # Path: native_tags/nodes.py # def do_function(parser, token): # """ # Performs a defined function on the passed arguments. # Normally this returns the output of the function into the template. # If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [function] [var args...] [name=value kwargs...] [as varname] %} # # Examples:: # # {% search '^(\d{3})$' 800 as match %} # # {% map sha1 hello world %} # # """ # name, args, kwargs = get_signature(token, True, True) # return FunctionNode(parser, name, *args, **kwargs) # # def do_comparison(parser, token): # """ # Compares passed arguments. # Attached functions should return boolean ``True`` or ``False``. # If the attached function returns ``True``, the first node list is rendered. # If the attached function returns ``False``, the second optional node list is rendered (part after the ``{% else %}`` statement). # If the last argument in the tag is ``negate``, then the opposite node list is rendered (like an ``ifnot`` tag). # # Syntax:: # # {% if_[comparison] [var args...] [name=value kwargs...] [negate] %} # {# first node list in here #} # {% else %} # {# second optional node list in here #} # {% endif_[comparison] %} # # # Supported comparisons are ``match``, ``find``, ``startswith``, ``endswith``, # ``less``, ``less_or_equal``, ``greater`` and ``greater_or_equal`` and many more. # Checkout the :ref:`contrib-index` for more examples # # Examples:: # # {% if_less some_object.id 3 %} # {{ some_object }} has an id less than 3. # {% endif_less %} # # {% if_match request.path '^/$' %} # Welcome home # {% endif_match %} # # """ # name, args, kwargs = get_signature(token, comparison=True) # name = name.replace('if_if', 'if') # end_tag = 'end' + name # kwargs['nodelist_true'] = parser.parse(('else', end_tag)) # token = parser.next_token() # if token.contents == 'else': # kwargs['nodelist_false'] = parser.parse((end_tag,)) # parser.delete_first_token() # else: # kwargs['nodelist_false'] = template.NodeList() # if name.startswith('if_'): # name = name.split('if_')[1] # return ComparisonNode(parser, name, *args, **kwargs) # # def do_block(parser, token): # """ # Process several nodes inside a single block # Block functions take ``context``, ``nodelist`` as first arguments # If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [block] [var args...] [name=value kwargs...] [as varname] %} # ... nodelist ... # {% end[block] %} # # Examples:: # # {% render_block as rendered_output %} # {{ request.path }}/blog/{{ blog.slug }} # {% endrender_block %} # # {% highlight_block python %} # import this # {% endhighlight_block %} # # """ # name, args, kwargs = get_signature(token, contextable=True) # kwargs['nodelist'] = parser.parse(('end%s' % name,)) # parser.delete_first_token() # return BlockNode(parser, name, *args, **kwargs) # # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func . Output only the next line.
register.tags[tag_name] = do_function
Given snippet: <|code_start|> register = Library() for tag_name in native_register['comparison']: if not tag_name.startswith('if'): tag_name = 'if_%s' % tag_name <|code_end|> , continue by predicting the next line. Consider current file imports: from django.template import Library from native_tags.nodes import do_function, do_comparison, do_block from native_tags.registry import register as native_register and context: # Path: native_tags/nodes.py # def do_function(parser, token): # """ # Performs a defined function on the passed arguments. # Normally this returns the output of the function into the template. # If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [function] [var args...] [name=value kwargs...] [as varname] %} # # Examples:: # # {% search '^(\d{3})$' 800 as match %} # # {% map sha1 hello world %} # # """ # name, args, kwargs = get_signature(token, True, True) # return FunctionNode(parser, name, *args, **kwargs) # # def do_comparison(parser, token): # """ # Compares passed arguments. # Attached functions should return boolean ``True`` or ``False``. # If the attached function returns ``True``, the first node list is rendered. # If the attached function returns ``False``, the second optional node list is rendered (part after the ``{% else %}`` statement). # If the last argument in the tag is ``negate``, then the opposite node list is rendered (like an ``ifnot`` tag). # # Syntax:: # # {% if_[comparison] [var args...] [name=value kwargs...] [negate] %} # {# first node list in here #} # {% else %} # {# second optional node list in here #} # {% endif_[comparison] %} # # # Supported comparisons are ``match``, ``find``, ``startswith``, ``endswith``, # ``less``, ``less_or_equal``, ``greater`` and ``greater_or_equal`` and many more. # Checkout the :ref:`contrib-index` for more examples # # Examples:: # # {% if_less some_object.id 3 %} # {{ some_object }} has an id less than 3. # {% endif_less %} # # {% if_match request.path '^/$' %} # Welcome home # {% endif_match %} # # """ # name, args, kwargs = get_signature(token, comparison=True) # name = name.replace('if_if', 'if') # end_tag = 'end' + name # kwargs['nodelist_true'] = parser.parse(('else', end_tag)) # token = parser.next_token() # if token.contents == 'else': # kwargs['nodelist_false'] = parser.parse((end_tag,)) # parser.delete_first_token() # else: # kwargs['nodelist_false'] = template.NodeList() # if name.startswith('if_'): # name = name.split('if_')[1] # return ComparisonNode(parser, name, *args, **kwargs) # # def do_block(parser, token): # """ # Process several nodes inside a single block # Block functions take ``context``, ``nodelist`` as first arguments # If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [block] [var args...] [name=value kwargs...] [as varname] %} # ... nodelist ... # {% end[block] %} # # Examples:: # # {% render_block as rendered_output %} # {{ request.path }}/blog/{{ blog.slug }} # {% endrender_block %} # # {% highlight_block python %} # import this # {% endhighlight_block %} # # """ # name, args, kwargs = get_signature(token, contextable=True) # kwargs['nodelist'] = parser.parse(('end%s' % name,)) # parser.delete_first_token() # return BlockNode(parser, name, *args, **kwargs) # # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func which might include code, classes, or functions. Output only the next line.
register.tags[tag_name] = do_comparison
Predict the next line after this snippet: <|code_start|> register = Library() for tag_name in native_register['comparison']: if not tag_name.startswith('if'): tag_name = 'if_%s' % tag_name register.tags[tag_name] = do_comparison for tag_name in native_register['function']: register.tags[tag_name] = do_function for tag_name in native_register['block']: <|code_end|> using the current file's imports: from django.template import Library from native_tags.nodes import do_function, do_comparison, do_block from native_tags.registry import register as native_register and any relevant context from other files: # Path: native_tags/nodes.py # def do_function(parser, token): # """ # Performs a defined function on the passed arguments. # Normally this returns the output of the function into the template. # If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [function] [var args...] [name=value kwargs...] [as varname] %} # # Examples:: # # {% search '^(\d{3})$' 800 as match %} # # {% map sha1 hello world %} # # """ # name, args, kwargs = get_signature(token, True, True) # return FunctionNode(parser, name, *args, **kwargs) # # def do_comparison(parser, token): # """ # Compares passed arguments. # Attached functions should return boolean ``True`` or ``False``. # If the attached function returns ``True``, the first node list is rendered. # If the attached function returns ``False``, the second optional node list is rendered (part after the ``{% else %}`` statement). # If the last argument in the tag is ``negate``, then the opposite node list is rendered (like an ``ifnot`` tag). # # Syntax:: # # {% if_[comparison] [var args...] [name=value kwargs...] [negate] %} # {# first node list in here #} # {% else %} # {# second optional node list in here #} # {% endif_[comparison] %} # # # Supported comparisons are ``match``, ``find``, ``startswith``, ``endswith``, # ``less``, ``less_or_equal``, ``greater`` and ``greater_or_equal`` and many more. # Checkout the :ref:`contrib-index` for more examples # # Examples:: # # {% if_less some_object.id 3 %} # {{ some_object }} has an id less than 3. # {% endif_less %} # # {% if_match request.path '^/$' %} # Welcome home # {% endif_match %} # # """ # name, args, kwargs = get_signature(token, comparison=True) # name = name.replace('if_if', 'if') # end_tag = 'end' + name # kwargs['nodelist_true'] = parser.parse(('else', end_tag)) # token = parser.next_token() # if token.contents == 'else': # kwargs['nodelist_false'] = parser.parse((end_tag,)) # parser.delete_first_token() # else: # kwargs['nodelist_false'] = template.NodeList() # if name.startswith('if_'): # name = name.split('if_')[1] # return ComparisonNode(parser, name, *args, **kwargs) # # def do_block(parser, token): # """ # Process several nodes inside a single block # Block functions take ``context``, ``nodelist`` as first arguments # If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. # # Syntax:: # # {% [block] [var args...] [name=value kwargs...] [as varname] %} # ... nodelist ... # {% end[block] %} # # Examples:: # # {% render_block as rendered_output %} # {{ request.path }}/blog/{{ blog.slug }} # {% endrender_block %} # # {% highlight_block python %} # import this # {% endhighlight_block %} # # """ # name, args, kwargs = get_signature(token, contextable=True) # kwargs['nodelist'] = parser.parse(('end%s' % name,)) # parser.delete_first_token() # return BlockNode(parser, name, *args, **kwargs) # # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func . Output only the next line.
register.tags[tag_name] = do_block
Given snippet: <|code_start|> Syntax:: {% include_feed [feed_url] [num_items] [template_name] %} Example:: {% include_feed "http://www2.ljworld.com/rss/headlines/" 10 feed_includes/ljworld_headlines.html %} """ feed = feedparser.parse(feed_url) items = [] if len(args) == 2: # num_items, template_name num_items, template_name = args elif len(args) == 1: # template_name num_items, template_name = None, args[0] else: raise TemplateSyntaxError("'include_feed' tag takes either two or three arguments") num_items = int(num_items) or len(feed['entries']) for i in range(num_items): pub_date = feed['entries'][i].updated_parsed published = datetime.date(pub_date[0], pub_date[1], pub_date[2]) items.append({ 'title': feed['entries'][i].title, 'summary': feed['entries'][i].summary, 'link': feed['entries'][i].link, 'date': published }) return template_name, { 'items': items, 'feed': feed } <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import feedparser from django.template import TemplateSyntaxError from native_tags.decorators import function and context: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): which might include code, classes, or functions. Output only the next line.
include_feed = function(include_feed, inclusion=True)
Continue the code snippet: <|code_start|> def randrange(*args,**kwargs): if len(args)==1: args = (0,args[0]) return _random.randrange(*args,**kwargs) <|code_end|> . Use current file imports: import random as _random from native_tags.decorators import function and context (classes, functions, or code) from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
randrange = function(randrange)
Using the snippet: <|code_start|> def tester(f): def inner(unit): args, kwargs = f.test.get('args', ()), f.test.get('kwargs', {}) result = len(kwargs) and f(*args, **kwargs) or f(*args) unit.assertEquals(result, f.test.get('result', True)) return inner attrs = {} <|code_end|> , determine the next line of code. You have imports: from django.test import TestCase from native_tags.registry import register and context (class names, function names, or code) available: # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func . Output only the next line.
for bucket,items in register.items():
Predict the next line after this snippet: <|code_start|>try: except ImportError: highlighter = None def highlight_style(cssclass='highlight', **kwargs): """ Returns the CSS from the ``HtmlFormatter``. ``cssclass`` is the name of the ``div`` css class to use Syntax:: {% highlight_style [cssclass] [formatter options] %} Example:: {% highlight_style code linenos=true %} """ if highlighter is None: return '' return HtmlFormatter(**kwargs).get_style_defs('.%s' % cssclass) <|code_end|> using the current file's imports: from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name from pygments import highlight as highlighter from native_tags.decorators import function, block and any relevant context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
highlight_style = function(highlight_style)
Based on the snippet: <|code_start|> {% highlight 'print "Hello World"' python linenos=true %} """ if highlighter is None: return '<pre>%s</pre>' % code return highlighter(code or '', get_lexer_by_name(lexer), HtmlFormatter(**kwargs)) highlight = function(highlight, is_safe=True) def highlight_block(context, nodelist, lexer, **kwargs): """ Code is nodelist ``rendered`` in ``context`` Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight_block [lexer name] [formatter options] %} ... source code .. {% endhighlight_block %} Example:: {% highlight_block python linenos=true %} print '{{ request.path }}' {% endhighlight_block %} """ if highlighter is None: return '<pre>%s</pre>' % str(nodelist.render(context) or '') return highlighter(nodelist.render(context) or '', get_lexer_by_name(lexer), HtmlFormatter(**kwargs)) <|code_end|> , predict the immediate next line with the help of imports: from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name from pygments import highlight as highlighter from native_tags.decorators import function, block and context (classes, functions, sometimes code) from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
highlight_block = block(highlight_block, is_safe=True)
Next line prediction: <|code_start|> CMDS = ('title','axes.type','axes.label','type','encoding','fill','color','scale','legend') def parse_cmd(value): value = value.lstrip() for cmd in CMDS: if value.startswith(cmd): return cmd,value[len(cmd):].strip() return None, None def gchart(context, nodelist, type, dataset, **kwargs): G = GChart(type, dataset, encoding=kwargs.pop('encoding','text')) for node in nodelist: if isinstance(node, TextNode): for part in node.render(context).splitlines(): cmd,value = parse_cmd(part) if cmd is None: continue if cmd.startswith('axes'): cmd = getattr(G.axes, cmd[5:]) else: cmd = getattr(G, cmd) cmd(*value.split()) if 'instance' in kwargs: return G return G.img(**kwargs) <|code_end|> . Use current file imports: (from django.template import VariableNode, TextNode from GChartWrapper import GChart from native_tags.decorators import block) and context including class names, function names, or small code snippets from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
gchart = block(gchart)
Given snippet: <|code_start|>""" Template tags which can do retrieval of content from any model. """ def _get_model(model): m = get_model(*model.split('.')) if m is None: raise TemplateSyntaxError("Generic content tag got invalid model: %s" % model) return m def get_latest_object(model, field=None): """ Retrieves the latest object from a given model, in that model's default ordering, and stores it in a context variable. The optional field argument specifies which field to get_latest_by, otherwise the model's default is used Syntax:: {% get_latest_object [app_name].[model_name] [field] as [varname] %} Example:: {% get_latest_object comments.freecomment submitted_date as latest_comment %} """ return _get_model(model)._default_manager.latest(field) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.db.models import get_model from django.template import TemplateSyntaxError from native_tags.decorators import function and context: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): which might include code, classes, or functions. Output only the next line.
get_latest_object = function(get_latest_object)
Given snippet: <|code_start|> def calendar(format, *args, **kwargs): """ Creates a formatted ``HTMLCalendar``. Argument ``format`` can be one of ``month``, ``year``, or ``yearpage`` Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``, ``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage`` Syntax:: {% calendar month [year] [month] %} {% calendar year [year] %} {% calendar yearpage [year] %} Example:: {% calendr month 2009 10 %} """ cal = HTMLCalendar(kwargs.pop('firstweekday', 0)) return getattr(cal, 'format%s' % format)(*args, **kwargs) <|code_end|> , continue by predicting the next line. Consider current file imports: from calendar import HTMLCalendar from native_tags.decorators import function and context: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): which might include code, classes, or functions. Output only the next line.
calendar = function(calendar)
Continue the code snippet: <|code_start|>if django_version >= (1, 5, 0): else: def hexd(algo, value): lookup = { 'md5': md5_constructor, 'sha1': sha_constructor, 'sha': sha_constructor, } try: lookup.update({ 'sha224': hashlib.sha224, 'sha256': hashlib.sha256, 'sha384': hashlib.sha384, 'sha512': hashlib.sha512, }) except ImportError: pass try: return lookup[algo](value).hexdigest() except IndexError: return '' def hashtag(algo, lib=False): def inner(value): return hexd(algo, value) <|code_end|> . Use current file imports: from django import VERSION as django_version from hashlib import md5 as md5_constructor, sha1 as sha_constructor from django.utils.hashcompat import md5_constructor, sha_constructor from native_tags.decorators import function, filter import hashlib and context (classes, functions, or code) from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
return filter(function(inner),
Here is a snippet: <|code_start|>if django_version >= (1, 5, 0): else: def hexd(algo, value): lookup = { 'md5': md5_constructor, 'sha1': sha_constructor, 'sha': sha_constructor, } try: lookup.update({ 'sha224': hashlib.sha224, 'sha256': hashlib.sha256, 'sha384': hashlib.sha384, 'sha512': hashlib.sha512, }) except ImportError: pass try: return lookup[algo](value).hexdigest() except IndexError: return '' def hashtag(algo, lib=False): def inner(value): return hexd(algo, value) <|code_end|> . Write the next line using the current file imports: from django import VERSION as django_version from hashlib import md5 as md5_constructor, sha1 as sha_constructor from django.utils.hashcompat import md5_constructor, sha_constructor from native_tags.decorators import function, filter import hashlib and context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): , which may include functions, classes, or code. Output only the next line.
return filter(function(inner),
Based on the snippet: <|code_start|> def matches(pattern, text): 'String comparison. True if string ``text`` matches regex ``pattern``' return re.compile(str(pattern)).match(text) <|code_end|> , predict the immediate next line with the help of imports: import re from native_tags.decorators import comparison, function and context (classes, functions, sometimes code) from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
matches = comparison(matches)
Using the snippet: <|code_start|> def matches(pattern, text): 'String comparison. True if string ``text`` matches regex ``pattern``' return re.compile(str(pattern)).match(text) matches = comparison(matches) matches.test = {'args':('\d','_'),'result':None} def substitute(search, replace, text): 'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``' return re.sub(re.compile(str(search)), replace, text) <|code_end|> , determine the next line of code. You have imports: import re from native_tags.decorators import comparison, function and context (class names, function names, or code) available: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
substitute = function(substitute)
Predict the next line after this snippet: <|code_start|> Return a list of the results of applying the function to the items of the argument sequence(s). Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). Syntax:: {% map [function] [sequence] %} {% map [function] [item1 item2 ...] %} For example:: {% map sha1 hello world %} calculates:: [sha1(hello), sha1(world)] """ if len(sequence)==1: sequence = sequence[0] return map(get_func(func_name, False), sequence) <|code_end|> using the current file's imports: from native_tags.decorators import function from native_tags.registry import register import operator and any relevant context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
do_map = function(do_map, name='map')
Using the snippet: <|code_start|> Does looping while setting a context variable work """ t = "{% for i in items %}{% add 1 i as roomba %}{{roomba}}{% endfor %}" o = render(t, {'items':[1,2,3]}) self.assertEqual(o, "234") def test_b64encode(self): self.assertEqual(render('{% b64encode "hello world" %}'), 'aGVsbG8gd29ybGQ=') def test_b64decode(self): self.assertEqual(render('{% b64decode encoded %}', {'encoded':'aGVsbG8gd29ybGQ='}), 'hello world') def test_dynamic(self): self.assertEqual(eval(render('{% dynamic a b c d=1 e=2 %}')), ['a', 'b', 'c', ('d', 1), ('e', 2)]) def test_no_render(self): self.assertEqual(eval(render('{% no_render a b c d d=1 e=2 f=var %}', {'var':'hello'})), ['a', 'b', 'c', 'd', ('d', '1'), ('e', '2'), ('f', 'var')]) def test_filter_args(self): self.assertEqual(render('{{ var|myfilter:"baz" }}', {'var':'foobar'}), 'foobarbaz') def test_adder(self): self.assertEqual(render('{% load native humanize %}{% add 1000 100 as num %}{{ num|intcomma }}'), '1,100') def test_cmp_kwargs(self): self.assertEqual(render('{% if_cmp_kwargs foo=bar %}yup{% endif_cmp_kwargs %}'), 'yup') def test_zremove_tag(self): <|code_end|> , determine the next line of code. You have imports: import datetime import math import hashlib import pygments import GChartWrapper import feedparser import markdown from django.contrib.auth.models import User from django.template import Template, Context, TemplateSyntaxError from django.test import TestCase from django.core.serializers import deserialize from django.core.cache import cache from native_tags.registry import register, AlreadyRegistered from native_tags.nodes import get_cache_key from native_tags.nodes import split and context (class names, function names, or code) available: # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func # # class AlreadyRegistered(Exception): # "The function you are trying to register is already in the registry" # pass # # Path: native_tags/nodes.py # def get_cache_key(bucket, name, args, kwargs): # """ # Gets a unique SHA1 cache key for any call to a native tag. # Use args and kwargs in hash so that the same arguments use the same key # """ # u = ''.join(map(str, (bucket, name, args, kwargs))) # return 'native_tags.%s' % sha_constructor(u).hexdigest() . Output only the next line.
self.assert_('add' in register['function'])
Given snippet: <|code_start|> self.assert_('add' in register['function']) register.unregister('function', 'add') self.assert_(not 'add' in register['function']) def test_inclusion(self): self.assertEqual(render('{% myinc cheese %}'), 'im just here for the cheese') def test_map_builtins(self): self.assertEqual(render('{% map len l1 l2 l3 %}', {'l1':[1], 'l2':[1,2], 'l3':[1,2,3]}), '[1, 2, 3]') def test_smartypants(self): # this should b bombing, but i get DEBUG as False when testing despite the settings (just in testing?) self.assertEqual(render('{{ value|smartypants }}', {'value': 'wtf'}), 'wtf') def test_custom_if(self): self.assertEqual(render('{% ifsomething %}yup{% endifsomething %}'), 'yup') def test_filter_faker(self): self.assertRaises(TemplateSyntaxError, render, '{% sha1 "my | filter | faker" %}') def test_math(self): self.assertAlmostEqual(float(render('{% acos .3 %}')), 1.26610367278) self.assertEqual(float(render('{{ 1.5|floor }}')), 1.) self.assertEqual(float(render('{{ 4|sqrt }}')), 2.) self.assertAlmostEqual(float(render('{{ 180|radians }}')), math.pi) def test_native_debug(self): self.assertEqual(render('{% native_debug as debug %}{{ debug.keys|safe }}'), "['function', 'comparison', 'filter', 'block']") def test_cache(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import math import hashlib import pygments import GChartWrapper import feedparser import markdown from django.contrib.auth.models import User from django.template import Template, Context, TemplateSyntaxError from django.test import TestCase from django.core.serializers import deserialize from django.core.cache import cache from native_tags.registry import register, AlreadyRegistered from native_tags.nodes import get_cache_key from native_tags.nodes import split and context: # Path: native_tags/registry.py # def register(self, bucket, name_or_func, func=None): # """ # Add a function to the registry by name # """ # assert bucket in self, 'Bucket %s is unknown' % bucket # if func is None and hasattr(name_or_func, '__name__'): # name = name_or_func.__name__ # func = name_or_func # elif func: # name = name_or_func # if name in self[bucket]: # raise AlreadyRegistered('The function %s is already registered' % name) # # self[bucket][name] = func # # class AlreadyRegistered(Exception): # "The function you are trying to register is already in the registry" # pass # # Path: native_tags/nodes.py # def get_cache_key(bucket, name, args, kwargs): # """ # Gets a unique SHA1 cache key for any call to a native tag. # Use args and kwargs in hash so that the same arguments use the same key # """ # u = ''.join(map(str, (bucket, name, args, kwargs))) # return 'native_tags.%s' % sha_constructor(u).hexdigest() which might include code, classes, or functions. Output only the next line.
k = get_cache_key('function', 'date', (), {})
Given the following code snippet before the placeholder: <|code_start|>""" Filters for converting plain text to HTML and enhancing the typographic appeal of text on the Web. """ def apply_markup(value, arg=None): """ Applies text-to-HTML conversion. Takes an optional argument to specify the name of a filter to use. """ if arg is not None: return formatter(value, filter_name=arg) return formatter(value) <|code_end|> , predict the next line using imports from the current file: from django.conf import settings from django.template import TemplateSyntaxError from native_tags.decorators import filter from _markup import formatter from smartypants import smartyPants and context including class names, function names, and sometimes code from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
apply_markup = filter(apply_markup, is_safe=True)
Given the following code snippet before the placeholder: <|code_start|> def document(o): 'Returns the docstring for a given object' try: return o.__doc__ or '' except AttributeError: return '' <|code_end|> , predict the next line using imports from the current file: from native_tags.decorators import function, block, filter from django.template import Template, Context from native_tags.registry import register and context including class names, function names, and sometimes code from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
document = filter(function(document))
Next line prediction: <|code_start|> def document(o): 'Returns the docstring for a given object' try: return o.__doc__ or '' except AttributeError: return '' document = filter(function(document)) def do_set(context, **kwargs): 'Updates the context with the keyword arguments' context.update(kwargs) return '' do_set = function(do_set, takes_context=1, name='set') def do_del(context, *args): 'Deletes template variables from the context' for name in args: del context[name] return '' do_del = function(do_del, resolve=0, takes_context=1, name='del') def render_block(context, nodelist): 'Simply renders the nodelist with the current context' return nodelist.render(context) <|code_end|> . Use current file imports: (from native_tags.decorators import function, block, filter from django.template import Template, Context from native_tags.registry import register) and context including class names, function names, or small code snippets from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
render_block = block(render_block)
Predict the next line after this snippet: <|code_start|> def document(o): 'Returns the docstring for a given object' try: return o.__doc__ or '' except AttributeError: return '' <|code_end|> using the current file's imports: from native_tags.decorators import function, block, filter from django.template import Template, Context from native_tags.registry import register and any relevant context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
document = filter(function(document))
Predict the next line for this snippet: <|code_start|> def codectag(encoding, codec=True): codec = 'b%d%s' % (encoding, codec and 'encode' or 'decode') def inner(s, *args, **kwargs): return getattr(base64, codec)(s, *args, **kwargs) inner.__name__ = codec inner.__doc__ = getattr(base64, codec).__doc__ + """ Syntax:: {%% %s [string] [options] %%} """ % codec <|code_end|> with the help of current file imports: import base64 from native_tags.decorators import function, filter from hashlib import sha1 and context from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): , which may contain function names, class names, or code. Output only the next line.
return filter(function(inner))
Given the code snippet: <|code_start|> def codectag(encoding, codec=True): codec = 'b%d%s' % (encoding, codec and 'encode' or 'decode') def inner(s, *args, **kwargs): return getattr(base64, codec)(s, *args, **kwargs) inner.__name__ = codec inner.__doc__ = getattr(base64, codec).__doc__ + """ Syntax:: {%% %s [string] [options] %%} """ % codec <|code_end|> , generate the next line using the imports in this file: import base64 from native_tags.decorators import function, filter from hashlib import sha1 and context (functions, classes, or occasionally code) from other files: # Path: native_tags/decorators.py # def tag(bucket, doc): # def wrapped(inner, **options): . Output only the next line.
return filter(function(inner))
Given the code snippet: <|code_start|> def WatchForEnter(self,event): event.Skip() if event.GetKeyCode()==13: # enter self.UpdateWildcard() def UpdateWildcard(self,event=None): wildcard=self.textbox.Value if '*' not in wildcard: wildcard+='*' files=glob.glob(wildcard) self.listbox.Fill(files) def Click(self,event): file=event.GetString() if file: self.SetCursor('arrowwait') self.UpdateWindowUI() self.Refresh() <|code_end|> , generate the next line using the imports in this file: from .dialogs.waxy import * from .run_sim import Plot import os,sys import glob and context (functions, classes, or occasionally code) from other files: # Path: plasticity/run_sim.py # def Plot(sim): # gray=pylab.cm.gray # pylab.ion() # # try: # if not sim['params']['display']: # return # except TypeError: # sent a string # sim=zpickle.load(sim) # # # try: # if sim['params']['display_module']: # pass # except: # sim['params']['display_module']=False # # if sim['params']['display_module']: # try: # module=__import__(sim['params']['display_module'],fromlist=['UserPlot']) # except ImportError: # sim['params']['display']=False # print("Error","Error in Import: %s. Turning display off. %s" % ( # sim['params']['display_module'], # sys.exc_info())) # return # # try: # module.UserPlot(None,sim) # pylab.draw() # return # except ValueError: # sim['params']['display']=False # print("Error in display. Turning display off") # return # # try: # # im=weights2image(sim['params'],sim['weights']) # ax=pylab.subplot(221) # pylab.pcolor(im,cmap=gray) # ax.set_axis_bgcolor('k') # pylab.axis('equal') # # num_moments=sim['moments_mat'].shape[0] # # # ax=pylab.subplot(222) # ax.hold(False) # if num_moments==1: # num_neurons=sim['moments_mat'].shape[1] # for k in range(num_neurons): # pylab.plot(sim['t_mat'],sim['moments_mat'][0,k,:],'-o') # ax.hold(True) # elif num_moments==2: # num_neurons=sim['moments_mat'].shape[1] # for k in range(num_neurons): # pylab.plot(sim['t_mat'],sim['moments_mat'][0,k,:],'b-o') # ax2=pylab.twinx(ax) # pylab.plot(sim['t_mat'],sim['moments_mat'][1,k,:],'g-o') # ax2.yaxis.tick_right() # # else: # num_neurons=sim['moments_mat'].shape[1] # for k in range(num_neurons): # for i in range(num_moments): # pylab.plot(sim['t_mat'],sim['moments_mat'][i,k,:],'-o') # ax.hold(True) # # # # pylab.subplot(223) # pylab.hold(False) # response_mat=sim['response_mat'] # response_var_list=sim['response_var_list'] # # # styles=['b-','g-','r-','k-'] # ls=len(styles) # for i,r in enumerate(response_var_list[-1]): # x=r[1] # y=r[2] # # pylab.plot(x,y,styles[i % ls]+"o") # pylab.hold(True) # # pylab.subplot(224) # pylab.hold(False) # for i,r in enumerate(response_mat): # pylab.plot(r,styles[i % ls]) # pylab.hold(True) # # # pylab.draw() # # # except ValueError: # sim['params']['display']=False # print("Error in display. Turning display off") # return . Output only the next line.
Plot(file)
Predict the next line after this snippet: <|code_start|> """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=False, force_send=False) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Make the fake data to use if not os.path.exists(self.meta_path): os.makedirs(self.meta_path) test_meta_content = { 'index_date': datetime.utcnow().isoformat()+'Z', 'bibcode': 'test4', 'provider': 'mnras', 'ft_source': 'wrong_source' } with open(self.test_expected, 'w') as test_meta_file: json.dump(test_meta_content, test_meta_file) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> using the current file's imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and any relevant context from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Given snippet: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'DIFFERING_FULL_TEXT' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] which might include code, classes, or functions. Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Continue the code snippet: <|code_start|> """ Function that reads previously extracted data. It expects a json-type payload that has been converted into a Python dictionary. :param payload_dictionary: the complete extracted content and meta-data of the document payload :return: modified dictionary with recovered content or None if files do not exist """ meta_output_file_path = payload_dictionary['meta_path'] bibcode_pair_tree_path = os.path.dirname(meta_output_file_path) if payload_dictionary['file_format'] == "pdf-grobid": full_text_output_file_path = os.path.join(bibcode_pair_tree_path, 'grobid_fulltext.xml') else: full_text_output_file_path = os.path.join(bibcode_pair_tree_path, 'fulltext.txt.gz') content = {} if os.path.exists(meta_output_file_path): meta_dict = read_file(meta_output_file_path, json_format=True) for key, value in meta_dict.items(): content[key] = value if os.path.exists(full_text_output_file_path): fulltext = read_file(full_text_output_file_path, json_format=False) content['fulltext'] = fulltext else: content['fulltext'] = "" # Read the custom extractions of content logger.debug('Copying extra meta content') <|code_end|> . Use current file imports: import os import json import gzip from adsft.rules import META_CONTENT from adsputils import setup_logging, load_config and context (classes, functions, or code) from other files: # Path: adsft/rules.py # META_CONTENT = { # 'xml': { # 'fulltext': { # 'xpath': ['//body', # '//section[@type="body"]', # '//journalarticle-body', # '//bdy', # '//app-group', # '//section[not(@type="acknowledgments" or @type="dataAccess" or @type="dataAvailability" or @type="superSection")]' # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//ack', # '//section[@type="acknowledgments"]', # '//subsection[@type="acknowledgement" ' # 'or @type="acknowledgment"]' # ], # 'type': 'string', # 'info': '', # }, # 'dataset': { # 'xpath': ['//named-content[@content-type="dataset"]'], # 'type': 'list', # 'info': 'xlink:href', # }, # 'facility': { # 'xpath': ['//named-content[@content-type="facility"]'], # 'type': 'list', # 'info': 'xlink:href', # } # }, # 'teixml': { # 'fulltext': { # 'xpath': ['//body', # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//div[@type="acknowledgement"]', # ], # 'type': 'string', # 'info': '', # }, # }, # 'xmlelsevier': { # 'fulltext': { # 'xpath': ['//body', # '//raw-text', # '//appendices', # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//acknowledgment', # '//ack', # '//section[@type="acknowledgments"]', # '//subsection[@type="acknowledgement" ' # 'or @type="acknowledgment"]', # '//*[local-name()="acknowledgment"]' # ], # 'type': 'string', # 'info': '', # }, # 'dataset': { # 'xpath': ['//named-content[@content-type="dataset"]'], # 'type': 'list', # 'info': 'xlink:href', # } # }, # 'html': { # 'introduction': [ # '//h2[contains(.,"ntroduction")]', # '//h3[contains(.,"ntroduction")]', # '//p[contains(.,"Abstract")]', # ], # 'references': [ # '//h2[contains(.,"References")]' # ], # 'table': [ # '//table' # ], # 'table_links': [ # '//a[contains(@href, "TABLE_NAME")]' # ], # 'head': [ # '//head' # ] # }, # 'txt': {'fulltext': ['']}, # 'ocr': {'fulltext': ['']}, # 'http': {'fulltext': ['']}, # 'pdf': {'fulltext': ['']}, # 'pdf-grobid': {'grobid_fulltext': ['']}, # } . Output only the next line.
for meta_key_word in META_CONTENT[payload_dictionary['file_format']]:
Given snippet: <|code_start|> class TestFileStreamInput(test_base.TestUnit): """ Class that tests the FileStreamInput class and its methods. """ def test_file_stream_input_extract_file(self): """ Tests the extract method. It checks that the number of rows extracted by the class is actually the number of rows inside the file by explicitly opening the file and reading the number of lines. :return: no return """ <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import unittest import os import re import math from builtins import chr from adsft import utils from adsft.tests import test_base and context: # Path: adsft/utils.py # class FileInputStream(object): # class TextCleaner(object): # def __init__(self, input_stream): # def print_info(self): # def extract(self, force_extract=False, force_send=False): # def __init__(self, text): # def translate(self): # def decode(self): # def normalise(self): # def trimwords(self, maxlength=100): # def run(self, translate=True, decode=True, normalise=True, trim=True): # def get_filenames(file_string): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] which might include code, classes, or functions. Output only the next line.
FileInputStream = utils.FileInputStream(self.test_file)
Here is a snippet: <|code_start|> :return: no return """ try: os.remove(self.meta_file) except OSError: pass try: os.remove(self.full_text_file) except OSError: pass try: os.remove(self.acknowledgement_file) except OSError: pass try: os.rmdir(self.bibcode_pair_tree) except OSError: pass def test_loads_the_content_correctly_and_makes_folders(self): """ Tests the write_content method. Checks that the folder to contain the full text and meta data is created. :return: no return """ <|code_end|> . Write the next line using the current file imports: import unittest import os import json from adsft import writer, reader from adsft.tests import test_base and context from other files: # Path: adsft/writer.py # def write_to_temp_file(payload, temp_path='/tmp/', json_format=True): # def move_temp_file_to_file(temp_file_name, new_file_name): # def write_file(file_name, payload, json_format=True): # def write_content(payload_dictionary): # def extract_content(input_list, **kwargs): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] , which may include functions, classes, or code. Output only the next line.
content = writer.write_content(self.dict_item)
Next line prediction: <|code_start|> :return: no return """ content = writer.write_content(self.dict_item) self.assertTrue(os.path.exists(self.full_text_file), msg=os.path.exists(self.full_text_file)) def test_pipeline_extract_content_extracts_fulltext_correctly(self): """ Tests the extract_content method. Checks that the full text written to disk matches the ful text that we expect to be written to disk. N. B. Do not let the name extract_content portray anything. It is simply to keep the same naming convention as the other workers. extract_content is the main method the worker will run. :return: no return """ self.dict_item['file_format'] = 'txt' pipeline_payload = [self.dict_item] return_payload = writer.extract_content(pipeline_payload) self.assertTrue(return_payload, 1) full_text = '' <|code_end|> . Use current file imports: (import unittest import os import json from adsft import writer, reader from adsft.tests import test_base ) and context including class names, function names, or small code snippets from other files: # Path: adsft/writer.py # def write_to_temp_file(payload, temp_path='/tmp/', json_format=True): # def move_temp_file_to_file(temp_file_name, new_file_name): # def write_file(file_name, payload, json_format=True): # def write_content(payload_dictionary): # def extract_content(input_list, **kwargs): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(self.dict_item['meta_path'].replace('meta.json', 'fulltext.txt.gz'), json_format=False)
Based on the snippet: <|code_start|> }, {'fulltext_exists.links': {'bibcode': ['test'], 'file': ['tests/test_unit/stub_data/te/st/test.pdf'], 'provider': ['TEST']} }, {'fulltext_wrong.links': {'bibcode': ['test'], 'file': ['tests/test_unit/stub_data/te/st/test.ocr'], 'provider': ['']} } ] stub_data = { 'integration': {'path': integration_path, 'files': integration_files} } path = stub_data[test_name]['path'] files = stub_data[test_name]['files'] for file_dictionary in files: file_name = list(file_dictionary.keys())[0] file_ = file_dictionary[file_name] test_bibcode_ = file_['bibcode'] test_file_ = file_['file'] test_provider_ = file_['provider'] <|code_end|> , predict the immediate next line with the help of imports: import sys import os import unittest import time import json from builtins import range from mock import MagicMock from adsft import tasks, app from adsft import checker and context (classes, functions, sometimes code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/app.py # class ADSFulltextCelery(ADSCelery): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] . Output only the next line.
links_file_path = os.path.join(tasks.app.conf['PROJ_HOME'], path) + file_name
Using the snippet: <|code_start|> }, {'fulltext_exists.links': {'bibcode': ['test'], 'file': ['tests/test_unit/stub_data/te/st/test.pdf'], 'provider': ['TEST']} }, {'fulltext_wrong.links': {'bibcode': ['test'], 'file': ['tests/test_unit/stub_data/te/st/test.ocr'], 'provider': ['']} } ] stub_data = { 'integration': {'path': integration_path, 'files': integration_files} } path = stub_data[test_name]['path'] files = stub_data[test_name]['files'] for file_dictionary in files: file_name = list(file_dictionary.keys())[0] file_ = file_dictionary[file_name] test_bibcode_ = file_['bibcode'] test_file_ = file_['file'] test_provider_ = file_['provider'] <|code_end|> , determine the next line of code. You have imports: import sys import os import unittest import time import json from builtins import range from mock import MagicMock from adsft import tasks, app from adsft import checker and context (class names, function names, or code) available: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/app.py # class ADSFulltextCelery(ADSCelery): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] . Output only the next line.
links_file_path = os.path.join(tasks.app.conf['PROJ_HOME'], path) + file_name
Given the following code snippet before the placeholder: <|code_start|> build_links(test_name='integration') self.meta_path = '' self.channel_list = None def tearDown(self): unittest.TestCase.tearDown(self) self.app.close_app() tasks.app = self._app def helper_get_details(self, test_publish): """ Generates a bunch of relevant information about the stub data being used. The attribute names should be relevant. :param test_publish: the file to the test stub file :return: no return """ with open(os.path.join(self.proj_home, test_publish), "r") as f: lines = f.readlines() self.nor = len(lines) self.bibcode, self.ft_source, self.provider = \ lines[0].strip().split('\t') self.bibcode_list = [i.strip().split('\t')[0] for i in lines] <|code_end|> , predict the next line using imports from the current file: import sys import os import unittest import time import json from builtins import range from mock import MagicMock from adsft import tasks, app from adsft import checker and context including class names, function names, and sometimes code from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/app.py # class ADSFulltextCelery(ADSCelery): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] . Output only the next line.
self.test_expected = checker.create_meta_path(
Predict the next line after this snippet: <|code_start|> """ self.clean_up_path(self.expected_paths) super(TestNotExtractedBefore, self).tearDown() def test_extraction_of_non_extracted(self): """ Publishes a packet that contains a bibcode that has a full text content path that differs to the one that was used the previous time full text content was extracted. Then it ensures all the files generated are removed. :return: no return """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=False, force_send=False) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> using the current file's imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and any relevant context from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Using the snippet: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'NOT_EXTRACTED_BEFORE' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> , determine the next line of code. You have imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (class names, function names, or code) available: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Given snippet: <|code_start|> if payload_dictionary['file_format'] == 'pdf-grobid': full_text_output_file_path = os.path.join(bibcode_pair_tree_path, 'grobid_fulltext.xml') else: full_text_output_file_path = os.path.join(bibcode_pair_tree_path, 'fulltext.txt.gz') if 'UPDATE' in payload_dictionary and \ payload_dictionary['UPDATE'] == 'FORCE_TO_SEND' and \ os.path.exists(meta_output_file_path) and os.path.exists(full_text_output_file_path): # Data was already extracted and saved return if not os.path.exists(bibcode_pair_tree_path): try: os.makedirs(bibcode_pair_tree_path) except OSError: raise OSError # Write everything but the full text content to the meta.json meta_dict = {} for const in ('meta_path', 'ft_source', 'bibcode', 'provider', 'UPDATE', 'file_format', 'index_date', 'dataset', 'facility'): try: meta_dict[const] = payload_dictionary[const] logger.debug('Adding meta content: %s', const) except KeyError: #print('Missing meta content: {0}'.format(const)) continue # Write the custom extractions of content to the meta.json logger.debug('Copying extra meta content') <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import json import tempfile import shutil import gzip import traceback from adsft.rules import META_CONTENT from adsputils import setup_logging, load_config and context: # Path: adsft/rules.py # META_CONTENT = { # 'xml': { # 'fulltext': { # 'xpath': ['//body', # '//section[@type="body"]', # '//journalarticle-body', # '//bdy', # '//app-group', # '//section[not(@type="acknowledgments" or @type="dataAccess" or @type="dataAvailability" or @type="superSection")]' # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//ack', # '//section[@type="acknowledgments"]', # '//subsection[@type="acknowledgement" ' # 'or @type="acknowledgment"]' # ], # 'type': 'string', # 'info': '', # }, # 'dataset': { # 'xpath': ['//named-content[@content-type="dataset"]'], # 'type': 'list', # 'info': 'xlink:href', # }, # 'facility': { # 'xpath': ['//named-content[@content-type="facility"]'], # 'type': 'list', # 'info': 'xlink:href', # } # }, # 'teixml': { # 'fulltext': { # 'xpath': ['//body', # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//div[@type="acknowledgement"]', # ], # 'type': 'string', # 'info': '', # }, # }, # 'xmlelsevier': { # 'fulltext': { # 'xpath': ['//body', # '//raw-text', # '//appendices', # ], # 'type': 'string', # 'info': '', # }, # 'acknowledgements': { # 'xpath': ['//acknowledgment', # '//ack', # '//section[@type="acknowledgments"]', # '//subsection[@type="acknowledgement" ' # 'or @type="acknowledgment"]', # '//*[local-name()="acknowledgment"]' # ], # 'type': 'string', # 'info': '', # }, # 'dataset': { # 'xpath': ['//named-content[@content-type="dataset"]'], # 'type': 'list', # 'info': 'xlink:href', # } # }, # 'html': { # 'introduction': [ # '//h2[contains(.,"ntroduction")]', # '//h3[contains(.,"ntroduction")]', # '//p[contains(.,"Abstract")]', # ], # 'references': [ # '//h2[contains(.,"References")]' # ], # 'table': [ # '//table' # ], # 'table_links': [ # '//a[contains(@href, "TABLE_NAME")]' # ], # 'head': [ # '//head' # ] # }, # 'txt': {'fulltext': ['']}, # 'ocr': {'fulltext': ['']}, # 'http': {'fulltext': ['']}, # 'pdf': {'fulltext': ['']}, # 'pdf-grobid': {'grobid_fulltext': ['']}, # } which might include code, classes, or functions. Output only the next line.
for meta_key_word in META_CONTENT[payload_dictionary['file_format']]:
Here is a snippet: <|code_start|> #from adsft import extraction, rules, utils class TestFullRangeFormatExtraction(test_base.TestGeneric): """ Class that tests all format types that are expected to be sent to the RabbitMQ instance. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: """ super(TestFullRangeFormatExtraction, self).setUp() #self.dict_item = {'ft_source': self.test_stub_xml, #'file_format': 'xml', #'provider': 'MNRAS'} #self.extractor = extraction.EXTRACTOR_FACTORY['xml'](self.dict_item) <|code_end|> . Write the next line using the current file imports: import unittest import os import sys import json import httpretty import pdb from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] , which may include functions, classes, or code. Output only the next line.
self.grobid_service = tasks.app.conf['GROBID_SERVICE']
Predict the next line after this snippet: <|code_start|> #if arguments['ft_source'].endswith('.pdf') is False: tasks.task_extract(arguments) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for i, path in enumerate(self.expected_paths): meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'NOT_EXTRACTED_BEFORE' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> using the current file's imports: import unittest import os import sys import json import httpretty import pdb from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and any relevant context from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Given snippet: <|code_start|> self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Make the fake data to use if not os.path.exists(self.meta_path): os.makedirs(self.meta_path) test_meta_content = { 'index_date': datetime.utcnow().isoformat()+'Z', 'bibcode': self.bibcode, 'provider': self.provider, 'ft_source': self.ft_source } with open(self.test_expected.replace('meta.json', 'fulltext.txt.gz'), 'w')\ as test_full_text_file: test_full_text_file.write('Full text content') time.sleep(2) with open(self.test_expected, 'w') as test_meta_file: json.dump(test_meta_content, test_meta_file) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import os import sys import json import time from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] which might include code, classes, or functions. Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Using the snippet: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'STALE_CONTENT' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> , determine the next line of code. You have imports: import unittest import os import sys import json import time from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (class names, function names, or code) available: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Next line prediction: <|code_start|> logger.debug('Setting variables') if 'max_queue_size' in kwargs: max_queue_size = kwargs['max_queue_size'] logger.debug('Max queue size overridden: %d', kwargs['max_queue_size']) else: max_queue_size = 0 if facility_ner and not force_extract: task_str = 'task_identify_facilities' else: task_str = 'task_check_if_extract' logger.info('Publishing records to: %s', task_str) i = 0 total = len(records.payload) for record in records.payload: logger.debug('Publishing [%i/%i]: [%s]', i+1, total, record['bibcode']) if max_queue_size and i >= max_queue_size: logger.info('Max_queue_size reached, stopping. (Max queue size = %d)', max_queue_size) break if diagnose: print("[{}/{}] Calling '{}' with '{}'".format(i+1, total, task_str, str(record))) logger.debug("[%i/%i] Calling '%s' with '%s'", i+1, total, task_str, str(record)) if i % 100000 == 0: logger.info("[%i/%i] Calling '%s'", i+1, total, task_str) <|code_end|> . Use current file imports: (import sys import os import tempfile import argparse import json from builtins import zip from builtins import str from adsft import tasks, utils from adsputils import setup_logging, load_config) and context including class names, function names, or small code snippets from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/utils.py # class FileInputStream(object): # class TextCleaner(object): # def __init__(self, input_stream): # def print_info(self): # def extract(self, force_extract=False, force_send=False): # def __init__(self, text): # def translate(self): # def decode(self): # def normalise(self): # def trimwords(self, maxlength=100): # def run(self, translate=True, decode=True, normalise=True, trim=True): # def get_filenames(file_string): . Output only the next line.
getattr(tasks, task_str).delay(record)
Based on the snippet: <|code_start|>#!/usr/bin/env python # ============================= INITIALIZATION ==================================== # proj_home = os.path.realpath(os.path.dirname(__file__)) config = load_config(proj_home=proj_home) logger = setup_logging('run.py', proj_home=proj_home, level=config.get('LOGGING_LEVEL', 'INFO'), attach_stdout=config.get('LOG_STDOUT', False)) # =============================== FUNCTIONS ======================================= # def read_links_from_file(file_input, force_extract=False, force_send=False): """ Opens the link file given and parses the content into a set of lists. :param file_input: path to the link file :param force_extract: did the user bypass the internal checks :param force_send: always send results to master, even for already extracted files :return: file stream type (see utils.py) """ <|code_end|> , predict the immediate next line with the help of imports: import sys import os import tempfile import argparse import json from builtins import zip from builtins import str from adsft import tasks, utils from adsputils import setup_logging, load_config and context (classes, functions, sometimes code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/utils.py # class FileInputStream(object): # class TextCleaner(object): # def __init__(self, input_stream): # def print_info(self): # def extract(self, force_extract=False, force_send=False): # def __init__(self, text): # def translate(self): # def decode(self): # def normalise(self): # def trimwords(self, maxlength=100): # def run(self, translate=True, decode=True, normalise=True, trim=True): # def get_filenames(file_string): . Output only the next line.
FileInputStream = utils.FileInputStream(file_input)
Next line prediction: <|code_start|> class TestWorkers(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) <|code_end|> . Use current file imports: (import sys import os import json import unittest import httpretty from mock import patch from adsft import app, tasks, checker from adsmsg import FulltextUpdate) and context including class names, function names, or small code snippets from other files: # Path: adsft/app.py # class ADSFulltextCelery(ADSCelery): # # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] . Output only the next line.
self.proj_home = tasks.app.conf['PROJ_HOME']
Given the following code snippet before the placeholder: <|code_start|> class TestWorkers(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) <|code_end|> , predict the next line using imports from the current file: import sys import os import json import unittest import httpretty from mock import patch from adsft import app, tasks, checker from adsmsg import FulltextUpdate and context including class names, function names, and sometimes code from other files: # Path: adsft/app.py # class ADSFulltextCelery(ADSCelery): # # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] . Output only the next line.
self.proj_home = tasks.app.conf['PROJ_HOME']
Based on the snippet: <|code_start|> """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=False, force_send=False) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Make the fake data to use if not os.path.exists(self.meta_path): os.makedirs(self.meta_path) test_meta_content = { 'index_date': datetime.utcnow().isoformat()+'Z', 'bibcode': 'test4', 'provider': 'mnras' } with open(self.test_expected, 'w') as test_meta_file: json.dump(test_meta_content, test_meta_file) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> , predict the immediate next line with the help of imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (classes, functions, sometimes code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Continue the code snippet: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'MISSING_FULL_TEXT' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> . Use current file imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (classes, functions, or code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Next line prediction: <|code_start|> :return: no return """ self.clean_up_path(self.expected_paths) super(TestForcedExtractor, self).tearDown() def test_forced_send(self): """ Tests that when a user specifies 'force_extract' that the full text is extracted regardless of its underlying reason for being or not being extracted. :return: no return """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=False, force_send=True) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> . Use current file imports: (import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file) and context including class names, function names, or small code snippets from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Continue the code snippet: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'FORCE_TO_SEND' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> . Use current file imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (classes, functions, or code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Based on the snippet: <|code_start|> :return: dictionary containing two lists. One for PDF files and the other for normal files. It adds the extra keyword UPDATE which explains why the extraction of the full text is required. """ NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", "FORCE_TO_SEND"] publish_list_of_standard_dictionaries = [] publish_list_of_pdf_dictionaries = [] for message in message_list: # message should be a dictionary if 'UPDATE' in message \ and message['UPDATE'] == 'FORCE_TO_EXTRACT': update = 'FORCE_TO_EXTRACT' elif 'UPDATE' in message \ and message['UPDATE'] == 'FORCE_TO_SEND': update = 'FORCE_TO_SEND' elif meta_output_exists(message, extract_path): meta_content = load_meta_file(message, extract_path) update = meta_needs_update(message, meta_content, extract_path) else: logger.debug('No existing meta file') update = 'NOT_EXTRACTED_BEFORE' # only check the first filename <|code_end|> , predict the immediate next line with the help of imports: import sys import os import json import ptree import traceback from . import utils from stat import ST_MTIME from datetime import datetime from dateutil.parser import parse from adsft.utils import get_filenames from adsputils import setup_logging, load_config and context (classes, functions, sometimes code) from other files: # Path: adsft/utils.py # def get_filenames(file_string): # """convert passed string containing one or more files to an array of files # # file_string could be a sigle file, a simple comma separated list of files # or it could include a comman in either the filename or the pathname # we can't use a comma as a delimeter # instead, since all paths are absolute, we use the first two directory names # in the absolution path as a delimter # example simple input: # /proj/ads/fulltext/sources/A+A/backdata/2003/17/aah3724/aah3724.right.html,/proj/ads/fulltext/sources/A+A/backdata/2003/17/aah3724/tableE.1.html # example input with comman in filename: # /proj/ads/fulltext/sources/downloads/cache/POS/pos.sissa.it//archive/conferences/075/001/BHs,%20GR%20and%20Strings_001.pdf # """ # if file_string[0] != '/': # raise ValueError('expected absolute pathname to start with / character: {}'.format(file_string)) # second_slash_index = file_string.index('/', 1) # third_slash_index = file_string.index('/', second_slash_index+1) # prefix = file_string[:third_slash_index+1] # # # split input string over prefix delimeter, add prefix back to string # files = [prefix+f for f in file_string.split(prefix) if f] # # remove trailing commas, they are actual delimiters # for i in range(0, len(files)): # if files[i][-1] == ',': # files[i] = files[i][:-1] # # return files . Output only the next line.
ft = get_filenames(message['ft_source'])[0]
Continue the code snippet: <|code_start|> :return: no return """ self.clean_up_path(self.expected_paths) super(TestForcedExtractor, self).tearDown() def test_forced_extraction(self): """ Tests that when a user specifies 'force_extract' that the full text is extracted regardless of its underlying reason for being or not being extracted. :return: no return """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=True, force_send=False) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> . Use current file imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file from run import read_links_from_file and context (classes, functions, or code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Given the following code snippet before the placeholder: <|code_start|> # Now we do call the extraction task with the proper arguments tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'FORCE_TO_EXTRACT' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) if os.path.exists(fulltext_path): <|code_end|> , predict the next line using imports from the current file: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file from run import read_links_from_file and context including class names, function names, and sometimes code from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Predict the next line for this snippet: <|code_start|>if sys.version_info > (3,): class TestCheckIfExtracted(test_base.TestUnit): """ Tests the CheckIfExtract worker's methods, i.e., the unit functions. """ def test_file_not_extracted_before(self): """ Tests the meta_output_exists function. It should find that there is not already a meta file that exists, which is defined in test_file_stub. :return: no return """ <|code_end|> with the help of current file imports: import sys import unittest import os import re from builtins import str from adsft import utils, checker from adsft.tests import test_base and context from other files: # Path: adsft/utils.py # class FileInputStream(object): # class TextCleaner(object): # def __init__(self, input_stream): # def print_info(self): # def extract(self, force_extract=False, force_send=False): # def __init__(self, text): # def translate(self): # def decode(self): # def normalise(self): # def trimwords(self, maxlength=100): # def run(self, translate=True, decode=True, normalise=True, trim=True): # def get_filenames(file_string): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] , which may contain function names, class names, or code. Output only the next line.
FileInputStream = utils.FileInputStream(self.test_file_stub)
Based on the snippet: <|code_start|>if sys.version_info > (3,): class TestCheckIfExtracted(test_base.TestUnit): """ Tests the CheckIfExtract worker's methods, i.e., the unit functions. """ def test_file_not_extracted_before(self): """ Tests the meta_output_exists function. It should find that there is not already a meta file that exists, which is defined in test_file_stub. :return: no return """ FileInputStream = utils.FileInputStream(self.test_file_stub) FileInputStream.extract() payload = FileInputStream.payload[0] <|code_end|> , predict the immediate next line with the help of imports: import sys import unittest import os import re from builtins import str from adsft import utils, checker from adsft.tests import test_base and context (classes, functions, sometimes code) from other files: # Path: adsft/utils.py # class FileInputStream(object): # class TextCleaner(object): # def __init__(self, input_stream): # def print_info(self): # def extract(self, force_extract=False, force_send=False): # def __init__(self, text): # def translate(self): # def decode(self): # def normalise(self): # def trimwords(self, maxlength=100): # def run(self, translate=True, decode=True, normalise=True, trim=True): # def get_filenames(file_string): # # Path: adsft/checker.py # def file_last_modified_time(file_input): # def create_meta_path(dict_input, extract_path): # def meta_output_exists(file_input, extract_path): # def load_meta_file(file_input, extract_path): # def meta_needs_update(dict_input, meta_content, # extract_path): # def check_if_extract(message_list, extract_path): # NEEDS_UPDATE = ["MISSING_FULL_TEXT", "DIFFERING_FULL_TEXT", "STALE_CONTENT", # "STALE_META", "NOT_EXTRACTED_BEFORE", "FORCE_TO_EXTRACT", # "FORCE_TO_SEND"] # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
exists = checker.meta_output_exists(
Using the snippet: <|code_start|> :return: no return """ self.clean_up_path(self.expected_paths) super(TestExtraAcknowledgment, self).tearDown() def test_extra_acknowledment(self): """ Submits a file to the RabbitMQ that contains a bibcode that should result in an acknowlegements file is created. It checks that this file is created and then removes all the content created by the tests. :return: no return """ sys.path.append(self.app.conf['PROJ_HOME']) # User loads the list of full text files and publishes them to the # first queue records = read_links_from_file(self.test_publish, force_extract=False, force_send=False) self.helper_get_details(self.test_publish) self.assertEqual( len(records.bibcode), self.nor, 'The number of records should match' ' the number of lines. It does not: ' '{0} [{1}]'.format(len(records.bibcode), self.nor)) self.assertTrue(len(records.payload) == 1) # Call the task to check if it should be extracted but mock the extraction task <|code_end|> , determine the next line of code. You have imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (class names, function names, or code) available: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:
Continue the code snippet: <|code_start|> tasks.task_extract(actual) self.assertTrue(task_output_results.called) # After the extractor, the meta writer should write all the payloads to # disk in the correct folders for path in self.expected_paths: meta_path = os.path.join(path, 'meta.json') self.assertTrue( os.path.exists(meta_path), 'Meta file not created: {0}'.format(path) ) if os.path.exists(meta_path): with open(meta_path, 'r') as meta_file: meta_content = meta_file.read() self.assertTrue( 'NOT_EXTRACTED_BEFORE' in meta_content, 'meta file does not contain the right extract keyword: {0}' .format(meta_content) ) fulltext_path = os.path.join(path, 'fulltext.txt.gz') self.assertTrue( os.path.exists(fulltext_path), 'Full text file not created: %s'.format(path) ) # unless changed, tests/test_integration/stub_data/full_test_elsevier.xml if os.path.exists(fulltext_path): <|code_end|> . Use current file imports: import unittest import os import sys import json from mock import patch from adsft import tasks, reader from adsft.tests import test_base from datetime import datetime from mock import patch from run import read_links_from_file and context (classes, functions, or code) from other files: # Path: adsft/tasks.py # def task_check_if_extract(message): # def task_extract(message): # def task_extract_grobid(message): # def task_output_results(msg): # def task_identify_facilities(message): # # Path: adsft/reader.py # def read_file(input_filename, json_format=True): # def read_content(payload_dictionary): # # Path: adsft/tests/test_base.py # def build_links(test_name): # def setUp(self): # def tearDown(self): # def setUp(self): # def tearDown(self): # def helper_get_details(self, test_publish): # def calculate_expected_folders(self, full_text_links): # def clean_up_path(self, paths): # class TestUnit(unittest.TestCase): # class TestGeneric(unittest.TestCase): # PROJ_HOME = self.app.conf['PROJ_HOME'] . Output only the next line.
fulltext_content = reader.read_file(fulltext_path, json_format=False)
Here is a snippet: <|code_start|> class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) class RegistrationForm(forms.Form): email = forms.EmailField(widget=forms.TextInput(attrs={'size':'30'})) username = forms.CharField(widget=forms.TextInput(attrs={'size':'20'})) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class ContactPublicForm(ModelForm): captcha = ReCaptchaField() class Meta: <|code_end|> . Write the next line using the current file imports: from captcha.fields import ReCaptchaField from django import forms as forms from django.forms import ModelForm from .models import ContactMessage and context from other files: # Path: server/apps/main/models.py # class ContactMessage(models.Model): # # name = models.CharField(max_length=50) # email = models.EmailField(max_length=60) # phone = models.CharField(max_length=50, blank=True) # message = models.TextField() # # created_on = models.DateTimeField('created_on', auto_now_add=True) # # class Meta: # ordering = ['id'] # # def __str__(self): # return self.name , which may include functions, classes, or code. Output only the next line.
model = ContactMessage
Next line prediction: <|code_start|> def test_api_token(self): url = reverse('api-token') u4 = user_model.objects.create_user(username='User4', email='user4@foo.com', password='pass') u4.is_active = True u4.save() try: token = Token.objects.get(user=u4) # There should be no token for u3 self.assertEqual(1, 0) except: pass resp = self.client.get(url, data={'format': 'json'}) self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) ok = self.client.login(email='user4@foo.com', password='pass') self.assertTrue(ok) resp = self.client.get(url, data={'format': 'json'}) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) deserialized = json.loads(resp.content.decode()) self.assertEqual(len(deserialized), 1) token = Token.objects.get(user=u4) self.assertEqual(deserialized['token'], token.key) resp = self.client.get(url, data={'format': 'json'}) self.assertEqual(resp.status_code, status.HTTP_200_OK) def test_serializer(self): account = Account.objects.latest('created_at') <|code_end|> . Use current file imports: (import json import pytz from django.conf import settings from django.contrib.auth import get_user_model from django.test import Client, TestCase from django.utils import timezone from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.reverse import reverse from rest_framework.test import APIClient, APIRequestFactory from .models import * from .serializers import AccountSerializer from .tasks import * from rest_framework.test import APITestCase) and context including class names, function names, or small code snippets from other files: # Path: server/apps/authentication/serializers.py # class AccountSerializer(serializers.ModelSerializer): # password = serializers.CharField(write_only=True, required=False) # confirm_password = serializers.CharField(write_only=True, required=False) # # class Meta: # model = Account # fields = ('id', 'email', 'username', 'created_at', 'updated_at', # 'name', 'tagline', 'password', # 'confirm_password',) # read_only_fields = ('created_at', 'updated_at',) # # def create(self, validated_data): # return Account.objects.create(**validated_data) # # def update(self, instance, validated_data): # instance.username = validated_data.get('username', instance.username) # instance.tagline = validated_data.get('tagline', instance.tagline) # # instance.save() # # password = validated_data.get('password', None) # confirm_password = validated_data.get('confirm_password', None) # # if password and confirm_password and password == confirm_password: # instance.set_password(password) # instance.is_active = True # instance.save() # # update_session_auth_hash(self.context.get('request'), instance) # # return instance # # def to_representation(self, obj): # data = super(AccountSerializer, self).to_representation(obj) # # return data . Output only the next line.
serialized_account = AccountSerializer(account)
Based on the snippet: <|code_start|>class APITokenViewSet(APIView): """ View to get User's token """ def get(self, request, format=None): """ Update thumbnail and tiny file field """ if request.user.is_anonymous: # User most login before they can get a token # This not only ensures the user has registered, and has an account # but that the account is active return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) data_dic = {} try: token = Token.objects.get(user=request.user) mystatus = status.HTTP_200_OK except: token = Token.objects.create(user=request.user) mystatus = status.HTTP_201_CREATED data_dic['token'] = token.key return Response(data_dic, status=mystatus) class AccountViewSet(viewsets.ModelViewSet): lookup_field = 'username' <|code_end|> , predict the immediate next line with the help of imports: import json import logging from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from allauth.socialaccount.helpers import complete_social_login from allauth.socialaccount.models import SocialApp, SocialLogin, SocialToken from allauth.socialaccount.providers.facebook.views import fb_complete_login from rest_framework import permissions, status, views, viewsets from rest_framework.authentication import SessionAuthentication from rest_framework.authtoken.models import Token from rest_framework.decorators import action, permission_classes from rest_framework.parsers import JSONParser from rest_framework.permissions import AllowAny from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from apps.utils.permissions import * from .models import Account from .permissions import IsAccountOwner from .serializers import * from .tasks import send_new_user_notification and context (classes, functions, sometimes code) from other files: # Path: server/apps/authentication/models.py # class Account(AbstractBaseUser): # # TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones] # # email = models.EmailField(unique=True) # username = models.CharField(max_length=40, unique=True) # slug = models.SlugField(max_length=60, unique=True) # # name = models.CharField(verbose_name='Full Name', max_length=120, blank=True) # tagline = models.CharField(max_length=260, blank=True) # # external_avatar_url = models.CharField(max_length=260, blank=True, null=True) # # is_staff = models.BooleanField(default=False) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # # objects = AccountManager() # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] # # class Meta: # ordering = ['slug'] # # def save(self, *args, **kwargs): # # slug = slugify(self.username) # self.slug = slug # count = 0 # while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists(): # self.slug = '{0}{1}'.format(slug, count) # logger.debug('Slug conflict. Trying again with {0}'.format(self.slug)) # count += 1 # # super(Account, self).save(*args, **kwargs) # # def __str__(self): # return '@{0}'.format(self.username) # # def get_full_name(self): # return self.name # # def get_short_name(self): # if (self.name != ''): # # Try to extract the first name # names = self.name.split() # first_name = names[0] # return first_name # return self.username # # # For full access to Permission system, we needed to add the PermissionMixin # def has_perm(self, perm, obj=None): # return True # # def has_perms(perm_list, obj=None): # return True # # def has_module_perms(self, app_label): # return True # # # Custom Methods # # -------------- # def get_absolute_url(self): # return '/account/%s/' % self.slug # # def get_edit_url(self): # return '%sedit/' % self.get_absolute_url() # # def get_token(self): # try: # token = Token.objects.get(user=self) # except: # token = Token.objects.create(user=self) # return token # # def get_gravatar_thumbnail_url(self, size=100): # # Set your variables here # email = self.email # default = 'identicon' # # # construct the url # gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?" # try: # # Python 3.4 # gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)}) # except: # # Python 2.7 # gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) # # return gravatar_url # # Path: server/apps/authentication/tasks.py # def send_new_user_notification(id, username, email): # ''' # Information about the ContactMe form is sent via # SQS to an EB worker, who will then send notifications # to our Staff # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # subject = 'User @{0} (ID={1}) has registered with email {2}'.format(username, id, email) # # logger.debug(subject) . Output only the next line.
queryset = Account.objects.all()
Here is a snippet: <|code_start|> def create(self, request): ''' When you create an object using the serializer's .save() method, the object's attributes are set literally. This means that a user registering with the password 'password' will have their password stored as 'password'. This is bad for a couple of reasons: 1) Storing passwords in plain text is a massive security issue. 2) Django hashes and salts passwords before comparing them, so the user wouldn't be able to log in using 'password' as their password. We solve this problem by overriding the .create() method for this viewset and using Account.objects.create_user() to create the Account object. ''' serializer = self.serializer_class(data=request.data) if serializer.is_valid(): password = serializer.validated_data['password'] confirm_password = serializer.validated_data['confirm_password'] if password and confirm_password and password == confirm_password: # Note that for now, Accounts default to is_active=False # which means that we need to manually active them # This is to keep the site secure until we go live account = Account.objects.create_user(**serializer.validated_data) account.set_password(serializer.validated_data['password']) account.save() # For now, we also want to email Admin every time anybody registers <|code_end|> . Write the next line using the current file imports: import json import logging from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from allauth.socialaccount.helpers import complete_social_login from allauth.socialaccount.models import SocialApp, SocialLogin, SocialToken from allauth.socialaccount.providers.facebook.views import fb_complete_login from rest_framework import permissions, status, views, viewsets from rest_framework.authentication import SessionAuthentication from rest_framework.authtoken.models import Token from rest_framework.decorators import action, permission_classes from rest_framework.parsers import JSONParser from rest_framework.permissions import AllowAny from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from apps.utils.permissions import * from .models import Account from .permissions import IsAccountOwner from .serializers import * from .tasks import send_new_user_notification and context from other files: # Path: server/apps/authentication/models.py # class Account(AbstractBaseUser): # # TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones] # # email = models.EmailField(unique=True) # username = models.CharField(max_length=40, unique=True) # slug = models.SlugField(max_length=60, unique=True) # # name = models.CharField(verbose_name='Full Name', max_length=120, blank=True) # tagline = models.CharField(max_length=260, blank=True) # # external_avatar_url = models.CharField(max_length=260, blank=True, null=True) # # is_staff = models.BooleanField(default=False) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # # objects = AccountManager() # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] # # class Meta: # ordering = ['slug'] # # def save(self, *args, **kwargs): # # slug = slugify(self.username) # self.slug = slug # count = 0 # while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists(): # self.slug = '{0}{1}'.format(slug, count) # logger.debug('Slug conflict. Trying again with {0}'.format(self.slug)) # count += 1 # # super(Account, self).save(*args, **kwargs) # # def __str__(self): # return '@{0}'.format(self.username) # # def get_full_name(self): # return self.name # # def get_short_name(self): # if (self.name != ''): # # Try to extract the first name # names = self.name.split() # first_name = names[0] # return first_name # return self.username # # # For full access to Permission system, we needed to add the PermissionMixin # def has_perm(self, perm, obj=None): # return True # # def has_perms(perm_list, obj=None): # return True # # def has_module_perms(self, app_label): # return True # # # Custom Methods # # -------------- # def get_absolute_url(self): # return '/account/%s/' % self.slug # # def get_edit_url(self): # return '%sedit/' % self.get_absolute_url() # # def get_token(self): # try: # token = Token.objects.get(user=self) # except: # token = Token.objects.create(user=self) # return token # # def get_gravatar_thumbnail_url(self, size=100): # # Set your variables here # email = self.email # default = 'identicon' # # # construct the url # gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?" # try: # # Python 3.4 # gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)}) # except: # # Python 2.7 # gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) # # return gravatar_url # # Path: server/apps/authentication/tasks.py # def send_new_user_notification(id, username, email): # ''' # Information about the ContactMe form is sent via # SQS to an EB worker, who will then send notifications # to our Staff # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # subject = 'User @{0} (ID={1}) has registered with email {2}'.format(username, id, email) # # logger.debug(subject) , which may include functions, classes, or code. Output only the next line.
send_new_user_notification(id=account.id, username=account.username, email=account.email)
Continue the code snippet: <|code_start|> # Get an instance of a logger logger = logging.getLogger(__name__) class AccountRedirectView(View): @method_decorator(login_required) def get(self, request): user = request.user return HttpResponseRedirect(reverse('account_detail', args=(user.username,))) class AccountDetailView(DetailView): <|code_end|> . Use current file imports: import json import logging import os from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import CreateView, DetailView, RedirectView, TemplateView, View from django.views.generic.edit import FormView, UpdateView from .forms import * from .models import Account and context (classes, functions, or code) from other files: # Path: server/apps/authentication/models.py # class Account(AbstractBaseUser): # # TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones] # # email = models.EmailField(unique=True) # username = models.CharField(max_length=40, unique=True) # slug = models.SlugField(max_length=60, unique=True) # # name = models.CharField(verbose_name='Full Name', max_length=120, blank=True) # tagline = models.CharField(max_length=260, blank=True) # # external_avatar_url = models.CharField(max_length=260, blank=True, null=True) # # is_staff = models.BooleanField(default=False) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # # objects = AccountManager() # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] # # class Meta: # ordering = ['slug'] # # def save(self, *args, **kwargs): # # slug = slugify(self.username) # self.slug = slug # count = 0 # while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists(): # self.slug = '{0}{1}'.format(slug, count) # logger.debug('Slug conflict. Trying again with {0}'.format(self.slug)) # count += 1 # # super(Account, self).save(*args, **kwargs) # # def __str__(self): # return '@{0}'.format(self.username) # # def get_full_name(self): # return self.name # # def get_short_name(self): # if (self.name != ''): # # Try to extract the first name # names = self.name.split() # first_name = names[0] # return first_name # return self.username # # # For full access to Permission system, we needed to add the PermissionMixin # def has_perm(self, perm, obj=None): # return True # # def has_perms(perm_list, obj=None): # return True # # def has_module_perms(self, app_label): # return True # # # Custom Methods # # -------------- # def get_absolute_url(self): # return '/account/%s/' % self.slug # # def get_edit_url(self): # return '%sedit/' % self.get_absolute_url() # # def get_token(self): # try: # token = Token.objects.get(user=self) # except: # token = Token.objects.create(user=self) # return token # # def get_gravatar_thumbnail_url(self, size=100): # # Set your variables here # email = self.email # default = 'identicon' # # # construct the url # gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?" # try: # # Python 3.4 # gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)}) # except: # # Python 2.7 # gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) # # return gravatar_url . Output only the next line.
model = Account
Given the following code snippet before the placeholder: <|code_start|> urlpatterns = [ path('', include('allauth.urls')), path('', AccountRedirectView.as_view(), name='account_redirect'), path('<slug:slug>/edit/', AccountUpdateView.as_view(), name='account_edit'), <|code_end|> , predict the next line using imports from the current file: from django.urls import include, path from .views import AccountDetailView, AccountRedirectView, AccountUpdateView and context including class names, function names, and sometimes code from other files: # Path: server/apps/authentication/views.py # class AccountDetailView(DetailView): # model = Account # template_name = 'authentication/detailVCard.html' # # def get_context_data(self, **kwargs): # context = super(AccountDetailView, self).get_context_data(**kwargs) # context['referer'] = self.request.META.get('HTTP_REFERER') # context['is_owner'] = (self.object == self.request.user) # return context # # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(AccountDetailView, self).dispatch(request, *args, **kwargs) # # class AccountRedirectView(View): # @method_decorator(login_required) # def get(self, request): # user = request.user # # return HttpResponseRedirect(reverse('account_detail', args=(user.username,))) # # class AccountUpdateView(UpdateView): # model = Account # form_class = AccountUpdateForm # template_name = 'form.html' # # def form_valid(self, form): # self.object = form.save(commit=False) # self.object.time_zone = form.cleaned_data.get('time_zone') # self.object.save() # # # Update session as well # self.request.session['django_timezone'] = str(form.cleaned_data.get('time_zone')) # # return HttpResponseRedirect(self.get_success_url()) # # def get_context_data(self, **kwargs): # context = super(AccountUpdateView, self).get_context_data(**kwargs) # context['referer'] = self.request.META.get('HTTP_REFERER') # # return context # # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(AccountUpdateView, self).dispatch(request, *args, **kwargs) . Output only the next line.
path('<slug:slug>/', AccountDetailView.as_view(), name='account_detail'),
Given snippet: <|code_start|> urlpatterns = [ path('', include('allauth.urls')), path('', AccountRedirectView.as_view(), name='account_redirect'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.urls import include, path from .views import AccountDetailView, AccountRedirectView, AccountUpdateView and context: # Path: server/apps/authentication/views.py # class AccountDetailView(DetailView): # model = Account # template_name = 'authentication/detailVCard.html' # # def get_context_data(self, **kwargs): # context = super(AccountDetailView, self).get_context_data(**kwargs) # context['referer'] = self.request.META.get('HTTP_REFERER') # context['is_owner'] = (self.object == self.request.user) # return context # # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(AccountDetailView, self).dispatch(request, *args, **kwargs) # # class AccountRedirectView(View): # @method_decorator(login_required) # def get(self, request): # user = request.user # # return HttpResponseRedirect(reverse('account_detail', args=(user.username,))) # # class AccountUpdateView(UpdateView): # model = Account # form_class = AccountUpdateForm # template_name = 'form.html' # # def form_valid(self, form): # self.object = form.save(commit=False) # self.object.time_zone = form.cleaned_data.get('time_zone') # self.object.save() # # # Update session as well # self.request.session['django_timezone'] = str(form.cleaned_data.get('time_zone')) # # return HttpResponseRedirect(self.get_success_url()) # # def get_context_data(self, **kwargs): # context = super(AccountUpdateView, self).get_context_data(**kwargs) # context['referer'] = self.request.META.get('HTTP_REFERER') # # return context # # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(AccountUpdateView, self).dispatch(request, *args, **kwargs) which might include code, classes, or functions. Output only the next line.
path('<slug:slug>/edit/', AccountUpdateView.as_view(), name='account_edit'),
Here is a snippet: <|code_start|> class AccountAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): if obj: <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .forms import AdminUserChangeForm, AdminUserCreationForm from .models import * and context from other files: # Path: server/apps/authentication/forms.py # class AdminUserChangeForm(forms.ModelForm): # """A form for updating users. Includes all the fields on # the user, but replaces the password field with admin's # password hash display field. # """ # password = ReadOnlyPasswordHashField() # # class Meta: # model = Account # fields = ('username', 'email', 'password', 'name', 'is_active', 'is_staff', 'is_admin') # # def clean_password(self): # # Regardless of what the user provides, return the initial value. # # This is done here, rather than on the field, because the # # field does not have access to the initial value # return self.initial["password"] # # class AdminUserCreationForm(forms.ModelForm): # """A form for creating new users. Includes all the required # fields, plus a repeated password.""" # password1 = forms.CharField(label='Password', widget=forms.PasswordInput) # password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) # # class Meta: # model = Account # fields = ('username', 'email', 'name', 'is_staff', ) # # def clean_password2(self): # # Check that the two password entries match # password1 = self.cleaned_data.get("password1") # password2 = self.cleaned_data.get("password2") # if password1 and password2 and password1 != password2: # raise forms.ValidationError("Passwords don't match") # return password2 # # def save(self, commit=True): # # Save the provided password in hashed format # user = super(AdminUserCreationForm, self).save(commit=False) # user.set_password(self.cleaned_data["password1"]) # if commit: # user.save() # return user , which may include functions, classes, or code. Output only the next line.
return AdminUserChangeForm
Predict the next line for this snippet: <|code_start|> class AccountAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): if obj: return AdminUserChangeForm else: <|code_end|> with the help of current file imports: from django.contrib import admin from .forms import AdminUserChangeForm, AdminUserCreationForm from .models import * and context from other files: # Path: server/apps/authentication/forms.py # class AdminUserChangeForm(forms.ModelForm): # """A form for updating users. Includes all the fields on # the user, but replaces the password field with admin's # password hash display field. # """ # password = ReadOnlyPasswordHashField() # # class Meta: # model = Account # fields = ('username', 'email', 'password', 'name', 'is_active', 'is_staff', 'is_admin') # # def clean_password(self): # # Regardless of what the user provides, return the initial value. # # This is done here, rather than on the field, because the # # field does not have access to the initial value # return self.initial["password"] # # class AdminUserCreationForm(forms.ModelForm): # """A form for creating new users. Includes all the required # fields, plus a repeated password.""" # password1 = forms.CharField(label='Password', widget=forms.PasswordInput) # password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) # # class Meta: # model = Account # fields = ('username', 'email', 'name', 'is_staff', ) # # def clean_password2(self): # # Check that the two password entries match # password1 = self.cleaned_data.get("password1") # password2 = self.cleaned_data.get("password2") # if password1 and password2 and password1 != password2: # raise forms.ValidationError("Passwords don't match") # return password2 # # def save(self, commit=True): # # Save the provided password in hashed format # user = super(AdminUserCreationForm, self).save(commit=False) # user.set_password(self.cleaned_data["password1"]) # if commit: # user.save() # return user , which may contain function names, class names, or code. Output only the next line.
return AdminUserCreationForm
Given the code snippet: <|code_start|> class TimeZoneFormField(forms.TypedChoiceField): def __init__(self, *args, **kwargs): def coerce_to_pytz(val): try: return pytz.timezone(val) except pytz.UnknownTimeZoneError: raise ValidationError("Unknown time zone: '%s'" % val) defaults = { 'coerce': coerce_to_pytz, 'choices': [(tz, tz) for tz in pytz.common_timezones], 'empty_value': None, } defaults.update(kwargs) super(TimeZoneFormField, self).__init__(*args, **defaults) class AccountUpdateForm(ModelForm): time_zone = TimeZoneFormField() class Meta: <|code_end|> , generate the next line using the imports in this file: import pytz from captcha.fields import ReCaptchaField from django import forms as forms from django.conf import settings from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.forms import ModelForm from allauth.account.forms import LoginForm, SignupForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Field, Layout, Submit from .models import Account and context (functions, classes, or occasionally code) from other files: # Path: server/apps/authentication/models.py # class Account(AbstractBaseUser): # # TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones] # # email = models.EmailField(unique=True) # username = models.CharField(max_length=40, unique=True) # slug = models.SlugField(max_length=60, unique=True) # # name = models.CharField(verbose_name='Full Name', max_length=120, blank=True) # tagline = models.CharField(max_length=260, blank=True) # # external_avatar_url = models.CharField(max_length=260, blank=True, null=True) # # is_staff = models.BooleanField(default=False) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # # objects = AccountManager() # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] # # class Meta: # ordering = ['slug'] # # def save(self, *args, **kwargs): # # slug = slugify(self.username) # self.slug = slug # count = 0 # while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists(): # self.slug = '{0}{1}'.format(slug, count) # logger.debug('Slug conflict. Trying again with {0}'.format(self.slug)) # count += 1 # # super(Account, self).save(*args, **kwargs) # # def __str__(self): # return '@{0}'.format(self.username) # # def get_full_name(self): # return self.name # # def get_short_name(self): # if (self.name != ''): # # Try to extract the first name # names = self.name.split() # first_name = names[0] # return first_name # return self.username # # # For full access to Permission system, we needed to add the PermissionMixin # def has_perm(self, perm, obj=None): # return True # # def has_perms(perm_list, obj=None): # return True # # def has_module_perms(self, app_label): # return True # # # Custom Methods # # -------------- # def get_absolute_url(self): # return '/account/%s/' % self.slug # # def get_edit_url(self): # return '%sedit/' % self.get_absolute_url() # # def get_token(self): # try: # token = Token.objects.get(user=self) # except: # token = Token.objects.create(user=self) # return token # # def get_gravatar_thumbnail_url(self, size=100): # # Set your variables here # email = self.email # default = 'identicon' # # # construct the url # gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?" # try: # # Python 3.4 # gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)}) # except: # # Python 2.7 # gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) # # return gravatar_url . Output only the next line.
model = Account
Based on the snippet: <|code_start|>""" Custom User Model """ # import code for encoding urls and generating md5 hashes # Get an instance of a logger logger = logging.getLogger(__name__) def new_sign_up(sender, **kwargs): account = kwargs['user'] logger.info('A new user has signed up! - {username}'.format(username=account.username)) logger.debug('--> New User: ' + str(account)) <|code_end|> , predict the immediate next line with the help of imports: import hashlib import logging import os import urllib.parse import uuid import pytz from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models from django.db.models import Q from django.template.defaultfilters import slugify from allauth.account.signals import user_signed_up from rest_framework.authtoken.models import Token from .tasks import send_new_user_notification and context (classes, functions, sometimes code) from other files: # Path: server/apps/authentication/tasks.py # def send_new_user_notification(id, username, email): # ''' # Information about the ContactMe form is sent via # SQS to an EB worker, who will then send notifications # to our Staff # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # subject = 'User @{0} (ID={1}) has registered with email {2}'.format(username, id, email) # # logger.debug(subject) . Output only the next line.
send_new_user_notification(id=account.id, username=account.username, email=account.email)
Continue the code snippet: <|code_start|> urlpatterns = [ path('login/', APILoginViewSet.as_view(), name='api-login'), path('logout/', APILogoutViewSet.as_view(), name='api-logout'), <|code_end|> . Use current file imports: from django.urls import include, path from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.views import obtain_auth_token from .api_views import APILoginViewSet, APILogoutViewSet, APITokenViewSet, APIUserInfoViewSet, FacebookLoginOrSignup and context (classes, functions, or code) from other files: # Path: server/apps/authentication/api_views.py # class APILoginViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # @csrf_exempt # def post(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # data = JSONParser().parse(request) # serializer = LoginCustomSerializer(data=data) # # if serializer.is_valid(): # email = serializer.data.get('email') # password = serializer.data.get('password') # # if not request.user.is_anonymous: # return Response('Already Logged-in', status=status.HTTP_403_FORBIDDEN) # # account = authenticate(email=email, password=password) # # if account is not None: # if account.is_active: # login(request, account) # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # # return Response(data) # else: # return Response('This account is not Active.', status=status.HTTP_401_UNAUTHORIZED) # else: # return Response('Username/password combination invalid.', status=status.HTTP_401_UNAUTHORIZED) # # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # # data_dic = {"Error":"GET not supported for this command"} # # logout(request) # mystatus = status.HTTP_400_BAD_REQUEST # # return Response(data_dic, status=mystatus) # # class APILogoutViewSet(APIView): # permission_classes = (permissions.IsAuthenticated,) # # def post(self, request, format=None): # logout(request) # # return Response({}, status=status.HTTP_204_NO_CONTENT) # # class APITokenViewSet(APIView): # """ # View to get User's token # """ # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # data_dic = {} # # try: # token = Token.objects.get(user=request.user) # mystatus = status.HTTP_200_OK # except: # token = Token.objects.create(user=request.user) # mystatus = status.HTTP_201_CREATED # # data_dic['token'] = token.key # return Response(data_dic, status=mystatus) # # class APIUserInfoViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # account = request.user # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # return Response(data) # # class FacebookLoginOrSignup(APIView): # # permission_classes = (AllowAny,) # # # this is a public api!!! # authentication_classes = (EverybodyCanAuthentication,) # # def dispatch(self, *args, **kwargs): # return super(FacebookLoginOrSignup, self).dispatch(*args, **kwargs) # # def post(self, request): # data = JSONParser().parse(request) # access_token = data.get('access_token', '') # # try: # app = SocialApp.objects.get(provider="facebook") # token = SocialToken(app=app, token=access_token) # # # check token against facebook # login = fb_complete_login(app, token) # login.token = token # login.state = SocialLogin.state_from_request(request) # # # add or update the user into users table # ret = complete_social_login(request, login) # # # if we get here we've succeeded # return Response(status=200, data={ # 'success': True, # 'username': request.user.username, # 'user_id': request.user.pk, # }) # # except: # # return Response(status=401 ,data={ # 'success': False, # 'reason': "Bad Access Token", # }) . Output only the next line.
path('token/', APITokenViewSet.as_view(), name='api-token'),
Continue the code snippet: <|code_start|> urlpatterns = [ path('login/', APILoginViewSet.as_view(), name='api-login'), path('logout/', APILogoutViewSet.as_view(), name='api-logout'), path('token/', APITokenViewSet.as_view(), name='api-token'), <|code_end|> . Use current file imports: from django.urls import include, path from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.views import obtain_auth_token from .api_views import APILoginViewSet, APILogoutViewSet, APITokenViewSet, APIUserInfoViewSet, FacebookLoginOrSignup and context (classes, functions, or code) from other files: # Path: server/apps/authentication/api_views.py # class APILoginViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # @csrf_exempt # def post(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # data = JSONParser().parse(request) # serializer = LoginCustomSerializer(data=data) # # if serializer.is_valid(): # email = serializer.data.get('email') # password = serializer.data.get('password') # # if not request.user.is_anonymous: # return Response('Already Logged-in', status=status.HTTP_403_FORBIDDEN) # # account = authenticate(email=email, password=password) # # if account is not None: # if account.is_active: # login(request, account) # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # # return Response(data) # else: # return Response('This account is not Active.', status=status.HTTP_401_UNAUTHORIZED) # else: # return Response('Username/password combination invalid.', status=status.HTTP_401_UNAUTHORIZED) # # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # # data_dic = {"Error":"GET not supported for this command"} # # logout(request) # mystatus = status.HTTP_400_BAD_REQUEST # # return Response(data_dic, status=mystatus) # # class APILogoutViewSet(APIView): # permission_classes = (permissions.IsAuthenticated,) # # def post(self, request, format=None): # logout(request) # # return Response({}, status=status.HTTP_204_NO_CONTENT) # # class APITokenViewSet(APIView): # """ # View to get User's token # """ # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # data_dic = {} # # try: # token = Token.objects.get(user=request.user) # mystatus = status.HTTP_200_OK # except: # token = Token.objects.create(user=request.user) # mystatus = status.HTTP_201_CREATED # # data_dic['token'] = token.key # return Response(data_dic, status=mystatus) # # class APIUserInfoViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # account = request.user # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # return Response(data) # # class FacebookLoginOrSignup(APIView): # # permission_classes = (AllowAny,) # # # this is a public api!!! # authentication_classes = (EverybodyCanAuthentication,) # # def dispatch(self, *args, **kwargs): # return super(FacebookLoginOrSignup, self).dispatch(*args, **kwargs) # # def post(self, request): # data = JSONParser().parse(request) # access_token = data.get('access_token', '') # # try: # app = SocialApp.objects.get(provider="facebook") # token = SocialToken(app=app, token=access_token) # # # check token against facebook # login = fb_complete_login(app, token) # login.token = token # login.state = SocialLogin.state_from_request(request) # # # add or update the user into users table # ret = complete_social_login(request, login) # # # if we get here we've succeeded # return Response(status=200, data={ # 'success': True, # 'username': request.user.username, # 'user_id': request.user.pk, # }) # # except: # # return Response(status=401 ,data={ # 'success': False, # 'reason': "Bad Access Token", # }) . Output only the next line.
path('user-info/', APIUserInfoViewSet.as_view(), name='api-user-info'),
Predict the next line for this snippet: <|code_start|> urlpatterns = [ path('login/', APILoginViewSet.as_view(), name='api-login'), path('logout/', APILogoutViewSet.as_view(), name='api-logout'), path('token/', APITokenViewSet.as_view(), name='api-token'), path('user-info/', APIUserInfoViewSet.as_view(), name='api-user-info'), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api-token-auth/', csrf_exempt(obtain_auth_token), name='api-token-auth'), <|code_end|> with the help of current file imports: from django.urls import include, path from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.views import obtain_auth_token from .api_views import APILoginViewSet, APILogoutViewSet, APITokenViewSet, APIUserInfoViewSet, FacebookLoginOrSignup and context from other files: # Path: server/apps/authentication/api_views.py # class APILoginViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # @csrf_exempt # def post(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # data = JSONParser().parse(request) # serializer = LoginCustomSerializer(data=data) # # if serializer.is_valid(): # email = serializer.data.get('email') # password = serializer.data.get('password') # # if not request.user.is_anonymous: # return Response('Already Logged-in', status=status.HTTP_403_FORBIDDEN) # # account = authenticate(email=email, password=password) # # if account is not None: # if account.is_active: # login(request, account) # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # # return Response(data) # else: # return Response('This account is not Active.', status=status.HTTP_401_UNAUTHORIZED) # else: # return Response('Username/password combination invalid.', status=status.HTTP_401_UNAUTHORIZED) # # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # # data_dic = {"Error":"GET not supported for this command"} # # logout(request) # mystatus = status.HTTP_400_BAD_REQUEST # # return Response(data_dic, status=mystatus) # # class APILogoutViewSet(APIView): # permission_classes = (permissions.IsAuthenticated,) # # def post(self, request, format=None): # logout(request) # # return Response({}, status=status.HTTP_204_NO_CONTENT) # # class APITokenViewSet(APIView): # """ # View to get User's token # """ # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # data_dic = {} # # try: # token = Token.objects.get(user=request.user) # mystatus = status.HTTP_200_OK # except: # token = Token.objects.create(user=request.user) # mystatus = status.HTTP_201_CREATED # # data_dic['token'] = token.key # return Response(data_dic, status=mystatus) # # class APIUserInfoViewSet(APIView): # """ # View to list all users in the system. # # * Requires token authentication. # * Only admin users are able to access this view. # """ # #permission_classes = () # # def get(self, request, format=None): # """ # Update thumbnail and tiny file field # """ # if request.user.is_anonymous: # # User most login before they can get a token # # This not only ensures the user has registered, and has an account # # but that the account is active # return Response('User not recognized.', status=status.HTTP_403_FORBIDDEN) # # account = request.user # # serialized = AccountSerializer(account) # data = serialized.data # # # Add the token to the return serialization # try: # token = Token.objects.get(user=account) # except: # token = Token.objects.create(user=account) # # data['token'] = token.key # # return Response(data) # # class FacebookLoginOrSignup(APIView): # # permission_classes = (AllowAny,) # # # this is a public api!!! # authentication_classes = (EverybodyCanAuthentication,) # # def dispatch(self, *args, **kwargs): # return super(FacebookLoginOrSignup, self).dispatch(*args, **kwargs) # # def post(self, request): # data = JSONParser().parse(request) # access_token = data.get('access_token', '') # # try: # app = SocialApp.objects.get(provider="facebook") # token = SocialToken(app=app, token=access_token) # # # check token against facebook # login = fb_complete_login(app, token) # login.token = token # login.state = SocialLogin.state_from_request(request) # # # add or update the user into users table # ret = complete_social_login(request, login) # # # if we get here we've succeeded # return Response(status=200, data={ # 'success': True, # 'username': request.user.username, # 'user_id': request.user.pk, # }) # # except: # # return Response(status=401 ,data={ # 'success': False, # 'reason': "Bad Access Token", # }) , which may contain function names, class names, or code. Output only the next line.
path('facebook-signup/?', csrf_exempt(FacebookLoginOrSignup.as_view()), name='facebook-login-signup'),
Given the code snippet: <|code_start|> class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth import update_session_auth_hash from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import Account and context (functions, classes, or occasionally code) from other files: # Path: server/apps/authentication/models.py # class Account(AbstractBaseUser): # # TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones] # # email = models.EmailField(unique=True) # username = models.CharField(max_length=40, unique=True) # slug = models.SlugField(max_length=60, unique=True) # # name = models.CharField(verbose_name='Full Name', max_length=120, blank=True) # tagline = models.CharField(max_length=260, blank=True) # # external_avatar_url = models.CharField(max_length=260, blank=True, null=True) # # is_staff = models.BooleanField(default=False) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # # objects = AccountManager() # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] # # class Meta: # ordering = ['slug'] # # def save(self, *args, **kwargs): # # slug = slugify(self.username) # self.slug = slug # count = 0 # while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists(): # self.slug = '{0}{1}'.format(slug, count) # logger.debug('Slug conflict. Trying again with {0}'.format(self.slug)) # count += 1 # # super(Account, self).save(*args, **kwargs) # # def __str__(self): # return '@{0}'.format(self.username) # # def get_full_name(self): # return self.name # # def get_short_name(self): # if (self.name != ''): # # Try to extract the first name # names = self.name.split() # first_name = names[0] # return first_name # return self.username # # # For full access to Permission system, we needed to add the PermissionMixin # def has_perm(self, perm, obj=None): # return True # # def has_perms(perm_list, obj=None): # return True # # def has_module_perms(self, app_label): # return True # # # Custom Methods # # -------------- # def get_absolute_url(self): # return '/account/%s/' % self.slug # # def get_edit_url(self): # return '%sedit/' % self.get_absolute_url() # # def get_token(self): # try: # token = Token.objects.get(user=self) # except: # token = Token.objects.create(user=self) # return token # # def get_gravatar_thumbnail_url(self, size=100): # # Set your variables here # email = self.email # default = 'identicon' # # # construct the url # gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?" # try: # # Python 3.4 # gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)}) # except: # # Python 2.7 # gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) # # return gravatar_url . Output only the next line.
model = Account
Given the following code snippet before the placeholder: <|code_start|> class APIMessageViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ <|code_end|> , predict the next line using imports from the current file: import json from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, status, viewsets from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAdminUser from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from .models import ContactMessage from .permissions import ContactMessagePermission from .serializers import ContactMessageSerializer from .tasks import send_contact_me_notification and context including class names, function names, and sometimes code from other files: # Path: server/apps/main/models.py # class ContactMessage(models.Model): # # name = models.CharField(max_length=50) # email = models.EmailField(max_length=60) # phone = models.CharField(max_length=50, blank=True) # message = models.TextField() # # created_on = models.DateTimeField('created_on', auto_now_add=True) # # class Meta: # ordering = ['id'] # # def __str__(self): # return self.name # # Path: server/apps/main/permissions.py # class ContactMessagePermission(permissions.BasePermission): # """ # Custom permission to only allow owners of an object to access (read/write) # """ # # def has_permission(self, request, view): # if request.method == 'POST': # return True # else: # return request.user.is_staff # # def has_object_permission(self, request, view, obj): # # Everybody can submit # return request.user.is_staff # # Path: server/apps/main/serializers.py # class ContactMessageSerializer(serializers.ModelSerializer): # class Meta: # model = ContactMessage # fields = ('id', 'name', 'email', 'phone', 'message', 'created_on') # read_only_fields = ('created_on') # # Path: server/apps/main/tasks.py # def send_contact_me_notification(instance): # ''' # Use SNS to notify Staff of person trying to contact # us via the Landing Page # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # message = '==========================\n' # message += '%s\n' % instance.name # message += '%s\n' % instance.email # message += '==========================\n' # message += instance.message # message += '\n' # message += '==========================\n' # # mail_admins(subject='New Message', message=message) # # return True . Output only the next line.
queryset = ContactMessage.objects.all()
Next line prediction: <|code_start|> class APIMessageViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = ContactMessage.objects.all() serializer_class = ContactMessageSerializer <|code_end|> . Use current file imports: (import json from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, status, viewsets from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAdminUser from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from .models import ContactMessage from .permissions import ContactMessagePermission from .serializers import ContactMessageSerializer from .tasks import send_contact_me_notification) and context including class names, function names, or small code snippets from other files: # Path: server/apps/main/models.py # class ContactMessage(models.Model): # # name = models.CharField(max_length=50) # email = models.EmailField(max_length=60) # phone = models.CharField(max_length=50, blank=True) # message = models.TextField() # # created_on = models.DateTimeField('created_on', auto_now_add=True) # # class Meta: # ordering = ['id'] # # def __str__(self): # return self.name # # Path: server/apps/main/permissions.py # class ContactMessagePermission(permissions.BasePermission): # """ # Custom permission to only allow owners of an object to access (read/write) # """ # # def has_permission(self, request, view): # if request.method == 'POST': # return True # else: # return request.user.is_staff # # def has_object_permission(self, request, view, obj): # # Everybody can submit # return request.user.is_staff # # Path: server/apps/main/serializers.py # class ContactMessageSerializer(serializers.ModelSerializer): # class Meta: # model = ContactMessage # fields = ('id', 'name', 'email', 'phone', 'message', 'created_on') # read_only_fields = ('created_on') # # Path: server/apps/main/tasks.py # def send_contact_me_notification(instance): # ''' # Use SNS to notify Staff of person trying to contact # us via the Landing Page # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # message = '==========================\n' # message += '%s\n' % instance.name # message += '%s\n' % instance.email # message += '==========================\n' # message += instance.message # message += '\n' # message += '==========================\n' # # mail_admins(subject='New Message', message=message) # # return True . Output only the next line.
permission_classes = (ContactMessagePermission,)
Given snippet: <|code_start|> class APIMessageViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = ContactMessage.objects.all() <|code_end|> , continue by predicting the next line. Consider current file imports: import json from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, status, viewsets from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAdminUser from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from .models import ContactMessage from .permissions import ContactMessagePermission from .serializers import ContactMessageSerializer from .tasks import send_contact_me_notification and context: # Path: server/apps/main/models.py # class ContactMessage(models.Model): # # name = models.CharField(max_length=50) # email = models.EmailField(max_length=60) # phone = models.CharField(max_length=50, blank=True) # message = models.TextField() # # created_on = models.DateTimeField('created_on', auto_now_add=True) # # class Meta: # ordering = ['id'] # # def __str__(self): # return self.name # # Path: server/apps/main/permissions.py # class ContactMessagePermission(permissions.BasePermission): # """ # Custom permission to only allow owners of an object to access (read/write) # """ # # def has_permission(self, request, view): # if request.method == 'POST': # return True # else: # return request.user.is_staff # # def has_object_permission(self, request, view, obj): # # Everybody can submit # return request.user.is_staff # # Path: server/apps/main/serializers.py # class ContactMessageSerializer(serializers.ModelSerializer): # class Meta: # model = ContactMessage # fields = ('id', 'name', 'email', 'phone', 'message', 'created_on') # read_only_fields = ('created_on') # # Path: server/apps/main/tasks.py # def send_contact_me_notification(instance): # ''' # Use SNS to notify Staff of person trying to contact # us via the Landing Page # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # message = '==========================\n' # message += '%s\n' % instance.name # message += '%s\n' % instance.email # message += '==========================\n' # message += instance.message # message += '\n' # message += '==========================\n' # # mail_admins(subject='New Message', message=message) # # return True which might include code, classes, or functions. Output only the next line.
serializer_class = ContactMessageSerializer
Given the following code snippet before the placeholder: <|code_start|> class APIMessageViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = ContactMessage.objects.all() serializer_class = ContactMessageSerializer permission_classes = (ContactMessagePermission,) def get_queryset(self): """ This view should return a list of all records for the currently authenticated user. """ #user = self.request.user return ContactMessage.objects.all() def perform_create(self, serializer): # Include the owner attribute directly, rather than from request data. instance = serializer.save() # Schedule a task to send email <|code_end|> , predict the next line using imports from the current file: import json from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, status, viewsets from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAdminUser from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from .models import ContactMessage from .permissions import ContactMessagePermission from .serializers import ContactMessageSerializer from .tasks import send_contact_me_notification and context including class names, function names, and sometimes code from other files: # Path: server/apps/main/models.py # class ContactMessage(models.Model): # # name = models.CharField(max_length=50) # email = models.EmailField(max_length=60) # phone = models.CharField(max_length=50, blank=True) # message = models.TextField() # # created_on = models.DateTimeField('created_on', auto_now_add=True) # # class Meta: # ordering = ['id'] # # def __str__(self): # return self.name # # Path: server/apps/main/permissions.py # class ContactMessagePermission(permissions.BasePermission): # """ # Custom permission to only allow owners of an object to access (read/write) # """ # # def has_permission(self, request, view): # if request.method == 'POST': # return True # else: # return request.user.is_staff # # def has_object_permission(self, request, view, obj): # # Everybody can submit # return request.user.is_staff # # Path: server/apps/main/serializers.py # class ContactMessageSerializer(serializers.ModelSerializer): # class Meta: # model = ContactMessage # fields = ('id', 'name', 'email', 'phone', 'message', 'created_on') # read_only_fields = ('created_on') # # Path: server/apps/main/tasks.py # def send_contact_me_notification(instance): # ''' # Use SNS to notify Staff of person trying to contact # us via the Landing Page # # :param instance: ContactMessage object to email # :return: Nothing # ''' # # message = '==========================\n' # message += '%s\n' % instance.name # message += '%s\n' % instance.email # message += '==========================\n' # message += instance.message # message += '\n' # message += '==========================\n' # # mail_admins(subject='New Message', message=message) # # return True . Output only the next line.
send_contact_me_notification(instance)
Predict the next line for this snippet: <|code_start|> SOURCES = { "census": census_loading, "epa": epa_loading, <|code_end|> with the help of current file imports: import os import sys import argparse from sitegeist.data.census import loading as census_loading from sitegeist.data.epa import loading as epa_loading from sitegeist.data.locations import loading as locations_loading from sitegeist.data.schools import loading as schools_loading from sitegeist.data import conf and context from other files: # Path: sitegeist/data/census/loading.py # def _chunks(l, n): # def reset(): # def load_tracts(): # def load_tract_records(keys): # def load(): # # Path: sitegeist/data/epa/loading.py # def load(): # # Path: sitegeist/data/locations/loading.py # def _dl_path(): # def name_func(state, field): # def inner(feature): # def slug_func(field): # def inner(feature): # def label_point_func(feature): # def avg(items): # def reset(): # def load_tracts(): # def load_zcta_boundaries(): # def load_tract_boundaries(): # def load(force=False): # # Path: sitegeist/data/schools/loading.py # DATA_URL = "http://nces.ed.gov/ccd/data/zip/sc091a_csv.zip" # def load(): # # Path: sitegeist/data/conf.py # def load_config(path): , which may contain function names, class names, or code. Output only the next line.
"locations": locations_loading,
Based on the snippet: <|code_start|> SOURCES = { "census": census_loading, "epa": epa_loading, "locations": locations_loading, <|code_end|> , predict the immediate next line with the help of imports: import os import sys import argparse from sitegeist.data.census import loading as census_loading from sitegeist.data.epa import loading as epa_loading from sitegeist.data.locations import loading as locations_loading from sitegeist.data.schools import loading as schools_loading from sitegeist.data import conf and context (classes, functions, sometimes code) from other files: # Path: sitegeist/data/census/loading.py # def _chunks(l, n): # def reset(): # def load_tracts(): # def load_tract_records(keys): # def load(): # # Path: sitegeist/data/epa/loading.py # def load(): # # Path: sitegeist/data/locations/loading.py # def _dl_path(): # def name_func(state, field): # def inner(feature): # def slug_func(field): # def inner(feature): # def label_point_func(feature): # def avg(items): # def reset(): # def load_tracts(): # def load_zcta_boundaries(): # def load_tract_boundaries(): # def load(force=False): # # Path: sitegeist/data/schools/loading.py # DATA_URL = "http://nces.ed.gov/ccd/data/zip/sc091a_csv.zip" # def load(): # # Path: sitegeist/data/conf.py # def load_config(path): . Output only the next line.
"schools": schools_loading,
Using the snippet: <|code_start|> SOURCES = { "census": census_loading, "epa": epa_loading, "locations": locations_loading, "schools": schools_loading, } if __name__ == "__main__": parser = argparse.ArgumentParser(description="Load Sitegeist data sources") parser.add_argument("sources", metavar="SOURCES", nargs="+", help="one or more source: %s" % ", ".join(sorted(SOURCES.keys()))) parser.add_argument("-c", "--config", dest="config", metavar='PATH', help="path to config file") parser.add_argument("-d", "--dryrun", dest="dryrun", action="store_true", help="load data source, but do not save to database") args = parser.parse_args() if args.config: path = os.path.abspath(os.path.expandvars(os.path.expanduser(args.config))) <|code_end|> , determine the next line of code. You have imports: import os import sys import argparse from sitegeist.data.census import loading as census_loading from sitegeist.data.epa import loading as epa_loading from sitegeist.data.locations import loading as locations_loading from sitegeist.data.schools import loading as schools_loading from sitegeist.data import conf and context (class names, function names, or code) available: # Path: sitegeist/data/census/loading.py # def _chunks(l, n): # def reset(): # def load_tracts(): # def load_tract_records(keys): # def load(): # # Path: sitegeist/data/epa/loading.py # def load(): # # Path: sitegeist/data/locations/loading.py # def _dl_path(): # def name_func(state, field): # def inner(feature): # def slug_func(field): # def inner(feature): # def label_point_func(feature): # def avg(items): # def reset(): # def load_tracts(): # def load_zcta_boundaries(): # def load_tract_boundaries(): # def load(force=False): # # Path: sitegeist/data/schools/loading.py # DATA_URL = "http://nces.ed.gov/ccd/data/zip/sc091a_csv.zip" # def load(): # # Path: sitegeist/data/conf.py # def load_config(path): . Output only the next line.
conf.load_config(path)