Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
Args:
ion (str): name of atom that was intercalated, e.g. 'Li'.
fmt (str): matplotlib format style. Check the matplotlib
docs for options.
"""
# Calculated with the relax() function in
# twod_materials.stability.startup. If you are using other input
# parameters, you need to recalculate these values!
ion_ev_fu = {'Li': -1.7540797, 'Mg': -1.31976062, 'Al': -3.19134607}
energy = Vasprun('vasprun.xml').final_energy
composition = Structure.from_file('POSCAR').composition
# Get the formula (with single-digit integers preceded by a '_').
twod_material = list(composition.reduced_formula)
twod_formula = str()
for i in range(len(twod_material)):
try:
int(twod_material[i])
twod_formula += '_{}'.format(twod_material[i])
except:
twod_formula += twod_material[i]
twod_ev_fu = energy / composition.get_reduced_composition_and_factor()[1]
data = [(0, 0, 0, twod_ev_fu)] # (at% ion, n_ions, E_F, abs_energy)
for directory in [
dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)]:
<|code_end|>
using the current file's imports:
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import operator
from scipy.spatial import ConvexHull
from twod_materials.utils import is_converged
from pymatgen.core.structure import Structure
from pymatgen.core.composition import Composition
from pymatgen.io.vasp.outputs import Vasprun
and any relevant context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
. Output only the next line. | if is_converged(directory): |
Based on the snippet: <|code_start|>from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
converged = {}
for directory in directories:
os.chdir(directory)
converged[directory] = False
<|code_end|>
, predict the immediate next line with the help of imports:
from twod_materials.friction.startup import run_friction_calculations
from twod_materials.friction.analysis import plot_gamma_surface
from twod_materials.utils import is_converged
import os
import time
and context (classes, functions, sometimes code) from other files:
# Path: twod_materials/friction/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def run_gamma_calculations(submit=True, step_size=0.5):
# def run_normal_force_calculations(basin_and_saddle_dirs,
# spacings=np.arange(1.5, 4.25, 0.25),
# submit=True):
#
# Path: twod_materials/friction/analysis.py
# def plot_gamma_surface(fmt='pdf'):
# """
# Collect the energies from a grid of static energy
# calculations to plot the Gamma surface between two layers of the 2D
# material.
#
# Args:
# fmt (str): matplotlib format style. Check the matplotlib
# docs for options.
# """
#
# os.chdir('friction/lateral')
#
# static_dirs = [
# d.split('x') for d in os.listdir(os.getcwd()) if 'x' in d and
# len(d) == 3
# ]
#
# n_divs_x = max([int(d[0]) for d in static_dirs])
# n_divs_y = max([int(d[1]) for d in static_dirs])
#
# lattice = Structure.from_file('POSCAR').lattice
# area = np.cross(lattice._matrix[0], lattice._matrix[1])[2]
#
# ax = plt.figure(figsize=(n_divs_x * 1.2, n_divs_y * 1.2)).gca()
#
# ax.set_xlim(0, n_divs_x + 1)
# ax.set_ylim(0, n_divs_y + 1)
#
# ENERGY_ARRAY = []
#
# X_VALUES = range(n_divs_x + 1)
# Y_VALUES = range(n_divs_y + 1)
#
# not_converged = []
# for x in X_VALUES:
# ENERGY_ARRAY.append([])
# for y in Y_VALUES:
# dir = '{}x{}'.format(x, y)
# os.chdir(dir)
# try:
# energy = Vasprun('vasprun.xml').final_energy / area
# ENERGY_ARRAY[x].append(energy)
# except:
# not_converged.append('{}x{}'.format(x, y))
# ENERGY_ARRAY[x].append(0)
# os.chdir('../')
# ENERGY_ARRAY[x].append(ENERGY_ARRAY[x][0])
#
# ENERGY_ARRAY.append([])
# #ENERGY_ARRAY[n_divs_x] = ENERGY_ARRAY[0]
#
# if not_converged:
# warnings.warn('{} did not converge.'.format(not_converged))
# for coords in not_converged:
# ENERGY_ARRAY[
# int(coords.split('x')[0])][int(coords.split('x')[1])] = energy
#
# minima = []
# maxima = []
# for x in X_VALUES:
# minima.append(min(ENERGY_ARRAY[x]))
# maxima.append(max(ENERGY_ARRAY[x]))
#
# abs_minimum = min(minima)
# abs_maximum = max(maxima)
#
# for x in range(n_divs_x + 1):
# for y in range(n_divs_y + 1):
#
# # Plot all energies relative to the global minimum.
# scaled_energy = ENERGY_ARRAY[x][y] - abs_minimum
# if '{}x{}'.format(x, y) in not_converged:
# color_code = 'w'
# else:
# color_code = plt.cm.jet(
# scaled_energy / (abs_maximum - abs_minimum)
# )
#
# ax.add_patch(plt.Rectangle((x, y), width=1, height=1,
# facecolor=color_code,
# linewidth=0))
#
# # Get rid of annoying ticks.
# ax.axes.get_yaxis().set_ticks([])
# ax.axes.get_xaxis().set_ticks([])
#
# os.chdir('../../')
#
# plt.savefig('gamma_surface.{}'.format(fmt), transparent=True)
# plt.close()
#
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
. Output only the next line. | run_friction_calculations() |
Here is a snippet: <|code_start|> converged = {}
for directory in directories:
os.chdir(directory)
converged[directory] = False
run_friction_calculations()
os.chdir('../')
loop = True
while loop:
time.sleep(INTERVAL)
loop = False
for directory in directories:
os.chdir(directory)
converged[directory] = True
for subdirectory in [
dir for dir in os.listdir(os.getcwd())
if os.path.isdir(dir)]:
if not is_converged(subdirectory):
converged[directory] = False
break
if not converged[directory]:
print('>> Not all directories converged')
loop = True
print('>> Plotting gamma surface for {}'.format(directory))
<|code_end|>
. Write the next line using the current file imports:
from twod_materials.friction.startup import run_friction_calculations
from twod_materials.friction.analysis import plot_gamma_surface
from twod_materials.utils import is_converged
import os
import time
and context from other files:
# Path: twod_materials/friction/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def run_gamma_calculations(submit=True, step_size=0.5):
# def run_normal_force_calculations(basin_and_saddle_dirs,
# spacings=np.arange(1.5, 4.25, 0.25),
# submit=True):
#
# Path: twod_materials/friction/analysis.py
# def plot_gamma_surface(fmt='pdf'):
# """
# Collect the energies from a grid of static energy
# calculations to plot the Gamma surface between two layers of the 2D
# material.
#
# Args:
# fmt (str): matplotlib format style. Check the matplotlib
# docs for options.
# """
#
# os.chdir('friction/lateral')
#
# static_dirs = [
# d.split('x') for d in os.listdir(os.getcwd()) if 'x' in d and
# len(d) == 3
# ]
#
# n_divs_x = max([int(d[0]) for d in static_dirs])
# n_divs_y = max([int(d[1]) for d in static_dirs])
#
# lattice = Structure.from_file('POSCAR').lattice
# area = np.cross(lattice._matrix[0], lattice._matrix[1])[2]
#
# ax = plt.figure(figsize=(n_divs_x * 1.2, n_divs_y * 1.2)).gca()
#
# ax.set_xlim(0, n_divs_x + 1)
# ax.set_ylim(0, n_divs_y + 1)
#
# ENERGY_ARRAY = []
#
# X_VALUES = range(n_divs_x + 1)
# Y_VALUES = range(n_divs_y + 1)
#
# not_converged = []
# for x in X_VALUES:
# ENERGY_ARRAY.append([])
# for y in Y_VALUES:
# dir = '{}x{}'.format(x, y)
# os.chdir(dir)
# try:
# energy = Vasprun('vasprun.xml').final_energy / area
# ENERGY_ARRAY[x].append(energy)
# except:
# not_converged.append('{}x{}'.format(x, y))
# ENERGY_ARRAY[x].append(0)
# os.chdir('../')
# ENERGY_ARRAY[x].append(ENERGY_ARRAY[x][0])
#
# ENERGY_ARRAY.append([])
# #ENERGY_ARRAY[n_divs_x] = ENERGY_ARRAY[0]
#
# if not_converged:
# warnings.warn('{} did not converge.'.format(not_converged))
# for coords in not_converged:
# ENERGY_ARRAY[
# int(coords.split('x')[0])][int(coords.split('x')[1])] = energy
#
# minima = []
# maxima = []
# for x in X_VALUES:
# minima.append(min(ENERGY_ARRAY[x]))
# maxima.append(max(ENERGY_ARRAY[x]))
#
# abs_minimum = min(minima)
# abs_maximum = max(maxima)
#
# for x in range(n_divs_x + 1):
# for y in range(n_divs_y + 1):
#
# # Plot all energies relative to the global minimum.
# scaled_energy = ENERGY_ARRAY[x][y] - abs_minimum
# if '{}x{}'.format(x, y) in not_converged:
# color_code = 'w'
# else:
# color_code = plt.cm.jet(
# scaled_energy / (abs_maximum - abs_minimum)
# )
#
# ax.add_patch(plt.Rectangle((x, y), width=1, height=1,
# facecolor=color_code,
# linewidth=0))
#
# # Get rid of annoying ticks.
# ax.axes.get_yaxis().set_ticks([])
# ax.axes.get_xaxis().set_ticks([])
#
# os.chdir('../../')
#
# plt.savefig('gamma_surface.{}'.format(fmt), transparent=True)
# plt.close()
#
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
, which may include functions, classes, or code. Output only the next line. | plot_gamma_surface() |
Using the snippet: <|code_start|>
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
converged = {}
for directory in directories:
os.chdir(directory)
converged[directory] = False
run_friction_calculations()
os.chdir('../')
loop = True
while loop:
time.sleep(INTERVAL)
loop = False
for directory in directories:
os.chdir(directory)
converged[directory] = True
for subdirectory in [
dir for dir in os.listdir(os.getcwd())
if os.path.isdir(dir)]:
<|code_end|>
, determine the next line of code. You have imports:
from twod_materials.friction.startup import run_friction_calculations
from twod_materials.friction.analysis import plot_gamma_surface
from twod_materials.utils import is_converged
import os
import time
and context (class names, function names, or code) available:
# Path: twod_materials/friction/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def run_gamma_calculations(submit=True, step_size=0.5):
# def run_normal_force_calculations(basin_and_saddle_dirs,
# spacings=np.arange(1.5, 4.25, 0.25),
# submit=True):
#
# Path: twod_materials/friction/analysis.py
# def plot_gamma_surface(fmt='pdf'):
# """
# Collect the energies from a grid of static energy
# calculations to plot the Gamma surface between two layers of the 2D
# material.
#
# Args:
# fmt (str): matplotlib format style. Check the matplotlib
# docs for options.
# """
#
# os.chdir('friction/lateral')
#
# static_dirs = [
# d.split('x') for d in os.listdir(os.getcwd()) if 'x' in d and
# len(d) == 3
# ]
#
# n_divs_x = max([int(d[0]) for d in static_dirs])
# n_divs_y = max([int(d[1]) for d in static_dirs])
#
# lattice = Structure.from_file('POSCAR').lattice
# area = np.cross(lattice._matrix[0], lattice._matrix[1])[2]
#
# ax = plt.figure(figsize=(n_divs_x * 1.2, n_divs_y * 1.2)).gca()
#
# ax.set_xlim(0, n_divs_x + 1)
# ax.set_ylim(0, n_divs_y + 1)
#
# ENERGY_ARRAY = []
#
# X_VALUES = range(n_divs_x + 1)
# Y_VALUES = range(n_divs_y + 1)
#
# not_converged = []
# for x in X_VALUES:
# ENERGY_ARRAY.append([])
# for y in Y_VALUES:
# dir = '{}x{}'.format(x, y)
# os.chdir(dir)
# try:
# energy = Vasprun('vasprun.xml').final_energy / area
# ENERGY_ARRAY[x].append(energy)
# except:
# not_converged.append('{}x{}'.format(x, y))
# ENERGY_ARRAY[x].append(0)
# os.chdir('../')
# ENERGY_ARRAY[x].append(ENERGY_ARRAY[x][0])
#
# ENERGY_ARRAY.append([])
# #ENERGY_ARRAY[n_divs_x] = ENERGY_ARRAY[0]
#
# if not_converged:
# warnings.warn('{} did not converge.'.format(not_converged))
# for coords in not_converged:
# ENERGY_ARRAY[
# int(coords.split('x')[0])][int(coords.split('x')[1])] = energy
#
# minima = []
# maxima = []
# for x in X_VALUES:
# minima.append(min(ENERGY_ARRAY[x]))
# maxima.append(max(ENERGY_ARRAY[x]))
#
# abs_minimum = min(minima)
# abs_maximum = max(maxima)
#
# for x in range(n_divs_x + 1):
# for y in range(n_divs_y + 1):
#
# # Plot all energies relative to the global minimum.
# scaled_energy = ENERGY_ARRAY[x][y] - abs_minimum
# if '{}x{}'.format(x, y) in not_converged:
# color_code = 'w'
# else:
# color_code = plt.cm.jet(
# scaled_energy / (abs_maximum - abs_minimum)
# )
#
# ax.add_patch(plt.Rectangle((x, y), width=1, height=1,
# facecolor=color_code,
# linewidth=0))
#
# # Get rid of annoying ticks.
# ax.axes.get_yaxis().set_ticks([])
# ax.axes.get_xaxis().set_ticks([])
#
# os.chdir('../../')
#
# plt.savefig('gamma_surface.{}'.format(fmt), transparent=True)
# plt.close()
#
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
. Output only the next line. | if not is_converged(subdirectory): |
Predict the next line for this snippet: <|code_start|>"""
Relaxes 2D materials in all subdirectories of the current working
directory, along with their most stable competing species. At a
specified INTERVAL, checks if all relaxations have converged. Once all
are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
for directory in directories:
os.chdir(directory)
run_linemode_calculation()
os.chdir('../')
loop = True
while loop:
print('>> Checking convergence')
finished = []
for directory in directories:
<|code_end|>
with the help of current file imports:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.electronic_structure.startup import (
run_linemode_calculation
)
from twod_materials.electronic_structure.analysis import (
plot_normal_band_structure
)
and context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/electronic_structure/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# PBE_INCAR_DICT = {'EDIFF': 1e-6, 'IBRION': 2, 'ISIF': 3,
# 'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True,
# 'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4,
# 'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1,
# 'ENCUT': 500, 'ISPIN': 2}
# HSE_INCAR_DICT = {'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25,
# 'ALGO': 'D', 'TIME': 0.4, 'NSW': 0,
# 'LVTOT': True, 'LVHAR': True, 'LORBIT': 11,
# 'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate',
# 'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1,
# 'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2}
# def run_pbe_calculation(dim=2, submit=True, force_overwrite=False):
# def run_hse_prep_calculation(dim=2, submit=True):
# def run_hse_calculation(dim=2, submit=True, force_overwrite=False,
# destroy_prep_directory=False):
#
# Path: twod_materials/electronic_structure/analysis.py
# def get_band_edges():
# def plot_band_alignments(directories, run_type='PBE', fmt='pdf'):
# def plot_local_potential(axis=2, ylim=(-20, 0), fmt='pdf'):
# def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt='pdf'):
# def plot_color_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_elt_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_orb_projected_bands(orbitals, fmt='pdf', ylim=(-5, 5)):
# def get_effective_mass():
# def plot_density_of_states(fmt='pdf'):
# def get_fermi_velocities():
# def find_dirac_nodes():
# def plot_spin_texture(inner_index, outer_index, center=(0, 0), fmt='pdf'):
# H_BAR = 6.582119514e-16 # eV*s
# M_0 = 9.10938356e-31 # kg
# N_KPTS = 6 # Number of k-points included in the parabola.
# E = {'electron': {'left': [], 'right': []},
# 'hole': {'left': [], 'right': []}}
, which may contain function names, class names, or code. Output only the next line. | if is_converged('{}/pbe_bands'.format(directory)): |
Predict the next line after this snippet: <|code_start|>"""
Relaxes 2D materials in all subdirectories of the current working
directory, along with their most stable competing species. At a
specified INTERVAL, checks if all relaxations have converged. Once all
are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
for directory in directories:
os.chdir(directory)
<|code_end|>
using the current file's imports:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.electronic_structure.startup import (
run_linemode_calculation
)
from twod_materials.electronic_structure.analysis import (
plot_normal_band_structure
)
and any relevant context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/electronic_structure/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# PBE_INCAR_DICT = {'EDIFF': 1e-6, 'IBRION': 2, 'ISIF': 3,
# 'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True,
# 'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4,
# 'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1,
# 'ENCUT': 500, 'ISPIN': 2}
# HSE_INCAR_DICT = {'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25,
# 'ALGO': 'D', 'TIME': 0.4, 'NSW': 0,
# 'LVTOT': True, 'LVHAR': True, 'LORBIT': 11,
# 'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate',
# 'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1,
# 'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2}
# def run_pbe_calculation(dim=2, submit=True, force_overwrite=False):
# def run_hse_prep_calculation(dim=2, submit=True):
# def run_hse_calculation(dim=2, submit=True, force_overwrite=False,
# destroy_prep_directory=False):
#
# Path: twod_materials/electronic_structure/analysis.py
# def get_band_edges():
# def plot_band_alignments(directories, run_type='PBE', fmt='pdf'):
# def plot_local_potential(axis=2, ylim=(-20, 0), fmt='pdf'):
# def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt='pdf'):
# def plot_color_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_elt_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_orb_projected_bands(orbitals, fmt='pdf', ylim=(-5, 5)):
# def get_effective_mass():
# def plot_density_of_states(fmt='pdf'):
# def get_fermi_velocities():
# def find_dirac_nodes():
# def plot_spin_texture(inner_index, outer_index, center=(0, 0), fmt='pdf'):
# H_BAR = 6.582119514e-16 # eV*s
# M_0 = 9.10938356e-31 # kg
# N_KPTS = 6 # Number of k-points included in the parabola.
# E = {'electron': {'left': [], 'right': []},
# 'hole': {'left': [], 'right': []}}
. Output only the next line. | run_linemode_calculation() |
Here is a snippet: <|code_start|>from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
for directory in directories:
os.chdir(directory)
run_linemode_calculation()
os.chdir('../')
loop = True
while loop:
print('>> Checking convergence')
finished = []
for directory in directories:
if is_converged('{}/pbe_bands'.format(directory)):
finished.append(directory)
if len(finished) == len(directories):
print('>> Plotting band structures')
for directory in finished:
os.chdir('{}/pbe_bands'.format(directory))
<|code_end|>
. Write the next line using the current file imports:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.electronic_structure.startup import (
run_linemode_calculation
)
from twod_materials.electronic_structure.analysis import (
plot_normal_band_structure
)
and context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/electronic_structure/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# PBE_INCAR_DICT = {'EDIFF': 1e-6, 'IBRION': 2, 'ISIF': 3,
# 'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True,
# 'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4,
# 'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1,
# 'ENCUT': 500, 'ISPIN': 2}
# HSE_INCAR_DICT = {'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25,
# 'ALGO': 'D', 'TIME': 0.4, 'NSW': 0,
# 'LVTOT': True, 'LVHAR': True, 'LORBIT': 11,
# 'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate',
# 'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1,
# 'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2}
# def run_pbe_calculation(dim=2, submit=True, force_overwrite=False):
# def run_hse_prep_calculation(dim=2, submit=True):
# def run_hse_calculation(dim=2, submit=True, force_overwrite=False,
# destroy_prep_directory=False):
#
# Path: twod_materials/electronic_structure/analysis.py
# def get_band_edges():
# def plot_band_alignments(directories, run_type='PBE', fmt='pdf'):
# def plot_local_potential(axis=2, ylim=(-20, 0), fmt='pdf'):
# def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt='pdf'):
# def plot_color_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_elt_projected_bands(ylim=(-5, 5), fmt='pdf'):
# def plot_orb_projected_bands(orbitals, fmt='pdf', ylim=(-5, 5)):
# def get_effective_mass():
# def plot_density_of_states(fmt='pdf'):
# def get_fermi_velocities():
# def find_dirac_nodes():
# def plot_spin_texture(inner_index, outer_index, center=(0, 0), fmt='pdf'):
# H_BAR = 6.582119514e-16 # eV*s
# M_0 = 9.10938356e-31 # kg
# N_KPTS = 6 # Number of k-points included in the parabola.
# E = {'electron': {'left': [], 'right': []},
# 'hole': {'left': [], 'right': []}}
, which may include functions, classes, or code. Output only the next line. | plot_normal_band_structure() |
Using the snippet: <|code_start|> bs = vasprun.get_band_structure()
cbm = bs.get_cbm()['energy'] - evac
vbm = bs.get_vbm()['energy'] - evac
edges = {'cbm': cbm, 'vbm': vbm, 'efermi': efermi}
return edges
def plot_band_alignments(directories, run_type='PBE', fmt='pdf'):
"""
Plot CBM's and VBM's of all compounds together, relative to the band
edges of H2O.
Args:
directories (list): list of the directory paths for materials
to include in the plot.
run_type (str): 'PBE' or 'HSE', so that the function knows which
subdirectory to go into (pbe_bands or hse_bands).
fmt (str): matplotlib format style. Check the matplotlib
docs for options.
"""
if run_type == 'HSE':
subdirectory = 'hse_bands'
else:
subdirectory = 'pbe_bands'
band_gaps = {}
for directory in directories:
<|code_end|>
, determine the next line of code. You have imports:
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.core.operations import SymmOp
from pymatgen.io.vasp.outputs import Vasprun, Locpot, VolumetricData
from pymatgen.io.vasp.inputs import Incar
from pymatgen.electronic_structure.plotter import BSPlotter, BSPlotterProjected
from pymatgen.electronic_structure.bandstructure import BandStructure
from pymatgen.electronic_structure.core import Spin
from twod_materials.utils import is_converged
and context (class names, function names, or code) available:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
. Output only the next line. | if is_converged('{}/{}'.format(directory, subdirectory)): |
Given snippet: <|code_start|> submission_command = 'qsub runjob'
elif QUEUE == 'slurm':
write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP)
submission_command = 'sbatch runjob'
if submit:
os.system(submission_command)
os.chdir('../')
def run_hse_prep_calculation(dim=2, submit=True):
"""
Submits a quick static calculation to calculate the IBZKPT
file using a smaller number of k-points (200/atom instead of
1000/atom). The other outputs from this calculation are
essentially useless.
Args:
dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
submit (bool): Whether or not to submit the job.
"""
if not os.path.isdir('hse_prep'):
os.mkdir('hse_prep')
os.chdir('hse_prep')
os.system('cp ../CONTCAR ./POSCAR')
if os.path.isfile('../POTCAR'):
os.system('cp POTCAR .')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import math
import twod_materials
from twod_materials.utils import *
from twod_materials.stability.startup import relax
from pymatgen.io.vasp.inputs import Kpoints, Incar
from pymatgen.symmetry.bandstructure import HighSymmKpath
from pymatgen.core.structure import Structure
from monty.serialization import loadfn
and context:
# Path: twod_materials/stability/startup.py
# def relax(dim=2, submit=True, force_overwrite=False):
# """
# Writes input files and (optionally) submits a self-consistent
# relaxation. Should be run before pretty much anything else, in
# order to get the right energy and structure of the material.
#
# Args:
# dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
# submit (bool): Whether or not to submit the job.
# force_overwrite (bool): Whether or not to overwrite files
# if an already converged vasprun.xml exists in the
# directory.
# """
#
# if force_overwrite or not utl.is_converged(os.getcwd()):
# directory = os.getcwd().split('/')[-1]
#
# # vdw_kernel.bindat file required for VDW calculations.
# if VDW_KERNEL != '/path/to/vdw_kernel.bindat':
# os.system('cp {} .'.format(VDW_KERNEL))
# # KPOINTS
# Kpoints.automatic_density(Structure.from_file('POSCAR'),
# 1000).write_file('KPOINTS')
#
# # INCAR
# INCAR_DICT.update({'MAGMOM': utl.get_magmom_string()})
# Incar.from_dict(INCAR_DICT).write_file('INCAR')
# # POTCAR
# utl.write_potcar()
#
# # Special tasks only performed for 2D materials.
# if dim == 2:
# # Ensure 20A interlayer vacuum
# utl.add_vacuum(20 - utl.get_spacing(), 0.9)
# # Remove all z k-points.
# kpts_lines = open('KPOINTS').readlines()
# with open('KPOINTS', 'w') as kpts:
# for line in kpts_lines[:3]:
# kpts.write(line)
# kpts.write(kpts_lines[3].split()[0] + ' '
# + kpts_lines[3].split()[1] + ' 1')
#
# # Submission script
# if QUEUE == 'pbs':
# utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00',
# VASP_2D)
# submission_command = 'qsub runjob'
#
# elif QUEUE == 'slurm':
# utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00',
# VASP_2D)
# submission_command = 'sbatch runjob'
#
# if submit:
# os.system(submission_command)
which might include code, classes, or functions. Output only the next line. | relax(dim=2, submit=False) |
Next line prediction: <|code_start|>are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
competing_species = get_competing_species(directories)
relax_competing_species(competing_species)
for directory in directories:
os.chdir(directory)
relax()
os.chdir('../')
loop = True
while loop:
print('>> Checking convergence')
finished_2d, finished_3d = [], []
for directory in directories:
<|code_end|>
. Use current file imports:
(import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances))
and context including class names, function names, or small code snippets from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | if is_converged(directory): |
Given the following code snippet before the placeholder: <|code_start|>"""
Relaxes 2D materials in all subdirectories of the current working
directory, along with their most stable competing species. At a
specified INTERVAL, checks if all relaxations have converged. Once all
are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
competing_species = get_competing_species(directories)
relax_competing_species(competing_species)
for directory in directories:
os.chdir(directory)
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances)
and context including class names, function names, and sometimes code from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | relax() |
Based on the snippet: <|code_start|>"""
Relaxes 2D materials in all subdirectories of the current working
directory, along with their most stable competing species. At a
specified INTERVAL, checks if all relaxations have converged. Once all
are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
competing_species = get_competing_species(directories)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances)
and context (classes, functions, sometimes code) from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | relax_competing_species(competing_species) |
Given the following code snippet before the placeholder: <|code_start|>"""
Relaxes 2D materials in all subdirectories of the current working
directory, along with their most stable competing species. At a
specified INTERVAL, checks if all relaxations have converged. Once all
are converged, calculates and plots the formation energies of all 2D
materials as stability_plot.pdf.
"""
from __future__ import print_function, division, unicode_literals
INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances)
and context including class names, function names, and sometimes code from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | competing_species = get_competing_species(directories) |
Given the code snippet: <|code_start|>INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
competing_species = get_competing_species(directories)
relax_competing_species(competing_species)
for directory in directories:
os.chdir(directory)
relax()
os.chdir('../')
loop = True
while loop:
print('>> Checking convergence')
finished_2d, finished_3d = [], []
for directory in directories:
if is_converged(directory):
finished_2d.append(directory)
for directory in competing_species:
if is_converged('all_competitors/{}'.format(directory[0])):
finished_3d.append(directory[0])
if len(finished_2d + finished_3d) == len(
directories + competing_species):
print('>> Plotting hull distances')
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances)
and context (functions, classes, or occasionally code) from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | plot_hull_distances(get_hull_distances(finished_2d)) |
Predict the next line after this snippet: <|code_start|>INTERVAL = 360 # Seconds between convergence checks
directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
and dir not in ['all_competitors']]
if __name__ == '__main__':
competing_species = get_competing_species(directories)
relax_competing_species(competing_species)
for directory in directories:
os.chdir(directory)
relax()
os.chdir('../')
loop = True
while loop:
print('>> Checking convergence')
finished_2d, finished_3d = [], []
for directory in directories:
if is_converged(directory):
finished_2d.append(directory)
for directory in competing_species:
if is_converged('all_competitors/{}'.format(directory[0])):
finished_3d.append(directory[0])
if len(finished_2d + finished_3d) == len(
directories + competing_species):
print('>> Plotting hull distances')
<|code_end|>
using the current file's imports:
import os
import time
from twod_materials.utils import is_converged
from twod_materials.stability.startup import relax, relax_competing_species
from twod_materials.stability.analysis import (get_competing_species,
get_hull_distances,
plot_hull_distances)
and any relevant context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
#
# Path: twod_materials/stability/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# INCAR_DICT = {
# '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0,
# 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1,
# 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True,
# 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22,
# 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True,
# 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2
# }
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
# QUEUE = config_vars['queue_system'].lower()
# QUEUE = 'slurm'
# QUEUE = 'pbs'
# def relax(dim=2, submit=True, force_overwrite=False):
#
# Path: twod_materials/stability/analysis.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# MPR = MPRester(os.environ['MP_API'])
# MPR = MPRester(config_vars['mp_api'])
# def get_competing_phases():
# def get_hull_distance(competing_phase_directory='../competing_phases'):
# def plot_hull_distances(hull_distances, fmt='pdf'):
. Output only the next line. | plot_hull_distances(get_hull_distances(finished_2d)) |
Predict the next line for this snippet: <|code_start|> entry.entry_id) for entry in decomp[0]
]
return competing_phases
def get_hull_distance(competing_phase_directory='../competing_phases'):
"""
Calculate the material's distance to the thermodynamic hull,
based on species in the Materials Project database.
Args:
competing_phase_directory (str): absolute or relative path
to the location where your competing phases have been
relaxed. The default expectation is that they are stored
in a directory named 'competing_phases' at the same level
as your material's relaxation directory.
Returns:
float. distance (eV/atom) between the material and the
hull.
"""
finished_competitors = {}
original_directory = os.getcwd()
# Determine which competing phases have been relaxed in the current
# framework and store them in a dictionary ({formula: entry}).
if os.path.isdir(competing_phase_directory):
os.chdir(competing_phase_directory)
for comp_dir in [
dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir) and
<|code_end|>
with the help of current file imports:
import os
import operator
import matplotlib as mpl
import matplotlib.pyplot as plt
import twod_materials
from pymatgen.phasediagram.analyzer import PDAnalyzer
from pymatgen.phasediagram.maker import PhaseDiagram
from pymatgen.core.structure import Structure
from pymatgen.io.vasp.outputs import Vasprun
from pymatgen.entries.computed_entries import ComputedEntry
from pymatgen.matproj.rest import MPRester
from monty.serialization import loadfn
from twod_materials.utils import is_converged
and context from other files:
# Path: twod_materials/utils.py
# def is_converged(directory):
# """
# Check if a relaxation has converged.
#
# Args:
# directory (str): path to directory to check.
#
# Returns:
# boolean. Whether or not the job is converged.
# """
#
# try:
# if Vasprun('{}/vasprun.xml'.format(directory)).converged:
# return True
# else:
# return False
#
# except:
# return False
, which may contain function names, class names, or code. Output only the next line. | is_converged(dir) |
Given the following code snippet before the placeholder: <|code_start|>
@patch('atexit.register')
@patch('werkzeug.serving.is_running_from_reloader')
@patch('ecs_scheduler.app.scheduld.create')
@patch('ecs_scheduler.app.webapi')
@patch('ecs_scheduler.app.datacontext.Jobs')
@patch('ecs_scheduler.app.operations.DirectQueue')
@patch('ecs_scheduler.app.env')
class CreateTests(unittest.TestCase):
def test_runs_setup_in_prod_mode(
self, env, queue_class, datacontext, webapi, create_scheduld, reloader,
exit_register
):
reloader.return_value = False
<|code_end|>
, predict the next line using imports from the current file:
import logging
import unittest
from unittest.mock import patch, ANY
from ecs_scheduler.app import create
and context including class names, function names, and sometimes code from other files:
# Path: ecs_scheduler/app.py
# def create():
# """
# Start the ECS scheduler daemon and create the flask server.
#
# :returns: The flask server instance
# """
# try:
# env.init()
#
# _logger.info('ECS Scheduler v%s', env.get_version())
# app = webapi.create()
#
# try:
# from uwsgidecorators import postfork
# postfork(functools.partial(_setup_application, app))
# except ImportError:
# # NOTE: Flask in debug mode will restart after initial startup
# # so only setup application state in the main Flask process
# # to avoid duplicate daemons and other side-effects
# # see: https://github.com/pallets/werkzeug/blob/master/werkzeug/_reloader.py
# if werkzeug.serving.is_running_from_reloader() or not app.debug:
# _setup_application(app)
#
# return app
# except Exception:
# _logger.critical('unhandled startup exception', exc_info=True)
# raise
. Output only the next line. | webapi.create.return_value.debug = False |
Given the code snippet: <|code_start|> id: Override
required:
- containerName
properties:
containerName:
type: string
description: The name of the container in the task
definition to apply the overrides to
environment:
type: object
description: >
Environment variable overrides for the named
container as "NAME": "VALUE" pairs
responses:
201:
description: Job created and scheduled
400:
description: Invalid body
409:
description: Job already exists
415:
description: Invalid request media type
default:
description: Server error
"""
job_data = flask.request.json
try:
new_job = self._dc.create(job_data)
except InvalidJobData as ex:
flask_restful.abort(400, messages=ex.errors)
<|code_end|>
, generate the next line using the imports in this file:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context (functions, classes, or occasionally code) from other files:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
. Output only the next line. | except JobAlreadyExists as ex: |
Predict the next line for this snippet: <|code_start|> :param datacontext: The jobs data context for loading and saving jobs
"""
self._ops_queue = ops_queue
self._dc = datacontext
def get(self, job_id):
"""
Get a job
The job for the given id.
---
tags:
- jobs
produces:
- application/json
parameters:
- name: job_id
in: path
type: string
required: true
description: the job id
responses:
200:
description: The job for job id
404:
description: Job not found
default:
description: Server error
"""
try:
job = self._dc.get(job_id)
<|code_end|>
with the help of current file imports:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context from other files:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
, which may contain function names, class names, or code. Output only the next line. | except JobNotFound: |
Given the following code snippet before the placeholder: <|code_start|> then taskCount tasks will be started instead
- schema:
id: Override
required:
- containerName
properties:
containerName:
type: string
description: The name of the container in the task
definition to apply the overrides to
environment:
type: object
description: >
Environment variable overrides for the named
container as "NAME": "VALUE" pairs
responses:
201:
description: Job created and scheduled
400:
description: Invalid body
409:
description: Job already exists
415:
description: Invalid request media type
default:
description: Server error
"""
job_data = flask.request.json
try:
new_job = self._dc.create(job_data)
<|code_end|>
, predict the next line using imports from the current file:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context including class names, function names, and sometimes code from other files:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
. Output only the next line. | except InvalidJobData as ex: |
Given the following code snippet before the placeholder: <|code_start|> description: Job already exists
415:
description: Invalid request media type
default:
description: Server error
"""
job_data = flask.request.json
try:
new_job = self._dc.create(job_data)
except InvalidJobData as ex:
flask_restful.abort(400, messages=ex.errors)
except JobAlreadyExists as ex:
flask_restful.abort(
409, message=f'Job {ex.job_id} already exists.'
)
web_response = _job_committed_response(new_job.id)
_post_operation(
JobOperation.add(new_job.id), self._ops_queue, web_response
)
return web_response, 201
def _parse_pagination(self, data):
obj, errors = self._pagination_schema.load(data)
if errors:
flask_restful.abort(400, messages=errors)
else:
return obj
def _set_pagination(self, result, pagination, total):
prev_link = self._pagination_link(
<|code_end|>
, predict the next line using imports from the current file:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context including class names, function names, and sometimes code from other files:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
. Output only the next line. | Pagination( |
Continue the code snippet: <|code_start|> description: The name of the container in the task
definition to apply the overrides to
environment:
type: object
description: >
Environment variable overrides for the named
container as "NAME": "VALUE" pairs
responses:
201:
description: Job created and scheduled
400:
description: Invalid body
409:
description: Job already exists
415:
description: Invalid request media type
default:
description: Server error
"""
job_data = flask.request.json
try:
new_job = self._dc.create(job_data)
except InvalidJobData as ex:
flask_restful.abort(400, messages=ex.errors)
except JobAlreadyExists as ex:
flask_restful.abort(
409, message=f'Job {ex.job_id} already exists.'
)
web_response = _job_committed_response(new_job.id)
_post_operation(
<|code_end|>
. Use current file imports:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context (classes, functions, or code) from other files:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
. Output only the next line. | JobOperation.add(new_job.id), self._ops_queue, web_response |
Using the snippet: <|code_start|> ops_queue.post(job_op)
except Exception:
_logger.exception('Exception when posting job operation to ops queue.')
flask_restful.abort(
500,
item=job_response,
message='Job update was saved correctly but failed'
' to post update message to scheduler.'
)
_job_response_schema = JobResponseSchema(_job_link, strict=True)
class Jobs(flask_restful.Resource):
"""
Jobs REST Resource
REST operations for a collection of jobs.
"""
def __init__(self, ops_queue, datacontext):
"""
Create jobs resource.
:param ops_queue: Ops queue to post job operations to after
updating document store
:param datacontext: The jobs data context for loading and saving jobs
"""
self._ops_queue = ops_queue
self._dc = datacontext
<|code_end|>
, determine the next line of code. You have imports:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context (class names, function names, or code) available:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
. Output only the next line. | self._pagination_schema = PaginationSchema() |
Given snippet: <|code_start|>
def _job_link(job_id):
return {
'rel': 'item',
'title': f'Job for {job_id}',
'href': flask.url_for(Job.__name__.lower(), job_id=job_id),
}
def _job_committed_response(job_id):
return {
'id': job_id,
'link': _job_link(job_id),
}
def _post_operation(job_op, ops_queue, job_response):
try:
ops_queue.post(job_op)
except Exception:
_logger.exception('Exception when posting job operation to ops queue.')
flask_restful.abort(
500,
item=job_response,
message='Job update was saved correctly but failed'
' to post update message to scheduler.'
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import logging
import flask
import flask_restful
from itertools import islice
from ..datacontext import JobAlreadyExists, JobNotFound, InvalidJobData
from ..models import Pagination, JobOperation
from ..serialization import PaginationSchema, JobResponseSchema
and context:
# Path: ecs_scheduler/datacontext.py
# class JobAlreadyExists(JobError):
# """Job exists error."""
# pass
#
# class JobNotFound(JobError):
# """Job not found error."""
# pass
#
# class InvalidJobData(JobError):
# """Invalid job data error."""
#
# def __init__(self, job_id, errors, *args, **kwargs):
# """
# Create a job error.
#
# :param job_id: The job id related to the failed jobs call
# :param errors: Job validation errors
# :param *args: Additional exception positional arguments
# :param **kwargs: Additional exception keyword arugments
# """
# super().__init__(job_id, *args, **kwargs)
# self.errors = errors
#
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
#
# Path: ecs_scheduler/serialization.py
# class PaginationSchema(marshmallow.Schema):
# """Schema for pagination arguments."""
# skip = marshmallow.fields.Integer(missing=0)
# count = marshmallow.fields.Integer(missing=10)
#
# @marshmallow.post_load
# def make_pagination(self, data):
# for field in self.fields.keys():
# data[field] = max(0, data[field])
# return Pagination(**data)
#
# @marshmallow.pre_dump
# def adjust_page_frame(self, obj):
# if (
# obj.total <= 0
# or (obj.skip + obj.count) <= 0
# or obj.skip >= obj.total
# ):
# return {}
# obj.skip = max(0, obj.skip)
#
# @marshmallow.post_dump
# def strip_defaults(self, data):
# return {
# k: v for k, v in data.items()
# if v != self._get_field_missing_value(k)
# }
#
# def _get_field_missing_value(self, name):
# field = self.fields.get(name)
# return field.missing if field else None
#
# class JobResponseSchema(JobSchema):
# """
# Schema of a job response.
#
# This extends JobSchema to deserialize a Job into a REST JSON
# representation.
#
# Used for serialization only.
# """
# # override id to include in dump output
# id = marshmallow.fields.String(dump_only=True)
# link = marshmallow.fields.Method('link_generator', dump_only=True)
# lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
# lastRunTasks = marshmallow.fields.List(
# marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
# )
# estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
#
# def __init__(self, link_func, *args, **kwargs):
# self._link_func = link_func
# super().__init__(*args, **kwargs)
#
# def link_generator(self, obj):
# return self._link_func(obj['id'])
which might include code, classes, or functions. Output only the next line. | _job_response_schema = JobResponseSchema(_job_link, strict=True) |
Using the snippet: <|code_start|>
@patch('ecs_scheduler.scheduld.execution.triggers.get')
class JobExecutorTests(unittest.TestCase):
def setUp(self):
with patch('boto3.client'), \
patch.dict(
os.environ,
{
'ECSS_ECS_CLUSTER': 'testCluster',
'ECSS_NAME': 'testName',
},
clear=True
):
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.scheduld.execution import JobExecutor, JobResult
and context (class names, function names, or code) available:
# Path: ecs_scheduler/scheduld/execution.py
# class JobExecutor:
# """
# The executor run by all scheduled jobs.
#
# :attribute RETVAL_CHECKED_TASKS: The return value of the job executor when
# it successfully verifies the state of ECS
# for a job but starts no new tasks
# :attribute RETVAL_STARTED_TASKS: The return value of the job executor when
# it started new ECS tasks for a job
# :attribute OVERRIDE_TAG: If the job contains task overrides add the job id
# to the overrides when launching a task so it can
# be identified later
# """
# RETVAL_CHECKED_TASKS = 0
# RETVAL_STARTED_TASKS = 1
# OVERRIDE_TAG = 'ECS_SCHEDULER_OVERRIDE_TAG'
#
# def __init__(self):
# """Create an executor."""
# self._ecs = boto3.client('ecs')
# self._cluster_name = env.get_var('ECS_CLUSTER', required=True)
# self._my_name = env.get_var('NAME', default='ecs-scheduler')
#
# def __call__(self, **job_data):
# """
# Call the executor.
#
# :param job_data: The job data dictionary
# :returns: An executor return value
# """
# task_name = job_data.get('taskDefinition', job_data['id'])
# running_tasks = self._ecs.list_tasks(
# cluster=self._cluster_name,
# family=task_name,
# desiredStatus='RUNNING'
# )
# running_task_count = self._calculate_running_count(
# job_data, running_tasks['taskArns']
# )
# expected_task_count = self._calculate_expected_count(job_data)
# needed_task_count = max(0, expected_task_count - running_task_count)
#
# if needed_task_count:
# task_info = self._launch_tasks(
# task_name, needed_task_count, job_data
# )
# _logger.info(
# 'Launched %s "%s" tasks for job %s',
# needed_task_count, task_name, job_data['id']
# )
# return JobResult(self.RETVAL_STARTED_TASKS, task_info)
#
# _logger.info(
# 'Checked status for "%s" and no additional tasks were needed',
# job_data['id']
# )
# return JobResult(self.RETVAL_CHECKED_TASKS)
#
# def _calculate_running_count(self, job_data, task_arns):
# if task_arns and 'overrides' in job_data:
# tasks = self._ecs.describe_tasks(
# cluster=self._cluster_name, tasks=task_arns
# )
# overridden_tasks = [
# task for task in tasks['tasks']
# if self._is_overridden_by_job(task, job_data['id'])
# ]
# return len(overridden_tasks)
# else:
# return len(task_arns)
#
# def _is_overridden_by_job(self, task, job_id):
# return any(
# env.get('name') == self.OVERRIDE_TAG
# and env.get('value') == job_id
# for overrides in task['overrides']['containerOverrides']
# for env in overrides.get('environment', [])
# )
#
# def _calculate_expected_count(self, job_data):
# trigger_data = job_data.get('trigger', {})
# trigger = triggers.get(trigger_data.get('type'))
# return trigger.determine_task_count(job_data)
#
# def _launch_tasks(self, task_def_id, task_count, job_data):
# run_kwargs = {
# 'cluster': self._cluster_name,
# 'taskDefinition': task_def_id,
# 'startedBy': self._my_name
# }
#
# self._add_overrides(run_kwargs, job_data)
#
# task_info = []
# while task_count > 0:
# run_kwargs['count'] = min(task_count, _MAX_TASK_COUNT)
# response = self._ecs.run_task(**run_kwargs)
# failures = response['failures']
# if failures:
# _logger.warning(
# 'Task "%s" start failures: %s', task_def_id, failures
# )
# task_info.extend({
# 'taskId': t['taskArn'],
# 'hostId': t['containerInstanceArn'],
# } for t in response['tasks'])
# task_count -= _MAX_TASK_COUNT
# return task_info
#
# def _add_overrides(self, run_kwargs, job_data):
# overrides = job_data.get('overrides')
# if overrides:
# # APScheduler only gives me a shallow copy of kwargs on each job
# # run so deep copy before manipulating
# tagged_overrides = copy.deepcopy(overrides)
# for override in tagged_overrides:
# override['environment'][self.OVERRIDE_TAG] = job_data['id']
# ecs_overrides = [
# {
# 'name': override['containerName'],
# 'environment': [
# {'name': k, 'value': v}
# for k, v in override['environment'].items()
# ],
# } for override in tagged_overrides
# ]
# run_kwargs['overrides'] = {'containerOverrides': ecs_overrides}
#
# class JobResult:
# """The result of a job run."""
# return_code: int
# task_info: List[Dict[str, str]] = None
. Output only the next line. | self._exec = JobExecutor() |
Using the snippet: <|code_start|>
class SpecTests(unittest.TestCase):
@patch('flask_swagger.swagger')
@patch('ecs_scheduler.webapi.spec.flask')
def test_get(self, fake_flask, fake_swagger):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from unittest.mock import patch
from ecs_scheduler.webapi.spec import Spec
and context (class names, function names, or code) available:
# Path: ecs_scheduler/webapi/spec.py
# class Spec(flask_restful.Resource):
# """Swagger spec REST resource."""
#
# def get(self):
# """
# API spec
# Return the swagger api specification.
# ---
# tags:
# - docs
# produces:
# - application/json
# responses:
# 200:
# description: API spec documentation
# """
# swag = flask_swagger.swagger(flask.current_app)
# swag['info']['version'] = env.get_version()
# swag['info']['title'] = 'ECS Scheduler Web Api (webapi)'
# swag['basePath'] = '/'
# return swag
. Output only the next line. | spec = Spec() |
Given snippet: <|code_start|>
class HomeTests(unittest.TestCase):
@patch('flask.url_for', side_effect=lambda name: 'foo/' + name)
def test_get(self, fake_url):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from unittest.mock import patch
from ecs_scheduler.webapi.home import Home
and context:
# Path: ecs_scheduler/webapi/home.py
# class Home(flask_restful.Resource):
# """Home url REST resource."""
#
# def get(self):
# """
# Home
# Available endpoints for the web api.
# ---
# tags:
# - docs
# produces:
# - application/json
# responses:
# 200:
# description: List of available endpoints
# """
# return {
# 'resources': [
# {
# 'link': {
# 'rel': 'jobs',
# 'title': 'Jobs',
# 'href': flask.url_for(Jobs.__name__.lower()),
# },
# },
# {
# 'link': {
# 'rel': 'spec',
# 'title': 'Spec',
# 'href': flask.url_for(Spec.__name__.lower()),
# },
# }
# ],
# }
which might include code, classes, or functions. Output only the next line. | home = Home() |
Next line prediction: <|code_start|>
class NoOpTriggerTests(unittest.TestCase):
def test_determine_task_count_returns_task_count(self):
test_data = {'taskCount': 10}
<|code_end|>
. Use current file imports:
(import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.triggers import (
NoOpTrigger, SqsTrigger, get, init, _triggers
))
and context including class names, function names, or small code snippets from other files:
# Path: ecs_scheduler/triggers.py
# def init():
# def get(trigger_name):
# def determine_task_count(self, job_data):
# def __init__(self):
# def determine_task_count(self, job_data):
# def _calculate_task_count(self, message_count, job_data):
# class NoOpTrigger:
# class SqsTrigger:
. Output only the next line. | trigger = NoOpTrigger() |
Given the code snippet: <|code_start|>
class NoOpTriggerTests(unittest.TestCase):
def test_determine_task_count_returns_task_count(self):
test_data = {'taskCount': 10}
trigger = NoOpTrigger()
count = trigger.determine_task_count(test_data)
self.assertEqual(10, count)
def test_determine_task_count_returns_task_count_if_less_than_max(self):
test_data = {'taskCount': 10, 'maxCount': 20}
trigger = NoOpTrigger()
count = trigger.determine_task_count(test_data)
self.assertEqual(10, count)
def test_determine_task_count_returns_max_count_if_greater_than_max(self):
test_data = {'taskCount': 30, 'maxCount': 20}
trigger = NoOpTrigger()
count = trigger.determine_task_count(test_data)
self.assertEqual(20, count)
class SqsTriggerTests(unittest.TestCase):
def setUp(self):
with patch('boto3.resource'):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.triggers import (
NoOpTrigger, SqsTrigger, get, init, _triggers
)
and context (functions, classes, or occasionally code) from other files:
# Path: ecs_scheduler/triggers.py
# def init():
# def get(trigger_name):
# def determine_task_count(self, job_data):
# def __init__(self):
# def determine_task_count(self, job_data):
# def _calculate_task_count(self, message_count, job_data):
# class NoOpTrigger:
# class SqsTrigger:
. Output only the next line. | self._trigger = SqsTrigger() |
Based on the snippet: <|code_start|> }
fake_queue = Mock(attributes={'ApproximateNumberOfMessages': 10})
self._trigger._sqs.get_queue_by_name.return_value = fake_queue
count = self._trigger.determine_task_count(test_data)
self.assertEqual(3, count)
@patch('boto3.resource')
@patch.dict('ecs_scheduler.triggers._triggers', {})
class InitTests(unittest.TestCase):
def test(self, fake_resource):
init()
self.assertEqual(2, len(_triggers))
self.assertIsInstance(_triggers['sqs'], SqsTrigger)
self.assertIsInstance(_triggers['noop'], NoOpTrigger)
class TestTrigger():
pass
@patch.dict(
'ecs_scheduler.triggers._triggers',
{'test': TestTrigger(), 'noop': NoOpTrigger()}
)
class GetTests(unittest.TestCase):
def test_get_named_trigger(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.triggers import (
NoOpTrigger, SqsTrigger, get, init, _triggers
)
and context (classes, functions, sometimes code) from other files:
# Path: ecs_scheduler/triggers.py
# def init():
# def get(trigger_name):
# def determine_task_count(self, job_data):
# def __init__(self):
# def determine_task_count(self, job_data):
# def _calculate_task_count(self, message_count, job_data):
# class NoOpTrigger:
# class SqsTrigger:
. Output only the next line. | trigger = get('test') |
Here is a snippet: <|code_start|> test_data = {
'taskCount': 1,
'trigger': {'queueName': 'testQueue', 'messagesPerTask': 10},
}
fake_queue = Mock(attributes={'ApproximateNumberOfMessages': 2})
self._trigger._sqs.get_queue_by_name.return_value = fake_queue
count = self._trigger.determine_task_count(test_data)
self.assertEqual(1, count)
def test_determine_task_count_returns_task_count_if_calculated_value_lower(
self
):
test_data = {
'taskCount': 3,
'trigger': {'queueName': 'testQueue', 'messagesPerTask': 10},
}
fake_queue = Mock(attributes={'ApproximateNumberOfMessages': 10})
self._trigger._sqs.get_queue_by_name.return_value = fake_queue
count = self._trigger.determine_task_count(test_data)
self.assertEqual(3, count)
@patch('boto3.resource')
@patch.dict('ecs_scheduler.triggers._triggers', {})
class InitTests(unittest.TestCase):
def test(self, fake_resource):
<|code_end|>
. Write the next line using the current file imports:
import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.triggers import (
NoOpTrigger, SqsTrigger, get, init, _triggers
)
and context from other files:
# Path: ecs_scheduler/triggers.py
# def init():
# def get(trigger_name):
# def determine_task_count(self, job_data):
# def __init__(self):
# def determine_task_count(self, job_data):
# def _calculate_task_count(self, message_count, job_data):
# class NoOpTrigger:
# class SqsTrigger:
, which may include functions, classes, or code. Output only the next line. | init() |
Given the code snippet: <|code_start|> 'trigger': {'queueName': 'testQueue', 'messagesPerTask': 10},
}
fake_queue = Mock(attributes={'ApproximateNumberOfMessages': 2})
self._trigger._sqs.get_queue_by_name.return_value = fake_queue
count = self._trigger.determine_task_count(test_data)
self.assertEqual(1, count)
def test_determine_task_count_returns_task_count_if_calculated_value_lower(
self
):
test_data = {
'taskCount': 3,
'trigger': {'queueName': 'testQueue', 'messagesPerTask': 10},
}
fake_queue = Mock(attributes={'ApproximateNumberOfMessages': 10})
self._trigger._sqs.get_queue_by_name.return_value = fake_queue
count = self._trigger.determine_task_count(test_data)
self.assertEqual(3, count)
@patch('boto3.resource')
@patch.dict('ecs_scheduler.triggers._triggers', {})
class InitTests(unittest.TestCase):
def test(self, fake_resource):
init()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from unittest.mock import patch, Mock
from ecs_scheduler.triggers import (
NoOpTrigger, SqsTrigger, get, init, _triggers
)
and context (functions, classes, or occasionally code) from other files:
# Path: ecs_scheduler/triggers.py
# def init():
# def get(trigger_name):
# def determine_task_count(self, job_data):
# def __init__(self):
# def determine_task_count(self, job_data):
# def _calculate_task_count(self, message_count, job_data):
# class NoOpTrigger:
# class SqsTrigger:
. Output only the next line. | self.assertEqual(2, len(_triggers)) |
Predict the next line for this snippet: <|code_start|> representation.
Used for serialization only.
"""
# override id to include in dump output
id = marshmallow.fields.String(dump_only=True)
link = marshmallow.fields.Method('link_generator', dump_only=True)
lastRun = marshmallow.fields.LocalDateTime(dump_only=True)
lastRunTasks = marshmallow.fields.List(
marshmallow.fields.Nested(TaskInfoSchema), dump_only=True
)
estimatedNextRun = marshmallow.fields.LocalDateTime(dump_only=True)
def __init__(self, link_func, *args, **kwargs):
self._link_func = link_func
super().__init__(*args, **kwargs)
def link_generator(self, obj):
return self._link_func(obj['id'])
class PaginationSchema(marshmallow.Schema):
"""Schema for pagination arguments."""
skip = marshmallow.fields.Integer(missing=0)
count = marshmallow.fields.Integer(missing=10)
@marshmallow.post_load
def make_pagination(self, data):
for field in self.fields.keys():
data[field] = max(0, data[field])
<|code_end|>
with the help of current file imports:
import random
import re
import apscheduler.triggers.cron
import marshmallow
from pytz.exceptions import UnknownTimeZoneError
from .models import Pagination
and context from other files:
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
, which may contain function names, class names, or code. Output only the next line. | return Pagination(**data) |
Based on the snippet: <|code_start|> self.assertEqual(operation, op.operation)
self.assertIs(job_id, op.job_id)
def test_add_creates_op(self):
job_id = 'foo'
op = JobOperation.add(job_id)
self.assertEqual(JobOperation.ADD, op.operation)
self.assertIs(job_id, op.job_id)
def test_modify_creates_op(self):
job_id = 'foo'
op = JobOperation.modify(job_id)
self.assertEqual(JobOperation.MODIFY, op.operation)
self.assertIs(job_id, op.job_id)
def test_remove_creates_op(self):
job_id = 'foo'
op = JobOperation.remove(job_id)
self.assertEqual(JobOperation.REMOVE, op.operation)
self.assertIs(job_id, op.job_id)
class PaginationTests(unittest.TestCase):
def test_ctor_sets_attributes(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from ecs_scheduler.models import Pagination, JobOperation
and context (classes, functions, sometimes code) from other files:
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
. Output only the next line. | page = Pagination(12, 42) |
Predict the next line for this snippet: <|code_start|>
class JobOperationTests(unittest.TestCase):
def test_ctor(self):
operation = 5
job_id = 'foo'
<|code_end|>
with the help of current file imports:
import unittest
from ecs_scheduler.models import Pagination, JobOperation
and context from other files:
# Path: ecs_scheduler/models.py
# class Pagination:
# """
# Job pagination parameters.
#
# :param skip: The number of jobs to skip
# :param count: The number of jobs to return
# :param total: The total number of jobs across all pages;
# used to calculate next and prev page links
# """
# skip: int
# count: int
# total: int = 0
#
# class JobOperation:
# """
# A job operation used to communicate changes to the scheduler via
# the ops queue between the web api and the scheduler daemon.
#
# :attribute ADD: Add operation label
# :attribute MODIFY: Modify operation label
# :attribute REMOVE: Remove operation label
# """
# ADD = 1
# MODIFY = 2
# REMOVE = 3
#
# @classmethod
# def add(cls, job_id):
# """
# Create an add job operation.
#
# :param job_id: The string id of the job to add to the scheduler
# """
# return cls(cls.ADD, job_id)
#
# @classmethod
# def modify(cls, job_id):
# """
# Create a modify job operation
#
# :param job_id: The string id of the job to modify in the scheduler
# """
# return cls(cls.MODIFY, job_id)
#
# @classmethod
# def remove(cls, job_id):
# """
# Create a remove job operation.
#
# :param job_id: The string id of the job to remove from the scheduler
# """
# return cls(cls.REMOVE, job_id)
#
# def __init__(self, operation, job_id):
# """
# Create a job operation.
#
# Use the factory class methods instead of __init___ directly
# to create an instance.
#
# :param operation: The operation label
# :param job_id: The string id of the job to apply the operation to
# """
# self.operation = operation
# self.job_id = job_id
, which may contain function names, class names, or code. Output only the next line. | op = JobOperation(operation, job_id) |
Based on the snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
ttf1 = load_fixture('Samyak-Malayalam1.ttf')
ttf2 = load_fixture('Samyak-Malayalam2.ttf')
def test_identification(ttf1):
assert isinstance(ttf1, TtfFile)
def test_no_differences(ttf1):
difference = ttf1.compare(ttf1)
assert difference is None
@pytest.fixture
def differences(ttf1, ttf2):
return ttf1.compare(ttf2).details
@skip_unless_tools_exist('showttf')
def test_diff(differences):
expected_diff = get_data('ttf_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('showttf')
def test_compare_non_existing(monkeypatch, ttf1):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.fonts import TtfFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and context (classes, functions, sometimes code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Here is a snippet: <|code_start|>#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_FILE1_PATH = data('text_ascii1')
TEST_FILE2_PATH = data('text_ascii2')
@pytest.fixture
def rom1(tmpdir):
path = str(tmpdir.join('coreboot1'))
subprocess.check_call(['cbfstool', path, 'create', '-m', 'x86', '-s', '32768'], shell=False)
subprocess.check_call(['cbfstool', path, 'add', '-f', TEST_FILE1_PATH, '-n', 'text', '-t', 'raw'], shell=False)
<|code_end|>
. Write the next line using the current file imports:
import struct
import pytest
import subprocess
from diffoscope.comparators.cbfs import CbfsFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import data, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
, which may include functions, classes, or code. Output only the next line. | return specialize(FilesystemFile(path)) |
Given the following code snippet before the placeholder: <|code_start|>def test_no_differences(img1):
difference = img1.compare(img1)
assert difference is None
@pytest.fixture
def differences(img1, img2):
return img1.compare(img2).details
@pytest.mark.skipif(not guestfs_working(), reason='guestfs not working on the system')
@skip_unless_tools_exist('qemu-img')
@skip_unless_module_exists('guestfs')
def test_differences(differences):
assert differences[0].source1 == 'test1.ext4.tar'
tarinfo = differences[0].details[0]
tardiff = differences[0].details[1]
encodingdiff = tardiff.details[0]
assert tarinfo.source1 == 'file list'
assert tarinfo.source2 == 'file list'
assert tardiff.source1 == './date.txt'
assert tardiff.source2 == './date.txt'
assert encodingdiff.source1 == 'encoding'
assert encodingdiff.source2 == 'encoding'
expected_diff = get_data('ext4_expected_diffs')
found_diff = tarinfo.unified_diff + tardiff.unified_diff + encodingdiff.unified_diff
assert expected_diff == found_diff
@pytest.mark.skipif(not guestfs_working(), reason='guestfs not working on the system')
@skip_unless_tools_exist('qemu-img')
@skip_unless_module_exists('guestfs')
def test_compare_non_existing(monkeypatch, img1):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
import guestfs
from diffoscope.config import Config
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.fsimage import FsImageFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_module_exists
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_TAR1_PATH = os.path.join(os.path.dirname(__file__), 'data/test1.tar')
TEST_TAR2_PATH = os.path.join(os.path.dirname(__file__), 'data/test2.tar')
TEST_TARS = (TEST_TAR1_PATH, TEST_TAR2_PATH)
def run(capsys, *args):
with pytest.raises(SystemExit) as exc:
<|code_end|>
. Use current file imports:
(import os
import pytest
import signal
import tempfile
from diffoscope.main import main)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/main.py
# def main(args=None):
# if args is None:
# args = sys.argv[1:]
# signal.signal(signal.SIGTERM, sigterm_handler)
# parsed_args = None
# try:
# with profile('main', 'parse_args'):
# parser = create_parser()
# parsed_args = parser.parse_args(args)
# sys.exit(run_diffoscope(parsed_args))
# except KeyboardInterrupt:
# logger.info('Keyboard Interrupt')
# sys.exit(2)
# except BrokenPipeError:
# sys.exit(2)
# except Exception:
# traceback.print_exc()
# if parsed_args and parsed_args.debugger:
# import pdb
# pdb.post_mortem()
# sys.exit(2)
# finally:
# with profile('main', 'cleanup'):
# clean_all_temp_files()
#
# # Print profiling output at the very end
# if parsed_args is not None:
# ProfileManager().finish(parsed_args)
. Output only the next line. | main(args) |
Given the following code snippet before the placeholder: <|code_start|>
image1 = load_fixture('test1.jpg')
image2 = load_fixture('test2.jpg')
image1_meta = load_fixture('test1_meta.jpg')
image2_meta = load_fixture('test2_meta.jpg')
def identify_version():
out = subprocess.check_output(['identify', '-version'])
# First line is expected to look like
# "Version: ImageMagick 6.9.6-6 Q16 x86_64 20161125 ..."
return out.decode('utf-8').splitlines()[0].split()[2].strip()
def test_identification(image1):
assert isinstance(image1, JPEGImageFile)
def test_no_differences(image1):
difference = image1.compare(image1)
assert difference is None
@pytest.fixture
def differences(image1, image2):
return image1.compare(image2).details
@skip_unless_tools_exist('img2txt', 'identify')
def test_diff(differences):
expected_diff = get_data('jpeg_image_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('img2txt', 'identify')
def test_compare_non_existing(monkeypatch, image1):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
import subprocess
from diffoscope.config import Config
from diffoscope.comparators.image import JPEGImageFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/image.py
# class JPEGImageFile(File):
# RE_FILE_TYPE = re.compile(r'\bJPEG image data\b')
#
# def compare_details(self, other, source=None):
# return [
# Difference.from_command(Img2Txt, self.path, other.path),
# Difference.from_command(
# Identify,
# self.path,
# other.path,
# source="Image metadata",
# ),
# ]
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Here is a snippet: <|code_start|>#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
image1 = load_fixture('test1.jpg')
image2 = load_fixture('test2.jpg')
image1_meta = load_fixture('test1_meta.jpg')
image2_meta = load_fixture('test2_meta.jpg')
def identify_version():
out = subprocess.check_output(['identify', '-version'])
# First line is expected to look like
# "Version: ImageMagick 6.9.6-6 Q16 x86_64 20161125 ..."
return out.decode('utf-8').splitlines()[0].split()[2].strip()
def test_identification(image1):
<|code_end|>
. Write the next line using the current file imports:
import pytest
import subprocess
from diffoscope.config import Config
from diffoscope.comparators.image import JPEGImageFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
and context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/image.py
# class JPEGImageFile(File):
# RE_FILE_TYPE = re.compile(r'\bJPEG image data\b')
#
# def compare_details(self, other, source=None):
# return [
# Difference.from_command(Img2Txt, self.path, other.path),
# Difference.from_command(
# Identify,
# self.path,
# other.path,
# source="Image metadata",
# ),
# ]
, which may include functions, classes, or code. Output only the next line. | assert isinstance(image1, JPEGImageFile) |
Next line prediction: <|code_start|>
self._diff.write(line)
if line[0] in ('-', '+'):
if line[0] == self._direction:
self._block_len += 1
else:
self._block_len = 1
self._direction = line[0]
if self._block_len >= self._max_lines:
return self.skip_block
else:
self._block_len = 1
self._direction = line[0]
return self.read_hunk
def skip_block(self, line):
if self._remaining_hunk_lines == 0 or line[0] != self._direction:
removed = self._block_len - Config().max_diff_block_lines_saved
if removed:
self._diff.write('%s[ %d lines removed ]\n' % (self._direction, removed))
return self.read_hunk(line)
self._block_len += 1
self._remaining_hunk_lines -= 1
return self.skip_block
<|code_end|>
. Use current file imports:
(import re
import io
import os
import errno
import fcntl
import hashlib
import logging
import threading
import subprocess
from multiprocessing.dummy import Queue
from diffoscope.tempfiles import get_temporary_directory
from .tools import tool_required
from .config import Config)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | @tool_required('diff') |
Using the snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
DIFF_CHUNK = 4096
logger = logging.getLogger(__name__)
re_diff_change = re.compile(r'^([+-@]).*', re.MULTILINE)
class DiffParser(object):
RANGE_RE = re.compile(
r'^@@\s+-(?P<start1>\d+)(,(?P<len1>\d+))?\s+\+(?P<start2>\d+)(,(?P<len2>\d+))?\s+@@$',
)
def __init__(self, output, end_nl_q1, end_nl_q2):
self._output = output
self._end_nl_q1 = end_nl_q1
self._end_nl_q2 = end_nl_q2
self._action = self.read_headers
self._diff = io.StringIO()
self._success = False
self._remaining_hunk_lines = None
self._block_len = None
self._direction = None
self._end_nl = None
<|code_end|>
, determine the next line of code. You have imports:
import re
import io
import os
import errno
import fcntl
import hashlib
import logging
import threading
import subprocess
from multiprocessing.dummy import Queue
from diffoscope.tempfiles import get_temporary_directory
from .tools import tool_required
from .config import Config
and context (class names, function names, or code) available:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | self._max_lines = Config().max_diff_block_lines_saved |
Next line prediction: <|code_start|>#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
try:
except ImportError: # noqa
tlsh = None
logger = logging.getLogger(__name__)
class Xxd(Command):
<|code_end|>
. Use current file imports:
(import io
import os
import sys
import logging
import binascii
import tlsh
from diffoscope.tools import tool_required
from diffoscope.exc import RequiredToolNotFound
from diffoscope.config import Config
from diffoscope.excludes import any_excluded
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from ..missing_file import MissingFile
from .command import Command
from .specialize import specialize
from ..directory import FilesystemDirectory, FilesystemFile, compare_directories)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/excludes.py
# def any_excluded(*filenames):
# return len(filter_excludes(filenames)) != len(filenames)
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | @tool_required('xxd') |
Here is a snippet: <|code_start|> specialize(file2)
if isinstance(file1, MissingFile):
file1.other_file = file2
elif isinstance(file2, MissingFile):
file2.other_file = file1
elif file1.__class__.__name__ != file2.__class__.__name__:
return file1.compare_bytes(file2, source)
with profile('compare_files (cumulative)', file1):
return file1.compare(file2, source)
def compare_commented_files(file1, file2, comment=None, source=None):
difference = compare_files(file1, file2, source=source)
if comment:
if difference is None:
difference = Difference(None, file1.name, file2.name)
difference.add_comment(comment)
return difference
def bail_if_non_existing(*paths):
if not all(map(os.path.lexists, paths)):
for path in paths:
if not os.path.lexists(path):
sys.stderr.write('%s: %s: No such file or directory\n' % (sys.argv[0], path))
sys.exit(2)
def compare_binary_files(file1, file2, source=None):
try:
return Difference.from_command(
Xxd, file1.path, file2.path,
source=[file1.name, file2.name], has_internal_linenos=True)
<|code_end|>
. Write the next line using the current file imports:
import io
import os
import sys
import logging
import binascii
import tlsh
from diffoscope.tools import tool_required
from diffoscope.exc import RequiredToolNotFound
from diffoscope.config import Config
from diffoscope.excludes import any_excluded
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from ..missing_file import MissingFile
from .command import Command
from .specialize import specialize
from ..directory import FilesystemDirectory, FilesystemFile, compare_directories
and context from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/excludes.py
# def any_excluded(*filenames):
# return len(filter_excludes(filenames)) != len(filenames)
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
, which may include functions, classes, or code. Output only the next line. | except RequiredToolNotFound: |
Next line prediction: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
try:
except ImportError: # noqa
tlsh = None
logger = logging.getLogger(__name__)
class Xxd(Command):
@tool_required('xxd')
def cmdline(self):
return ['xxd', self.path]
def compare_root_paths(path1, path2):
<|code_end|>
. Use current file imports:
(import io
import os
import sys
import logging
import binascii
import tlsh
from diffoscope.tools import tool_required
from diffoscope.exc import RequiredToolNotFound
from diffoscope.config import Config
from diffoscope.excludes import any_excluded
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from ..missing_file import MissingFile
from .command import Command
from .specialize import specialize
from ..directory import FilesystemDirectory, FilesystemFile, compare_directories)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/excludes.py
# def any_excluded(*filenames):
# return len(filter_excludes(filenames)) != len(filenames)
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | if not Config().new_file: |
Next line prediction: <|code_start|># (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
try:
except ImportError: # noqa
tlsh = None
logger = logging.getLogger(__name__)
class Xxd(Command):
@tool_required('xxd')
def cmdline(self):
return ['xxd', self.path]
def compare_root_paths(path1, path2):
if not Config().new_file:
bail_if_non_existing(path1, path2)
<|code_end|>
. Use current file imports:
(import io
import os
import sys
import logging
import binascii
import tlsh
from diffoscope.tools import tool_required
from diffoscope.exc import RequiredToolNotFound
from diffoscope.config import Config
from diffoscope.excludes import any_excluded
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from ..missing_file import MissingFile
from .command import Command
from .specialize import specialize
from ..directory import FilesystemDirectory, FilesystemFile, compare_directories)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/excludes.py
# def any_excluded(*filenames):
# return len(filter_excludes(filenames)) != len(filenames)
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | if any_excluded(path1, path2): |
Given the following code snippet before the placeholder: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
try:
except ImportError: # noqa
tlsh = None
logger = logging.getLogger(__name__)
class Xxd(Command):
@tool_required('xxd')
def cmdline(self):
return ['xxd', self.path]
def compare_root_paths(path1, path2):
if not Config().new_file:
bail_if_non_existing(path1, path2)
if any_excluded(path1, path2):
return None
if os.path.isdir(path1) and os.path.isdir(path2):
return compare_directories(path1, path2)
container1 = FilesystemDirectory(os.path.dirname(path1)).as_container
<|code_end|>
, predict the next line using imports from the current file:
import io
import os
import sys
import logging
import binascii
import tlsh
from diffoscope.tools import tool_required
from diffoscope.exc import RequiredToolNotFound
from diffoscope.config import Config
from diffoscope.excludes import any_excluded
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from ..missing_file import MissingFile
from .command import Command
from .specialize import specialize
from ..directory import FilesystemDirectory, FilesystemFile, compare_directories
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
#
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/excludes.py
# def any_excluded(*filenames):
# return len(filter_excludes(filenames)) != len(filenames)
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | file1 = specialize(FilesystemFile(path1, container=container1)) |
Next line prediction: <|code_start|> self.print_func = create_limited_print_func(
print_func,
Config().max_text_report_size,
)
self.color = color
super().__init__()
def start(self, difference):
try:
super().start(difference)
except PrintLimitReached:
self.print_func("Max output size reached.", force=True)
def visit_difference(self, difference):
if self.depth == 0:
self.output("--- {}".format(difference.source1))
self.output("+++ {}".format(difference.source2))
elif difference.source1 == difference.source2:
self.output(u"├── {}".format(difference.source1))
else:
self.output(u"│ --- {}".format(difference.source1))
self.output(u"├── +++ {}".format(difference.source2))
for x in difference.comments:
self.output(u"│┄ {}".format(x))
diff = difference.unified_diff
if diff:
<|code_end|>
. Use current file imports:
(import re
from diffoscope.diff import color_unified_diff
from diffoscope.config import Config
from .utils import Presenter, create_limited_print_func, PrintLimitReached)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/diff.py
# def color_unified_diff(diff):
# RESET = '\033[0m'
# RED, GREEN, CYAN = '\033[31m', '\033[32m', '\033[0;36m'
#
# def repl(m):
# return '{}{}{}'.format({
# '-': RED,
# '@': CYAN,
# '+': GREEN,
# }[m.group(1)], m.group(0), RESET)
#
# return re_diff_change.sub(repl, diff)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/presenters/utils.py
# class Presenter(object):
# def __init__(self):
# self.depth = 0
#
# def start(self, difference):
# self.visit(difference)
#
# def visit(self, difference):
# self.visit_difference(difference)
#
# self.depth += 1
#
# for x in difference.details:
# self.visit(x)
#
# self.depth -= 1
#
# def visit_difference(self, difference):
# raise NotImplementedError()
#
# @classmethod
# def indent(cls, val, prefix):
# # As an optimisation, output as much as possible in one go to avoid
# # unnecessary splitting, interpolating, etc.
# #
# # We don't use textwrap.indent as that unnecessarily calls
# # str.splitlines, etc.
# return prefix + val.rstrip().replace('\n', '\n{}'.format(prefix))
#
# def create_limited_print_func(print_func, max_page_size):
# count = 0
#
# def fn(val, force=False, count=count):
# print_func(val)
#
# if force or max_page_size == 0:
# return
#
# count += len(val)
# if count >= max_page_size:
# raise PrintLimitReached()
#
# return fn
#
# class PrintLimitReached(Exception):
# pass
. Output only the next line. | self.output(color_unified_diff(diff) if self.color else diff, True) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
class TextPresenter(Presenter):
PREFIX = u'│ '
RE_PREFIX = re.compile(r'(^|\n)')
def __init__(self, print_func, color):
self.print_func = create_limited_print_func(
print_func,
<|code_end|>
, predict the next line using imports from the current file:
import re
from diffoscope.diff import color_unified_diff
from diffoscope.config import Config
from .utils import Presenter, create_limited_print_func, PrintLimitReached
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/diff.py
# def color_unified_diff(diff):
# RESET = '\033[0m'
# RED, GREEN, CYAN = '\033[31m', '\033[32m', '\033[0;36m'
#
# def repl(m):
# return '{}{}{}'.format({
# '-': RED,
# '@': CYAN,
# '+': GREEN,
# }[m.group(1)], m.group(0), RESET)
#
# return re_diff_change.sub(repl, diff)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/presenters/utils.py
# class Presenter(object):
# def __init__(self):
# self.depth = 0
#
# def start(self, difference):
# self.visit(difference)
#
# def visit(self, difference):
# self.visit_difference(difference)
#
# self.depth += 1
#
# for x in difference.details:
# self.visit(x)
#
# self.depth -= 1
#
# def visit_difference(self, difference):
# raise NotImplementedError()
#
# @classmethod
# def indent(cls, val, prefix):
# # As an optimisation, output as much as possible in one go to avoid
# # unnecessary splitting, interpolating, etc.
# #
# # We don't use textwrap.indent as that unnecessarily calls
# # str.splitlines, etc.
# return prefix + val.rstrip().replace('\n', '\n{}'.format(prefix))
#
# def create_limited_print_func(print_func, max_page_size):
# count = 0
#
# def fn(val, force=False, count=count):
# print_func(val)
#
# if force or max_page_size == 0:
# return
#
# count += len(val)
# if count >= max_page_size:
# raise PrintLimitReached()
#
# return fn
#
# class PrintLimitReached(Exception):
# pass
. Output only the next line. | Config().max_text_report_size, |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
class TextPresenter(Presenter):
PREFIX = u'│ '
RE_PREFIX = re.compile(r'(^|\n)')
def __init__(self, print_func, color):
<|code_end|>
, determine the next line of code. You have imports:
import re
from diffoscope.diff import color_unified_diff
from diffoscope.config import Config
from .utils import Presenter, create_limited_print_func, PrintLimitReached
and context (class names, function names, or code) available:
# Path: diffoscope/diff.py
# def color_unified_diff(diff):
# RESET = '\033[0m'
# RED, GREEN, CYAN = '\033[31m', '\033[32m', '\033[0;36m'
#
# def repl(m):
# return '{}{}{}'.format({
# '-': RED,
# '@': CYAN,
# '+': GREEN,
# }[m.group(1)], m.group(0), RESET)
#
# return re_diff_change.sub(repl, diff)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/presenters/utils.py
# class Presenter(object):
# def __init__(self):
# self.depth = 0
#
# def start(self, difference):
# self.visit(difference)
#
# def visit(self, difference):
# self.visit_difference(difference)
#
# self.depth += 1
#
# for x in difference.details:
# self.visit(x)
#
# self.depth -= 1
#
# def visit_difference(self, difference):
# raise NotImplementedError()
#
# @classmethod
# def indent(cls, val, prefix):
# # As an optimisation, output as much as possible in one go to avoid
# # unnecessary splitting, interpolating, etc.
# #
# # We don't use textwrap.indent as that unnecessarily calls
# # str.splitlines, etc.
# return prefix + val.rstrip().replace('\n', '\n{}'.format(prefix))
#
# def create_limited_print_func(print_func, max_page_size):
# count = 0
#
# def fn(val, force=False, count=count):
# print_func(val)
#
# if force or max_page_size == 0:
# return
#
# count += len(val)
# if count >= max_page_size:
# raise PrintLimitReached()
#
# return fn
#
# class PrintLimitReached(Exception):
# pass
. Output only the next line. | self.print_func = create_limited_print_func( |
Using the snippet: <|code_start|># (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
class TextPresenter(Presenter):
PREFIX = u'│ '
RE_PREFIX = re.compile(r'(^|\n)')
def __init__(self, print_func, color):
self.print_func = create_limited_print_func(
print_func,
Config().max_text_report_size,
)
self.color = color
super().__init__()
def start(self, difference):
try:
super().start(difference)
<|code_end|>
, determine the next line of code. You have imports:
import re
from diffoscope.diff import color_unified_diff
from diffoscope.config import Config
from .utils import Presenter, create_limited_print_func, PrintLimitReached
and context (class names, function names, or code) available:
# Path: diffoscope/diff.py
# def color_unified_diff(diff):
# RESET = '\033[0m'
# RED, GREEN, CYAN = '\033[31m', '\033[32m', '\033[0;36m'
#
# def repl(m):
# return '{}{}{}'.format({
# '-': RED,
# '@': CYAN,
# '+': GREEN,
# }[m.group(1)], m.group(0), RESET)
#
# return re_diff_change.sub(repl, diff)
#
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/presenters/utils.py
# class Presenter(object):
# def __init__(self):
# self.depth = 0
#
# def start(self, difference):
# self.visit(difference)
#
# def visit(self, difference):
# self.visit_difference(difference)
#
# self.depth += 1
#
# for x in difference.details:
# self.visit(x)
#
# self.depth -= 1
#
# def visit_difference(self, difference):
# raise NotImplementedError()
#
# @classmethod
# def indent(cls, val, prefix):
# # As an optimisation, output as much as possible in one go to avoid
# # unnecessary splitting, interpolating, etc.
# #
# # We don't use textwrap.indent as that unnecessarily calls
# # str.splitlines, etc.
# return prefix + val.rstrip().replace('\n', '\n{}'.format(prefix))
#
# def create_limited_print_func(print_func, max_page_size):
# count = 0
#
# def fn(val, force=False, count=count):
# print_func(val)
#
# if force or max_page_size == 0:
# return
#
# count += len(val)
# if count >= max_page_size:
# raise PrintLimitReached()
#
# return fn
#
# class PrintLimitReached(Exception):
# pass
. Output only the next line. | except PrintLimitReached: |
Predict the next line after this snippet: <|code_start|>#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
re_html = re.compile(r'.*<body(?P<body>.*)<div class="footer">', re.MULTILINE | re.DOTALL)
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
def run(capsys, *args):
with pytest.raises(SystemExit) as exc:
prev = os.getcwd()
os.chdir(DATA_DIR)
try:
<|code_end|>
using the current file's imports:
import os
import re
import pytest
from diffoscope.main import main
and any relevant context from other files:
# Path: diffoscope/main.py
# def main(args=None):
# if args is None:
# args = sys.argv[1:]
# signal.signal(signal.SIGTERM, sigterm_handler)
# parsed_args = None
# try:
# with profile('main', 'parse_args'):
# parser = create_parser()
# parsed_args = parser.parse_args(args)
# sys.exit(run_diffoscope(parsed_args))
# except KeyboardInterrupt:
# logger.info('Keyboard Interrupt')
# sys.exit(2)
# except BrokenPipeError:
# sys.exit(2)
# except Exception:
# traceback.print_exc()
# if parsed_args and parsed_args.debugger:
# import pdb
# pdb.post_mortem()
# sys.exit(2)
# finally:
# with profile('main', 'cleanup'):
# clean_all_temp_files()
#
# # Print profiling output at the very end
# if parsed_args is not None:
# ProfileManager().finish(parsed_args)
. Output only the next line. | main(args + ('test1.tar', 'test2.tar')) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
zip1 = load_fixture('test1.zip')
zip2 = load_fixture('test2.zip')
mozzip1 = load_fixture('test1.mozzip')
mozzip2 = load_fixture('test2.mozzip')
def test_identification(zip1):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from diffoscope.comparators.zip import ZipFile, MozillaZipFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/comparators/zip.py
# class ZipFile(File):
# CONTAINER_CLASS = ZipContainer
# RE_FILE_TYPE = re.compile(r'^(Zip archive|Java archive|EPUB document|OpenDocument (Text|Spreadsheet|Presentation|Drawing|Formula|Template|Text Template))\b')
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(Zipinfo, self.path, other.path) or \
# Difference.from_command(ZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
#
# class MozillaZipFile(File):
# CONTAINER_CLASS = MozillaZipContainer
#
# @staticmethod
# def recognizes(file):
# # Mozilla-optimized ZIPs start with a 32-bit little endian integer
# # indicating the amount of data to preload, followed by the ZIP
# # central directory (with a PK\x01\x02 signature)
# with open(file.path, 'rb') as f:
# preload = f.read(4)
# if len(preload) == 4:
# signature = f.read(4)
# return signature == b'PK\x01\x02'
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(MozillaZipinfo, self.path, other.path) or \
# Difference.from_command(MozillaZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
. Output only the next line. | assert isinstance(zip1, ZipFile) |
Next line prediction: <|code_start|>
def test_identification(zip1):
assert isinstance(zip1, ZipFile)
def test_no_differences(zip1):
difference = zip1.compare(zip1)
assert difference is None
@pytest.fixture
def differences(zip1, zip2):
return zip1.compare(zip2).details
@skip_unless_tools_exist('zipinfo')
def test_metadata(differences):
expected_diff = get_data('zip_zipinfo_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('zipinfo')
def test_compressed_files(differences):
assert differences[1].source1 == 'dir/text'
assert differences[1].source2 == 'dir/text'
expected_diff = get_data('text_ascii_expected_diff')
assert differences[1].unified_diff == expected_diff
@skip_unless_tools_exist('zipinfo')
def test_compare_non_existing(monkeypatch, zip1):
assert_non_existing(monkeypatch, zip1)
def test_mozzip_identification(mozzip1):
<|code_end|>
. Use current file imports:
(import pytest
from diffoscope.comparators.zip import ZipFile, MozillaZipFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/comparators/zip.py
# class ZipFile(File):
# CONTAINER_CLASS = ZipContainer
# RE_FILE_TYPE = re.compile(r'^(Zip archive|Java archive|EPUB document|OpenDocument (Text|Spreadsheet|Presentation|Drawing|Formula|Template|Text Template))\b')
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(Zipinfo, self.path, other.path) or \
# Difference.from_command(ZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
#
# class MozillaZipFile(File):
# CONTAINER_CLASS = MozillaZipContainer
#
# @staticmethod
# def recognizes(file):
# # Mozilla-optimized ZIPs start with a 32-bit little endian integer
# # indicating the amount of data to preload, followed by the ZIP
# # central directory (with a PK\x01\x02 signature)
# with open(file.path, 'rb') as f:
# preload = f.read(4)
# if len(preload) == 4:
# signature = f.read(4)
# return signature == b'PK\x01\x02'
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(MozillaZipinfo, self.path, other.path) or \
# Difference.from_command(MozillaZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
. Output only the next line. | assert isinstance(mozzip1, MozillaZipFile) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
def test_destination(tmpdir):
def create(x):
path = os.path.join(str(tmpdir.mkdir(x)), 'src')
os.symlink('/{}'.format(x), path)
<|code_end|>
, generate the next line using the imports in this file:
import os
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import get_data
and context (functions, classes, or occasionally code) from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | return specialize(FilesystemFile(path)) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
# 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_FILE1_PATH = data('text_ascii1')
TEST_FILE2_PATH = data('text_ascii2')
def test_no_differences():
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import shutil
import pytest
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.directory import compare_directories
from diffoscope.comparators.utils.specialize import specialize
from utils.data import data, get_data
and context (classes, functions, sometimes code) from other files:
# Path: diffoscope/comparators/directory.py
# def compare_directories(path1, path2, source=None):
# return FilesystemDirectory(path1).compare(FilesystemDirectory(path2))
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | difference = compare_directories(os.path.dirname(__file__), os.path.dirname(__file__)) |
Given the code snippet: <|code_start|> tmpdir.mkdir('a')
tmpdir.mkdir('a/dir')
tmpdir.mkdir('b')
tmpdir.mkdir('b/dir')
shutil.copy(TEST_FILE1_PATH, str(tmpdir.join('a/dir/text')))
shutil.copy(TEST_FILE2_PATH, str(tmpdir.join('b/dir/text')))
os.utime(str(tmpdir.join('a/dir/text')), (0, 0))
os.utime(str(tmpdir.join('b/dir/text')), (0, 0))
os.utime(str(tmpdir.join('a/dir')), (0, 0))
os.utime(str(tmpdir.join('b/dir')), (0, 0))
os.utime(str(tmpdir.join('a')), (0, 0))
os.utime(str(tmpdir.join('b')), (0, 0))
return compare_directories(str(tmpdir.join('a')), str(tmpdir.join('b'))).details
def test_content(differences):
assert differences[0].source1 == 'dir'
assert differences[0].details[0].source1 == 'text'
expected_diff = get_data('text_ascii_expected_diff')
assert differences[0].details[0].unified_diff == expected_diff
def test_stat(differences):
assert 'stat' in differences[0].details[0].details[0].source1
def test_compare_to_file(tmpdir):
path = str(tmpdir.join('file'))
with open(path, 'w') as f:
f.write("content")
<|code_end|>
, generate the next line using the imports in this file:
import os
import shutil
import pytest
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.directory import compare_directories
from diffoscope.comparators.utils.specialize import specialize
from utils.data import data, get_data
and context (functions, classes, or occasionally code) from other files:
# Path: diffoscope/comparators/directory.py
# def compare_directories(path1, path2, source=None):
# return FilesystemDirectory(path1).compare(FilesystemDirectory(path2))
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | a = specialize(FilesystemFile(str(tmpdir.mkdir('dir')))) |
Next line prediction: <|code_start|>
# these were generated with:
# echo 'public class Test { static public void Main () {} }' > test.cs
# mcs -out:test1.exe test.cs ; sleep 2; mcs -out:test2.exe test.cs
exe1 = load_fixture('test1.exe')
exe2 = load_fixture('test2.exe')
def test_identification(exe1):
assert isinstance(exe1, MonoExeFile)
def test_no_differences(exe1):
difference = exe1.compare(exe1)
assert difference is None
@pytest.fixture
def differences(exe1, exe2):
return exe1.compare(exe2).details
@skip_unless_tools_exist('pedump')
def test_diff(differences):
expected_diff = get_data('pe_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('pedump')
def test_compare_non_existing(monkeypatch, exe1):
<|code_end|>
. Use current file imports:
(import pytest
from diffoscope.config import Config
from diffoscope.comparators.mono import MonoExeFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Given snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
text_ascii1 = load_fixture('text_ascii1')
@pytest.fixture
def devnull():
return specialize(FilesystemFile('/dev/null'))
@pytest.fixture
def differences(devnull, text_ascii1):
return devnull.compare_bytes(text_ascii1)
@pytest.fixture
def differences_reverse(text_ascii1, devnull):
return text_ascii1.compare_bytes(devnull)
def test_identification(devnull):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.device import Device
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data, normalize_zeros
from utils.tools import skip_unless_tools_exist
and context:
# Path: diffoscope/comparators/device.py
# class Device(File):
# @staticmethod
# def recognizes(file):
# return file.is_device()
#
# def get_device(self):
# assert isinstance(self, FilesystemFile)
# st = os.lstat(self.name)
# return st.st_mode, os.major(st.st_rdev), os.minor(st.st_rdev)
#
# def has_same_content_as(self, other):
# logger.debug("has_same_content: %s %s", self, other)
# try:
# return self.get_device() == other.get_device()
# except (AttributeError, OSError):
# # 'other' is not a device, or something.
# logger.debug("has_same_content: Not a device: %s", other)
# return False
#
# def create_placeholder(self):
# with get_named_temporary_file(mode='w+', delete=False) as f:
# f.write(format_device(*self.get_device()))
# f.flush()
# return f.name
#
# @property
# def path(self):
# if not hasattr(self, '_placeholder'):
# self._placeholder = self.create_placeholder()
# return self._placeholder
#
# def cleanup(self):
# if hasattr(self, '_placeholder'):
# os.remove(self._placeholder)
# del self._placeholder
# super().cleanup()
#
# def compare(self, other, source=None):
# with open(self.path) as my_content, \
# open(other.path) as other_content:
# return Difference.from_text_readers(my_content, other_content, self.name, other.name, source=source, comment="device")
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
which might include code, classes, or functions. Output only the next line. | assert isinstance(devnull, Device) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
text_ascii1 = load_fixture('text_ascii1')
@pytest.fixture
def devnull():
<|code_end|>
. Write the next line using the current file imports:
import pytest
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.device import Device
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data, normalize_zeros
from utils.tools import skip_unless_tools_exist
and context from other files:
# Path: diffoscope/comparators/device.py
# class Device(File):
# @staticmethod
# def recognizes(file):
# return file.is_device()
#
# def get_device(self):
# assert isinstance(self, FilesystemFile)
# st = os.lstat(self.name)
# return st.st_mode, os.major(st.st_rdev), os.minor(st.st_rdev)
#
# def has_same_content_as(self, other):
# logger.debug("has_same_content: %s %s", self, other)
# try:
# return self.get_device() == other.get_device()
# except (AttributeError, OSError):
# # 'other' is not a device, or something.
# logger.debug("has_same_content: Not a device: %s", other)
# return False
#
# def create_placeholder(self):
# with get_named_temporary_file(mode='w+', delete=False) as f:
# f.write(format_device(*self.get_device()))
# f.flush()
# return f.name
#
# @property
# def path(self):
# if not hasattr(self, '_placeholder'):
# self._placeholder = self.create_placeholder()
# return self._placeholder
#
# def cleanup(self):
# if hasattr(self, '_placeholder'):
# os.remove(self._placeholder)
# del self._placeholder
# super().cleanup()
#
# def compare(self, other, source=None):
# with open(self.path) as my_content, \
# open(other.path) as other_content:
# return Difference.from_text_readers(my_content, other_content, self.name, other.name, source=source, comment="device")
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
, which may include functions, classes, or code. Output only the next line. | return specialize(FilesystemFile('/dev/null')) |
Based on the snippet: <|code_start|> raise NotImplementedError()
# Remove any temporary data associated with the file. The function
# should be idempotent and work during the destructor.
def cleanup(self):
if hasattr(self, '_as_container'):
del self._as_container
def __del__(self):
self.cleanup()
# This might be different from path and is used to do file extension matching
@property
def name(self):
return self._name
@property
def container(self):
return self._container
@property
def as_container(self):
if not hasattr(self.__class__, 'CONTAINER_CLASS'):
if hasattr(self, '_other_file'):
return self._other_file.__class__.CONTAINER_CLASS(self)
return None
if not hasattr(self, '_as_container'):
logger.debug('instantiating %s for %s', self.__class__.CONTAINER_CLASS, self)
try:
self._as_container = self.__class__.CONTAINER_CLASS(self)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import abc
import magic
import logging
import subprocess
import tlsh
from diffoscope.exc import RequiredToolNotFound, OutputParsingError
from diffoscope.tools import tool_required
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from .compare import compare_binary_files
and context (classes, functions, sometimes code) from other files:
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# class OutputParsingError(Exception):
# def __init__(self, command, object):
# self.command = command
# self.object_class = object.__class__
#
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
. Output only the next line. | except RequiredToolNotFound: |
Using the snippet: <|code_start|> difference = self._compare_using_details(other, source)
# no differences detected inside? let's at least do a binary diff
if difference is None:
difference = self.compare_bytes(other, source=source)
if difference is None:
return None
difference.add_comment(
"No file format specific differences found inside, "
"yet data differs ({})".format(self.magic_file_type),
)
except subprocess.CalledProcessError as e:
difference = self.compare_bytes(other, source=source)
if e.output:
output = re.sub(r'^', ' ', e.output.decode('utf-8', errors='replace'), flags=re.MULTILINE)
else:
output = '<none>'
cmd = ' '.join(e.cmd)
if difference is None:
return None
difference.add_comment("Command `%s` exited with %d. Output:\n%s"
% (cmd, e.returncode, output))
except RequiredToolNotFound as e:
difference = self.compare_bytes(other, source=source)
if difference is None:
return None
difference.add_comment(
"'%s' not available in path. Falling back to binary comparison." % e.command)
package = e.get_package()
if package:
difference.add_comment("Install '%s' to get a better output." % package)
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import abc
import magic
import logging
import subprocess
import tlsh
from diffoscope.exc import RequiredToolNotFound, OutputParsingError
from diffoscope.tools import tool_required
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from .compare import compare_binary_files
and context (class names, function names, or code) available:
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# class OutputParsingError(Exception):
# def __init__(self, command, object):
# self.command = command
# self.object_class = object.__class__
#
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
. Output only the next line. | except OutputParsingError as e: |
Based on the snippet: <|code_start|> if not details:
return None
difference = Difference(None, self.name, other.name, source=source)
difference.add_details(details)
return difference
def has_same_content_as(self, other):
logger.debug('Binary.has_same_content: %s %s', self, other)
if os.path.isdir(self.path) or os.path.isdir(other.path):
return False
# try comparing small files directly first
try:
my_size = os.path.getsize(self.path)
other_size = os.path.getsize(other.path)
except OSError:
# files not readable (e.g. broken symlinks) or something else,
# just assume they are different
return False
if my_size == other_size and my_size <= SMALL_FILE_THRESHOLD:
try:
with profile('command', 'cmp (internal)'):
with open(self.path, 'rb') as file1, open(other.path, 'rb') as file2:
return file1.read() == file2.read()
except OSError:
# one or both files could not be opened for some reason,
# assume they are different
return False
return self.cmp_external(other)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import abc
import magic
import logging
import subprocess
import tlsh
from diffoscope.exc import RequiredToolNotFound, OutputParsingError
from diffoscope.tools import tool_required
from diffoscope.profiling import profile
from diffoscope.difference import Difference
from .compare import compare_binary_files
and context (classes, functions, sometimes code) from other files:
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# class OutputParsingError(Exception):
# def __init__(self, command, object):
# self.command = command
# self.object_class = object.__class__
#
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
. Output only the next line. | @tool_required('cmp') |
Predict the next line for this snippet: <|code_start|>
bzip1 = load_fixture('test1.bz2')
bzip2 = load_fixture('test2.bz2')
def test_identification(bzip1):
assert isinstance(bzip1, Bzip2File)
def test_no_differences(bzip1):
difference = bzip1.compare(bzip1)
assert difference is None
@pytest.fixture
def differences(bzip1, bzip2):
return bzip1.compare(bzip2).details
@skip_unless_tools_exist('bzip2')
def test_content_source(differences):
assert differences[0].source1 == 'test1'
assert differences[0].source2 == 'test2'
@skip_unless_tools_exist('bzip2')
def test_content_source_without_extension(tmpdir, bzip1, bzip2):
path1 = str(tmpdir.join('test1'))
path2 = str(tmpdir.join('test2'))
shutil.copy(bzip1.path, path1)
shutil.copy(bzip2.path, path2)
<|code_end|>
with the help of current file imports:
import shutil
import pytest
from diffoscope.comparators.bzip2 import Bzip2File
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
, which may contain function names, class names, or code. Output only the next line. | bzip1 = specialize(FilesystemFile(path1)) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2014-2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
try:
except ImportError: # noqa
tlsh = None
logger = logging.getLogger(__name__)
def perform_fuzzy_matching(members1, members2):
<|code_end|>
. Use current file imports:
import logging
import operator
import tlsh
from diffoscope.config import Config
and context (classes, functions, or code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | if tlsh == None or Config().fuzzy_threshold == 0: |
Given the following code snippet before the placeholder: <|code_start|>
class1 = load_fixture('Test1.class')
class2 = load_fixture('Test2.class')
def javap_version():
try:
out = subprocess.check_output(['javap', '-version'])
except subprocess.CalledProcessError as e:
out = e.output
return out.decode('UTF-8').strip()
def test_identification(class1):
assert isinstance(class1, ClassFile)
def test_no_differences(class1):
difference = class1.compare(class1)
assert difference is None
@pytest.fixture
def differences(class1, class2):
return class1.compare(class2).details
@skip_unless_tool_is_at_least('javap', javap_version, '1.8')
def test_diff(differences):
expected_diff = get_data('class_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('javap')
def test_compare_non_existing(monkeypatch, class1):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
import subprocess
from diffoscope.config import Config
from diffoscope.comparators.java import ClassFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Next line prediction: <|code_start|>
# Generated by: ssh-keygen -t dsa -C "Test1"
opensshpubkey1 = load_fixture('test_openssh_pub_key1.pub')
# Generated by: ssh-keygen -t rsa -b 4096 -C "Test2"
opensshpubkey2 = load_fixture('test_openssh_pub_key2.pub')
def openssh_version():
out = subprocess.check_output(('ssh', '-V'), stderr=subprocess.STDOUT)
return out.decode().split()[0].split('_')[1]
def test_identification(opensshpubkey1):
assert isinstance(opensshpubkey1, PublicKeyFile)
def test_no_differences(opensshpubkey1):
difference = opensshpubkey1.compare(opensshpubkey1)
assert difference is None
@pytest.fixture
def differences(opensshpubkey1, opensshpubkey2):
return opensshpubkey1.compare(opensshpubkey2).details
@skip_unless_tool_is_at_least('ssh-keygen', openssh_version, '6.9')
def test_diff(differences):
expected_diff = get_data('openssh_pub_key_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('ssh-keygen')
def test_compare_non_existing(monkeypatch, opensshpubkey1):
<|code_end|>
. Use current file imports:
(import pytest
import subprocess
from diffoscope.config import Config
from diffoscope.comparators.openssh import PublicKeyFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Predict the next line after this snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
javascript1 = load_fixture('test1.js')
javascript2 = load_fixture('test2.js')
def test_identification(javascript1):
assert isinstance(javascript1, JavaScriptFile)
def test_no_differences(javascript1):
difference = javascript1.compare(javascript1)
assert difference is None
@pytest.fixture
def differences(javascript1, javascript2):
return javascript1.compare(javascript2).details
@skip_unless_tools_exist('js-beautify')
def test_diff(differences):
expected_diff = get_data('javascript_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('js-beautify')
def test_compare_non_existing(monkeypatch, javascript1):
<|code_end|>
using the current file's imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.javascript import JavaScriptFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and any relevant context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Next line prediction: <|code_start|>@pytest.fixture
def differences(gzip1, gzip2):
return gzip1.compare(gzip2).details
def test_metadata(differences):
assert differences[0].source1 == 'metadata'
assert differences[0].source2 == 'metadata'
expected_diff = get_data('gzip_metadata_expected_diff')
assert differences[0].unified_diff == expected_diff
def test_content_source(differences):
assert differences[1].source1 == 'test1'
assert differences[1].source2 == 'test2'
def test_content_source_without_extension(tmpdir, gzip1, gzip2):
path1 = str(tmpdir.join('test1'))
path2 = str(tmpdir.join('test2'))
shutil.copy(gzip1.path, path1)
shutil.copy(gzip2.path, path2)
gzip1 = specialize(FilesystemFile(path1))
gzip2 = specialize(FilesystemFile(path2))
difference = gzip1.compare(gzip2).details
assert difference[1].source1 == 'test1-content'
assert difference[1].source2 == 'test2-content'
def test_content_diff(differences):
expected_diff = get_data('text_ascii_expected_diff')
assert differences[1].unified_diff == expected_diff
def test_compare_non_existing(monkeypatch, gzip1):
<|code_end|>
. Use current file imports:
(import shutil
import pytest
from diffoscope.config import Config
from diffoscope.comparators.gzip import GzipFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Continue the code snippet: <|code_start|>gzip1 = load_fixture('test1.gz')
gzip2 = load_fixture('test2.gz')
def test_identification(gzip1):
assert isinstance(gzip1, GzipFile)
def test_no_differences(gzip1):
difference = gzip1.compare(gzip1)
assert difference is None
@pytest.fixture
def differences(gzip1, gzip2):
return gzip1.compare(gzip2).details
def test_metadata(differences):
assert differences[0].source1 == 'metadata'
assert differences[0].source2 == 'metadata'
expected_diff = get_data('gzip_metadata_expected_diff')
assert differences[0].unified_diff == expected_diff
def test_content_source(differences):
assert differences[1].source1 == 'test1'
assert differences[1].source2 == 'test2'
def test_content_source_without_extension(tmpdir, gzip1, gzip2):
path1 = str(tmpdir.join('test1'))
path2 = str(tmpdir.join('test2'))
shutil.copy(gzip1.path, path1)
shutil.copy(gzip2.path, path2)
<|code_end|>
. Use current file imports:
import shutil
import pytest
from diffoscope.config import Config
from diffoscope.comparators.gzip import GzipFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data
and context (classes, functions, or code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | gzip1 = specialize(FilesystemFile(path1)) |
Using the snippet: <|code_start|> assert differences[1].details[0].details[1].details[0].comment == 'Files in package differ'
def test_identical_files_in_md5sums(deb1, deb2):
for name in ['./usr/share/doc/test/README.Debian', './usr/share/doc/test/copyright']:
assert deb1.md5sums[name] == deb2.md5sums[name]
def test_identification_of_data_tar(deb1, deb2, monkeypatch):
orig_func = DebDataTarFile.recognizes
@staticmethod
def probe(file):
ret = orig_func(file)
if ret:
test_identification_of_data_tar.found = True
return ret
test_identification_of_data_tar.found = False
monkeypatch.setattr(DebDataTarFile, 'recognizes', probe)
deb1.compare(deb2)
assert test_identification_of_data_tar.found
def test_skip_comparison_of_known_identical_files(deb1, deb2, monkeypatch):
compared = set()
orig_func = diffoscope.comparators.utils.compare.compare_files
def probe(file1, file2, source=None):
compared.add(file1.name)
return orig_func(file1, file2, source=None)
monkeypatch.setattr(diffoscope.comparators.utils.compare, 'compare_files', probe)
deb1.compare(deb2)
assert './usr/share/doc/test/README.Debian' not in compared
def test_compare_non_existing(monkeypatch, deb1):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import diffoscope.comparators
from diffoscope.config import Config
from diffoscope.comparators.deb import DebFile, Md5sumsFile, DebDataTarFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data
and context (class names, function names, or code) available:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Given the code snippet: <|code_start|>
deb1 = load_fixture('test1.deb')
deb2 = load_fixture('test2.deb')
def test_identification(deb1):
assert isinstance(deb1, DebFile)
def test_no_differences(deb1):
difference = deb1.compare(deb1)
assert difference is None
@pytest.fixture
def differences(deb1, deb2):
return deb1.compare(deb2).details
def test_metadata(differences):
expected_diff = get_data('deb_metadata_expected_diff')
assert differences[0].unified_diff == expected_diff
def test_compressed_files(differences):
assert differences[1].source1 == 'control.tar.gz'
assert differences[2].source1 == 'data.tar.gz'
def test_identification_of_md5sums_outside_deb(tmpdir):
path = str(tmpdir.join('md5sums'))
open(path, 'w')
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import diffoscope.comparators
from diffoscope.config import Config
from diffoscope.comparators.deb import DebFile, Md5sumsFile, DebDataTarFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data
and context (functions, classes, or occasionally code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | f = specialize(FilesystemFile(path)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
image1 = load_fixture('test1.ico')
image2 = load_fixture('test2.ico')
image1_meta = load_fixture('test1_meta.ico')
image2_meta = load_fixture('test2_meta.ico')
def test_identification(image1):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from diffoscope.comparators.image import ICOImageFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
from test_jpeg_image import identify_version
and context:
# Path: diffoscope/comparators/image.py
# class ICOImageFile(File):
# RE_FILE_TYPE = re.compile(r'\bMS Windows icon resource\b')
#
# def compare_details(self, other, source=None):
# differences = []
#
# # img2txt does not support .ico files directly so convert to .PNG.
# try:
# png_a, png_b = [ICOImageFile.convert(x) for x in (self, other)]
# except subprocess.CalledProcessError: # noqa
# pass
# else:
# differences.append(Difference.from_command(Img2Txt, png_a, png_b))
#
# differences.append(Difference.from_command(
# Identify,
# self.path,
# other.path,
# source="Image metadata",
# ))
#
# return differences
#
# @staticmethod
# @tool_required('convert')
# def convert(file):
# result = get_named_temporary_file(suffix='.png').name
#
# subprocess.check_call(('convert', file.path, result))
#
# return result
which might include code, classes, or functions. Output only the next line. | assert isinstance(image1, ICOImageFile) |
Here is a snippet: <|code_start|>
@pytest.fixture
def differences(iso1, iso2):
return iso1.compare(iso2).details
@skip_unless_tools_exist('isoinfo')
def test_iso9660_content(differences):
expected_diff = get_data('iso9660_content_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('isoinfo')
def test_iso9660_rockridge(differences):
expected_diff = get_data('iso9660_rockridge_expected_diff')
assert differences[1].unified_diff == expected_diff
@skip_unless_tools_exist('isoinfo')
def test_symlink(differences):
assert differences[3].comment == 'symlink'
expected_diff = get_data('symlink_expected_diff')
assert differences[3].unified_diff == expected_diff
@skip_unless_tools_exist('isoinfo')
def test_compressed_files(differences):
assert differences[2].source1 == 'text'
assert differences[2].source2 == 'text'
expected_diff = get_data('text_ascii_expected_diff')
assert differences[2].unified_diff == expected_diff
@skip_unless_tools_exist('isoinfo')
def test_compare_non_existing(monkeypatch, iso1):
<|code_end|>
. Write the next line using the current file imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.missing_file import MissingFile
from diffoscope.comparators.iso9660 import Iso9660File
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
, which may include functions, classes, or code. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Given snippet: <|code_start|>
epub1 = load_fixture('test1.epub')
epub2 = load_fixture('test2.epub')
def test_identification(epub1):
assert isinstance(epub1, ZipFile)
def test_no_differences(epub1):
difference = epub1.compare(epub1)
assert difference is None
@pytest.fixture
def differences(epub1, epub2):
return epub1.compare(epub2).details
@skip_unless_tools_exist('zipinfo')
def test_differences(differences):
assert differences[0].source1 == 'zipinfo {}'
assert differences[0].source2 == 'zipinfo {}'
assert differences[1].source1 == 'content.opf'
assert differences[1].source2 == 'content.opf'
assert differences[2].source1 == 'toc.ncx'
assert differences[2].source2 == 'toc.ncx'
assert differences[3].source1 == 'ch001.xhtml'
assert differences[3].source2 == 'ch001.xhtml'
expected_diff = get_data('epub_expected_diffs')
assert expected_diff == "".join(map(lambda x: x.unified_diff, differences))
@skip_unless_tools_exist('zipinfo')
def test_compare_non_existing(monkeypatch, epub1):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.zip import ZipFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and context:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/zip.py
# class ZipFile(File):
# CONTAINER_CLASS = ZipContainer
# RE_FILE_TYPE = re.compile(r'^(Zip archive|Java archive|EPUB document|OpenDocument (Text|Spreadsheet|Presentation|Drawing|Formula|Template|Text Template))\b')
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(Zipinfo, self.path, other.path) or \
# Difference.from_command(ZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
which might include code, classes, or functions. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
epub1 = load_fixture('test1.epub')
epub2 = load_fixture('test2.epub')
def test_identification(epub1):
<|code_end|>
. Use current file imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.zip import ZipFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and context (classes, functions, or code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/comparators/zip.py
# class ZipFile(File):
# CONTAINER_CLASS = ZipContainer
# RE_FILE_TYPE = re.compile(r'^(Zip archive|Java archive|EPUB document|OpenDocument (Text|Spreadsheet|Presentation|Drawing|Formula|Template|Text Template))\b')
#
# def compare_details(self, other, source=None):
# zipinfo_difference = Difference.from_command(Zipinfo, self.path, other.path) or \
# Difference.from_command(ZipinfoVerbose, self.path, other.path)
# return [zipinfo_difference]
. Output only the next line. | assert isinstance(epub1, ZipFile) |
Continue the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
def output_all(difference, parsed_args, has_differences):
"""
Generate all known output formats.
"""
if difference is None:
return
FORMATS = {
'text': {
'fn': text,
'target': parsed_args.text_output,
},
'html': {
'fn': html,
'target': parsed_args.html_output,
},
'json': {
<|code_end|>
. Use current file imports:
import sys
import logging
from ..profiling import profile
from .text import TextPresenter
from .json import JSONPresenter
from .html import output_html, output_html_directory
from .utils import make_printer
from .markdown import MarkdownTextPresenter
from .restructuredtext import RestructuredTextPresenter
and context (classes, functions, or code) from other files:
# Path: diffoscope/presenters/text.py
# class TextPresenter(Presenter):
# PREFIX = u'│ '
# RE_PREFIX = re.compile(r'(^|\n)')
#
# def __init__(self, print_func, color):
# self.print_func = create_limited_print_func(
# print_func,
# Config().max_text_report_size,
# )
# self.color = color
#
# super().__init__()
#
# def start(self, difference):
# try:
# super().start(difference)
# except PrintLimitReached:
# self.print_func("Max output size reached.", force=True)
#
# def visit_difference(self, difference):
# if self.depth == 0:
# self.output("--- {}".format(difference.source1))
# self.output("+++ {}".format(difference.source2))
# elif difference.source1 == difference.source2:
# self.output(u"├── {}".format(difference.source1))
# else:
# self.output(u"│ --- {}".format(difference.source1))
# self.output(u"├── +++ {}".format(difference.source2))
#
# for x in difference.comments:
# self.output(u"│┄ {}".format(x))
#
# diff = difference.unified_diff
#
# if diff:
# self.output(color_unified_diff(diff) if self.color else diff, True)
#
# def output(self, val, raw=False):
# self.print_func(
# self.indent(val, self.PREFIX * (self.depth + 0 if raw else -1)),
# )
#
# Path: diffoscope/presenters/json.py
# class JSONPresenter(Presenter):
# def __init__(self, print_func):
# self.root = []
# self.current = self.root
# self.print_func = print_func
#
# super().__init__()
#
# def start(self, difference):
# super().start(difference)
#
# self.print_func(json.dumps(self.root[0], indent=2, sort_keys=True))
#
# def visit_difference(self, difference):
# self.current.append({
# 'source1': difference.source1,
# 'source2': difference.source2,
# 'comments': [x for x in difference.comments],
# 'differences': [],
# 'unified_diff': difference.unified_diff,
# })
#
# self.current = self.current[-1]['differences']
#
# Path: diffoscope/presenters/utils.py
# @contextlib.contextmanager
# def make_printer(path):
# output = sys.stdout
#
# if path != '-':
# output = codecs.open(path, 'w', encoding='utf-8')
#
# def fn(*args, **kwargs):
# kwargs['file'] = output
# print(*args, **kwargs)
# fn.output = output
#
# yield fn
#
# if path != '-':
# output.close()
#
# Path: diffoscope/presenters/markdown.py
# class MarkdownTextPresenter(Presenter):
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func(x)
# self.print_func()
#
# if difference.unified_diff:
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# prefix = '#' * min(self.depth + 1, 6)
#
# self.print_func("{} {}".format(prefix, val))
# self.print_func()
#
# Path: diffoscope/presenters/restructuredtext.py
# class RestructuredTextPresenter(Presenter):
# TITLE_CHARS = '=-`:.\'"~^_*+#'
#
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func()
# self.print_func(x)
#
# if difference.unified_diff:
# self.print_func('::')
# self.print_func()
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# char = self.TITLE_CHARS[self.depth % len(self.TITLE_CHARS)]
#
# if self.depth < len(self.TITLE_CHARS):
# self.print_func(len(val) * char)
#
# self.print_func(val)
# self.print_func(len(val) * char)
# self.print_func()
. Output only the next line. | 'klass': JSONPresenter, |
Here is a snippet: <|code_start|># along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
def output_all(difference, parsed_args, has_differences):
"""
Generate all known output formats.
"""
if difference is None:
return
FORMATS = {
'text': {
'fn': text,
'target': parsed_args.text_output,
},
'html': {
'fn': html,
'target': parsed_args.html_output,
},
'json': {
'klass': JSONPresenter,
'target': parsed_args.json_output,
},
'markdown': {
<|code_end|>
. Write the next line using the current file imports:
import sys
import logging
from ..profiling import profile
from .text import TextPresenter
from .json import JSONPresenter
from .html import output_html, output_html_directory
from .utils import make_printer
from .markdown import MarkdownTextPresenter
from .restructuredtext import RestructuredTextPresenter
and context from other files:
# Path: diffoscope/presenters/text.py
# class TextPresenter(Presenter):
# PREFIX = u'│ '
# RE_PREFIX = re.compile(r'(^|\n)')
#
# def __init__(self, print_func, color):
# self.print_func = create_limited_print_func(
# print_func,
# Config().max_text_report_size,
# )
# self.color = color
#
# super().__init__()
#
# def start(self, difference):
# try:
# super().start(difference)
# except PrintLimitReached:
# self.print_func("Max output size reached.", force=True)
#
# def visit_difference(self, difference):
# if self.depth == 0:
# self.output("--- {}".format(difference.source1))
# self.output("+++ {}".format(difference.source2))
# elif difference.source1 == difference.source2:
# self.output(u"├── {}".format(difference.source1))
# else:
# self.output(u"│ --- {}".format(difference.source1))
# self.output(u"├── +++ {}".format(difference.source2))
#
# for x in difference.comments:
# self.output(u"│┄ {}".format(x))
#
# diff = difference.unified_diff
#
# if diff:
# self.output(color_unified_diff(diff) if self.color else diff, True)
#
# def output(self, val, raw=False):
# self.print_func(
# self.indent(val, self.PREFIX * (self.depth + 0 if raw else -1)),
# )
#
# Path: diffoscope/presenters/json.py
# class JSONPresenter(Presenter):
# def __init__(self, print_func):
# self.root = []
# self.current = self.root
# self.print_func = print_func
#
# super().__init__()
#
# def start(self, difference):
# super().start(difference)
#
# self.print_func(json.dumps(self.root[0], indent=2, sort_keys=True))
#
# def visit_difference(self, difference):
# self.current.append({
# 'source1': difference.source1,
# 'source2': difference.source2,
# 'comments': [x for x in difference.comments],
# 'differences': [],
# 'unified_diff': difference.unified_diff,
# })
#
# self.current = self.current[-1]['differences']
#
# Path: diffoscope/presenters/utils.py
# @contextlib.contextmanager
# def make_printer(path):
# output = sys.stdout
#
# if path != '-':
# output = codecs.open(path, 'w', encoding='utf-8')
#
# def fn(*args, **kwargs):
# kwargs['file'] = output
# print(*args, **kwargs)
# fn.output = output
#
# yield fn
#
# if path != '-':
# output.close()
#
# Path: diffoscope/presenters/markdown.py
# class MarkdownTextPresenter(Presenter):
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func(x)
# self.print_func()
#
# if difference.unified_diff:
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# prefix = '#' * min(self.depth + 1, 6)
#
# self.print_func("{} {}".format(prefix, val))
# self.print_func()
#
# Path: diffoscope/presenters/restructuredtext.py
# class RestructuredTextPresenter(Presenter):
# TITLE_CHARS = '=-`:.\'"~^_*+#'
#
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func()
# self.print_func(x)
#
# if difference.unified_diff:
# self.print_func('::')
# self.print_func()
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# char = self.TITLE_CHARS[self.depth % len(self.TITLE_CHARS)]
#
# if self.depth < len(self.TITLE_CHARS):
# self.print_func(len(val) * char)
#
# self.print_func(val)
# self.print_func(len(val) * char)
# self.print_func()
, which may include functions, classes, or code. Output only the next line. | 'klass': MarkdownTextPresenter, |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
def output_all(difference, parsed_args, has_differences):
"""
Generate all known output formats.
"""
if difference is None:
return
FORMATS = {
'text': {
'fn': text,
'target': parsed_args.text_output,
},
'html': {
'fn': html,
'target': parsed_args.html_output,
},
'json': {
'klass': JSONPresenter,
'target': parsed_args.json_output,
},
'markdown': {
'klass': MarkdownTextPresenter,
'target': parsed_args.markdown_output,
},
'restructuredtext': {
<|code_end|>
. Use current file imports:
(import sys
import logging
from ..profiling import profile
from .text import TextPresenter
from .json import JSONPresenter
from .html import output_html, output_html_directory
from .utils import make_printer
from .markdown import MarkdownTextPresenter
from .restructuredtext import RestructuredTextPresenter)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/presenters/text.py
# class TextPresenter(Presenter):
# PREFIX = u'│ '
# RE_PREFIX = re.compile(r'(^|\n)')
#
# def __init__(self, print_func, color):
# self.print_func = create_limited_print_func(
# print_func,
# Config().max_text_report_size,
# )
# self.color = color
#
# super().__init__()
#
# def start(self, difference):
# try:
# super().start(difference)
# except PrintLimitReached:
# self.print_func("Max output size reached.", force=True)
#
# def visit_difference(self, difference):
# if self.depth == 0:
# self.output("--- {}".format(difference.source1))
# self.output("+++ {}".format(difference.source2))
# elif difference.source1 == difference.source2:
# self.output(u"├── {}".format(difference.source1))
# else:
# self.output(u"│ --- {}".format(difference.source1))
# self.output(u"├── +++ {}".format(difference.source2))
#
# for x in difference.comments:
# self.output(u"│┄ {}".format(x))
#
# diff = difference.unified_diff
#
# if diff:
# self.output(color_unified_diff(diff) if self.color else diff, True)
#
# def output(self, val, raw=False):
# self.print_func(
# self.indent(val, self.PREFIX * (self.depth + 0 if raw else -1)),
# )
#
# Path: diffoscope/presenters/json.py
# class JSONPresenter(Presenter):
# def __init__(self, print_func):
# self.root = []
# self.current = self.root
# self.print_func = print_func
#
# super().__init__()
#
# def start(self, difference):
# super().start(difference)
#
# self.print_func(json.dumps(self.root[0], indent=2, sort_keys=True))
#
# def visit_difference(self, difference):
# self.current.append({
# 'source1': difference.source1,
# 'source2': difference.source2,
# 'comments': [x for x in difference.comments],
# 'differences': [],
# 'unified_diff': difference.unified_diff,
# })
#
# self.current = self.current[-1]['differences']
#
# Path: diffoscope/presenters/utils.py
# @contextlib.contextmanager
# def make_printer(path):
# output = sys.stdout
#
# if path != '-':
# output = codecs.open(path, 'w', encoding='utf-8')
#
# def fn(*args, **kwargs):
# kwargs['file'] = output
# print(*args, **kwargs)
# fn.output = output
#
# yield fn
#
# if path != '-':
# output.close()
#
# Path: diffoscope/presenters/markdown.py
# class MarkdownTextPresenter(Presenter):
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func(x)
# self.print_func()
#
# if difference.unified_diff:
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# prefix = '#' * min(self.depth + 1, 6)
#
# self.print_func("{} {}".format(prefix, val))
# self.print_func()
#
# Path: diffoscope/presenters/restructuredtext.py
# class RestructuredTextPresenter(Presenter):
# TITLE_CHARS = '=-`:.\'"~^_*+#'
#
# def __init__(self, print_func):
# self.print_func = print_func
# super().__init__()
#
# def visit_difference(self, difference):
# if difference.source1 == difference.source2:
# self.title(difference.source1)
# else:
# self.title("Comparing {} & {}".format(
# difference.source1,
# difference.source2,
# ))
#
# for x in difference.comments:
# self.print_func()
# self.print_func(x)
#
# if difference.unified_diff:
# self.print_func('::')
# self.print_func()
# self.print_func(self.indent(difference.unified_diff, ' '))
# self.print_func()
#
# def title(self, val):
# char = self.TITLE_CHARS[self.depth % len(self.TITLE_CHARS)]
#
# if self.depth < len(self.TITLE_CHARS):
# self.print_func(len(val) * char)
#
# self.print_func(val)
# self.print_func(len(val) * char)
# self.print_func()
. Output only the next line. | 'klass': RestructuredTextPresenter, |
Using the snippet: <|code_start|># diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
def unsquashfs_version():
# first line of 'unsquashfs -version' looks like:
# unsquashfs version 4.2-git (2013/03/13)
try:
out = subprocess.check_output(['unsquashfs', '-version'])
except subprocess.CalledProcessError as e:
out = e.output
return out.decode('UTF-8').splitlines()[0].split()[2].strip()
squashfs1 = load_fixture('test1.squashfs')
squashfs2 = load_fixture('test2.squashfs')
def test_identification(squashfs1):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import subprocess
from diffoscope.comparators.squashfs import SquashfsFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
from utils.nonexisting import assert_non_existing
and context (class names, function names, or code) available:
# Path: diffoscope/comparators/squashfs.py
# class SquashfsFile(File):
# CONTAINER_CLASS = SquashfsContainer
# RE_FILE_TYPE = re.compile(r'^Squashfs filesystem\b')
#
# def compare_details(self, other, source=None):
# return [Difference.from_command(SquashfsSuperblock, self.path, other.path),
# Difference.from_command(SquashfsListing, self.path, other.path)]
. Output only the next line. | assert isinstance(squashfs1, SquashfsFile) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Reiner Herrmann <reiner@reiner-h.de>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
ps1 = load_fixture('test1.ps')
ps2 = load_fixture('test2.ps')
def test_identification(ps1):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from diffoscope.comparators.ps import PsFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context (functions, classes, or occasionally code) from other files:
# Path: diffoscope/comparators/ps.py
# class PsFile(TextFile):
# RE_FILE_TYPE = re.compile(r'^PostScript document\b')
#
# def compare(self, other, source=None):
# differences = super().compare(other, source)
# details = None
# try:
# details = Difference.from_command(Pstotext, self.path, other.path)
# except RequiredToolNotFound: # noqa
# logger.debug('ps2ascii not found')
#
# if details:
# differences.add_details([details])
# return differences
. Output only the next line. | assert isinstance(ps1, PsFile) |
Here is a snippet: <|code_start|>
def skip_unless_tool_is_at_least():
func = skip_unless_tool_is_at_least
assert func('/missing', 1, 1).name is 'skip'
# pytest.skipif().args[0] contains the evaluated statement
assert func('cat', 1, 1).args[0] is False
assert func('cat', 1, '1.2d.45+b8').args[0] is True
def version():
return '4.3-git'
assert func('cat', version, '4.3').args[0] is False
@skip_unless_module_exists('tlsh')
def test_fuzzy_matching(fuzzy_tar1, fuzzy_tar2):
differences = fuzzy_tar1.compare(fuzzy_tar2).details
expected_diff = codecs.open(data('text_iso8859_expected_diff'), encoding='utf-8').read()
assert differences[1].source1 == './matching'
assert differences[1].source2 == './fuzzy'
assert 'similar' in differences[1].comment
assert differences[1].unified_diff == expected_diff
@skip_unless_module_exists('tlsh')
def test_fuzzy_matching_only_once(fuzzy_tar1, fuzzy_tar3):
differences = fuzzy_tar1.compare(fuzzy_tar3).details
assert len(differences) == 2
fuzzy_tar_in_tar1 = load_fixture('fuzzy-tar-in-tar1.tar')
fuzzy_tar_in_tar2 = load_fixture('fuzzy-tar-in-tar2.tar')
@skip_unless_module_exists('tlsh')
def test_no_fuzzy_matching(monkeypatch, fuzzy_tar_in_tar1, fuzzy_tar_in_tar2):
<|code_end|>
. Write the next line using the current file imports:
import codecs
import pytest
from diffoscope.config import Config
from diffoscope.difference import Difference
from diffoscope.comparators.utils.command import Command
from utils.data import data, load_fixture
from utils.tools import tools_missing, skip_unless_tools_exist, \
skip_unless_module_exists
and context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
, which may include functions, classes, or code. Output only the next line. | monkeypatch.setattr(Config(), 'fuzzy_threshold', 0) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_TAR1_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test1.tar')
TEST_TAR2_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test2.tar')
def run(capsys, *args):
with pytest.raises(SystemExit) as exc:
<|code_end|>
. Use current file imports:
import os
import sys
import json
import pytest
from diffoscope.main import main
from diffoscope.progress import ProgressManager, StatusFD
from comparators.utils.tools import skip_unless_module_exists
and context (classes, functions, or code) from other files:
# Path: diffoscope/main.py
# def main(args=None):
# if args is None:
# args = sys.argv[1:]
# signal.signal(signal.SIGTERM, sigterm_handler)
# parsed_args = None
# try:
# with profile('main', 'parse_args'):
# parser = create_parser()
# parsed_args = parser.parse_args(args)
# sys.exit(run_diffoscope(parsed_args))
# except KeyboardInterrupt:
# logger.info('Keyboard Interrupt')
# sys.exit(2)
# except BrokenPipeError:
# sys.exit(2)
# except Exception:
# traceback.print_exc()
# if parsed_args and parsed_args.debugger:
# import pdb
# pdb.post_mortem()
# sys.exit(2)
# finally:
# with profile('main', 'cleanup'):
# clean_all_temp_files()
#
# # Print profiling output at the very end
# if parsed_args is not None:
# ProfileManager().finish(parsed_args)
#
# Path: diffoscope/progress.py
# class ProgressManager(object):
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# if not self._singleton:
# self.reset()
#
# def reset(self):
# self.total = 0
# self.current = 0
# self.observers = []
#
# def setup(self, parsed_args):
# # Show progress bar if user explicitly asked for it, otherwise show if
# # STDOUT is a tty.
# if parsed_args.progress or \
# (parsed_args.progress is None and sys.stdout.isatty()):
# try:
# self.register(ProgressBar())
# except ImportError:
# # User asked for bar, so show them the error
# if parsed_args.progress:
# raise
#
# if parsed_args.status_fd:
# self.register(StatusFD(os.fdopen(parsed_args.status_fd, 'w')))
#
# ##
#
# def register(self, observer):
# logger.debug("Registering %s as a progress observer", observer)
#
# self.observers.append(observer)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
#
# self.current += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def new_total(self, delta, msg):
# self.total += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def finish(self):
# for x in self.observers:
# x.finish()
#
# class StatusFD(object):
# def __init__(self, fileobj):
# self.fileobj = fileobj
#
# def notify(self, current, total, msg):
# print(json.dumps({
# 'msg': msg,
# 'total': total,
# 'current': current,
# }), file=self.fileobj)
#
# def finish(self):
# pass
. Output only the next line. | main(args) |
Predict the next line for this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_TAR1_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test1.tar')
TEST_TAR2_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test2.tar')
def run(capsys, *args):
with pytest.raises(SystemExit) as exc:
main(args)
out, err = capsys.readouterr()
return exc.value.code, out, err
@skip_unless_module_exists('progressbar')
def test_progress(capsys):
ret, _, err = run(capsys, TEST_TAR1_PATH, TEST_TAR2_PATH, '--progress')
assert ret == 1
assert "ETA" in err
def test_status_fd(capsys):
<|code_end|>
with the help of current file imports:
import os
import sys
import json
import pytest
from diffoscope.main import main
from diffoscope.progress import ProgressManager, StatusFD
from comparators.utils.tools import skip_unless_module_exists
and context from other files:
# Path: diffoscope/main.py
# def main(args=None):
# if args is None:
# args = sys.argv[1:]
# signal.signal(signal.SIGTERM, sigterm_handler)
# parsed_args = None
# try:
# with profile('main', 'parse_args'):
# parser = create_parser()
# parsed_args = parser.parse_args(args)
# sys.exit(run_diffoscope(parsed_args))
# except KeyboardInterrupt:
# logger.info('Keyboard Interrupt')
# sys.exit(2)
# except BrokenPipeError:
# sys.exit(2)
# except Exception:
# traceback.print_exc()
# if parsed_args and parsed_args.debugger:
# import pdb
# pdb.post_mortem()
# sys.exit(2)
# finally:
# with profile('main', 'cleanup'):
# clean_all_temp_files()
#
# # Print profiling output at the very end
# if parsed_args is not None:
# ProfileManager().finish(parsed_args)
#
# Path: diffoscope/progress.py
# class ProgressManager(object):
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# if not self._singleton:
# self.reset()
#
# def reset(self):
# self.total = 0
# self.current = 0
# self.observers = []
#
# def setup(self, parsed_args):
# # Show progress bar if user explicitly asked for it, otherwise show if
# # STDOUT is a tty.
# if parsed_args.progress or \
# (parsed_args.progress is None and sys.stdout.isatty()):
# try:
# self.register(ProgressBar())
# except ImportError:
# # User asked for bar, so show them the error
# if parsed_args.progress:
# raise
#
# if parsed_args.status_fd:
# self.register(StatusFD(os.fdopen(parsed_args.status_fd, 'w')))
#
# ##
#
# def register(self, observer):
# logger.debug("Registering %s as a progress observer", observer)
#
# self.observers.append(observer)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
#
# self.current += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def new_total(self, delta, msg):
# self.total += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def finish(self):
# for x in self.observers:
# x.finish()
#
# class StatusFD(object):
# def __init__(self, fileobj):
# self.fileobj = fileobj
#
# def notify(self, current, total, msg):
# print(json.dumps({
# 'msg': msg,
# 'total': total,
# 'current': current,
# }), file=self.fileobj)
#
# def finish(self):
# pass
, which may contain function names, class names, or code. Output only the next line. | ProgressManager().register(StatusFD(sys.stderr)) |
Given the following code snippet before the placeholder: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
TEST_TAR1_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test1.tar')
TEST_TAR2_PATH = os.path.join(os.path.dirname(__file__), 'data', 'test2.tar')
def run(capsys, *args):
with pytest.raises(SystemExit) as exc:
main(args)
out, err = capsys.readouterr()
return exc.value.code, out, err
@skip_unless_module_exists('progressbar')
def test_progress(capsys):
ret, _, err = run(capsys, TEST_TAR1_PATH, TEST_TAR2_PATH, '--progress')
assert ret == 1
assert "ETA" in err
def test_status_fd(capsys):
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import json
import pytest
from diffoscope.main import main
from diffoscope.progress import ProgressManager, StatusFD
from comparators.utils.tools import skip_unless_module_exists
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/main.py
# def main(args=None):
# if args is None:
# args = sys.argv[1:]
# signal.signal(signal.SIGTERM, sigterm_handler)
# parsed_args = None
# try:
# with profile('main', 'parse_args'):
# parser = create_parser()
# parsed_args = parser.parse_args(args)
# sys.exit(run_diffoscope(parsed_args))
# except KeyboardInterrupt:
# logger.info('Keyboard Interrupt')
# sys.exit(2)
# except BrokenPipeError:
# sys.exit(2)
# except Exception:
# traceback.print_exc()
# if parsed_args and parsed_args.debugger:
# import pdb
# pdb.post_mortem()
# sys.exit(2)
# finally:
# with profile('main', 'cleanup'):
# clean_all_temp_files()
#
# # Print profiling output at the very end
# if parsed_args is not None:
# ProfileManager().finish(parsed_args)
#
# Path: diffoscope/progress.py
# class ProgressManager(object):
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# if not self._singleton:
# self.reset()
#
# def reset(self):
# self.total = 0
# self.current = 0
# self.observers = []
#
# def setup(self, parsed_args):
# # Show progress bar if user explicitly asked for it, otherwise show if
# # STDOUT is a tty.
# if parsed_args.progress or \
# (parsed_args.progress is None and sys.stdout.isatty()):
# try:
# self.register(ProgressBar())
# except ImportError:
# # User asked for bar, so show them the error
# if parsed_args.progress:
# raise
#
# if parsed_args.status_fd:
# self.register(StatusFD(os.fdopen(parsed_args.status_fd, 'w')))
#
# ##
#
# def register(self, observer):
# logger.debug("Registering %s as a progress observer", observer)
#
# self.observers.append(observer)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
#
# self.current += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def new_total(self, delta, msg):
# self.total += delta
# for x in self.observers:
# x.notify(self.current, self.total, msg)
#
# def finish(self):
# for x in self.observers:
# x.finish()
#
# class StatusFD(object):
# def __init__(self, fileobj):
# self.fileobj = fileobj
#
# def notify(self, current, total, msg):
# print(json.dumps({
# 'msg': msg,
# 'total': total,
# 'current': current,
# }), file=self.fileobj)
#
# def finish(self):
# pass
. Output only the next line. | ProgressManager().register(StatusFD(sys.stderr)) |
Given the following code snippet before the placeholder: <|code_start|> difference = ascii1.compare(ascii1)
assert difference is None
def test_difference_in_ascii(ascii1, ascii2):
difference = ascii1.compare(ascii2)
assert difference is not None
expected_diff = get_data('text_ascii_expected_diff')
assert difference.unified_diff == expected_diff
assert not difference.comments
assert len(difference.details) == 0
unicode1 = load_fixture('text_unicode1')
unicode2 = load_fixture('text_unicode2')
def test_difference_in_unicode(unicode1, unicode2):
difference = unicode1.compare(unicode2)
expected_diff = codecs.open(data('text_unicode_expected_diff'), encoding='utf-8').read()
assert difference.unified_diff == expected_diff
iso8859 = load_fixture('text_iso8859')
def test_difference_between_iso88591_and_unicode(iso8859, unicode1):
difference = iso8859.compare(unicode1)
expected_diff = codecs.open(data('text_iso8859_expected_diff'), encoding='utf-8').read()
assert difference.unified_diff == expected_diff
def test_difference_between_iso88591_and_unicode_only(iso8859, tmpdir):
utf8_path = str(tmpdir.join('utf8'))
with open(utf8_path, 'wb') as f:
f.write(codecs.open(data('text_iso8859'), encoding='iso8859-1').read().encode('utf-8'))
<|code_end|>
, predict the next line using imports from the current file:
import codecs
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import data, load_fixture, get_data
from utils.nonexisting import assert_non_existing
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | utf8 = specialize(FilesystemFile(utf8_path)) |
Here is a snippet: <|code_start|># along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
xz1 = load_fixture('test1.xz')
xz2 = load_fixture('test2.xz')
def test_identification(xz1):
assert isinstance(xz1, XzFile)
def test_no_differences(xz1):
difference = xz1.compare(xz1)
assert difference is None
@pytest.fixture
def differences(xz1, xz2):
return xz1.compare(xz2).details
@skip_unless_tools_exist('xz')
def test_content_source(differences):
assert differences[0].source1 == 'test1'
assert differences[0].source2 == 'test2'
@skip_unless_tools_exist('xz')
def test_content_source_without_extension(tmpdir, xz1, xz2):
path1 = str(tmpdir.join('test1'))
path2 = str(tmpdir.join('test2'))
shutil.copy(xz1.path, path1)
shutil.copy(xz2.path, path2)
<|code_end|>
. Write the next line using the current file imports:
import shutil
import pytest
from diffoscope.comparators.xz import XzFile
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
, which may include functions, classes, or code. Output only the next line. | xz1 = specialize(FilesystemFile(path1)) |
Given snippet: <|code_start|>def differences(tar1, tar2):
return tar1.compare(tar2).details
def test_listing(differences):
expected_diff = get_data('tar_listing_expected_diff')
assert differences[0].unified_diff == expected_diff
def test_symlinks(differences):
assert differences[2].source1 == 'dir/link'
assert differences[2].source2 == 'dir/link'
assert differences[2].comment == 'symlink'
expected_diff = get_data('symlink_expected_diff')
assert differences[2].unified_diff == expected_diff
def test_text_file(differences):
assert differences[1].source1 == 'dir/text'
assert differences[1].source2 == 'dir/text'
expected_diff = get_data('text_ascii_expected_diff')
assert differences[1].unified_diff == expected_diff
def test_compare_non_existing(monkeypatch, tar1):
assert_non_existing(monkeypatch, tar1)
no_permissions_tar = load_fixture('no-perms.tar')
# Reported as Debian #797164. This is a good way to notice if we unpack directories
# as we won't be able to remove files in one if we don't have write permissions.
def test_no_permissions_dir_in_tarball(monkeypatch, no_permissions_tar):
# We want to make sure OSError is not raised.
# Comparing with non-existing file makes it easy to make sure all files are unpacked
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.tar import TarFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.nonexisting import assert_non_existing
and context:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
which might include code, classes, or functions. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
def filter_excludes(filenames):
result = []
for x in filenames:
<|code_end|>
, determine the next line of code. You have imports:
import fnmatch
import logging
from diffoscope.config import Config
and context (class names, function names, or code) available:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | for y in Config().excludes: |
Here is a snippet: <|code_start|># (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class Pstotext(Command):
@tool_required('ps2ascii')
def cmdline(self):
return ['ps2ascii', self.path]
class PsFile(TextFile):
RE_FILE_TYPE = re.compile(r'^PostScript document\b')
def compare(self, other, source=None):
differences = super().compare(other, source)
details = None
try:
details = Difference.from_command(Pstotext, self.path, other.path)
<|code_end|>
. Write the next line using the current file imports:
import re
import logging
from diffoscope.exc import RequiredToolNotFound
from diffoscope.tools import tool_required
from diffoscope.difference import Difference
from .text import TextFile
from .utils.command import Command
and context from other files:
# Path: diffoscope/exc.py
# class RequiredToolNotFound(Exception):
# def __init__(self, command):
# self.command = command
#
# def get_package(self):
# try:
# providers = EXTERNAL_TOOLS[self.command]
# except KeyError: # noqa
# return None
#
# return providers.get(get_current_os(), None)
#
# Path: diffoscope/tools.py
# def tool_required(command):
# """
# Decorator that checks if the specified tool is installed
# """
# if not hasattr(tool_required, 'all'):
# tool_required.all = set()
# tool_required.all.add(command)
# def wrapper(original_function):
# if find_executable(command):
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# with profile('command', command):
# return original_function(*args, **kwargs)
# else:
# @functools.wraps(original_function)
# def tool_check(*args, **kwargs):
# from .exc import RequiredToolNotFound
# raise RequiredToolNotFound(command)
# return tool_check
# return wrapper
, which may include functions, classes, or code. Output only the next line. | except RequiredToolNotFound: # noqa |
Continue the code snippet: <|code_start|> def get_member(self, member_name):
raise NotImplementedError()
def get_all_members(self):
# If your get_member implementation is O(n) then this will be O(n^2)
# cost. In such cases it is HIGHLY RECOMMENDED to override this as well
for name in self.get_member_names():
yield name, self.get_member(name)
def comparisons(self, other):
my_members = self.get_members()
my_reminders = collections.OrderedDict()
other_members = other.get_members()
with Progress(max(len(my_members), len(other_members))) as p:
# keep it sorted like my members
while my_members:
my_member_name, my_member = my_members.popitem(last=False)
if my_member_name in other_members:
yield my_member, other_members.pop(my_member_name), NO_COMMENT
p.step(msg=my_member.progress_name)
else:
my_reminders[my_member_name] = my_member
my_members = my_reminders
for my_name, other_name, score in perform_fuzzy_matching(my_members, other_members):
comment = 'Files similar despite different names (difference score: %d)' % score
yield my_members.pop(my_name), other_members.pop(other_name), comment
p.step(2, msg=my_name)
<|code_end|>
. Use current file imports:
import abc
import logging
import itertools
import collections
from diffoscope.config import Config
from diffoscope.progress import Progress
from ..missing_file import MissingFile
from .fuzzy import perform_fuzzy_matching
from .specialize import specialize
from .compare import compare_commented_files
and context (classes, functions, or code) from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/progress.py
# class Progress(object):
# def __init__(self, total, msg=""):
# self.current = 0
# self.total = total
#
# ProgressManager().new_total(total, msg)
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, exc_traceback):
# self.step(self.total - self.current)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
# if not delta:
# return
#
# self.current += delta
# ProgressManager().step(delta, msg)
#
# Path: diffoscope/comparators/utils/fuzzy.py
# def perform_fuzzy_matching(members1, members2):
# if tlsh == None or Config().fuzzy_threshold == 0:
# return
# already_compared = set()
# # Perform local copies because they will be modified by consumer
# members1 = dict(members1)
# members2 = dict(members2)
# for name1, file1 in members1.items():
# if file1.is_directory() or not file1.fuzzy_hash:
# continue
# comparisons = []
# for name2, file2 in members2.items():
# if name2 in already_compared or file2.is_directory() or not file2.fuzzy_hash:
# continue
# comparisons.append((tlsh.diff(file1.fuzzy_hash, file2.fuzzy_hash), name2))
# if comparisons:
# comparisons.sort(key=operator.itemgetter(0))
# score, name2 = comparisons[0]
# logger.debug('fuzzy top match %s %s: %d difference score', name1, name2, score)
# if score < Config().fuzzy_threshold:
# yield name1, name2, score
# already_compared.add(name2)
. Output only the next line. | if Config().new_file: |
Predict the next line after this snippet: <|code_start|> logger.debug("lookup_file(%s) -> %s", names, file)
specialize(file)
if not remainings:
return file
container = file.as_container
if not container:
return None
return container.lookup_file(*remainings)
@abc.abstractmethod
def get_member_names(self):
raise NotImplementedError()
@abc.abstractmethod
def get_member(self, member_name):
raise NotImplementedError()
def get_all_members(self):
# If your get_member implementation is O(n) then this will be O(n^2)
# cost. In such cases it is HIGHLY RECOMMENDED to override this as well
for name in self.get_member_names():
yield name, self.get_member(name)
def comparisons(self, other):
my_members = self.get_members()
my_reminders = collections.OrderedDict()
other_members = other.get_members()
<|code_end|>
using the current file's imports:
import abc
import logging
import itertools
import collections
from diffoscope.config import Config
from diffoscope.progress import Progress
from ..missing_file import MissingFile
from .fuzzy import perform_fuzzy_matching
from .specialize import specialize
from .compare import compare_commented_files
and any relevant context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/progress.py
# class Progress(object):
# def __init__(self, total, msg=""):
# self.current = 0
# self.total = total
#
# ProgressManager().new_total(total, msg)
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, exc_traceback):
# self.step(self.total - self.current)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
# if not delta:
# return
#
# self.current += delta
# ProgressManager().step(delta, msg)
#
# Path: diffoscope/comparators/utils/fuzzy.py
# def perform_fuzzy_matching(members1, members2):
# if tlsh == None or Config().fuzzy_threshold == 0:
# return
# already_compared = set()
# # Perform local copies because they will be modified by consumer
# members1 = dict(members1)
# members2 = dict(members2)
# for name1, file1 in members1.items():
# if file1.is_directory() or not file1.fuzzy_hash:
# continue
# comparisons = []
# for name2, file2 in members2.items():
# if name2 in already_compared or file2.is_directory() or not file2.fuzzy_hash:
# continue
# comparisons.append((tlsh.diff(file1.fuzzy_hash, file2.fuzzy_hash), name2))
# if comparisons:
# comparisons.sort(key=operator.itemgetter(0))
# score, name2 = comparisons[0]
# logger.debug('fuzzy top match %s %s: %d difference score', name1, name2, score)
# if score < Config().fuzzy_threshold:
# yield name1, name2, score
# already_compared.add(name2)
. Output only the next line. | with Progress(max(len(my_members), len(other_members))) as p: |
Given the following code snippet before the placeholder: <|code_start|> @abc.abstractmethod
def get_member_names(self):
raise NotImplementedError()
@abc.abstractmethod
def get_member(self, member_name):
raise NotImplementedError()
def get_all_members(self):
# If your get_member implementation is O(n) then this will be O(n^2)
# cost. In such cases it is HIGHLY RECOMMENDED to override this as well
for name in self.get_member_names():
yield name, self.get_member(name)
def comparisons(self, other):
my_members = self.get_members()
my_reminders = collections.OrderedDict()
other_members = other.get_members()
with Progress(max(len(my_members), len(other_members))) as p:
# keep it sorted like my members
while my_members:
my_member_name, my_member = my_members.popitem(last=False)
if my_member_name in other_members:
yield my_member, other_members.pop(my_member_name), NO_COMMENT
p.step(msg=my_member.progress_name)
else:
my_reminders[my_member_name] = my_member
my_members = my_reminders
<|code_end|>
, predict the next line using imports from the current file:
import abc
import logging
import itertools
import collections
from diffoscope.config import Config
from diffoscope.progress import Progress
from ..missing_file import MissingFile
from .fuzzy import perform_fuzzy_matching
from .specialize import specialize
from .compare import compare_commented_files
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
#
# Path: diffoscope/progress.py
# class Progress(object):
# def __init__(self, total, msg=""):
# self.current = 0
# self.total = total
#
# ProgressManager().new_total(total, msg)
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, exc_traceback):
# self.step(self.total - self.current)
#
# def step(self, delta=1, msg=""):
# delta = min(self.total - self.current, delta) # clamp
# if not delta:
# return
#
# self.current += delta
# ProgressManager().step(delta, msg)
#
# Path: diffoscope/comparators/utils/fuzzy.py
# def perform_fuzzy_matching(members1, members2):
# if tlsh == None or Config().fuzzy_threshold == 0:
# return
# already_compared = set()
# # Perform local copies because they will be modified by consumer
# members1 = dict(members1)
# members2 = dict(members2)
# for name1, file1 in members1.items():
# if file1.is_directory() or not file1.fuzzy_hash:
# continue
# comparisons = []
# for name2, file2 in members2.items():
# if name2 in already_compared or file2.is_directory() or not file2.fuzzy_hash:
# continue
# comparisons.append((tlsh.diff(file1.fuzzy_hash, file2.fuzzy_hash), name2))
# if comparisons:
# comparisons.sort(key=operator.itemgetter(0))
# score, name2 = comparisons[0]
# logger.debug('fuzzy top match %s %s: %d difference score', name1, name2, score)
# if score < Config().fuzzy_threshold:
# yield name1, name2, score
# already_compared.add(name2)
. Output only the next line. | for my_name, other_name, score in perform_fuzzy_matching(my_members, other_members): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
json1 = load_fixture('test1.json')
json2 = load_fixture('test2.json')
json3a = load_fixture('order1a.json')
json3b = load_fixture('order1b.json')
invalid_json = load_fixture('test_invalid.json')
def test_identification(json1):
<|code_end|>
with the help of current file imports:
import pytest
from diffoscope.comparators.json import JSONFile
from utils.data import load_fixture, get_data
from utils.nonexisting import assert_non_existing
and context from other files:
# Path: diffoscope/comparators/json.py
# class JSONFile(File):
# RE_FILE_EXTENSION = re.compile(r'\.json$')
#
# @staticmethod
# def recognizes(file):
# if JSONFile.RE_FILE_EXTENSION.search(file.name) is None:
# return False
#
# with open(file.path) as f:
# try:
# file.parsed = json.load(f, object_pairs_hook=collections.OrderedDict)
# except ValueError:
# return False
#
# return True
#
# def compare_details(self, other, source=None):
# difference = Difference.from_text(self.dumps(self), self.dumps(other),
# self.path, other.path)
# if difference:
# return [difference]
#
# difference = Difference.from_text(self.dumps(self, sort_keys=False),
# self.dumps(other, sort_keys=False),
# self.path, other.path,
# comment="ordering differences only")
# return [difference]
#
# @staticmethod
# def dumps(file, sort_keys=True):
# if not hasattr(file, 'parsed'):
# return ""
# return json.dumps(file.parsed, indent=4, sort_keys=sort_keys)
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(json1, JSONFile) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
# 2016-2017 Mattia Rizzolo <mattia@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
re_normalize_zeros = re.compile(
r'^(?P<prefix>[ \-\+])(?P<offset>[0-9a-f]+)(?=: )', re.MULTILINE,
)
def init_fixture(filename):
return pytest.fixture(
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import pytest
from diffoscope.comparators.binary import FilesystemFile
from diffoscope.comparators.utils.specialize import specialize
and context including class names, function names, and sometimes code from other files:
# Path: diffoscope/comparators/utils/specialize.py
# def specialize(file):
# for cls in ComparatorManager().classes:
# if isinstance(file, cls):
# return file
#
# # Does this file class match?
# flag = False
# if hasattr(cls, 'recognizes'):
# with profile('recognizes', file):
# flag = cls.recognizes(file)
# else:
# re_tests = [(x, y) for x, y in (
# (cls.RE_FILE_TYPE, file.magic_file_type),
# (cls.RE_FILE_EXTENSION, file.name),
# ) if x]
#
# # If neither are defined, it's *not* a match.
# if re_tests:
# flag = all(x.search(y) for x, y in re_tests)
#
# if not flag:
# continue
#
# # Found a match; perform type magic
# logger.debug("Using %s for %s", cls.__name__, file.name)
# new_cls = type(cls.__name__, (cls, type(file)), {})
# file.__class__ = new_cls
#
# return file
#
# logger.debug("Unidentified file. Magic says: %s", file.magic_file_type)
#
# return file
. Output only the next line. | lambda: specialize(FilesystemFile(filename)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
cpio1 = load_fixture('test1.cpio')
cpio2 = load_fixture('test2.cpio')
def test_identification(cpio1):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from diffoscope.comparators.cpio import CpioFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
from utils.nonexisting import assert_non_existing
and context:
# Path: diffoscope/comparators/cpio.py
# class CpioFile(File):
# CONTAINER_CLASS = LibarchiveContainer
# RE_FILE_TYPE = re.compile(r'\bcpio archive\b')
#
# def compare_details(self, other, source=None):
# return [Difference.from_text_readers(
# list_libarchive(self.path),
# list_libarchive(other.path),
# self.path,
# other.path,
# source="file list",
# )]
which might include code, classes, or functions. Output only the next line. | assert isinstance(cpio1, CpioFile) |
Predict the next line after this snippet: <|code_start|># along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
ipk1 = load_fixture('base-files_157-r45695_ar71xx.ipk')
ipk2 = load_fixture('base-files_157-r45918_ar71xx.ipk')
def test_identification(ipk1):
assert isinstance(ipk1, IpkFile)
def test_no_differences(ipk1):
difference = ipk1.compare(ipk1)
assert difference is None
@pytest.fixture
def differences(ipk1, ipk2):
return ipk1.compare(ipk2).details
def test_metadata(differences):
assert differences[0].source1 == 'metadata'
expected_diff = get_data('ipk_metadata_expected_diff')
assert differences[0].unified_diff == expected_diff
def test_compressed_files(differences):
assert differences[1].details[1].source1 == './data.tar.gz'
assert differences[1].details[2].source1 == './control.tar.gz'
def test_compare_non_existing(monkeypatch, ipk1):
<|code_end|>
using the current file's imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.ipk import IpkFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
and any relevant context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Next line prediction: <|code_start|>
def test_identification(dex1):
assert isinstance(dex1, DexFile)
def test_no_differences(dex1):
difference = dex1.compare(dex1)
assert difference is None
@pytest.fixture
def differences(dex1, dex2):
return dex1.compare(dex2).details
@skip_unless_tools_exist('enjarify', 'zipinfo', 'javap')
@skip_unless_tool_is_at_least('javap', javap_version, '1.8')
@skip_unless_tool_is_at_least('enjarify', enjarify_version, '1.0.3')
def test_differences(differences):
assert differences[0].source1 == 'test1.jar'
assert differences[0].source2 == 'test2.jar'
zipinfo = differences[0].details[0]
classdiff = differences[0].details[1]
assert zipinfo.source1 == 'zipinfo -v {}'
assert zipinfo.source2 == 'zipinfo -v {}'
assert classdiff.source1 == 'com/example/MainActivity.class'
assert classdiff.source2 == 'com/example/MainActivity.class'
expected_diff = get_data('dex_expected_diffs')
found_diff = zipinfo.unified_diff + classdiff.details[0].unified_diff
assert expected_diff == found_diff
@skip_unless_tools_exist('enjarify', 'zipinfo', 'javap')
def test_compare_non_existing(monkeypatch, dex1):
<|code_end|>
. Use current file imports:
(import pytest
import subprocess
from diffoscope.config import Config
from diffoscope.comparators.dex import DexFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist, skip_unless_tool_is_at_least
from test_java import javap_version)
and context including class names, function names, or small code snippets from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Here is a snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope. If not, see <https://www.gnu.org/licenses/>.
icc1 = load_fixture('test1.icc')
icc2 = load_fixture('test2.icc')
def test_identification(icc1):
assert isinstance(icc1, IccFile)
def test_no_differences(icc1):
difference = icc1.compare(icc1)
assert difference is None
@pytest.fixture
def differences(icc1, icc2):
return icc1.compare(icc2).details
@skip_unless_tools_exist('cd-iccdump')
def test_diff(differences):
expected_diff = get_data('icc_expected_diff')
assert differences[0].unified_diff == expected_diff
@skip_unless_tools_exist('cd-iccdump')
def test_compare_non_existing(monkeypatch, icc1):
<|code_end|>
. Write the next line using the current file imports:
import pytest
from diffoscope.config import Config
from diffoscope.comparators.icc import IccFile
from diffoscope.comparators.missing_file import MissingFile
from utils.data import load_fixture, get_data
from utils.tools import skip_unless_tools_exist
and context from other files:
# Path: diffoscope/config.py
# class Config(object):
# max_diff_block_lines = 256
# max_diff_block_lines_parent = 50
# max_diff_block_lines_saved = float("inf")
# # html-dir output uses ratio * max-diff-block-lines as its limit
# max_diff_block_lines_html_dir_ratio = 4
# # GNU diff cannot process arbitrary large files :(
# max_diff_input_lines = 2 ** 20
# max_report_size = 2000 * 2 ** 10 # 2000 kB
# max_text_report_size = 0
# max_report_child_size = 500 * 2 ** 10
# new_file = False
# fuzzy_threshold = 60
# enforce_constraints = True
# excludes = ()
#
# _singleton = {}
#
# def __init__(self):
# self.__dict__ = self._singleton
#
# def __setattr__(self, k, v):
# super(Config, self).__setattr__(k, v)
#
# if self.enforce_constraints:
# self.check_constraints()
#
# def check_constraints(self):
# if self.max_diff_block_lines < self.max_diff_block_lines_parent: # noqa
# raise ValueError("max_diff_block_lines ({0.max_diff_block_lines}) "
# "cannot be smaller than max_diff_block_lines_parent "
# "({0.max_diff_block_lines_parent})".format(self),
# )
#
# max_ = self.max_diff_block_lines_html_dir_ratio * \
# self.max_diff_block_lines
# if self.max_diff_block_lines_saved < max_: # noqa
# raise ValueError("max_diff_block_lines_saved "
# "({0.max_diff_block_lines_saved}) cannot be smaller than "
# "{0.max_diff_block_lines_html_dir_ratio} * "
# "max_diff_block_lines ({1})".format(self, max_),
# )
, which may include functions, classes, or code. Output only the next line. | monkeypatch.setattr(Config(), 'new_file', True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.