Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>
class TestH5Utils(unittest.TestCase):
@withfile
def test_hdfopen(self, F):
attr = 'test'
v1, v2 = 5, 6
for group in [None, 'g']:
with hdfopen(F, group, replace=True) as f:
f.attrs[attr] = v1
assert os.path.exists(F), 'failed to create HDF file'
with hdfopen(F, group) as f:
assert f.attrs[attr] == v1, 'attribute value wrong'
with hdfopen(F, group, replace=True) as f:
f.attrs[attr] = v2
with hdfopen(F, group) as f:
assert f.attrs[attr] == v2, 'replacing attribute failed'
@withfile
def test_clear_h5_group(self, F):
with h5.File(F, 'w') as f:
f['foo/bar'] = [1,2,3]
f.attrs['baz'] = 5
with h5.File(F, 'a') as f:
assert 'foo' in f.keys(), 'missing key'
assert 'baz' in f.attrs.keys(), 'missing attribute'
<|code_end|>
. Use current file imports:
import unittest
import os
import numpy as np
import h5py as h5
import pandas as pd
from contextlib import contextmanager
from pandas.testing import assert_frame_equal
from ifcb.tests.utils import withfile
from ifcb.data.h5utils import hdfopen, clear_h5_group, pd2hdf, hdf2pd
and context (classes, functions, or code) from other files:
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/data/h5utils.py
# class hdfopen(object):
# """
# Context manager that opens an ``h5py.Group`` from an ``h5py.File``
# or other group.
#
# Parameters:
#
# * path - path to HDF5 file, or open HDF5 group
# * group - for HDF5 file paths, the path of the group to return (optional)
# for groups, a subgroup to require (optional)
# * replace - whether to replace any existing data
#
# :Example:
#
# >>> with hdfopen('myfile.h5','somegroup') as g:
# ... g.attrs['my_attr'] = 3
#
# """
# def __init__(self, path, group=None, replace=None):
# if isinstance(path, h5.Group):
# if group is not None:
# self.group = path.require_group(group)
# else:
# self.group = path
# if replace:
# clear_h5_group(self.group)
# self._file = None
# else:
# mode = 'w' if replace else 'r+'
# self._file = h5.File(path, mode)
# if group is not None:
# self.group = self._file.require_group(group)
# else:
# self.group = self._file
# def close(self):
# if self._file is not None:
# self._file.close()
# def __enter__(self, *args, **kw):
# return self.group
# def __exit__(self, *args):
# self.close()
# pass
#
# def clear_h5_group(h5group):
# """
# Delete all keys and attrs from an ``h5py.Group``.
#
# :param h5group: the h5py.Group
# """
# for k in h5group.keys(): del h5group[k]
# for k in h5group.attrs.keys(): del h5group.attrs[k]
#
# def pd2hdf(group, df, **kw):
# """
# Write ``pandas.DataFrame`` to HDF5 file. This differs
# from pandas's own HDF5 support by providing a slightly less
# optimized but easier-to-access format. Passes keywords
# through to each ``h5py.create_dataset`` operation.
#
# Layout of Pandas ``DataFrame`` / ``Series`` representation:
#
# * ``{path}`` (group): the group containing the dataframe
# * ``{path}.ptype`` (attribute): '``DataFrame``'
# * ``{path}/columns`` (dataset): 1d array of references to column data
# * ``{path}/columns.names`` (attribute, optional): 1d array of column names
# * ``{path}/{n}`` (dataset): 1d array of data for column n
# * ``{path}/index`` (dataset): 1d array of data for dataframe index
# * ``{path}/index.name`` (attribute, optional): name of index
#
# :param group: the ``h5py.Group`` to write the ``DataFrame`` to
# """
# group.attrs['ptype'] = 'DataFrame'
# refs = []
# for i in range(len(df.columns)):
# c = group.create_dataset(str(i), data=df.iloc[:,i], **kw)
# refs.append(c.ref)
# cols = group.create_dataset('columns', data=refs, dtype=H5_REF_TYPE)
# if df.columns.dtype == np.int64:
# cols.attrs['names'] = [int(col) for col in df.columns]
# else:
# cols.attrs['names'] = [col.encode('utf8') for col in df.columns]
# ix = group.create_dataset('index', data=df.index, **kw)
# if df.index.name is not None:
# ix.attrs['name'] = df.index.name
#
# def hdf2pd(group):
# """
# Read a ``pandas.DataFrame`` from an ``h5py.Group``.
#
# :param group: the ``h5py.Group`` to read from.
# """
# if group.attrs['ptype'] != 'DataFrame':
# raise ValueError('unrecognized HDF format')
# index = group['index']
# index_name = index.attrs.get('name',None)
# col_refs = group['columns']
# col_data = [np.array(group[r]) for r in col_refs]
# col_names = col_refs.attrs.get('names')
# if type(col_names[0]) == np.bytes_:
# col_names = [str(cn,'utf8') for cn in col_names]
# data = { k: v for k, v in zip(col_names, col_data) }
# index = pd.Series(index, name=index_name)
# return pd.DataFrame(data=data, index=index, columns=col_names)
. Output only the next line. | clear_h5_group(f) |
Predict the next line for this snippet: <|code_start|>
def read_ml_analyzed(path):
"""read from the legacy matlab files"""
mat = loadmat(path, squeeze_me=True)
# ignore variables other than the following
cols = ['filelist_all', 'looktime', 'minproctime', 'ml_analyzed', 'runtime']
# convert to dataframe
df = pd.DataFrame({ c: mat[c] for c in cols }, columns=cols)
df.index = df.pop('filelist_all') # index by bin LID
return df
def compute_ml_analyzed_s1_adc(adc):
"""compute ml_analyzed for an old instrument"""
# first, make sure this isn't an empty bin
if len(adc) == 0:
return np.nan, np.nan, np.nan
# we have targets, can proceed
MIN_PROC_TIME = 0.073
STEPS_PER_SEC = 40.
ML_PER_STEP = 5./48000.
FLOW_RATE = ML_PER_STEP * STEPS_PER_SEC # ml/s
<|code_end|>
with the help of current file imports:
import numpy as np
import pandas as pd
import scipy.stats as stats
from ifcb.data.adc import SCHEMA_VERSION_1, SCHEMA_VERSION_2
from scipy.io import loadmat
and context from other files:
# Path: ifcb/data/adc.py
# class SCHEMA_VERSION_1(object):
# """
# IFCB revision 1 schema.
# """
# _name = 'v1'
# _cols = range(15)
# TRIGGER = 0
# PROCESSING_END_TIME = 1
# FLUORESCENCE_LOW = 2
# FLUORESCENCE_HIGH = 3
# SCATTERING_LOW = 4
# SCATTERING_HIGH = 5
# COMPARATOR_PULSE = 6
# TRIGGER_OPEN_TIME = 7
# FRAME_GRAB_TIME = 8
# ROI_X = 9
# ROI_Y = 10
# ROI_WIDTH = 11
# ROI_HEIGHT = 12
# START_BYTE = 13
# VALVE_STATUS = 14
#
# class SCHEMA_VERSION_2(object):
# """
# IFCB revision 2 schema.
# """
# _name = 'v2'
# _cols = range(24)
# TRIGGER = 0
# ADC_TIME = 1
# PMT_A = 2
# PMT_B = 3
# PMT_C = 4
# PMT_D = 5
# PEAK_A = 6
# PEAK_B = 7
# PEAK_C = 8
# PEAK_D = 9
# TIME_OF_FLIGHT = 10
# GRAB_TIME_START = 11
# GRAB_TIME_END = 12
# ROI_X = 13
# ROI_Y = 14
# ROI_WIDTH = 15
# ROI_HEIGHT = 16
# START_BYTE = 17
# COMPARATOR_OUT = 18
# START_POINT = 19
# SIGNAL_LENGTH = 20
# STATUS = 21
# RUN_TIME = 22
# INHIBIT_TIME = 23
, which may contain function names, class names, or code. Output only the next line. | s = SCHEMA_VERSION_1 |
Using the snippet: <|code_start|> ml_analyzed, look_time, run_time = ma(row)
if ml_analyzed <= 0:
row = adc.iloc[-2]
run_time = row[s.ADC_TIME]
nz = adc[s.RUN_TIME].to_numpy().nonzero()[0]
mode_inhibit_time = stats.mode(np.diff(adc[s.INHIBIT_TIME].iloc[nz]))[0][0]
last_good_inhibit_time = adc[s.INHIBIT_TIME].iloc[nz[-1]]
inhibit_time = last_good_inhibit_time + (len(adc) - len(nz)) * mode_inhibit_time
look_time = run_time - inhibit_time
ml_analyzed = FLOW_RATE * (look_time / 60)
return ml_analyzed, look_time, run_time
def compute_ml_analyzed_s2(abin):
"""compute ml_analyzed for a new instrument"""
FLOW_RATE = 0.25 # ml/minute
# ml analyzed is (run time - inhibit time) * flow rate
run_time = abin.header('runTime')
inhibit_time = abin.header('inhibitTime')
look_time = run_time - inhibit_time
ml_analyzed = FLOW_RATE * (look_time / 60.)
if look_time > 0:
return ml_analyzed, look_time, run_time
else:
return compute_ml_analyzed_s2_adc(abin)
def compute_ml_analyzed(abin):
"""returns ml_analyzed, look time, run time"""
s = abin.schema
if s is SCHEMA_VERSION_1:
return compute_ml_analyzed_s1(abin)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import pandas as pd
import scipy.stats as stats
from ifcb.data.adc import SCHEMA_VERSION_1, SCHEMA_VERSION_2
from scipy.io import loadmat
and context (class names, function names, or code) available:
# Path: ifcb/data/adc.py
# class SCHEMA_VERSION_1(object):
# """
# IFCB revision 1 schema.
# """
# _name = 'v1'
# _cols = range(15)
# TRIGGER = 0
# PROCESSING_END_TIME = 1
# FLUORESCENCE_LOW = 2
# FLUORESCENCE_HIGH = 3
# SCATTERING_LOW = 4
# SCATTERING_HIGH = 5
# COMPARATOR_PULSE = 6
# TRIGGER_OPEN_TIME = 7
# FRAME_GRAB_TIME = 8
# ROI_X = 9
# ROI_Y = 10
# ROI_WIDTH = 11
# ROI_HEIGHT = 12
# START_BYTE = 13
# VALVE_STATUS = 14
#
# class SCHEMA_VERSION_2(object):
# """
# IFCB revision 2 schema.
# """
# _name = 'v2'
# _cols = range(24)
# TRIGGER = 0
# ADC_TIME = 1
# PMT_A = 2
# PMT_B = 3
# PMT_C = 4
# PMT_D = 5
# PEAK_A = 6
# PEAK_B = 7
# PEAK_C = 8
# PEAK_D = 9
# TIME_OF_FLIGHT = 10
# GRAB_TIME_START = 11
# GRAB_TIME_END = 12
# ROI_X = 13
# ROI_Y = 14
# ROI_WIDTH = 15
# ROI_HEIGHT = 16
# START_BYTE = 17
# COMPARATOR_OUT = 18
# START_POINT = 19
# SIGNAL_LENGTH = 20
# STATUS = 21
# RUN_TIME = 22
# INHIBIT_TIME = 23
. Output only the next line. | elif s is SCHEMA_VERSION_2: |
Given snippet: <|code_start|>
class TestHdr(unittest.TestCase):
def test_hdr(self):
for b in list_test_bins():
h = b.headers
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from ifcb.data.files import DataDirectory
from .fileset_info import list_test_bins, TEST_FILES
and context:
# Path: ifcb/data/files.py
# class DataDirectory(object):
# """
# Represents a directory containing IFCB raw data.
#
# Provides a dict-like interface allowing access to FilesetBins by LID.
# """
# def __init__(self, path='.', whitelist=DEFAULT_WHITELIST, blacklist=DEFAULT_BLACKLIST, filter=lambda x: True):
# """
# :param path: the path of the data directory
# :param whitelist: a list of directory names to allow
# :param blacklist: a list of directory names to disallow
# """
# self.path = path
# self.whitelist = whitelist
# self.blacklist = blacklist
# self.filter = filter
# def list_filesets(self):
# """
# Yield all filesets.
# """
# for dirpath, basename in list_filesets(self.path, whitelist=self.whitelist, blacklist=self.blacklist):
# basepath = os.path.join(dirpath, basename)
# fs = Fileset(basepath)
# if self.filter(fs):
# yield fs
# def find_fileset(self, lid):
# """
# Locate a fileset by LID. Returns None if it is not found.
#
# :param lid: the LID to search for
# :type lid: str
# :returns Fileset: the fileset, or None if not found
# """
# fs = find_fileset(self.path, lid, whitelist=self.whitelist, blacklist=self.blacklist)
# if fs is None:
# return None
# elif self.filter(fs):
# return fs
# def __iter__(self):
# # yield from list_filesets called with no keyword args
# for fs in self.list_filesets():
# yield FilesetBin(fs)
# def has_key(self, lid):
# # fast contains method that avoids iteration
# return self.find_fileset(lid) is not None
# def __getitem__(self, lid):
# fs = self.find_fileset(lid)
# if fs is None:
# raise KeyError('No fileset for %s found at or under %s' % (lid, self.path))
# return FilesetBin(fs)
# def __len__(self):
# """warning: for large datasets, this is very slow"""
# return sum(1 for _ in self)
# # subdirectories
# def list_descendants(self, **kw):
# """
# Find all 'leaf' data directories and yield ``DataDirectory``
# objects for each one. Note that this enforces blacklisting
# but not whitelisting (no fileset path validation is done).
# Accepts ``list_data_dirs`` keywords, except ``blacklist`` which
# takes on the value given in the constructor.
# """
# for dd in list_data_dirs(self.path, blacklist=self.blacklist, **kw):
# yield DataDirectory(dd)
# def __repr__(self):
# return '<DataDirectory %s>' % self.path
# def __str__(self):
# return self.path
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# TEST_FILES = {
# 'D20130526T095207_IFCB013': {
# 'n_rois': 19,
# 'n_targets': 118,
# 'roi_numbers': [7, 11, 13, 21, 32, 33, 47, 49, 54, 61, 66, 68, 73, 78, 80, 92, 99, 102, 114],
# 'roi_number': 99,
# 'roi_shape': (34, 64),
# 'roi_slice_coords': [slice(0,5), slice(0,5)],
# 'roi_slice': np.array([[172, 168, 172, 166, 171],
# [168, 170, 172, 171, 170],
# [167, 174, 171, 175, 168],
# [173, 171, 173, 170, 171],
# [176, 169, 176, 173, 172]], dtype=np.uint8),
# 'sizes': {
# 'roi': 98472,
# 'hdr': 2885,
# 'adc': 19395
# },
# 'headers': {
# 'KloehnPort': 'COM3',
# 'laserMotorSmallStep_ms': 1000,
# 'blobXgrowAmount': 20
# }
# },
# 'IFCB5_2012_028_081515': {
# 'n_rois': 6,
# 'n_targets': 7,
# 'roi_numbers': [1, 2, 3, 4, 5, 6],
# 'roi_number': 1,
# 'roi_shape': (45, 96),
# 'roi_slice_coords': [slice(0,5), slice(0,5)],
# 'roi_slice': np.array([[208, 207, 206, 206, 207],
# [206, 206, 206, 207, 206],
# [206, 207, 205, 206, 208],
# [208, 208, 208, 208, 209],
# [206, 206, 205, 207, 207]], dtype=np.uint8),
# 'stitched_roi_number': 3,
# 'roi_numbers_stitched': [1, 2, 3, 5, 6],
# 'stitched_roi_shape': (86, 263),
# 'stitched_roi_coords': [slice(23,27), slice(177,183)],
# 'stitched_roi_slice': np.array([[205, 204, 205, 0, 0, 0],
# [202, 203, 206, 0, 0, 0],
# [205, 206, 205, 204, 202, 202],
# [204, 202, 205, 203, 202, 204]], dtype=np.uint8),
# 'stitched_corners': {1: [208, 204, 205, 205],
# 2: [205, 199, 203, 197],
# 3: [210, 203, 207, 203],
# 5: [210, 209, 212, 209],
# 6: [212, 206, 209, 208]},
# 'sizes': {
# 'roi': 71083,
# 'hdr': 301,
# 'adc': 1004
# },
# 'headers': {
# 'binarizeThreshold': 30,
# 'fluorescencePhotomultiplierSetting': 0.6,
# }
# }
# }
which might include code, classes, or functions. Output only the next line. | eh = TEST_FILES[b.lid]['headers'] |
Based on the snippet: <|code_start|>
Also supports an "adc" property that is a Pandas DataFrame containing
ADC data. Subclasses are required to provide this. The default dictlike
implementation uses that property.
Context manager support is provided for implementations
that must open files or other data streams.
"""
@property
def lid(self):
"""
:returns str: the bin's LID.
"""
return self.pid.bin_lid
@property
@lru_cache()
def images_adc(self):
"""
:returns pandas.DataFrame: the ADC data, minus targets that
are not associated with images
"""
return self.adc[self.adc[self.schema.ROI_WIDTH] > 0]
@property
def timestamp(self):
"""
:returns datetime: the bin's timestamp.
"""
return self.pid.timestamp
@property
def schema(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import lru_cache
from .adc import SCHEMA
from .hdr import TEMPERATURE, HUMIDITY
from .utils import BaseDictlike
from ..metrics.ml_analyzed import compute_ml_analyzed
from .hdf import bin2hdf
from .zip import bin2zip
from .matlab import bin2mat
and context (classes, functions, sometimes code) from other files:
# Path: ifcb/data/adc.py
# SCHEMA = {
# 1: SCHEMA_VERSION_1,
# 2: SCHEMA_VERSION_2,
# SCHEMA_VERSION_1._name: SCHEMA_VERSION_1,
# SCHEMA_VERSION_2._name: SCHEMA_VERSION_2
# }
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
. Output only the next line. | return SCHEMA[self.pid.schema_version] |
Given the code snippet: <|code_start|> def _get_ml_analyzed(self):
return compute_ml_analyzed(self)
@property
def ml_analyzed(self):
ma, _, _ = self._get_ml_analyzed()
return ma
@property
def look_time(self):
_, lt, _ = self._get_ml_analyzed()
return lt
@property
def run_time(self):
_, _, rt = self._get_ml_analyzed()
return rt
@property
def inhibit_time(self):
return self.run_time - self.look_time
@property
def n_triggers(self):
try:
last_row = self.adc.iloc[-1]
except IndexError: # empty ADC file
return 0
return int(last_row[self.schema.TRIGGER])
@property
def trigger_rate(self):
"""return trigger rate in triggers / s"""
return 1.0 * self.n_triggers / self.run_time
@property
def temperature(self):
<|code_end|>
, generate the next line using the imports in this file:
from functools import lru_cache
from .adc import SCHEMA
from .hdr import TEMPERATURE, HUMIDITY
from .utils import BaseDictlike
from ..metrics.ml_analyzed import compute_ml_analyzed
from .hdf import bin2hdf
from .zip import bin2zip
from .matlab import bin2mat
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/adc.py
# SCHEMA = {
# 1: SCHEMA_VERSION_1,
# 2: SCHEMA_VERSION_2,
# SCHEMA_VERSION_1._name: SCHEMA_VERSION_1,
# SCHEMA_VERSION_2._name: SCHEMA_VERSION_2
# }
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
. Output only the next line. | return self.header(TEMPERATURE) |
Based on the snippet: <|code_start|> def ml_analyzed(self):
ma, _, _ = self._get_ml_analyzed()
return ma
@property
def look_time(self):
_, lt, _ = self._get_ml_analyzed()
return lt
@property
def run_time(self):
_, _, rt = self._get_ml_analyzed()
return rt
@property
def inhibit_time(self):
return self.run_time - self.look_time
@property
def n_triggers(self):
try:
last_row = self.adc.iloc[-1]
except IndexError: # empty ADC file
return 0
return int(last_row[self.schema.TRIGGER])
@property
def trigger_rate(self):
"""return trigger rate in triggers / s"""
return 1.0 * self.n_triggers / self.run_time
@property
def temperature(self):
return self.header(TEMPERATURE)
@property
def humidity(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import lru_cache
from .adc import SCHEMA
from .hdr import TEMPERATURE, HUMIDITY
from .utils import BaseDictlike
from ..metrics.ml_analyzed import compute_ml_analyzed
from .hdf import bin2hdf
from .zip import bin2zip
from .matlab import bin2mat
and context (classes, functions, sometimes code) from other files:
# Path: ifcb/data/adc.py
# SCHEMA = {
# 1: SCHEMA_VERSION_1,
# 2: SCHEMA_VERSION_2,
# SCHEMA_VERSION_1._name: SCHEMA_VERSION_1,
# SCHEMA_VERSION_2._name: SCHEMA_VERSION_2
# }
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
. Output only the next line. | return self.header(HUMIDITY) |
Given the following code snippet before the placeholder: <|code_start|> """
return self.pid.timestamp
@property
def schema(self):
return SCHEMA[self.pid.schema_version]
# context manager default implementation
def __enter__(self):
return self
def __exit__(self, *args):
pass
# dictlike interface
def keys(self):
yield from self.adc.index
def has_key(self, k):
return k in self.adc.index
def __len__(self):
return len(self.adc.index)
def get_target(self, target_number):
"""
Retrieve a target record by target number
:param target_number: the target number
"""
d = tuple(self.adc[c][target_number] for c in self.adc.columns)
return d
def __getitem__(self, target_number):
return self.get_target(target_number)
# metrics
@lru_cache()
def _get_ml_analyzed(self):
<|code_end|>
, predict the next line using imports from the current file:
from functools import lru_cache
from .adc import SCHEMA
from .hdr import TEMPERATURE, HUMIDITY
from .utils import BaseDictlike
from ..metrics.ml_analyzed import compute_ml_analyzed
from .hdf import bin2hdf
from .zip import bin2zip
from .matlab import bin2mat
and context including class names, function names, and sometimes code from other files:
# Path: ifcb/data/adc.py
# SCHEMA = {
# 1: SCHEMA_VERSION_1,
# 2: SCHEMA_VERSION_2,
# SCHEMA_VERSION_1._name: SCHEMA_VERSION_1,
# SCHEMA_VERSION_2._name: SCHEMA_VERSION_2
# }
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
. Output only the next line. | return compute_ml_analyzed(self) |
Using the snippet: <|code_start|>
class TestListUtils(unittest.TestCase):
def setUp(self):
self.data_dir = data_dir()
def test_list_data_dirs(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import os
import sys
import numpy as np
from ifcb.data import files
from .fileset_info import TEST_FILES, data_dir, WHITELIST, list_test_filesets, list_test_bins
and context (class names, function names, or code) available:
# Path: ifcb/data/files.py
# DEFAULT_BLACKLIST = ['skip','beads']
# DEFAULT_WHITELIST = ['data']
# class Fileset(object):
# class FilesetBin(BaseBin):
# class FilesetFragmentBin(FilesetBin):
# class DataDirectory(object):
# def __init__(self, basepath):
# def adc_path(self):
# def hdr_path(self):
# def roi_path(self):
# def pid(self):
# def lid(self):
# def exists(self):
# def getsizes(self):
# def getsize(self):
# def as_bin(self):
# def __repr__(self):
# def __str__(self):
# def __init__(self, fileset):
# def hdr_attributes(self):
# def timestamp(self):
# def to_hdf(self, hdf_file, group=None, replace=True, archive=False):
# def pid(self):
# def schema(self):
# def images(self):
# def headers(self):
# def header(self, key):
# def adc(self):
# def isopen(self):
# def close(self):
# def __enter__(self):
# def __exit__(self, *args):
# def as_single(self, target):
# def __repr__(self):
# def __str__(self):
# def __init__(self, fileset, target):
# def validate_path(filepath, blacklist=DEFAULT_BLACKLIST, whitelist=DEFAULT_WHITELIST):
# def list_filesets(dirpath, blacklist=DEFAULT_BLACKLIST, whitelist=DEFAULT_WHITELIST, sort=True, validate=True):
# def list_data_dirs(dirpath, blacklist=DEFAULT_BLACKLIST, sort=True, prune=True):
# def find_fileset(dirpath, lid, whitelist=['data'], blacklist=['skip','beads']):
# def __init__(self, path='.', whitelist=DEFAULT_WHITELIST, blacklist=DEFAULT_BLACKLIST, filter=lambda x: True):
# def list_filesets(self):
# def find_fileset(self, lid):
# def __iter__(self):
# def has_key(self, lid):
# def __getitem__(self, lid):
# def __len__(self):
# def list_descendants(self, **kw):
# def __repr__(self):
# def __str__(self):
# def time_filter(start='1970-01-01', end='3000-01-01'):
# def inner(fs):
#
# Path: ifcb/tests/data/fileset_info.py
# TEST_FILES = {
# 'D20130526T095207_IFCB013': {
# 'n_rois': 19,
# 'n_targets': 118,
# 'roi_numbers': [7, 11, 13, 21, 32, 33, 47, 49, 54, 61, 66, 68, 73, 78, 80, 92, 99, 102, 114],
# 'roi_number': 99,
# 'roi_shape': (34, 64),
# 'roi_slice_coords': [slice(0,5), slice(0,5)],
# 'roi_slice': np.array([[172, 168, 172, 166, 171],
# [168, 170, 172, 171, 170],
# [167, 174, 171, 175, 168],
# [173, 171, 173, 170, 171],
# [176, 169, 176, 173, 172]], dtype=np.uint8),
# 'sizes': {
# 'roi': 98472,
# 'hdr': 2885,
# 'adc': 19395
# },
# 'headers': {
# 'KloehnPort': 'COM3',
# 'laserMotorSmallStep_ms': 1000,
# 'blobXgrowAmount': 20
# }
# },
# 'IFCB5_2012_028_081515': {
# 'n_rois': 6,
# 'n_targets': 7,
# 'roi_numbers': [1, 2, 3, 4, 5, 6],
# 'roi_number': 1,
# 'roi_shape': (45, 96),
# 'roi_slice_coords': [slice(0,5), slice(0,5)],
# 'roi_slice': np.array([[208, 207, 206, 206, 207],
# [206, 206, 206, 207, 206],
# [206, 207, 205, 206, 208],
# [208, 208, 208, 208, 209],
# [206, 206, 205, 207, 207]], dtype=np.uint8),
# 'stitched_roi_number': 3,
# 'roi_numbers_stitched': [1, 2, 3, 5, 6],
# 'stitched_roi_shape': (86, 263),
# 'stitched_roi_coords': [slice(23,27), slice(177,183)],
# 'stitched_roi_slice': np.array([[205, 204, 205, 0, 0, 0],
# [202, 203, 206, 0, 0, 0],
# [205, 206, 205, 204, 202, 202],
# [204, 202, 205, 203, 202, 204]], dtype=np.uint8),
# 'stitched_corners': {1: [208, 204, 205, 205],
# 2: [205, 199, 203, 197],
# 3: [210, 203, 207, 203],
# 5: [210, 209, 212, 209],
# 6: [212, 206, 209, 208]},
# 'sizes': {
# 'roi': 71083,
# 'hdr': 301,
# 'adc': 1004
# },
# 'headers': {
# 'binarizeThreshold': 30,
# 'fluorescencePhotomultiplierSetting': 0.6,
# }
# }
# }
#
# def data_dir():
# for p in sys.path:
# fp = os.path.join(p, TEST_DATA_DIR)
# if os.path.exists(fp):
# return fp
# raise KeyError('cannot find %s on sys.path' % TEST_DATA_DIR)
#
# WHITELIST = ['data','white']
#
# def list_test_filesets():
# return [b.fileset for b in list_test_bins()]
#
# def list_test_bins():
# return list(_dd())
. Output only the next line. | for dd in files.list_data_dirs(self.data_dir): |
Given snippet: <|code_start|>
TARGET_ML_ANALYZED = {
'IFCB5_2012_028_081515': (0.003391470833333334, 0.8139530000000001, 1.251953),
'D20130526T095207_IFCB013': (5.080841170833334, 1219.401881, 1231.024861)
}
class TestMlAnalyzed(unittest.TestCase):
def test_ml_analyzed(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins, get_fileset_bin
from ifcb.metrics.ml_analyzed import compute_ml_analyzed
and context:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
which might include code, classes, or functions. Output only the next line. | for b in list_test_bins(): |
Next line prediction: <|code_start|>
TARGET_ML_ANALYZED = {
'IFCB5_2012_028_081515': (0.003391470833333334, 0.8139530000000001, 1.251953),
'D20130526T095207_IFCB013': (5.080841170833334, 1219.401881, 1231.024861)
}
class TestMlAnalyzed(unittest.TestCase):
def test_ml_analyzed(self):
for b in list_test_bins():
<|code_end|>
. Use current file imports:
(import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins, get_fileset_bin
from ifcb.metrics.ml_analyzed import compute_ml_analyzed)
and context including class names, function names, or small code snippets from other files:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/metrics/ml_analyzed.py
# def compute_ml_analyzed(abin):
# """returns ml_analyzed, look time, run time"""
# s = abin.schema
# if s is SCHEMA_VERSION_1:
# return compute_ml_analyzed_s1(abin)
# elif s is SCHEMA_VERSION_2:
# return compute_ml_analyzed_s2(abin)
. Output only the next line. | result = compute_ml_analyzed(b) |
Predict the next line after this snippet: <|code_start|>
SL_BIN_LID = 'IFCB5_2012_028_081515'
SL_MEDIAN = np.array([[205, 205, 205, 205, 205],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[205, 205, 205, 205, 205],
[205, 205, 205, 205, 205]])
SL_MEAN = np.array([[202, 202, 202, 202, 202],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[202, 202, 202, 202, 202],
[202, 202, 202, 202, 202]])
SL_27 = np.array([[ 27, 27, 27, 27, 27],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[ 27, 27, 27, 27, 27],
[ 27, 27, 27, 27, 27]])
SQ = np.array([[206, 205, 204, 206, 204],
[205, 204, 208, 205, 203],
[204, 203, 215, 204, 204],
[206, 204, 159, 207, 205],
[206, 204, 205, 206, 205]])
@unittest.skip('deprecated feature')
class TestSquare(unittest.TestCase):
def setUp(self):
<|code_end|>
using the current file's imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import get_fileset_bin
from ifcb.viz.utils import square_letterboxed, square, SQUARE_DEFAULT_SIZE
and any relevant context from other files:
# Path: ifcb/tests/data/fileset_info.py
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/viz/utils.py
# def square_letterboxed(img, size=SQUARE_DEFAULT_SIZE, fill_value='median'):
# if fill_value == 'median':
# fill_value = int(np.median(img))
# elif fill_value == 'mean':
# fill_value = int(np.mean(img))
# scale = 1.0 * size / max(img.shape)
# scaled = rescale(img, scale, mode='reflect', preserve_range=True).astype(np.uint8)
# h, w = scaled.shape
# ctr = size / 2
# letterboxed = np.zeros((size, size), dtype=np.uint8) + fill_value
# y = int(ctr - h/2)
# x = int(ctr - w/2)
# letterboxed[y:y+h,x:x+w] = scaled
# return letterboxed
#
# def square(img, size=SQUARE_DEFAULT_SIZE):
# scaled = resize(img, (size, size), mode='reflect', preserve_range=True).astype(np.uint8)
# return scaled
#
# SQUARE_DEFAULT_SIZE = 399
. Output only the next line. | b = get_fileset_bin(SL_BIN_LID) |
Continue the code snippet: <|code_start|> [ 27, 27, 27, 27, 27]])
SQ = np.array([[206, 205, 204, 206, 204],
[205, 204, 208, 205, 203],
[204, 203, 215, 204, 204],
[206, 204, 159, 207, 205],
[206, 204, 205, 206, 205]])
@unittest.skip('deprecated feature')
class TestSquare(unittest.TestCase):
def setUp(self):
b = get_fileset_bin(SL_BIN_LID)
self.img = b.images[1]
def test_square(self):
sq = square(self.img, size=5)
assert np.allclose(sq, SQ)
def test_size(self):
sq = square(self.img, 20)
assert sq.shape == (20, 20)
def test_default_size(self):
sq = square(self.img)
assert sq.shape[0] == SQUARE_DEFAULT_SIZE
assert sq.shape[1] == SQUARE_DEFAULT_SIZE
@unittest.skip('deprecated feature')
class TestSquareLetterboxed(unittest.TestCase):
def setUp(self):
b = get_fileset_bin(SL_BIN_LID)
self.img = b.images[1]
def test_fill_value_median(self):
<|code_end|>
. Use current file imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import get_fileset_bin
from ifcb.viz.utils import square_letterboxed, square, SQUARE_DEFAULT_SIZE
and context (classes, functions, or code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/viz/utils.py
# def square_letterboxed(img, size=SQUARE_DEFAULT_SIZE, fill_value='median'):
# if fill_value == 'median':
# fill_value = int(np.median(img))
# elif fill_value == 'mean':
# fill_value = int(np.mean(img))
# scale = 1.0 * size / max(img.shape)
# scaled = rescale(img, scale, mode='reflect', preserve_range=True).astype(np.uint8)
# h, w = scaled.shape
# ctr = size / 2
# letterboxed = np.zeros((size, size), dtype=np.uint8) + fill_value
# y = int(ctr - h/2)
# x = int(ctr - w/2)
# letterboxed[y:y+h,x:x+w] = scaled
# return letterboxed
#
# def square(img, size=SQUARE_DEFAULT_SIZE):
# scaled = resize(img, (size, size), mode='reflect', preserve_range=True).astype(np.uint8)
# return scaled
#
# SQUARE_DEFAULT_SIZE = 399
. Output only the next line. | sl = square_letterboxed(self.img, size=5) |
Based on the snippet: <|code_start|>SL_MEDIAN = np.array([[205, 205, 205, 205, 205],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[205, 205, 205, 205, 205],
[205, 205, 205, 205, 205]])
SL_MEAN = np.array([[202, 202, 202, 202, 202],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[202, 202, 202, 202, 202],
[202, 202, 202, 202, 202]])
SL_27 = np.array([[ 27, 27, 27, 27, 27],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[ 27, 27, 27, 27, 27],
[ 27, 27, 27, 27, 27]])
SQ = np.array([[206, 205, 204, 206, 204],
[205, 204, 208, 205, 203],
[204, 203, 215, 204, 204],
[206, 204, 159, 207, 205],
[206, 204, 205, 206, 205]])
@unittest.skip('deprecated feature')
class TestSquare(unittest.TestCase):
def setUp(self):
b = get_fileset_bin(SL_BIN_LID)
self.img = b.images[1]
def test_square(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import get_fileset_bin
from ifcb.viz.utils import square_letterboxed, square, SQUARE_DEFAULT_SIZE
and context (classes, functions, sometimes code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/viz/utils.py
# def square_letterboxed(img, size=SQUARE_DEFAULT_SIZE, fill_value='median'):
# if fill_value == 'median':
# fill_value = int(np.median(img))
# elif fill_value == 'mean':
# fill_value = int(np.mean(img))
# scale = 1.0 * size / max(img.shape)
# scaled = rescale(img, scale, mode='reflect', preserve_range=True).astype(np.uint8)
# h, w = scaled.shape
# ctr = size / 2
# letterboxed = np.zeros((size, size), dtype=np.uint8) + fill_value
# y = int(ctr - h/2)
# x = int(ctr - w/2)
# letterboxed[y:y+h,x:x+w] = scaled
# return letterboxed
#
# def square(img, size=SQUARE_DEFAULT_SIZE):
# scaled = resize(img, (size, size), mode='reflect', preserve_range=True).astype(np.uint8)
# return scaled
#
# SQUARE_DEFAULT_SIZE = 399
. Output only the next line. | sq = square(self.img, size=5) |
Given the code snippet: <|code_start|> [207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[202, 202, 202, 202, 202],
[202, 202, 202, 202, 202]])
SL_27 = np.array([[ 27, 27, 27, 27, 27],
[207, 204, 207, 205, 204],
[206, 206, 211, 204, 205],
[ 27, 27, 27, 27, 27],
[ 27, 27, 27, 27, 27]])
SQ = np.array([[206, 205, 204, 206, 204],
[205, 204, 208, 205, 203],
[204, 203, 215, 204, 204],
[206, 204, 159, 207, 205],
[206, 204, 205, 206, 205]])
@unittest.skip('deprecated feature')
class TestSquare(unittest.TestCase):
def setUp(self):
b = get_fileset_bin(SL_BIN_LID)
self.img = b.images[1]
def test_square(self):
sq = square(self.img, size=5)
assert np.allclose(sq, SQ)
def test_size(self):
sq = square(self.img, 20)
assert sq.shape == (20, 20)
def test_default_size(self):
sq = square(self.img)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import get_fileset_bin
from ifcb.viz.utils import square_letterboxed, square, SQUARE_DEFAULT_SIZE
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/viz/utils.py
# def square_letterboxed(img, size=SQUARE_DEFAULT_SIZE, fill_value='median'):
# if fill_value == 'median':
# fill_value = int(np.median(img))
# elif fill_value == 'mean':
# fill_value = int(np.mean(img))
# scale = 1.0 * size / max(img.shape)
# scaled = rescale(img, scale, mode='reflect', preserve_range=True).astype(np.uint8)
# h, w = scaled.shape
# ctr = size / 2
# letterboxed = np.zeros((size, size), dtype=np.uint8) + fill_value
# y = int(ctr - h/2)
# x = int(ctr - w/2)
# letterboxed[y:y+h,x:x+w] = scaled
# return letterboxed
#
# def square(img, size=SQUARE_DEFAULT_SIZE):
# scaled = resize(img, (size, size), mode='reflect', preserve_range=True).astype(np.uint8)
# return scaled
#
# SQUARE_DEFAULT_SIZE = 399
. Output only the next line. | assert sq.shape[0] == SQUARE_DEFAULT_SIZE |
Given the following code snippet before the placeholder: <|code_start|>
class TestMatBin(unittest.TestCase):
@withfile
def test_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from ifcb.data.matlab import bin2mat, MatBin
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context including class names, function names, and sometimes code from other files:
# Path: ifcb/data/matlab.py
# def bin2mat(b, mat_path):
# # ADC data
# adc = np.array(b.adc)
# # warning: reads all images into memory
# roi_numbers = sorted(b.images)
# images = [ b.images[r] for r in roi_numbers ]
# savemat(mat_path, {
# PID_VAR: str(b.lid), # remove non-bin parts of pid
# HEADERS_VAR: b.headers,
# ADC_VAR: adc,
# ROI_NUMBERS_VAR: roi_numbers,
# IMAGES_VAR: images
# }, long_field_names=True)
#
# class MatBin(BaseBin):
# def __init__(self, mat_path):
# self._mat = loadmat(mat_path, squeeze_me=True)
# self.pid = Pid(self._mat[PID_VAR])
# self.adc = pd.DataFrame(self._mat[ADC_VAR]);
# self.adc.index += 1 # 1-based indexes
# self.images = _MatBinImages(self._mat)
# rec = self._mat[HEADERS_VAR]
# rec_names = rec.dtype.names
# self.headers = { n : rec[n].item() for n in rec_names }
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | bin2mat(out_bin, path) |
Predict the next line for this snippet: <|code_start|>
class TestMatBin(unittest.TestCase):
@withfile
def test_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
bin2mat(out_bin, path)
<|code_end|>
with the help of current file imports:
import unittest
from ifcb.data.matlab import bin2mat, MatBin
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context from other files:
# Path: ifcb/data/matlab.py
# def bin2mat(b, mat_path):
# # ADC data
# adc = np.array(b.adc)
# # warning: reads all images into memory
# roi_numbers = sorted(b.images)
# images = [ b.images[r] for r in roi_numbers ]
# savemat(mat_path, {
# PID_VAR: str(b.lid), # remove non-bin parts of pid
# HEADERS_VAR: b.headers,
# ADC_VAR: adc,
# ROI_NUMBERS_VAR: roi_numbers,
# IMAGES_VAR: images
# }, long_field_names=True)
#
# class MatBin(BaseBin):
# def __init__(self, mat_path):
# self._mat = loadmat(mat_path, squeeze_me=True)
# self.pid = Pid(self._mat[PID_VAR])
# self.adc = pd.DataFrame(self._mat[ADC_VAR]);
# self.adc.index += 1 # 1-based indexes
# self.images = _MatBinImages(self._mat)
# rec = self._mat[HEADERS_VAR]
# rec_names = rec.dtype.names
# self.headers = { n : rec[n].item() for n in rec_names }
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
, which may contain function names, class names, or code. Output only the next line. | with MatBin(path) as in_bin: |
Continue the code snippet: <|code_start|>
class TestMatBin(unittest.TestCase):
@withfile
def test_roundtrip(self, path):
<|code_end|>
. Use current file imports:
import unittest
from ifcb.data.matlab import bin2mat, MatBin
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context (classes, functions, or code) from other files:
# Path: ifcb/data/matlab.py
# def bin2mat(b, mat_path):
# # ADC data
# adc = np.array(b.adc)
# # warning: reads all images into memory
# roi_numbers = sorted(b.images)
# images = [ b.images[r] for r in roi_numbers ]
# savemat(mat_path, {
# PID_VAR: str(b.lid), # remove non-bin parts of pid
# HEADERS_VAR: b.headers,
# ADC_VAR: adc,
# ROI_NUMBERS_VAR: roi_numbers,
# IMAGES_VAR: images
# }, long_field_names=True)
#
# class MatBin(BaseBin):
# def __init__(self, mat_path):
# self._mat = loadmat(mat_path, squeeze_me=True)
# self.pid = Pid(self._mat[PID_VAR])
# self.adc = pd.DataFrame(self._mat[ADC_VAR]);
# self.adc.index += 1 # 1-based indexes
# self.images = _MatBinImages(self._mat)
# rec = self._mat[HEADERS_VAR]
# rec_names = rec.dtype.names
# self.headers = { n : rec[n].item() for n in rec_names }
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | for out_bin in list_test_bins(): |
Using the snippet: <|code_start|>
class TestMatBin(unittest.TestCase):
@withfile
def test_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
bin2mat(out_bin, path)
with MatBin(path) as in_bin:
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from ifcb.data.matlab import bin2mat, MatBin
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context (class names, function names, or code) available:
# Path: ifcb/data/matlab.py
# def bin2mat(b, mat_path):
# # ADC data
# adc = np.array(b.adc)
# # warning: reads all images into memory
# roi_numbers = sorted(b.images)
# images = [ b.images[r] for r in roi_numbers ]
# savemat(mat_path, {
# PID_VAR: str(b.lid), # remove non-bin parts of pid
# HEADERS_VAR: b.headers,
# ADC_VAR: adc,
# ROI_NUMBERS_VAR: roi_numbers,
# IMAGES_VAR: images
# }, long_field_names=True)
#
# class MatBin(BaseBin):
# def __init__(self, mat_path):
# self._mat = loadmat(mat_path, squeeze_me=True)
# self.pid = Pid(self._mat[PID_VAR])
# self.adc = pd.DataFrame(self._mat[ADC_VAR]);
# self.adc.index += 1 # 1-based indexes
# self.images = _MatBinImages(self._mat)
# rec = self._mat[HEADERS_VAR]
# rec_names = rec.dtype.names
# self.headers = { n : rec[n].item() for n in rec_names }
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | assert_bin_equals(in_bin, out_bin) |
Given snippet: <|code_start|> :param height: the height of the image in pixels
:returns array-like: an 8-bit 2d image
"""
length = width * height
inroi.seek(byte_offset)
pixel_values = inroi.read(length)
return np.frombuffer(pixel_values, dtype=np.uint8).reshape((width,height))
class RoiFile(BaseDictlike):
"""
Wraps and provides access to an IFCB ``.roi`` file.
Provides context manager support for keeping the
file open while images are read from it. Also
provides dict-like support including len, iteration,
and access to images by target number.
Requires an associated ``.adc`` file or ``AdcFile`` object.
"""
def __init__(self, adc, roi_path):
"""
:param adc: the path of the ``.adc`` file, or an ``AdcFile`` object
:param roi_path: the path to the ``.roi`` file
"""
# duck type adc argument
self.adc = None
try:
adc.pid # should work for AdcFile objects
self.adc = adc
except AttributeError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
from functools import lru_cache
from .adc import AdcFile
from .utils import BaseDictlike
from .hdf import roi2hdf
and context:
# Path: ifcb/data/adc.py
# class AdcFile(BaseDictlike):
# """
# Represents an IFCB ``.adc`` file.
#
# Provides a dict-like interface; keys are target numbers,
# values are target records. Target records are tuples which
# are indexed according to values in the associated schema
# (accessible via the ``schema`` property).
#
# :Example:
#
# >>> adc = AdcFile('IFCB4_2013_007_123423.adc')
# >>> adc[23][adc.schema.ROI_WIDTH]
# 135
#
# """
# def __init__(self, adc_path, parse=False):
# """
# :param adc_path: the path of the ``.adc`` file.
# :param parse: whether to parse the file
# (if not, parsing is deferred until data is accessed)
# """
# self.path = adc_path
# self.pid = Pid(adc_path, parse=parse)
# self.schema_version = self.pid.schema_version
# self.schema = SCHEMA[self.schema_version]
# if parse:
# self.csv
# def getsize(self):
# """
# :return int: the size of the file
# """
# return os.path.getsize(self.path)
# @property
# def lid(self):
# """
# The bin's LID
# """
# return self.pid.lid
# @property
# @lru_cache()
# def csv(self):
# """
# The underlying CSV data as a ``pandas.DataFrame``
# """
# return parse_adc_file(self.path)
# def to_dataframe(self):
# """
# Return the ADC data as a ``pandas.DataFrame``. If the
# file has not been parsed yet, this opens the file, parses it,
# and closes it.
# """
# return self.csv
# def to_dict(self):
# """
# Return the ADC data as a dictionary
# """
# return self.csv.to_dict('series')
# def to_hdf(self, hdf_file, group=None, replace=True, **kw):
# """
# Write the ADC file to an HDF file or group.
#
# :param hdf_file: the root HDF file pathname or
# object (h5py.File or h5py.Group) in which to write
# the ADC data
# :param group: a path below the sub-group
# to use
# :param replace: whether to replace any existing data
# at that location in the HDF file
# """
# from .hdf import adc2hdf
# adc2hdf(self, hdf_file, group, replace=replace, **kw)
# def keys(self):
# """
# Yield the target numbers of this ADC file, in order.
# """
# yield from self.csv.index
# def has_key(self, k):
# return k in self.csv.index
# def __len__(self):
# return len(self.csv)
# def get_target(self, target_number):
# """
# Get the ADC data for a given target, as a tuple.
# """
# d = tuple(self.csv[c][target_number] for c in self.csv.columns)
# return d
# def __getitem__(self, target_number):
# return self.get_target(target_number)
# def __repr__(self):
# return '<ADC file %s>' % self.path
# def __str__(self):
# return self.path
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
which might include code, classes, or functions. Output only the next line. | self.adc = AdcFile(adc) |
Given the code snippet: <|code_start|>"""
Support for reading images from IFCB ``.roi`` files.
"""
def read_image(inroi, byte_offset, width, height):
"""
Read an image from raw 8-bit binary data.
:param inroi: an open file in binary read mode
:param byte_offset: the position in the file to seek to
:param width: the width of the image in pixels
:param height: the height of the image in pixels
:returns array-like: an 8-bit 2d image
"""
length = width * height
inroi.seek(byte_offset)
pixel_values = inroi.read(length)
return np.frombuffer(pixel_values, dtype=np.uint8).reshape((width,height))
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
from functools import lru_cache
from .adc import AdcFile
from .utils import BaseDictlike
from .hdf import roi2hdf
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/adc.py
# class AdcFile(BaseDictlike):
# """
# Represents an IFCB ``.adc`` file.
#
# Provides a dict-like interface; keys are target numbers,
# values are target records. Target records are tuples which
# are indexed according to values in the associated schema
# (accessible via the ``schema`` property).
#
# :Example:
#
# >>> adc = AdcFile('IFCB4_2013_007_123423.adc')
# >>> adc[23][adc.schema.ROI_WIDTH]
# 135
#
# """
# def __init__(self, adc_path, parse=False):
# """
# :param adc_path: the path of the ``.adc`` file.
# :param parse: whether to parse the file
# (if not, parsing is deferred until data is accessed)
# """
# self.path = adc_path
# self.pid = Pid(adc_path, parse=parse)
# self.schema_version = self.pid.schema_version
# self.schema = SCHEMA[self.schema_version]
# if parse:
# self.csv
# def getsize(self):
# """
# :return int: the size of the file
# """
# return os.path.getsize(self.path)
# @property
# def lid(self):
# """
# The bin's LID
# """
# return self.pid.lid
# @property
# @lru_cache()
# def csv(self):
# """
# The underlying CSV data as a ``pandas.DataFrame``
# """
# return parse_adc_file(self.path)
# def to_dataframe(self):
# """
# Return the ADC data as a ``pandas.DataFrame``. If the
# file has not been parsed yet, this opens the file, parses it,
# and closes it.
# """
# return self.csv
# def to_dict(self):
# """
# Return the ADC data as a dictionary
# """
# return self.csv.to_dict('series')
# def to_hdf(self, hdf_file, group=None, replace=True, **kw):
# """
# Write the ADC file to an HDF file or group.
#
# :param hdf_file: the root HDF file pathname or
# object (h5py.File or h5py.Group) in which to write
# the ADC data
# :param group: a path below the sub-group
# to use
# :param replace: whether to replace any existing data
# at that location in the HDF file
# """
# from .hdf import adc2hdf
# adc2hdf(self, hdf_file, group, replace=replace, **kw)
# def keys(self):
# """
# Yield the target numbers of this ADC file, in order.
# """
# yield from self.csv.index
# def has_key(self, k):
# return k in self.csv.index
# def __len__(self):
# return len(self.csv)
# def get_target(self, target_number):
# """
# Get the ADC data for a given target, as a tuple.
# """
# d = tuple(self.csv[c][target_number] for c in self.csv.columns)
# return d
# def __getitem__(self, target_number):
# return self.get_target(target_number)
# def __repr__(self):
# return '<ADC file %s>' % self.path
# def __str__(self):
# return self.path
#
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
. Output only the next line. | class RoiFile(BaseDictlike): |
Given the code snippet: <|code_start|>
PACKED = {
'IFCB5_2012_028_081515': {
'y': [0, 0, 137, 182, 182],
'x': [0, 238, 0, 0, 105],
'roi_number': [2, 3, 6, 5, 1]
},
'D20130526T095207_IFCB013': {
'y': [0, 89, 171, 237, 295, 337, 403, 453, 494, 237, 171, 337, 379, 527, 453, 527, 561, 561, 595],
'x': [0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 104, 96, 96, 0, 112, 88, 0, 72, 0],
'roi_number': [114, 61, 11, 78, 47, 73, 66, 21, 54, 49, 32, 33, 68, 7, 13, 80, 92, 102, 99]
}
}
class TestMosaic(unittest.TestCase):
def test_pack(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins
from ifcb.viz.mosaic import Mosaic
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/viz/mosaic.py
# class Mosaic(object):
# def __init__(self, the_bin, shape=(600, 800), scale=0.33, bg_color=200, coordinates=None):
# self.bin = the_bin
# self.shape = shape
# self.bg_color = bg_color
# self.scale = scale
# self.coordinates = coordinates
# @lru_cache()
# def _shapes(self):
# hs, ws, ix = [], [], []
# with self.bin:
# ii = InfilledImages(self.bin)
# for target_number in ii:
# h, w = ii.shape(target_number)
# hs.append(math.floor(h * self.scale))
# ws.append(math.floor(w * self.scale))
# ix.append(target_number)
# return zip(hs, ws, ix)
# def pack(self, max_pages=20):
# if self.coordinates is not None:
# return self.coordinates
# page_h, page_w = self.shape
# pages = [(page_h - 1, page_w - 1) for _ in range(max_pages)]
# packer = newPacker(sort_algo=SORT_AREA, rotation=False, pack_algo=GuillotineBafSlas)
# for r in self._shapes():
# packer.add_rect(*r)
# for p in pages:
# packer.add_bin(*p)
# packer.pack()
# COLS = ['page', 'y', 'x', 'h', 'w', 'roi_number']
# self.coordinates = pd.DataFrame(packer.rect_list(), columns=COLS)
# return self.coordinates
# def page(self, page=0):
# df = self.pack()
# page_h, page_w = self.shape
# page_image = np.zeros((page_h, page_w), dtype=np.uint8) + self.bg_color
# sdf = df[df.page == page]
# with self.bin:
# if self.bin.schema == SCHEMA_VERSION_1:
# ii = InfilledImages(self.bin)
# else:
# ii = self.bin.images
# for index, row in sdf.iterrows():
# y, x = row.y, row.x
# h, w = row.h, row.w
# unscaled_image = ii[row.roi_number]
# scaled_image = resize(unscaled_image, (h, w), mode='reflect', preserve_range=True)
# page_image[y:y+h, x:x+w] = scaled_image
# return page_image
. Output only the next line. | for b in list_test_bins(): |
Predict the next line after this snippet: <|code_start|>
PACKED = {
'IFCB5_2012_028_081515': {
'y': [0, 0, 137, 182, 182],
'x': [0, 238, 0, 0, 105],
'roi_number': [2, 3, 6, 5, 1]
},
'D20130526T095207_IFCB013': {
'y': [0, 89, 171, 237, 295, 337, 403, 453, 494, 237, 171, 337, 379, 527, 453, 527, 561, 561, 595],
'x': [0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 104, 96, 96, 0, 112, 88, 0, 72, 0],
'roi_number': [114, 61, 11, 78, 47, 73, 66, 21, 54, 49, 32, 33, 68, 7, 13, 80, 92, 102, 99]
}
}
class TestMosaic(unittest.TestCase):
def test_pack(self):
for b in list_test_bins():
if b.lid not in PACKED:
continue
<|code_end|>
using the current file's imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins
from ifcb.viz.mosaic import Mosaic
and any relevant context from other files:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/viz/mosaic.py
# class Mosaic(object):
# def __init__(self, the_bin, shape=(600, 800), scale=0.33, bg_color=200, coordinates=None):
# self.bin = the_bin
# self.shape = shape
# self.bg_color = bg_color
# self.scale = scale
# self.coordinates = coordinates
# @lru_cache()
# def _shapes(self):
# hs, ws, ix = [], [], []
# with self.bin:
# ii = InfilledImages(self.bin)
# for target_number in ii:
# h, w = ii.shape(target_number)
# hs.append(math.floor(h * self.scale))
# ws.append(math.floor(w * self.scale))
# ix.append(target_number)
# return zip(hs, ws, ix)
# def pack(self, max_pages=20):
# if self.coordinates is not None:
# return self.coordinates
# page_h, page_w = self.shape
# pages = [(page_h - 1, page_w - 1) for _ in range(max_pages)]
# packer = newPacker(sort_algo=SORT_AREA, rotation=False, pack_algo=GuillotineBafSlas)
# for r in self._shapes():
# packer.add_rect(*r)
# for p in pages:
# packer.add_bin(*p)
# packer.pack()
# COLS = ['page', 'y', 'x', 'h', 'w', 'roi_number']
# self.coordinates = pd.DataFrame(packer.rect_list(), columns=COLS)
# return self.coordinates
# def page(self, page=0):
# df = self.pack()
# page_h, page_w = self.shape
# page_image = np.zeros((page_h, page_w), dtype=np.uint8) + self.bg_color
# sdf = df[df.page == page]
# with self.bin:
# if self.bin.schema == SCHEMA_VERSION_1:
# ii = InfilledImages(self.bin)
# else:
# ii = self.bin.images
# for index, row in sdf.iterrows():
# y, x = row.y, row.x
# h, w = row.h, row.w
# unscaled_image = ii[row.roi_number]
# scaled_image = resize(unscaled_image, (h, w), mode='reflect', preserve_range=True)
# page_image[y:y+h, x:x+w] = scaled_image
# return page_image
. Output only the next line. | m = Mosaic(b, shape=(720, 1280), scale=1) |
Next line prediction: <|code_start|> def _shapes(self):
hs, ws, ix = [], [], []
with self.bin:
ii = InfilledImages(self.bin)
for target_number in ii:
h, w = ii.shape(target_number)
hs.append(math.floor(h * self.scale))
ws.append(math.floor(w * self.scale))
ix.append(target_number)
return zip(hs, ws, ix)
def pack(self, max_pages=20):
if self.coordinates is not None:
return self.coordinates
page_h, page_w = self.shape
pages = [(page_h - 1, page_w - 1) for _ in range(max_pages)]
packer = newPacker(sort_algo=SORT_AREA, rotation=False, pack_algo=GuillotineBafSlas)
for r in self._shapes():
packer.add_rect(*r)
for p in pages:
packer.add_bin(*p)
packer.pack()
COLS = ['page', 'y', 'x', 'h', 'w', 'roi_number']
self.coordinates = pd.DataFrame(packer.rect_list(), columns=COLS)
return self.coordinates
def page(self, page=0):
df = self.pack()
page_h, page_w = self.shape
page_image = np.zeros((page_h, page_w), dtype=np.uint8) + self.bg_color
sdf = df[df.page == page]
with self.bin:
<|code_end|>
. Use current file imports:
(from functools import lru_cache
from skimage.transform import resize
from rectpack import newPacker, SORT_AREA
from rectpack.guillotine import GuillotineBafSlas
from ifcb.data.adc import SCHEMA_VERSION_1
from ifcb.data.stitching import InfilledImages
import math
import numpy as np
import pandas as pd)
and context including class names, function names, or small code snippets from other files:
# Path: ifcb/data/adc.py
# class SCHEMA_VERSION_1(object):
# """
# IFCB revision 1 schema.
# """
# _name = 'v1'
# _cols = range(15)
# TRIGGER = 0
# PROCESSING_END_TIME = 1
# FLUORESCENCE_LOW = 2
# FLUORESCENCE_HIGH = 3
# SCATTERING_LOW = 4
# SCATTERING_HIGH = 5
# COMPARATOR_PULSE = 6
# TRIGGER_OPEN_TIME = 7
# FRAME_GRAB_TIME = 8
# ROI_X = 9
# ROI_Y = 10
# ROI_WIDTH = 11
# ROI_HEIGHT = 12
# START_BYTE = 13
# VALVE_STATUS = 14
#
# Path: ifcb/data/stitching.py
# class InfilledImages(BaseDictlike):
# """
# Wraps a bin's "images" property and provides access to infilled
# images. Images that are not infilled are passed through.
#
# Dict-like interface excludes from its keys target numbers that
# refer to the second ROI in a stitched pair.
# """
# def __init__(self, the_bin):
# self.bin = the_bin
# self.stitcher = Stitcher(the_bin)
# self.infiller = Infiller(the_bin)
# def keys(self):
# """
# Yield the target number of each ROI that is not the second
# ROI in a stitched pair.
# """
# for k in self.bin.images:
# if k not in self.stitcher.excluded_targets():
# yield k
# def has_key(self, target_number):
# """
# Exclude each target number from the bin's images that is
# second ROI from a stitched pair.
# """
# in_bin = target_number in self.bin
# excluded = target_number in self.stitcher.excluded_targets()
# return in_bin and not excluded
# def __getitem__(self, target_number):
# if target_number in self.stitcher:
# # stitch the images
# raw_stitch = self.stitcher[target_number]
# # construct infill
# infill = self.infiller[target_number]
# # sum the stitched and infill images
# infilled = raw_stitch.filled(0) + infill.filled(0)
# return infilled
# else:
# # this is not a stitched image
# return self.bin.images[target_number]
# @lru_cache()
# def _shapes(self):
# schema = self.bin.schema
# h_attr = '_{}'.format(schema.ROI_HEIGHT + 1)
# w_attr = '_{}'.format(schema.ROI_WIDTH + 1)
# shapes = {}
# for row in self.bin.images_adc.itertuples():
# target_number = row.Index
# h = getattr(row, h_attr)
# w = getattr(row, w_attr)
# shapes[target_number] = (h, w)
# for target_number in self.stitcher:
# shapes[target_number] = self.stitcher.shape(target_number)
# return shapes
# def shape(self, target_number):
# return self._shapes()[target_number]
# # convenience methods
# def raw_stitch(self, target_number):
# return self.stitcher[target_number]
. Output only the next line. | if self.bin.schema == SCHEMA_VERSION_1: |
Given snippet: <|code_start|>
class Mosaic(object):
def __init__(self, the_bin, shape=(600, 800), scale=0.33, bg_color=200, coordinates=None):
self.bin = the_bin
self.shape = shape
self.bg_color = bg_color
self.scale = scale
self.coordinates = coordinates
@lru_cache()
def _shapes(self):
hs, ws, ix = [], [], []
with self.bin:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import lru_cache
from skimage.transform import resize
from rectpack import newPacker, SORT_AREA
from rectpack.guillotine import GuillotineBafSlas
from ifcb.data.adc import SCHEMA_VERSION_1
from ifcb.data.stitching import InfilledImages
import math
import numpy as np
import pandas as pd
and context:
# Path: ifcb/data/adc.py
# class SCHEMA_VERSION_1(object):
# """
# IFCB revision 1 schema.
# """
# _name = 'v1'
# _cols = range(15)
# TRIGGER = 0
# PROCESSING_END_TIME = 1
# FLUORESCENCE_LOW = 2
# FLUORESCENCE_HIGH = 3
# SCATTERING_LOW = 4
# SCATTERING_HIGH = 5
# COMPARATOR_PULSE = 6
# TRIGGER_OPEN_TIME = 7
# FRAME_GRAB_TIME = 8
# ROI_X = 9
# ROI_Y = 10
# ROI_WIDTH = 11
# ROI_HEIGHT = 12
# START_BYTE = 13
# VALVE_STATUS = 14
#
# Path: ifcb/data/stitching.py
# class InfilledImages(BaseDictlike):
# """
# Wraps a bin's "images" property and provides access to infilled
# images. Images that are not infilled are passed through.
#
# Dict-like interface excludes from its keys target numbers that
# refer to the second ROI in a stitched pair.
# """
# def __init__(self, the_bin):
# self.bin = the_bin
# self.stitcher = Stitcher(the_bin)
# self.infiller = Infiller(the_bin)
# def keys(self):
# """
# Yield the target number of each ROI that is not the second
# ROI in a stitched pair.
# """
# for k in self.bin.images:
# if k not in self.stitcher.excluded_targets():
# yield k
# def has_key(self, target_number):
# """
# Exclude each target number from the bin's images that is
# second ROI from a stitched pair.
# """
# in_bin = target_number in self.bin
# excluded = target_number in self.stitcher.excluded_targets()
# return in_bin and not excluded
# def __getitem__(self, target_number):
# if target_number in self.stitcher:
# # stitch the images
# raw_stitch = self.stitcher[target_number]
# # construct infill
# infill = self.infiller[target_number]
# # sum the stitched and infill images
# infilled = raw_stitch.filled(0) + infill.filled(0)
# return infilled
# else:
# # this is not a stitched image
# return self.bin.images[target_number]
# @lru_cache()
# def _shapes(self):
# schema = self.bin.schema
# h_attr = '_{}'.format(schema.ROI_HEIGHT + 1)
# w_attr = '_{}'.format(schema.ROI_WIDTH + 1)
# shapes = {}
# for row in self.bin.images_adc.itertuples():
# target_number = row.Index
# h = getattr(row, h_attr)
# w = getattr(row, w_attr)
# shapes[target_number] = (h, w)
# for target_number in self.stitcher:
# shapes[target_number] = self.stitcher.shape(target_number)
# return shapes
# def shape(self, target_number):
# return self._shapes()[target_number]
# # convenience methods
# def raw_stitch(self, target_number):
# return self.stitcher[target_number]
which might include code, classes, or functions. Output only the next line. | ii = InfilledImages(self.bin) |
Given the code snippet: <|code_start|>
ALPHA = 'IFCBDTXYZ'
CHARS = '0123456789_' + ALPHA
class DestroyPid(object):
def __init__(self, pid):
self.pid = pid
def insert_character(self):
for d in CHARS:
for i in range(len(self.pid)+1):
yield self.pid[:i] + d + self.pid[i:]
def delete_character(self):
for i in range(len(self.pid)):
yield self.pid[:i] + self.pid[i+1:]
def mod_letter(self):
for i in range(len(self.pid)):
pc = self.pid[i]
if pc not in ALPHA:
continue
for c in ALPHA:
if c == pc: continue
yield self.pid[:i] + c + self.pid[i+1:]
# FIXME test cmp
class TestIdentifiers(unittest.TestCase):
def test_schema_version(self):
assert Pid(GOOD_V1).schema_version == 1, 'expected schema version 1'
assert Pid(GOOD_V2).schema_version == 2, 'expected schema version 2'
def test_unparse(self):
for pid in GOOD:
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import random
from ifcb.data import identifiers as ids
from ifcb.data.identifiers import Pid
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/identifiers.py
# def timestamp2regex(pattern):
# def c(pattern):
# def m(pattern, string):
# def col_or_scalar(o):
# def nones(n):
# def parse(pid):
# def unparse(parsed):
# def __init__(self, pid, parse=True):
# def isvalid(self):
# def copy(self):
# def __cmp__(self, other):
# def __eq__(self, other):
# def parsed(self):
# def __getattr__(self, name):
# def with_target(self, target_number, namespace=True):
# def timestamp(self):
# def __setattr__(self, name, value):
# def __repr__(self):
# def __str__(self):
# V1_PID_PATTERN = '(IFCB1_(yyyy_DDD_HHMMSS))(any)'
# V2_PID_PATTERN = '(D(yyyymmddTHHMMSS)_IFCB111)(any)'
# class Pid(object):
#
# Path: ifcb/data/identifiers.py
# class Pid(object):
# """
# Represents the permanent identifier of an IFCB bin.
# Provides attribute-based access to the relevant parsed
# fields of a PID. ``Pid``s sort by alpha.
# """
# def __init__(self, pid, parse=True):
# """
# Construct a Pid object from a string.
# Parsing is optional in case it needs
# to be deferred.
#
# :param pid: the pid
# :param parse: whether to parse
# """
# self.pid = pid
# self._parsed = None
# if parse:
# self.parsed
# def isvalid(self):
# """
# Check this PID for validity.
# """
# try:
# self.parsed # parse if not already
# return True
# except ValueError:
# pass
# return False
# def copy(self):
# new_pid = Pid(self.pid, parse=False)
# if self._parsed is not None:
# # avoid re-parsing
# new_pid._parsed = self._parsed.copy()
# return new_pid
# def __cmp__(self, other):
# try:
# if self.pid < other.pid:
# return -1
# elif self.pid > other.pid:
# return 1
# except AttributeError:
# if self.pid < other:
# return -1
# elif self.pid > other:
# return 1
# else:
# return 0
# def __eq__(self, other):
# try:
# return self.pid == other.pid
# except AttributeError:
# return self.pid == other
# @property
# def parsed(self):
# """
# The parsed PID
# """
# if self._parsed is None:
# # convert some properties to int
# p = parse(self.pid)
# for ip in ['target', 'instrument', 'schema_version']:
# if p[ip] is not None:
# p[ip] = int(p[ip])
# self._parsed = p
# return self._parsed
# def __getattr__(self, name):
# if name in ['pid','_parsed','parsed']:
# raise AttributeError
# try:
# return self.parsed[name]
# except KeyError:
# raise AttributeError
# def with_target(self, target_number, namespace=True):
# """
# Add a target number to the pid's bin_lid. Does not
# include product or extension. Optionally includes
# namespace prefix. This is more efficient than the
# following approach, which will preserve product
# and extension:
#
# >>> my_pid = Pid('IFCB1_2000_001_123456_blob')
# >>> new_pid = my_pid.copy()
# >>> new_pid.target = 927
# >>> new_pid
# <pid IFCB1_2000_001_123456_00927_blob>
#
# :param target_number: the target number
# :type target_number: int
# :param namespace: whether to include the namespace prefix
# :type namespace: bool
# :returns: the target ID (as a string)
# """
# ns = ''
# if namespace and self.namespace is not None:
# ns = self.namespace
# return ns + self.bin_lid + '_%05d' % target_number
# @property
# def timestamp(self):
# """
# The timestamp of the bin as a ``datetime``
# """
# return pd.to_datetime(self.parsed['timestamp'], format=self.parsed['timestamp_format'], utc=True)
# def __setattr__(self, name, value):
# if name == 'target':
# self.parsed # ensure parsing is complete
# self._parsed.update({ name: int(value) })
# self.pid = unparse(self._parsed)
# elif name in ['product', 'extension']:
# self.parsed # ensure parsing is complete
# self._parsed.update({ name: value })
# self.pid = unparse(self._parsed)
# else:
# super(Pid, self).__setattr__(name, value)
# def __repr__(self):
# return '<pid %s>' % self.pid
# def __str__(self):
# return self.pid
. Output only the next line. | assert ids.unparse(Pid(pid).parsed) == pid |
Given the code snippet: <|code_start|>GOOD_V1 = 'IFCB1_2000_001_123456'
GOOD_V2 = 'D20000101T123456_IFCB001'
GOOD = [GOOD_V1, GOOD_V2]
ALPHA = 'IFCBDTXYZ'
CHARS = '0123456789_' + ALPHA
class DestroyPid(object):
def __init__(self, pid):
self.pid = pid
def insert_character(self):
for d in CHARS:
for i in range(len(self.pid)+1):
yield self.pid[:i] + d + self.pid[i:]
def delete_character(self):
for i in range(len(self.pid)):
yield self.pid[:i] + self.pid[i+1:]
def mod_letter(self):
for i in range(len(self.pid)):
pc = self.pid[i]
if pc not in ALPHA:
continue
for c in ALPHA:
if c == pc: continue
yield self.pid[:i] + c + self.pid[i+1:]
# FIXME test cmp
class TestIdentifiers(unittest.TestCase):
def test_schema_version(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import random
from ifcb.data import identifiers as ids
from ifcb.data.identifiers import Pid
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/identifiers.py
# def timestamp2regex(pattern):
# def c(pattern):
# def m(pattern, string):
# def col_or_scalar(o):
# def nones(n):
# def parse(pid):
# def unparse(parsed):
# def __init__(self, pid, parse=True):
# def isvalid(self):
# def copy(self):
# def __cmp__(self, other):
# def __eq__(self, other):
# def parsed(self):
# def __getattr__(self, name):
# def with_target(self, target_number, namespace=True):
# def timestamp(self):
# def __setattr__(self, name, value):
# def __repr__(self):
# def __str__(self):
# V1_PID_PATTERN = '(IFCB1_(yyyy_DDD_HHMMSS))(any)'
# V2_PID_PATTERN = '(D(yyyymmddTHHMMSS)_IFCB111)(any)'
# class Pid(object):
#
# Path: ifcb/data/identifiers.py
# class Pid(object):
# """
# Represents the permanent identifier of an IFCB bin.
# Provides attribute-based access to the relevant parsed
# fields of a PID. ``Pid``s sort by alpha.
# """
# def __init__(self, pid, parse=True):
# """
# Construct a Pid object from a string.
# Parsing is optional in case it needs
# to be deferred.
#
# :param pid: the pid
# :param parse: whether to parse
# """
# self.pid = pid
# self._parsed = None
# if parse:
# self.parsed
# def isvalid(self):
# """
# Check this PID for validity.
# """
# try:
# self.parsed # parse if not already
# return True
# except ValueError:
# pass
# return False
# def copy(self):
# new_pid = Pid(self.pid, parse=False)
# if self._parsed is not None:
# # avoid re-parsing
# new_pid._parsed = self._parsed.copy()
# return new_pid
# def __cmp__(self, other):
# try:
# if self.pid < other.pid:
# return -1
# elif self.pid > other.pid:
# return 1
# except AttributeError:
# if self.pid < other:
# return -1
# elif self.pid > other:
# return 1
# else:
# return 0
# def __eq__(self, other):
# try:
# return self.pid == other.pid
# except AttributeError:
# return self.pid == other
# @property
# def parsed(self):
# """
# The parsed PID
# """
# if self._parsed is None:
# # convert some properties to int
# p = parse(self.pid)
# for ip in ['target', 'instrument', 'schema_version']:
# if p[ip] is not None:
# p[ip] = int(p[ip])
# self._parsed = p
# return self._parsed
# def __getattr__(self, name):
# if name in ['pid','_parsed','parsed']:
# raise AttributeError
# try:
# return self.parsed[name]
# except KeyError:
# raise AttributeError
# def with_target(self, target_number, namespace=True):
# """
# Add a target number to the pid's bin_lid. Does not
# include product or extension. Optionally includes
# namespace prefix. This is more efficient than the
# following approach, which will preserve product
# and extension:
#
# >>> my_pid = Pid('IFCB1_2000_001_123456_blob')
# >>> new_pid = my_pid.copy()
# >>> new_pid.target = 927
# >>> new_pid
# <pid IFCB1_2000_001_123456_00927_blob>
#
# :param target_number: the target number
# :type target_number: int
# :param namespace: whether to include the namespace prefix
# :type namespace: bool
# :returns: the target ID (as a string)
# """
# ns = ''
# if namespace and self.namespace is not None:
# ns = self.namespace
# return ns + self.bin_lid + '_%05d' % target_number
# @property
# def timestamp(self):
# """
# The timestamp of the bin as a ``datetime``
# """
# return pd.to_datetime(self.parsed['timestamp'], format=self.parsed['timestamp_format'], utc=True)
# def __setattr__(self, name, value):
# if name == 'target':
# self.parsed # ensure parsing is complete
# self._parsed.update({ name: int(value) })
# self.pid = unparse(self._parsed)
# elif name in ['product', 'extension']:
# self.parsed # ensure parsing is complete
# self._parsed.update({ name: value })
# self.pid = unparse(self._parsed)
# else:
# super(Pid, self).__setattr__(name, value)
# def __repr__(self):
# return '<pid %s>' % self.pid
# def __str__(self):
# return self.pid
. Output only the next line. | assert Pid(GOOD_V1).schema_version == 1, 'expected schema version 1' |
Here is a snippet: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_hdf(path)
with open_hdf(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
@withfile
def test_zip_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_zip(path)
with open_zip(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
@withfile
def test_mat_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_mat(path)
with open_mat(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
class TestOpenIdioms(unittest.TestCase):
def test_open_raw(self):
for a in list_test_bins():
adc_path = a.fileset.adc_path
<|code_end|>
. Write the next line using the current file imports:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context from other files:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
, which may include functions, classes, or code. Output only the next line. | b = open_raw(adc_path) |
Using the snippet: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_hdf(path)
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context (class names, function names, or code) available:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | with open_hdf(path) as in_bin: |
Given the code snippet: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_hdf(path)
with open_hdf(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
@withfile
def test_zip_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_zip(path)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context (functions, classes, or occasionally code) from other files:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | with open_zip(path) as in_bin: |
Given the following code snippet before the placeholder: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_hdf(path)
with open_hdf(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
@withfile
def test_zip_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_zip(path)
with open_zip(path) as in_bin:
assert_bin_equals(in_bin, out_bin)
@withfile
def test_mat_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_mat(path)
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context including class names, function names, and sometimes code from other files:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | with open_mat(path) as in_bin: |
Predict the next line for this snippet: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
<|code_end|>
with the help of current file imports:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context from other files:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
, which may contain function names, class names, or code. Output only the next line. | for out_bin in list_test_bins(): |
Given the following code snippet before the placeholder: <|code_start|>
class TestFormatConversionAPI(unittest.TestCase):
@withfile
def test_hdf_roundtrip(self, path):
for out_bin in list_test_bins():
with out_bin:
out_bin.to_hdf(path)
with open_hdf(path) as in_bin:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from ifcb.data.io import open_raw, open_hdf, open_zip, open_mat
from ifcb.tests.utils import withfile
from .fileset_info import list_test_bins
from .bins import assert_bin_equals
and context including class names, function names, and sometimes code from other files:
# Path: ifcb/data/io.py
# def open_raw(*files):
# """
# Open raw IFCB data.
#
# Takes one or more raw data filenames (only one is required)
# which should all be in the same directory and differ
# only by extension.
#
# Typically, just pass the pathname of the ADC file.
# """
# from .files import Fileset, FilesetBin
# basepath = os.path.commonprefix(files)
# basepath, _ = os.path.splitext(basepath)
# fs = Fileset(basepath)
# return FilesetBin(fs)
#
# def open_hdf(hdf_path, group=None):
# """
# Open IFCB data from an HDF file.
# """
# from .hdf import HdfBin
# return HdfBin(hdf_path, group=group)
#
# def open_zip(zip_path):
# from .zip import ZipBin
# return ZipBin(zip_path)
#
# def open_mat(mat_path):
# from .matlab import MatBin
# return MatBin(mat_path)
#
# Path: ifcb/tests/utils.py
# def withfile(method):
# """decorator that adds a named temporary file argument"""
# @wraps(method)
# def wrapper(*args, **kw):
# with test_file() as f:
# args = args + (f,)
# return method(*args, **kw)
# return wrapper
#
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# Path: ifcb/tests/data/bins.py
# def assert_bin_equals(in_bin, out_bin):
# # test keys
# assert set(in_bin) == set(out_bin)
# for k in in_bin.keys():
# assert k in in_bin, 'inconsistent dict behavior'
# assert k in out_bin, 'key membership does not match'
# assert 0 not in in_bin, 'zero-based index'
# assert 0 not in out_bin, 'zero-based index'
# # test ADC data
# for k in in_bin.keys():
# for a, b in zip(in_bin[k], out_bin[k]):
# assert np.isclose(a, b, equal_nan=True)
# # pid
# assert in_bin.pid == out_bin.pid, 'pid mismatch'
# assert in_bin.lid == out_bin.lid, 'lid mismatch'
# # timestamp
# assert in_bin.timestamp == out_bin.timestamp, 'timestamp mismatch'
# # schema
# assert in_bin.schema == out_bin.schema, 'schema mismatch'
# # headers
# assert set(in_bin.headers) == set(out_bin.headers), 'header keys mismatch'
# for k in in_bin.headers.keys():
# # headers should all have same names and values
# assert in_bin.headers[k] == out_bin.headers[k], 'header values mismatch'
# # images
# assert set(in_bin.images) == set(out_bin.images), 'image target numbers mismatch'
# for k in in_bin.images:
# assert np.all(in_bin.images[k] == out_bin.images[k]), 'image data mismatch'
. Output only the next line. | assert_bin_equals(in_bin, out_bin) |
Continue the code snippet: <|code_start|>
TARGET_METRICS = {
'IFCB5_2012_028_081515': {
'ml_analyzed': 0.0033914708,
'run_time': 1.251953,
'look_time': 0.813953,
'inhibit_time': 0.438,
'trigger_rate': 4.792512178971575,
TEMPERATURE: 11.4799732421875,
HUMIDITY: 32.167437512207,
},
'D20130526T095207_IFCB013': {
'ml_analyzed': 5.0808411708,
'run_time': 1231.024861,
'look_time': 1219.401881,
'inhibit_time': 11.62298,
'trigger_rate': 0.09585509093954846,
TEMPERATURE: 35.270397,
HUMIDITY: 2.48685,
}
}
class TestBinMetrics(unittest.TestCase):
def test_ml_analyzed(self):
<|code_end|>
. Use current file imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins, get_fileset_bin
from ifcb.data.hdr import TEMPERATURE, HUMIDITY
from .test_ml_analyzed import TARGET_ML_ANALYZED
and context (classes, functions, or code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/tests/metrics/test_ml_analyzed.py
# TARGET_ML_ANALYZED = {
# 'IFCB5_2012_028_081515': (0.003391470833333334, 0.8139530000000001, 1.251953),
# 'D20130526T095207_IFCB013': (5.080841170833334, 1219.401881, 1231.024861)
# }
. Output only the next line. | for met in list_test_bins(): |
Continue the code snippet: <|code_start|>
TARGET_METRICS = {
'IFCB5_2012_028_081515': {
'ml_analyzed': 0.0033914708,
'run_time': 1.251953,
'look_time': 0.813953,
'inhibit_time': 0.438,
'trigger_rate': 4.792512178971575,
<|code_end|>
. Use current file imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins, get_fileset_bin
from ifcb.data.hdr import TEMPERATURE, HUMIDITY
from .test_ml_analyzed import TARGET_ML_ANALYZED
and context (classes, functions, or code) from other files:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/tests/metrics/test_ml_analyzed.py
# TARGET_ML_ANALYZED = {
# 'IFCB5_2012_028_081515': (0.003391470833333334, 0.8139530000000001, 1.251953),
# 'D20130526T095207_IFCB013': (5.080841170833334, 1219.401881, 1231.024861)
# }
. Output only the next line. | TEMPERATURE: 11.4799732421875, |
Given snippet: <|code_start|>
TARGET_METRICS = {
'IFCB5_2012_028_081515': {
'ml_analyzed': 0.0033914708,
'run_time': 1.251953,
'look_time': 0.813953,
'inhibit_time': 0.438,
'trigger_rate': 4.792512178971575,
TEMPERATURE: 11.4799732421875,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from ifcb.tests.data.fileset_info import list_test_bins, get_fileset_bin
from ifcb.data.hdr import TEMPERATURE, HUMIDITY
from .test_ml_analyzed import TARGET_ML_ANALYZED
and context:
# Path: ifcb/tests/data/fileset_info.py
# def list_test_bins():
# return list(_dd())
#
# def get_fileset_bin(lid):
# return _dd()[lid]
#
# Path: ifcb/data/hdr.py
# TEMPERATURE = 'temperature'
#
# HUMIDITY = 'humidity'
#
# Path: ifcb/tests/metrics/test_ml_analyzed.py
# TARGET_ML_ANALYZED = {
# 'IFCB5_2012_028_081515': (0.003391470833333334, 0.8139530000000001, 1.251953),
# 'D20130526T095207_IFCB013': (5.080841170833334, 1219.401881, 1231.024861)
# }
which might include code, classes, or functions. Output only the next line. | HUMIDITY: 32.167437512207, |
Continue the code snippet: <|code_start|>"""
Support for stitching IFCB revision 1 images.
Note that this does not apply to data from commercial
IFCB instruments.
"""
### Stitching
<|code_end|>
. Use current file imports:
from functools import lru_cache
from scipy import ndimage as ndi
from .utils import BaseDictlike
import numpy as np
and context (classes, functions, or code) from other files:
# Path: ifcb/data/utils.py
# class BaseDictlike(object):
# """
# Provides as complete a readonly dict interface as possible,
# based on anything that implements ``keys`` and ``__getitem__``.
# when overriding, override ``has_key`` rather than ```__contains__``.
#
# Override any method if a more efficient implementation
# is available.
# """
# def keys(self):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
# """
# raise NotImplementedError
# def __getitem__(self, k):
# """
# Default implementation raises ``NotImplementedError``.
# This must be overridden for correct behavior.
#
# :param k: the key
# :type k: hashable
# """
# raise NotImplementedError
# def __iter__(self):
# yield from self.keys()
# def has_key(self, k):
# """
# Iterates over keys and returns first key for
# which equality test passes. This method is
# called by the ``__contains__`` special method.
#
# :param k: the key to test
# :type k: hashable
# """
# for ek in self.keys():
# if ek == k:
# return True
# return False
# def __contains__(self, k):
# return self.has_key(k)
# def items(self):
# """
# Yields item pairs, based on calling keys
# and then accessing each item.
# """
# for k in self.keys():
# yield k, self[k]
# def values(self):
# """
# Yields all values. Calls ``items``.
# """
# for k, v in self.items():
# yield v
# def __len__(self):
# n = 0
# for k in self.keys():
# n += 1
# return n
. Output only the next line. | class Stitcher(BaseDictlike): |
Given snippet: <|code_start|> type = request.GET.get('type', None)
filter = request.GET.get('filter', None)
data["page_size"] = settings.DME_PAGE_SIZE
try:
if type:
and_query = Q(type=type)
except Exception as e:
pass
if filter:
try:
filter_list = filter.split(" ")
or_query = Q(name__icontains=filter_list[0]) | Q(description__icontains=filter_list[0]) | Q(credit__icontains=filter_list[0])
for term in filter_list[1:]:
or_query.add((Q(name__icontains=term) | Q(description__icontains=term) | Q(credit__icontains=term)), or_query.connector)
except Exception as e:
pass
if and_query:
query = and_query
if or_query:
if query:
query.add(or_query,Q.AND)
else:
query = or_query
if query:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import math, json
from django.http import HttpResponse
from django.views.generic import View
from media_explorer.models import Element, Gallery, GalleryElement
from django.conf import settings
from django.db.models import Q
and context:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class Gallery(models.Model):
# """
# The Gallery model will contain info about our media gallery
# """
#
# name = models.CharField(max_length=100,blank=True,null=True)
# short_code = models.CharField(max_length=100,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# elements = models.ManyToManyField(Element, through="GalleryElement")
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Galleries"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# class GalleryElement(models.Model):
# """
# The Gallery Element model will contain list of elements
# """
#
# gallery = models.ForeignKey(Gallery)
# element = models.ForeignKey(Element)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# sort_by = models.IntegerField(blank=True,null=True,default='0')
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name = "Gallery element"
# verbose_name_plural = "Gallery elements"
# ordering = ["sort_by"]
which might include code, classes, or functions. Output only the next line. | data["total_entries"] = Element.objects.filter(query).count() |
Using the snippet: <|code_start|> def get(self, request, *args, **kwargs):
#NOTE: Code below must match GalleryList.get_queryset
#TODO - move to helper so you don't maintain same code twice
data = {}
query = None
and_query = None
or_query = None
filter = request.GET.get('filter', None)
data["page_size"] = settings.DME_PAGE_SIZE
if filter:
try:
filter_list = filter.split(" ")
or_query = Q(name__icontains=filter_list[0]) | Q(description__icontains=filter_list[0])
for term in filter_list[1:]:
or_query.add((Q(name__icontains=term) | Q(description__icontains=term)), or_query.connector)
except Exception as e:
pass
if and_query:
query = and_query
if or_query:
if query:
query.add(or_query,Q.AND)
else:
query = or_query
if query:
<|code_end|>
, determine the next line of code. You have imports:
import math, json
from django.http import HttpResponse
from django.views.generic import View
from media_explorer.models import Element, Gallery, GalleryElement
from django.conf import settings
from django.db.models import Q
and context (class names, function names, or code) available:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class Gallery(models.Model):
# """
# The Gallery model will contain info about our media gallery
# """
#
# name = models.CharField(max_length=100,blank=True,null=True)
# short_code = models.CharField(max_length=100,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# elements = models.ManyToManyField(Element, through="GalleryElement")
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Galleries"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# class GalleryElement(models.Model):
# """
# The Gallery Element model will contain list of elements
# """
#
# gallery = models.ForeignKey(Gallery)
# element = models.ForeignKey(Element)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# sort_by = models.IntegerField(blank=True,null=True,default='0')
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name = "Gallery element"
# verbose_name_plural = "Gallery elements"
# ordering = ["sort_by"]
. Output only the next line. | data["total_entries"] = Gallery.objects.filter(query).count() |
Continue the code snippet: <|code_start|>from __future__ import unicode_literals
#from django.db import connection
class Example(models.Model):
"""
Example model that uses MediaField and RichTextField
"""
name = models.CharField(null=True,blank=True)
<|code_end|>
. Use current file imports:
import os, datetime
from media_explorer.fields import MediaField, RichTextField
from django.db import models
and context (classes, functions, or code) from other files:
# Path: media_explorer/fields.py
# class MediaField(models.TextField):
# """The Django MediaField."""
#
# description = _("A Media Explorer custom model field")
#
# def __init__(self, id=None, type=None, \
# credit=None, caption=None, *args, **kwargs):
# self.id = id
# self.type = type
# self.caption = caption
# self.credit = credit
#
# kwargs['null'] = True
# kwargs['blank'] = True
#
# super(MediaField, self).__init__(*args, **kwargs)
#
# def deconstruct(self):
# name, path, args, kwargs = super(MediaField, self).deconstruct()
# del kwargs["null"]
# del kwargs["blank"]
# return name, path, args, kwargs
#
# def db_type(self, connection):
# return "longtext"
#
# def from_db_value(self, value, expression, connection, context):
# if value is None:
# return value
# return parse_media(value)
#
# def do_validation(self, media):
# if self.type and media.type and self.type != media.type:
# raise ValidationError("Invalid media type selected for this MediaField instance. It expected a '%s' but got a '%s' instead." % (self.type, media.type))
#
# #Override id/credit/caption
# if self.id : media.id = self.id
# if self.type: media.type = self.type
# if self.caption : media.caption = self.caption
# if self.credit: media.credit = self.credit
#
# #Validate that the image/video is in the system
# if media.type in ["image","video"] and \
# not Element.objects.filter(id=media.id,type=media.type).exists():
# raise ValidationError("Invalid %s selected. The %s was not found." % (media.type, media.type))
#
# #Validate that the gallery is in the system
# if media.type == "gallery" and \
# not Gallery.objects.filter(id=media.id).exists():
# raise ValidationError("Invalid %s selected. The %s was not found." % (media.type, media.type))
#
# return media
#
# def to_python(self, value):
# if isinstance(value, Media):
# return value
#
# if value is None:
# return value
#
# return self.do_validation(parse_media(value))
#
# def get_prep_value(self, value):
# value_dict = {}
#
# try:
# value_dict["id"] = value.id
# value_dict["type"] = value.type
# value_dict["caption"] = value.caption
# value_dict["credit"] = value.credit
# except:
# pass
#
# if type(value) is Element:
# value_dict["id"] = value.id
# value_dict["type"] = value.type
# value_dict["caption"] = None
# value_dict["credit"] = None
# if value.description:
# value_dict["caption"] = value.description
# if value.credit:
# value_dict["credit"] = value.credit
#
# if value_dict:
# self.do_validation(parse_media(value_dict))
# return str(json.dumps(value_dict))
#
# if value: return str(value)
# return value
#
# def formfield(self, **kwargs):
# defaults = {}
# defaults["form_class"] = MediaFormField
# defaults.update(kwargs)
# return super(MediaField, self).formfield(**defaults)
#
# class RichTextField(models.TextField):
# """The Django RichTextField."""
#
# description = _("A RichText Explorer custom model field")
#
# def __init__(self, *args, **kwargs):
# kwargs['null'] = True
# kwargs['blank'] = True
# super(RichTextField, self).__init__(*args, **kwargs)
#
# def deconstruct(self):
# name, path, args, kwargs = super(RichTextField, self).deconstruct()
# del kwargs["null"]
# del kwargs["blank"]
# return name, path, args, kwargs
#
# def db_type(self, connection):
# return "longtext"
#
# def from_db_value(self, value, expression, connection, context):
# if value is None:
# return value
# return parse_richtext(value)
#
# def do_validation(self, richtext):
# return richtext
#
# def to_python(self, value):
# if isinstance(value, RichText):
# return value
#
# if value is None:
# return value
#
# return self.do_validation(parse_richtext(value))
#
#
# def get_prep_value(self, value):
# if value: return str(value)
# return value
#
# def formfield(self, **kwargs):
# defaults = {}
# defaults["form_class"] = RichTextFormField
# defaults.update(kwargs)
# return super(RichTextField, self).formfield(**defaults)
. Output only the next line. | lead_media = MediaField() |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
#from django.db import connection
class Example(models.Model):
"""
Example model that uses MediaField and RichTextField
"""
name = models.CharField(null=True,blank=True)
lead_media = MediaField()
image = MediaField(type="image")
video = MediaField(type="video")
<|code_end|>
, predict the immediate next line with the help of imports:
import os, datetime
from media_explorer.fields import MediaField, RichTextField
from django.db import models
and context (classes, functions, sometimes code) from other files:
# Path: media_explorer/fields.py
# class MediaField(models.TextField):
# """The Django MediaField."""
#
# description = _("A Media Explorer custom model field")
#
# def __init__(self, id=None, type=None, \
# credit=None, caption=None, *args, **kwargs):
# self.id = id
# self.type = type
# self.caption = caption
# self.credit = credit
#
# kwargs['null'] = True
# kwargs['blank'] = True
#
# super(MediaField, self).__init__(*args, **kwargs)
#
# def deconstruct(self):
# name, path, args, kwargs = super(MediaField, self).deconstruct()
# del kwargs["null"]
# del kwargs["blank"]
# return name, path, args, kwargs
#
# def db_type(self, connection):
# return "longtext"
#
# def from_db_value(self, value, expression, connection, context):
# if value is None:
# return value
# return parse_media(value)
#
# def do_validation(self, media):
# if self.type and media.type and self.type != media.type:
# raise ValidationError("Invalid media type selected for this MediaField instance. It expected a '%s' but got a '%s' instead." % (self.type, media.type))
#
# #Override id/credit/caption
# if self.id : media.id = self.id
# if self.type: media.type = self.type
# if self.caption : media.caption = self.caption
# if self.credit: media.credit = self.credit
#
# #Validate that the image/video is in the system
# if media.type in ["image","video"] and \
# not Element.objects.filter(id=media.id,type=media.type).exists():
# raise ValidationError("Invalid %s selected. The %s was not found." % (media.type, media.type))
#
# #Validate that the gallery is in the system
# if media.type == "gallery" and \
# not Gallery.objects.filter(id=media.id).exists():
# raise ValidationError("Invalid %s selected. The %s was not found." % (media.type, media.type))
#
# return media
#
# def to_python(self, value):
# if isinstance(value, Media):
# return value
#
# if value is None:
# return value
#
# return self.do_validation(parse_media(value))
#
# def get_prep_value(self, value):
# value_dict = {}
#
# try:
# value_dict["id"] = value.id
# value_dict["type"] = value.type
# value_dict["caption"] = value.caption
# value_dict["credit"] = value.credit
# except:
# pass
#
# if type(value) is Element:
# value_dict["id"] = value.id
# value_dict["type"] = value.type
# value_dict["caption"] = None
# value_dict["credit"] = None
# if value.description:
# value_dict["caption"] = value.description
# if value.credit:
# value_dict["credit"] = value.credit
#
# if value_dict:
# self.do_validation(parse_media(value_dict))
# return str(json.dumps(value_dict))
#
# if value: return str(value)
# return value
#
# def formfield(self, **kwargs):
# defaults = {}
# defaults["form_class"] = MediaFormField
# defaults.update(kwargs)
# return super(MediaField, self).formfield(**defaults)
#
# class RichTextField(models.TextField):
# """The Django RichTextField."""
#
# description = _("A RichText Explorer custom model field")
#
# def __init__(self, *args, **kwargs):
# kwargs['null'] = True
# kwargs['blank'] = True
# super(RichTextField, self).__init__(*args, **kwargs)
#
# def deconstruct(self):
# name, path, args, kwargs = super(RichTextField, self).deconstruct()
# del kwargs["null"]
# del kwargs["blank"]
# return name, path, args, kwargs
#
# def db_type(self, connection):
# return "longtext"
#
# def from_db_value(self, value, expression, connection, context):
# if value is None:
# return value
# return parse_richtext(value)
#
# def do_validation(self, richtext):
# return richtext
#
# def to_python(self, value):
# if isinstance(value, RichText):
# return value
#
# if value is None:
# return value
#
# return self.do_validation(parse_richtext(value))
#
#
# def get_prep_value(self, value):
# if value: return str(value)
# return value
#
# def formfield(self, **kwargs):
# defaults = {}
# defaults["form_class"] = RichTextFormField
# defaults.update(kwargs)
# return super(RichTextField, self).formfield(**defaults)
. Output only the next line. | body = RichTextField() |
Given the code snippet: <|code_start|> Condition: Post has no image file or video url
Result: Fail with 400 error since no image or video_url is provided
"""
url = reverse("api-media-elements")
c = Client()
c.login(username="admin",password="password")
response = c.post(url, {},HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 400)
@override_settings(DME_RESIZE=False)
def test_image_upload_with_no_resize(self):
"""
Test image upload with no resize
Condition: User is logged in and authorized
Condition: Post has an image
Condition: Do not resize image
Result: Success
Result: Element count should equal 1
Result: ResizedImage count should equal 0
"""
url = reverse("api-media-elements")
c = Client()
c.login(username="admin",password="password")
test_path = os.path.dirname(os.path.abspath(__file__))
with open(test_path + '/Oxfam-Cambodia.jpg') as fp:
response = c.post(url, {'name':'test_image_upload_with_no_resize','image':fp},HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 200)
#Check the DB to make sure element is present
<|code_end|>
, generate the next line using the imports in this file:
import os
from django.test import TestCase, Client, override_settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from media_explorer.models import Element, ResizedImage
and context (functions, classes, or occasionally code) from other files:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class ResizedImage(models.Model):
# """
# The ResizedImage is a resized image version of Element.image
# """
#
# image = models.ForeignKey(Element)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# size = models.CharField(max_length=25,blank=True,null=True)
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name = "Resized image"
# verbose_name_plural = "Resized images"
#
# def html_img(self):
# try:
# return "<a target='_blank' href='" + self.image_url + "'><img style='width:100px' src='" + self.image_url + "'></a>"
# except:
# pass
#
# html_img.allow_tags = True
. Output only the next line. | count1 = Element.objects.filter(type="image",name="test_image_upload_with_no_resize",image_url__icontains="Oxfam-Cambodia").count() |
Next line prediction: <|code_start|> c = Client()
c.login(username="admin",password="password")
response = c.post(url, {},HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 400)
@override_settings(DME_RESIZE=False)
def test_image_upload_with_no_resize(self):
"""
Test image upload with no resize
Condition: User is logged in and authorized
Condition: Post has an image
Condition: Do not resize image
Result: Success
Result: Element count should equal 1
Result: ResizedImage count should equal 0
"""
url = reverse("api-media-elements")
c = Client()
c.login(username="admin",password="password")
test_path = os.path.dirname(os.path.abspath(__file__))
with open(test_path + '/Oxfam-Cambodia.jpg') as fp:
response = c.post(url, {'name':'test_image_upload_with_no_resize','image':fp},HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 200)
#Check the DB to make sure element is present
count1 = Element.objects.filter(type="image",name="test_image_upload_with_no_resize",image_url__icontains="Oxfam-Cambodia").count()
self.assertEqual(count1, 1)
#Check to make sure image was NOT resized
<|code_end|>
. Use current file imports:
(import os
from django.test import TestCase, Client, override_settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from media_explorer.models import Element, ResizedImage)
and context including class names, function names, or small code snippets from other files:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class ResizedImage(models.Model):
# """
# The ResizedImage is a resized image version of Element.image
# """
#
# image = models.ForeignKey(Element)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# size = models.CharField(max_length=25,blank=True,null=True)
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name = "Resized image"
# verbose_name_plural = "Resized images"
#
# def html_img(self):
# try:
# return "<a target='_blank' href='" + self.image_url + "'><img style='width:100px' src='" + self.image_url + "'></a>"
# except:
# pass
#
# html_img.allow_tags = True
. Output only the next line. | count2 = ResizedImage.objects.filter(image__type="image",image__name="test_image_upload_with_no_resize",image__image_url__icontains="Oxfam-Cambodia").count() |
Based on the snippet: <|code_start|>
class MediaFormField(forms.Field):
def __init__(self, name=None, required=False, widget=MediaWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
super(MediaFormField, self).__init__(required=required, widget=MediaWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
def clean(self, value):
if value:
try:
data = json.loads(value)
except Exception as e:
raise ValidationError("JSON parsing error: " + str(e))
return value
return None
class RichTextFormField(forms.Field):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from django.core.exceptions import ValidationError
from django import forms
from media_explorer.widgets import MediaWidget, RichTextWidget
and context (classes, functions, sometimes code) from other files:
# Path: media_explorer/widgets.py
# class MediaWidget(forms.Widget):
# template_name = 'admin/media_field.html'
#
# class Media:
# if getattr(settings,"DME_INCLUDE_JQUERY",True):
# js1 = (
# 'js/vendor/jquery/jquery-1.11.2.min.js',
# )
# else:
# js1 = ()
#
# js2 = (
# 'js/media_explorer/media_explorer.js',
# 'js/media_field_admin.js',
# )
#
# js = js1 + js2
#
# css = {
# 'all': (
# 'css/hide_media_fields.css',
# )
# }
#
# def render(self, name, value, attrs=None):
# context = {"name":name,"value":value}
# return mark_safe(render_to_string(self.template_name, context))
#
# class RichTextWidget(CKEditorWidget):
#
# class Media:
# if getattr(settings,"DME_INCLUDE_JQUERY",True):
# js1 = (
# 'js/vendor/jquery/jquery-1.11.2.min.js',
# )
# else:
# js1 = ()
#
# js2 = (
# 'js/vendor/jQuery-Impromptu-6.1.0/jquery-impromptu.min.js',
# 'js/media_explorer/media_explorer.js',
# 'ckeditor/ckeditor/plugins/media_explorer/callback.js',
# )
#
# js = js1 + js2
#
# css = {
# 'all': (
# 'js/vendor/jQuery-Impromptu-6.1.0/jquery-impromptu.min.css',
# )
# }
. Output only the next line. | def __init__(self, name=None, required=False, widget=RichTextWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs): |
Based on the snippet: <|code_start|>
def parse_media(string_or_obj):
"""Takes a JSON string, converts it into a Media object."""
data = {}
kwargs = {}
kwargs["id"] = None
kwargs["type"] = None
kwargs["caption"] = None
kwargs["credit"] = None
try:
if type(string_or_obj) is dict:
data = string_or_obj
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from media_explorer.models import Element, Gallery
from media_explorer.forms import MediaFormField, RichTextFormField
from django.db.models import signals, FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
and context (classes, functions, sometimes code) from other files:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class Gallery(models.Model):
# """
# The Gallery model will contain info about our media gallery
# """
#
# name = models.CharField(max_length=100,blank=True,null=True)
# short_code = models.CharField(max_length=100,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# elements = models.ManyToManyField(Element, through="GalleryElement")
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Galleries"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# Path: media_explorer/forms.py
# class MediaFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=MediaWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(MediaFormField, self).__init__(required=required, widget=MediaWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# try:
# data = json.loads(value)
# except Exception as e:
# raise ValidationError("JSON parsing error: " + str(e))
# return value
# return None
#
# class RichTextFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=RichTextWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(RichTextFormField, self).__init__(required=required, widget=RichTextWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# return value
# return None
. Output only the next line. | elif type(string_or_obj) is Element: |
Given the following code snippet before the placeholder: <|code_start|>
def parse_media(string_or_obj):
"""Takes a JSON string, converts it into a Media object."""
data = {}
kwargs = {}
kwargs["id"] = None
kwargs["type"] = None
kwargs["caption"] = None
kwargs["credit"] = None
try:
if type(string_or_obj) is dict:
data = string_or_obj
elif type(string_or_obj) is Element:
data["id"] = string_or_obj.id
data["type"] = string_or_obj.type
data["caption"] = string_or_obj.description
data["credit"] = string_or_obj.credit
<|code_end|>
, predict the next line using imports from the current file:
import json
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from media_explorer.models import Element, Gallery
from media_explorer.forms import MediaFormField, RichTextFormField
from django.db.models import signals, FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
and context including class names, function names, and sometimes code from other files:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class Gallery(models.Model):
# """
# The Gallery model will contain info about our media gallery
# """
#
# name = models.CharField(max_length=100,blank=True,null=True)
# short_code = models.CharField(max_length=100,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# elements = models.ManyToManyField(Element, through="GalleryElement")
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Galleries"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# Path: media_explorer/forms.py
# class MediaFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=MediaWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(MediaFormField, self).__init__(required=required, widget=MediaWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# try:
# data = json.loads(value)
# except Exception as e:
# raise ValidationError("JSON parsing error: " + str(e))
# return value
# return None
#
# class RichTextFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=RichTextWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(RichTextFormField, self).__init__(required=required, widget=RichTextWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# return value
# return None
. Output only the next line. | elif type(string_or_obj) is Gallery: |
Given the following code snippet before the placeholder: <|code_start|> del kwargs["blank"]
return name, path, args, kwargs
def db_type(self, connection):
return "longtext"
def from_db_value(self, value, expression, connection, context):
if value is None:
return value
return parse_richtext(value)
def do_validation(self, richtext):
return richtext
def to_python(self, value):
if isinstance(value, RichText):
return value
if value is None:
return value
return self.do_validation(parse_richtext(value))
def get_prep_value(self, value):
if value: return str(value)
return value
def formfield(self, **kwargs):
defaults = {}
<|code_end|>
, predict the next line using imports from the current file:
import json
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from media_explorer.models import Element, Gallery
from media_explorer.forms import MediaFormField, RichTextFormField
from django.db.models import signals, FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
and context including class names, function names, and sometimes code from other files:
# Path: media_explorer/models.py
# class Element(models.Model):
# """
# The Element model will contain images and videos
# NOTE: if type=video you can still have a thumbnail_image
# """
#
# TYPE_CHOICES = (('image','Image'),('video','Video'))
#
# name = models.CharField(max_length=150,blank=True,null=True)
# file_name = models.CharField(max_length=150,blank=True,null=True)
# original_file_name = models.CharField(max_length=150,blank=True,null=True)
# credit = models.CharField(max_length=255,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# image_url = models.CharField(max_length=255,blank=True,null=True)
# image_width = models.IntegerField(blank=True,null=True,default='0')
# image_height = models.IntegerField(blank=True,null=True,default='0')
# video_url = models.CharField(max_length=255,blank=True,null=True)
# video_embed = models.TextField(blank=True,null=True)
# manual_embed_code = models.BooleanField(_("Manually enter video embed code"), default=False)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# thumbnail_image_width = models.IntegerField(blank=True,null=True,default='0')
# thumbnail_image_height = models.IntegerField(blank=True,null=True,default='0')
# type = models.CharField(_("Type"), max_length=10, default="image",choices=TYPE_CHOICES)
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Elements"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# def save(self, *args, **kwargs):
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
# super(Element, self).save(*args, **kwargs)
#
# def save(self, *args, **kwargs):
#
# if not self.name:
# if self.type == "image":
# self.name = self.file_name
# elif self.type == "video":
# self.name = self.video_url
#
# super(Element, self).save(*args, **kwargs)
#
# save_again = False
#
# #Init thumbnail_image
# if self.type == "image" \
# and self.image \
# and not self.thumbnail_image:
# self.image_url = self.image.url
# self.thumbnail_image = self.image
# self.thumbnail_image_url = self.image.url
# save_again = True
#
# if save_again:
# super(Element, self).save(*args, **kwargs)
#
# class Gallery(models.Model):
# """
# The Gallery model will contain info about our media gallery
# """
#
# name = models.CharField(max_length=100,blank=True,null=True)
# short_code = models.CharField(max_length=100,blank=True,null=True)
# description = models.TextField(blank=True,null=True)
# thumbnail_image = models.ImageField(blank=True,null=True,max_length=255,upload_to="images/")
# thumbnail_image_url = models.CharField(max_length=255,blank=True,null=True)
# elements = models.ManyToManyField(Element, through="GalleryElement")
# created_at = models.DateTimeField(blank=True,null=True,auto_now_add=True)
# updated_at = models.DateTimeField(blank=True,null=True,auto_now=True)
#
# class Meta:
# verbose_name_plural = "Galleries"
#
# def __unicode__(self):
# return u"%s" % (self.name)
#
# Path: media_explorer/forms.py
# class MediaFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=MediaWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(MediaFormField, self).__init__(required=required, widget=MediaWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# try:
# data = json.loads(value)
# except Exception as e:
# raise ValidationError("JSON parsing error: " + str(e))
# return value
# return None
#
# class RichTextFormField(forms.Field):
# def __init__(self, name=None, required=False, widget=RichTextWidget, label=None, initial=None, help_text="", max_length=None, *args, **kwargs):
# super(RichTextFormField, self).__init__(required=required, widget=RichTextWidget, label=label, initial=initial, help_text=help_text, *args, **kwargs)
#
# def clean(self, value):
# if value:
# return value
# return None
. Output only the next line. | defaults["form_class"] = RichTextFormField |
Predict the next line after this snippet: <|code_start|>#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'app',
'panel'
]
def panel(title, content, link=None, level=None):
return {
'title': title,
'content': content,
'link': link,
'level': level
}
<|code_end|>
using the current file's imports:
from yubiadmin.util.app import App, render
from yubiadmin.apps import apps
and any relevant context from other files:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
. Output only the next line. | class DashboardApp(App): |
Using the snippet: <|code_start|># BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'app',
'panel'
]
def panel(title, content, link=None, level=None):
return {
'title': title,
'content': content,
'link': link,
'level': level
}
class DashboardApp(App):
hidden = True
def __call__(self, request):
panels = [panel for app in apps if not getattr(app, 'disabled', False)
and hasattr(app, 'dash_panels') for panel in app.dash_panels]
request.environ['yubiadmin.response'].extend('content',
<|code_end|>
, determine the next line of code. You have imports:
from yubiadmin.util.app import App, render
from yubiadmin.apps import apps
and context (class names, function names, or code) available:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
. Output only the next line. | render('dashboard', |
Next line prediction: <|code_start|> return value
def __init__(self, filename, legend=None, description=None, lang=None,
*args, **kwargs):
self.config = FileConfig(filename, [('content', self.Handler())])
self.legend = legend
self.description = description
if lang:
self.attrs['content']['ace-mode'] = lang
super(FileForm, self).__init__(*args, **kwargs)
self.content.label.text = 'File: %s' % filename
class DBConfigForm(ConfigForm):
"""
Complete form for editing a dbconfig-common generated for PHP.
"""
legend = 'Database'
description = 'Settings for connecting to the database.'
dbtype = TextField('Database type')
dbserver = TextField('Host')
dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
dbname = TextField('Database name')
dbuser = TextField('Username')
dbpass = PasswordField('Password',
widget=PasswordInput(hide_value=False))
def db_handler(self, varname, default):
pattern = r'\$%s=\'(.*)\';' % varname
writer = lambda x: '$%s=\'%s\';' % (varname, x)
<|code_end|>
. Use current file imports:
(from wtforms import Form
from wtforms.fields import (
TextField, IntegerField, PasswordField, TextAreaField, HiddenField, Field)
from wtforms.widgets import PasswordInput, TextArea
from wtforms.validators import Optional, NumberRange
from yubiadmin.util.config import RegexHandler, FileConfig, php_inserter)
and context including class names, function names, or small code snippets from other files:
# Path: yubiadmin/util/config.py
# class RegexHandler(object):
# def __init__(self, pattern, writer, reader=lambda x: x.group(1),
# inserter=lambda x, y: '%s\n%s' % (x, y),
# default=None):
# self.pattern = re.compile(pattern)
# self.writer = writer
# self.reader = reader
# self.inserter = inserter
# self.default = default
#
# def read(self, content):
# match = self.pattern.search(content)
# if match:
# return self.reader(match)
# return self.default
#
# def write(self, content, value):
# if value is None:
# value = ''
# if self.pattern.search(content):
# new_content = self.pattern.sub(self.writer(value), content, 1)
# if self.read(content) == self.read(new_content):
# #Value remains unchanged, don't re-write it.
# return content
# else:
# return new_content
# else:
# return self.inserter(content, self.writer(value))
#
# class FileConfig(MutableMapping):
# """
# Maps key-value pairs to a backing config file.
# You can manually edit the file by modifying self.content.
# """
# def __init__(self, filename, params=[]):
# self.filename = filename
# self.params = OrderedDict()
# for param in params:
# self.add_param(*param)
#
# def read(self):
# try:
# with open(self.filename, 'r') as file:
# self.content = unicode(file.read())
# except IOError as e:
# log.error(e)
# self.content = u''
# #Initialize all params from default values.
# for key in self.params:
# self[key] = self[key]
#
# def commit(self):
# if not os.path.isfile(self.filename):
# dir = os.path.dirname(self.filename)
# try:
# os.makedirs(dir)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise e
# with open(self.filename, 'w+') as file:
# #Fix all linebreaks
# file.write(os.linesep.join(self.content.splitlines()))
#
# def add_param(self, key, handler):
# self.params[key] = handler
#
# def __iter__(self):
# return self.params.__iter__()
#
# def __len__(self):
# return len(self.params)
#
# def __getitem__(self, key):
# return self.params[key].read(self.content)
#
# def __setitem__(self, key, value):
# self.content = self.params[key].write(self.content, value)
#
# def keys(self):
# return self.params.keys()
#
# def __delitem__(self, key):
# del self.params[key]
#
# def php_inserter(content, value):
# match = PHP_BLOCKS.search(content)
# if match:
# content = PHP_BLOCKS.sub(
# '<?php\g<1>\n%s\n?>' % (value), content)
# else:
# if content:
# content += os.linesep
# content += '<?php\n%s\n?>' % (value)
# return content
. Output only the next line. | return RegexHandler(pattern, writer, inserter=php_inserter, |
Given the following code snippet before the placeholder: <|code_start|> def load(self):
self.config.read()
for field in self:
if field.id in self.config:
field.process_data(self.config[field.id])
def save(self):
self.config.read()
for field in self:
if field.id in self.config:
self.config[field.id] = field.data
self.config.commit()
class FileForm(ConfigForm):
"""
Form that displays the entire content of a file.
"""
content = TextAreaField('File')
attrs = {'content': {'class': 'span9 code editor', 'rows': 25}}
class Handler(object):
def read(self, content):
return content
def write(self, content, value):
return value
def __init__(self, filename, legend=None, description=None, lang=None,
*args, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
from wtforms import Form
from wtforms.fields import (
TextField, IntegerField, PasswordField, TextAreaField, HiddenField, Field)
from wtforms.widgets import PasswordInput, TextArea
from wtforms.validators import Optional, NumberRange
from yubiadmin.util.config import RegexHandler, FileConfig, php_inserter
and context including class names, function names, and sometimes code from other files:
# Path: yubiadmin/util/config.py
# class RegexHandler(object):
# def __init__(self, pattern, writer, reader=lambda x: x.group(1),
# inserter=lambda x, y: '%s\n%s' % (x, y),
# default=None):
# self.pattern = re.compile(pattern)
# self.writer = writer
# self.reader = reader
# self.inserter = inserter
# self.default = default
#
# def read(self, content):
# match = self.pattern.search(content)
# if match:
# return self.reader(match)
# return self.default
#
# def write(self, content, value):
# if value is None:
# value = ''
# if self.pattern.search(content):
# new_content = self.pattern.sub(self.writer(value), content, 1)
# if self.read(content) == self.read(new_content):
# #Value remains unchanged, don't re-write it.
# return content
# else:
# return new_content
# else:
# return self.inserter(content, self.writer(value))
#
# class FileConfig(MutableMapping):
# """
# Maps key-value pairs to a backing config file.
# You can manually edit the file by modifying self.content.
# """
# def __init__(self, filename, params=[]):
# self.filename = filename
# self.params = OrderedDict()
# for param in params:
# self.add_param(*param)
#
# def read(self):
# try:
# with open(self.filename, 'r') as file:
# self.content = unicode(file.read())
# except IOError as e:
# log.error(e)
# self.content = u''
# #Initialize all params from default values.
# for key in self.params:
# self[key] = self[key]
#
# def commit(self):
# if not os.path.isfile(self.filename):
# dir = os.path.dirname(self.filename)
# try:
# os.makedirs(dir)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise e
# with open(self.filename, 'w+') as file:
# #Fix all linebreaks
# file.write(os.linesep.join(self.content.splitlines()))
#
# def add_param(self, key, handler):
# self.params[key] = handler
#
# def __iter__(self):
# return self.params.__iter__()
#
# def __len__(self):
# return len(self.params)
#
# def __getitem__(self, key):
# return self.params[key].read(self.content)
#
# def __setitem__(self, key, value):
# self.content = self.params[key].write(self.content, value)
#
# def keys(self):
# return self.params.keys()
#
# def __delitem__(self, key):
# del self.params[key]
#
# def php_inserter(content, value):
# match = PHP_BLOCKS.search(content)
# if match:
# content = PHP_BLOCKS.sub(
# '<?php\g<1>\n%s\n?>' % (value), content)
# else:
# if content:
# content += os.linesep
# content += '<?php\n%s\n?>' % (value)
# return content
. Output only the next line. | self.config = FileConfig(filename, [('content', self.Handler())]) |
Predict the next line for this snippet: <|code_start|> return value
def __init__(self, filename, legend=None, description=None, lang=None,
*args, **kwargs):
self.config = FileConfig(filename, [('content', self.Handler())])
self.legend = legend
self.description = description
if lang:
self.attrs['content']['ace-mode'] = lang
super(FileForm, self).__init__(*args, **kwargs)
self.content.label.text = 'File: %s' % filename
class DBConfigForm(ConfigForm):
"""
Complete form for editing a dbconfig-common generated for PHP.
"""
legend = 'Database'
description = 'Settings for connecting to the database.'
dbtype = TextField('Database type')
dbserver = TextField('Host')
dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
dbname = TextField('Database name')
dbuser = TextField('Username')
dbpass = PasswordField('Password',
widget=PasswordInput(hide_value=False))
def db_handler(self, varname, default):
pattern = r'\$%s=\'(.*)\';' % varname
writer = lambda x: '$%s=\'%s\';' % (varname, x)
<|code_end|>
with the help of current file imports:
from wtforms import Form
from wtforms.fields import (
TextField, IntegerField, PasswordField, TextAreaField, HiddenField, Field)
from wtforms.widgets import PasswordInput, TextArea
from wtforms.validators import Optional, NumberRange
from yubiadmin.util.config import RegexHandler, FileConfig, php_inserter
and context from other files:
# Path: yubiadmin/util/config.py
# class RegexHandler(object):
# def __init__(self, pattern, writer, reader=lambda x: x.group(1),
# inserter=lambda x, y: '%s\n%s' % (x, y),
# default=None):
# self.pattern = re.compile(pattern)
# self.writer = writer
# self.reader = reader
# self.inserter = inserter
# self.default = default
#
# def read(self, content):
# match = self.pattern.search(content)
# if match:
# return self.reader(match)
# return self.default
#
# def write(self, content, value):
# if value is None:
# value = ''
# if self.pattern.search(content):
# new_content = self.pattern.sub(self.writer(value), content, 1)
# if self.read(content) == self.read(new_content):
# #Value remains unchanged, don't re-write it.
# return content
# else:
# return new_content
# else:
# return self.inserter(content, self.writer(value))
#
# class FileConfig(MutableMapping):
# """
# Maps key-value pairs to a backing config file.
# You can manually edit the file by modifying self.content.
# """
# def __init__(self, filename, params=[]):
# self.filename = filename
# self.params = OrderedDict()
# for param in params:
# self.add_param(*param)
#
# def read(self):
# try:
# with open(self.filename, 'r') as file:
# self.content = unicode(file.read())
# except IOError as e:
# log.error(e)
# self.content = u''
# #Initialize all params from default values.
# for key in self.params:
# self[key] = self[key]
#
# def commit(self):
# if not os.path.isfile(self.filename):
# dir = os.path.dirname(self.filename)
# try:
# os.makedirs(dir)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise e
# with open(self.filename, 'w+') as file:
# #Fix all linebreaks
# file.write(os.linesep.join(self.content.splitlines()))
#
# def add_param(self, key, handler):
# self.params[key] = handler
#
# def __iter__(self):
# return self.params.__iter__()
#
# def __len__(self):
# return len(self.params)
#
# def __getitem__(self, key):
# return self.params[key].read(self.content)
#
# def __setitem__(self, key, value):
# self.content = self.params[key].write(self.content, value)
#
# def keys(self):
# return self.params.keys()
#
# def __delitem__(self, key):
# del self.params[key]
#
# def php_inserter(content, value):
# match = PHP_BLOCKS.search(content)
# if match:
# content = PHP_BLOCKS.sub(
# '<?php\g<1>\n%s\n?>' % (value), content)
# else:
# if content:
# content += os.linesep
# content += '<?php\n%s\n?>' % (value)
# return content
, which may contain function names, class names, or code. Output only the next line. | return RegexHandler(pattern, writer, inserter=php_inserter, |
Here is a snippet: <|code_start|># LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'settings'
]
SETTINGS_FILE = os.getenv('YUBIADMIN_SETTINGS',
'/etc/yubico/admin/yubiadmin.conf')
LOG_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(SETTINGS_FILE)),
'logging.conf')
VALUES = {
# Web interface
'USERNAME': 'user',
'PASSWORD': 'pass',
'INTERFACE': 'iface',
'PORT': 'port'
}
def parse(conf, settings={}):
for confkey, settingskey in VALUES.items():
if hasattr(conf, confkey):
settings[settingskey] = getattr(conf, confkey)
return settings
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import imp
import errno
import logging
import logging.config
from yubiadmin import default_settings
and context from other files:
# Path: yubiadmin/default_settings.py
# USERNAME = "yubiadmin"
# PASSWORD = "yubiadmin"
# INTERFACE = "127.0.0.1"
# PORT = 8080
, which may include functions, classes, or code. Output only the next line. | settings = parse(default_settings) |
Predict the next line after this snippet: <|code_start|> 'apt-get -y dist-upgrade -o '
'Dpkg::Options::="--force-confdef" -o '
'Dpkg::Options::="--force-confold" | '
'tee %s' % UPGRADE_LOG,
stdout=subprocess.PIPE, shell=True)
def __iter__(self):
yield """
<script type="text/javascript">
function reload() {
window.location.replace('/sys');
}
window.onload = function() {
setTimeout(reload, 10000);
}
</script>
<strong>Performing update, this may take a while...</strong><br/>
<pre>
"""
while True:
line = self.proc.stdout.readline()
if line:
yield line
else:
yield '</pre><br /><strong>Update complete!</strong>'
yield '<script type="text/javascript">reload();</script>'
break
<|code_end|>
using the current file's imports:
import os
import subprocess
from webob import Response
from threading import Timer
from yubiadmin.util.app import App, render
from yubiadmin.util.system import run
from yubiadmin.apps.dashboard import panel
and any relevant context from other files:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
#
# Path: yubiadmin/util/system.py
# def run(cmd):
# p = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# output = p.communicate()
# return p.returncode, output[0]
#
# Path: yubiadmin/apps/dashboard.py
# def panel(title, content, link=None, level=None):
# return {
# 'title': title,
# 'content': content,
# 'link': link,
# 'level': level
# }
. Output only the next line. | class SystemApp(App): |
Continue the code snippet: <|code_start|> return self.disabled
@property
def dash_panels(self):
if needs_restart():
yield panel('System', 'System restart required', level='danger')
updates = len(get_updates())
if updates > 0:
yield panel(
'System',
'There are <strong>%d</strong> updates available' % updates,
'/%s/general' % self.name,
'info'
)
_, time = run('date "+%a, %d %b %Y %H:%M"')
_, result = run('uptime')
rest = [x.strip() for x in result.split('up', 1)][1]
parts = [x.strip() for x in rest.split(',')]
uptime = parts[0] if not 'days' in parts[0] else '%s, %s' % \
tuple(parts[:2])
yield panel('System', 'Date: %s<br />Uptime: %s' %
(time, uptime), level='info')
def general(self, request):
alerts = []
if needs_restart():
alerts.append({'message': 'The machine needs to reboot.',
'type': 'error'})
<|code_end|>
. Use current file imports:
import os
import subprocess
from webob import Response
from threading import Timer
from yubiadmin.util.app import App, render
from yubiadmin.util.system import run
from yubiadmin.apps.dashboard import panel
and context (classes, functions, or code) from other files:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
#
# Path: yubiadmin/util/system.py
# def run(cmd):
# p = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# output = p.communicate()
# return p.returncode, output[0]
#
# Path: yubiadmin/apps/dashboard.py
# def panel(title, content, link=None, level=None):
# return {
# 'title': title,
# 'content': content,
# 'link': link,
# 'level': level
# }
. Output only the next line. | return render('/sys/general', alerts=alerts, updates=get_updates()) |
Based on the snippet: <|code_start|># 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'app'
]
UPGRADE_LOG = "/var/tmp/yubix-upgrade"
def get_updates():
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import subprocess
from webob import Response
from threading import Timer
from yubiadmin.util.app import App, render
from yubiadmin.util.system import run
from yubiadmin.apps.dashboard import panel
and context (classes, functions, sometimes code) from other files:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
#
# Path: yubiadmin/util/system.py
# def run(cmd):
# p = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# output = p.communicate()
# return p.returncode, output[0]
#
# Path: yubiadmin/apps/dashboard.py
# def panel(title, content, link=None, level=None):
# return {
# 'title': title,
# 'content': content,
# 'link': link,
# 'level': level
# }
. Output only the next line. | s, o = run("apt-get upgrade -s | awk -F'[][() ]+' '/^Inst/{print $2}'") |
Given snippet: <|code_start|>
while True:
line = self.proc.stdout.readline()
if line:
yield line
else:
yield '</pre><br /><strong>Update complete!</strong>'
yield '<script type="text/javascript">reload();</script>'
break
class SystemApp(App):
"""
YubiX System
"""
sections = ['general']
priority = 30
@property
def disabled(self):
#return not os.path.isdir('/usr/share/yubix')
return False
@property
def hidden(self):
return self.disabled
@property
def dash_panels(self):
if needs_restart():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
from webob import Response
from threading import Timer
from yubiadmin.util.app import App, render
from yubiadmin.util.system import run
from yubiadmin.apps.dashboard import panel
and context:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# def render(tmpl, **kwargs):
# return TemplateBinding(tmpl, **kwargs)
#
# Path: yubiadmin/util/system.py
# def run(cmd):
# p = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE,
# stderr=subprocess.PIPE)
# output = p.communicate()
# return p.returncode, output[0]
#
# Path: yubiadmin/apps/dashboard.py
# def panel(title, content, link=None, level=None):
# return {
# 'title': title,
# 'content': content,
# 'link': link,
# 'level': level
# }
which might include code, classes, or functions. Output only the next line. | yield panel('System', 'System restart required', level='danger') |
Using the snippet: <|code_start|># Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'app'
]
<|code_end|>
, determine the next line of code. You have imports:
import os
from yubiadmin.util.app import App
from yubiadmin.util.form import DBConfigForm
and context (class names, function names, or code) available:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# Path: yubiadmin/util/form.py
# class DBConfigForm(ConfigForm):
# """
# Complete form for editing a dbconfig-common generated for PHP.
# """
# legend = 'Database'
# description = 'Settings for connecting to the database.'
# dbtype = TextField('Database type')
# dbserver = TextField('Host')
# dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
# dbname = TextField('Database name')
# dbuser = TextField('Username')
# dbpass = PasswordField('Password',
# widget=PasswordInput(hide_value=False))
#
# def db_handler(self, varname, default):
# pattern = r'\$%s=\'(.*)\';' % varname
# writer = lambda x: '$%s=\'%s\';' % (varname, x)
# return RegexHandler(pattern, writer, inserter=php_inserter,
# default=default)
#
# def __init__(self, filename, *args, **kwargs):
# if not self.config:
# self.config = FileConfig(
# filename,
# [
# ('dbtype', self.db_handler(
# 'dbtype', kwargs.pop('dbtype', 'mysql'))),
# ('dbserver', self.db_handler(
# 'dbserver', kwargs.pop('dbserver', 'localhost'))),
# ('dbport', self.db_handler(
# 'dbport', kwargs.pop('dbport', ''))),
# ('dbname', self.db_handler(
# 'dbname', kwargs.pop('dbname', ''))),
# ('dbuser', self.db_handler(
# 'dbuser', kwargs.pop('dbuser', ''))),
# ('dbpass', self.db_handler(
# 'dbpass', kwargs.pop('dbpass', ''))),
# ]
# )
#
# super(DBConfigForm, self).__init__(*args, **kwargs)
. Output only the next line. | class YubikeyKsm(App): |
Predict the next line after this snippet: <|code_start|># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = [
'app'
]
class YubikeyKsm(App):
"""
YubiKey Key Storage Module
YubiKey KSM server
"""
sections = ['database']
@property
def disabled(self):
return not os.path.isfile('/etc/yubico/ksm/ykksm-config.php')
def database(self, request):
"""
Database Settings
"""
<|code_end|>
using the current file's imports:
import os
from yubiadmin.util.app import App
from yubiadmin.util.form import DBConfigForm
and any relevant context from other files:
# Path: yubiadmin/util/app.py
# class App(object):
# sections = []
# priority = 50
#
# @property
# def name(self):
# self.__class__.name = sys.modules[self.__module__].__file__ \
# .split('/')[-1].rsplit('.', 1)[0]
# return self.name
#
# def __call__(self, request):
# section_name = request.path_info_pop()
#
# if not section_name:
# return self.redirect('/%s/%s' % (self.name, self.sections[0]))
#
# if not hasattr(self, section_name):
# raise exc.HTTPNotFound
#
# sections = [{
# 'name': section,
# 'title': (getattr(self, section).__doc__ or section.capitalize()
# ).strip(),
# 'active': section == section_name,
# 'advanced': bool(getattr(getattr(self, section), 'advanced',
# False))
# } for section in self.sections]
#
# request.environ['yubiadmin.response'].extend('content', render(
# 'app_base',
# name=self.name,
# sections=sections,
# title='YubiAdmin - %s - %s' % (self.name, section_name)
# ))
#
# resp = getattr(self, section_name)(request)
# if isinstance(resp, Response):
# return resp
# request.environ['yubiadmin.response'].extend('page', resp)
#
# def redirect(self, url):
# raise exc.HTTPSeeOther(location=url)
#
# def render_forms(self, request, forms, template='form',
# success_msg='Settings updated!', **kwargs):
# alerts = []
# if not request.params:
# for form in filter(lambda x: hasattr(x, 'load'), forms):
# form.load()
# else:
# errors = False
# for form in forms:
# form.process(request.params)
# errors = not form.validate() or errors
# if not errors:
# try:
# if success_msg:
# alerts = [{'type': 'success', 'title': success_msg}]
# for form in filter(lambda x: hasattr(x, 'save'), forms):
# form.save()
# except Exception as e:
# alerts = [{'type': 'error', 'title': 'Error:',
# 'message': str(e)}]
# else:
# alerts = [{'type': 'error', 'title': 'Invalid data!'}]
#
# return render(template, target=request.path, fieldsets=forms,
# alerts=alerts, **kwargs)
#
# Path: yubiadmin/util/form.py
# class DBConfigForm(ConfigForm):
# """
# Complete form for editing a dbconfig-common generated for PHP.
# """
# legend = 'Database'
# description = 'Settings for connecting to the database.'
# dbtype = TextField('Database type')
# dbserver = TextField('Host')
# dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
# dbname = TextField('Database name')
# dbuser = TextField('Username')
# dbpass = PasswordField('Password',
# widget=PasswordInput(hide_value=False))
#
# def db_handler(self, varname, default):
# pattern = r'\$%s=\'(.*)\';' % varname
# writer = lambda x: '$%s=\'%s\';' % (varname, x)
# return RegexHandler(pattern, writer, inserter=php_inserter,
# default=default)
#
# def __init__(self, filename, *args, **kwargs):
# if not self.config:
# self.config = FileConfig(
# filename,
# [
# ('dbtype', self.db_handler(
# 'dbtype', kwargs.pop('dbtype', 'mysql'))),
# ('dbserver', self.db_handler(
# 'dbserver', kwargs.pop('dbserver', 'localhost'))),
# ('dbport', self.db_handler(
# 'dbport', kwargs.pop('dbport', ''))),
# ('dbname', self.db_handler(
# 'dbname', kwargs.pop('dbname', ''))),
# ('dbuser', self.db_handler(
# 'dbuser', kwargs.pop('dbuser', ''))),
# ('dbpass', self.db_handler(
# 'dbpass', kwargs.pop('dbpass', ''))),
# ]
# )
#
# super(DBConfigForm, self).__init__(*args, **kwargs)
. Output only the next line. | dbform = DBConfigForm('/etc/yubico/ksm/config-db.php', |
Next line prediction: <|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 this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class ConfigPath(object):
module_path = os.path.dirname(__file__)
##############################################
@staticmethod
def glsl(file_name):
return os.path.join(ConfigPath.module_path, 'glslv3', file_name)
####################################################################################################
<|code_end|>
. Use current file imports:
(import os
from PyOpenGLng.HighLevelApi.Shader import GlShaderManager, GlShaderProgramInterface)
and context including class names, function names, or small code snippets from other files:
# Path: PyOpenGLng/HighLevelApi/Shader.py
# class GlShaderManager(with_metaclass(SingletonMetaClass, object)):
#
# """ This class provides a shader manager where each shader or program are identified by a name
# and the shader sources are loaded from files.
#
# The shaders or programs can be accessed using an attribute or a dictionary interface. For
# example to get the shader *fixed_fragment* we can use either::
#
# shader_manager.fixed_fragment
# shader_manager.['fixed_fragment']
#
# We can test if an identifier exists using::
#
# 'fixed_fragment' in shader_manager
# """
#
# # Fixme: -> attributeDictionaryInterface
#
# ##############################################
#
# def __init__(self):
#
# self._shaders = {}
# self._programs = {}
#
# ##############################################
#
# def __contains__(self, name):
#
# return name in self._shaders or name in self._programs
#
# ##############################################
#
# def __getattr__(self, name):
#
# item = self._programs.get(name, None)
# if item is None:
# item = self._shaders.get(name, None)
# if item is None:
# raise KeyError(name)
#
# return item
#
# ##############################################
#
# __getitem__ = __getattr__
#
# ##############################################
#
# def has_visual(self):
#
# return bool(GL.glCreateShader)
#
# ##############################################
#
# def load_from_file(self, shader_name, shader_file_name):
#
# """ Load a shader from a source file and compile it. This shader is identified by
# *shader_name*.
# """
#
# if shader_name in self:
# raise NameError("Shader %s is already defined" % (shader_name))
#
# shader = GlShader(file_name=shader_file_name)
# shader.compile()
# self._shaders[shader_name] = shader
#
# return shader
#
# ##############################################
#
# def link_program(self, program_name, shader_list,
# program_interface=None,
# shader_program_class=GlShaderProgram,
# shader_program_args=(),
# ):
#
# """ Link a program with the given list of shader names. This program is identified by
# *shader_name*. The argument *program_interface* can be used to set the program interface.
# """
#
# if program_name in self:
# raise NameError("Program %s is already defined" % (program_name))
#
# shader_program = shader_program_class(program_name, *shader_program_args)
# for shader_name in shader_list:
# shader_program.attach_shader(self[shader_name])
# # Fixme: move to link ?
# if program_interface is not None:
# shader_program.set_program_interface(program_interface)
# shader_program.link()
# if program_interface is not None:
# shader_program.set_uniform_block_bindings()
# self._programs[program_name] = shader_program
#
# return shader_program
#
# class GlShaderProgramInterface(object):
#
# """ This class defines a programming interface for a program.
# """
#
# ##############################################
#
# def __init__(self, uniform_blocks, attributes):
#
# self._init_uniform_blocks(uniform_blocks)
# self._init_attributes(attributes)
#
# ##############################################
#
# def _init_uniform_blocks(self, uniform_blocks):
#
# self.uniform_blocks = AttributeDictionaryInterface()
# for binding_point, name in enumerate(uniform_blocks):
# pair = GlShaderProgramInterfaceUniformBlock(name, binding_point)
# self.uniform_blocks._dictionary[name] = pair
#
# ##############################################
#
# def _init_attributes(self, attributes):
#
# self.attributes = AttributeDictionaryInterface()
# for location, name in enumerate(attributes):
# pair = GlShaderProgramInterfaceAttribute(name, location)
# self.attributes._dictionary[name] = pair
. Output only the next line. | shader_manager = GlShaderManager() |
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 this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class ConfigPath(object):
module_path = os.path.dirname(__file__)
##############################################
@staticmethod
def glsl(file_name):
return os.path.join(ConfigPath.module_path, 'glslv3', file_name)
####################################################################################################
shader_manager = GlShaderManager()
<|code_end|>
using the current file's imports:
import os
from PyOpenGLng.HighLevelApi.Shader import GlShaderManager, GlShaderProgramInterface
and any relevant context from other files:
# Path: PyOpenGLng/HighLevelApi/Shader.py
# class GlShaderManager(with_metaclass(SingletonMetaClass, object)):
#
# """ This class provides a shader manager where each shader or program are identified by a name
# and the shader sources are loaded from files.
#
# The shaders or programs can be accessed using an attribute or a dictionary interface. For
# example to get the shader *fixed_fragment* we can use either::
#
# shader_manager.fixed_fragment
# shader_manager.['fixed_fragment']
#
# We can test if an identifier exists using::
#
# 'fixed_fragment' in shader_manager
# """
#
# # Fixme: -> attributeDictionaryInterface
#
# ##############################################
#
# def __init__(self):
#
# self._shaders = {}
# self._programs = {}
#
# ##############################################
#
# def __contains__(self, name):
#
# return name in self._shaders or name in self._programs
#
# ##############################################
#
# def __getattr__(self, name):
#
# item = self._programs.get(name, None)
# if item is None:
# item = self._shaders.get(name, None)
# if item is None:
# raise KeyError(name)
#
# return item
#
# ##############################################
#
# __getitem__ = __getattr__
#
# ##############################################
#
# def has_visual(self):
#
# return bool(GL.glCreateShader)
#
# ##############################################
#
# def load_from_file(self, shader_name, shader_file_name):
#
# """ Load a shader from a source file and compile it. This shader is identified by
# *shader_name*.
# """
#
# if shader_name in self:
# raise NameError("Shader %s is already defined" % (shader_name))
#
# shader = GlShader(file_name=shader_file_name)
# shader.compile()
# self._shaders[shader_name] = shader
#
# return shader
#
# ##############################################
#
# def link_program(self, program_name, shader_list,
# program_interface=None,
# shader_program_class=GlShaderProgram,
# shader_program_args=(),
# ):
#
# """ Link a program with the given list of shader names. This program is identified by
# *shader_name*. The argument *program_interface* can be used to set the program interface.
# """
#
# if program_name in self:
# raise NameError("Program %s is already defined" % (program_name))
#
# shader_program = shader_program_class(program_name, *shader_program_args)
# for shader_name in shader_list:
# shader_program.attach_shader(self[shader_name])
# # Fixme: move to link ?
# if program_interface is not None:
# shader_program.set_program_interface(program_interface)
# shader_program.link()
# if program_interface is not None:
# shader_program.set_uniform_block_bindings()
# self._programs[program_name] = shader_program
#
# return shader_program
#
# class GlShaderProgramInterface(object):
#
# """ This class defines a programming interface for a program.
# """
#
# ##############################################
#
# def __init__(self, uniform_blocks, attributes):
#
# self._init_uniform_blocks(uniform_blocks)
# self._init_attributes(attributes)
#
# ##############################################
#
# def _init_uniform_blocks(self, uniform_blocks):
#
# self.uniform_blocks = AttributeDictionaryInterface()
# for binding_point, name in enumerate(uniform_blocks):
# pair = GlShaderProgramInterfaceUniformBlock(name, binding_point)
# self.uniform_blocks._dictionary[name] = pair
#
# ##############################################
#
# def _init_attributes(self, attributes):
#
# self.attributes = AttributeDictionaryInterface()
# for location, name in enumerate(attributes):
# pair = GlShaderProgramInterfaceAttribute(name, location)
# self.attributes._dictionary[name] = pair
. Output only the next line. | position_shader_program_interface = GlShaderProgramInterface(uniform_blocks=('viewport',), |
Given snippet: <|code_start|>
def unmap_x_in(self, x):
""" Return x + inf
"""
return x + self.inf
##############################################
# Fixme: length -> size ?
def length(self):
""" Return sup - inf
"""
return self.sup - self.inf
##############################################
def zero_length(self):
""" Return sup == inf
"""
return self.sup == self.inf
##############################################
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import math
import sys
from .Functions import middle
and context:
# Path: PyOpenGLng/Math/Functions.py
# def middle(a, b):
# return .5 * (a + b)
which might include code, classes, or functions. Output only the next line. | def middle(self): |
Here is a snippet: <|code_start|>
# Fixme: scale!
positions, normals = unit_cube()
colour2 = (1, 0, 0, 1)
colour4 = (1, 0, 0, 1)
colour8 = (1, 0, 0, 1)
colour6 = (1, 0, 0, 1)
colour1 = (0, 1, 0, 1)
colour3 = (0, 1, 0, 1)
colour7 = (0, 1, 0, 1)
colour5 = (0, 1, 0, 1)
colours = np.array([
colour1, colour2, colour4, # left
colour1, colour4, colour3, # left
colour5, colour8, colour6, # right
colour8, colour5, colour7, # right
colour6, colour1, colour5, # bottom
colour6, colour2, colour1, # bottom
colour8, colour3, colour4, # top
colour8, colour7, colour3, # top
colour7, colour1, colour3, # far
colour7, colour5, colour1, # far
colour4, colour2, colour6, # near
colour8, colour4, colour6], # near
dtype=np.float32)
<|code_end|>
. Write the next line using the current file imports:
import math
import numpy as np
from .PrimitiveVertexArray import TriangleVertexArray
and context from other files:
# Path: PyOpenGLng/HighLevelApi/PrimitiveVertexArray.py
# class TriangleVertexArray(GlVertexArrayObject):
#
# """ Base class to draw primitives as triangles. """
#
# # Fixme: 3d
#
# ##############################################
#
# def __init__(self, items=None):
#
# super(TriangleVertexArray, self).__init__()
#
# self._number_of_items = 0
# self._positions_buffer = GlArrayBuffer()
# self._normals_buffer = GlArrayBuffer()
# self._colours_buffer = GlArrayBuffer()
#
# if items is not None:
# self.set(*items)
#
# ##############################################
#
# def set(self, positions, normals, colours):
#
# """ Set the vertex array from an iterable of triangles. """
#
# self._number_of_items = positions.shape[0]
#
# # Fixme:
# # - set from high level primitive: slow
# # - set from Numpy array: fast but check for mistake
#
# # vertex = np.zeros((self._number_of_objects, 3), dtype='f') # dtype=np.float
#
# self._positions_buffer.set(positions)
# self._normals_buffer.set(normals)
# self._colours_buffer.set(colours)
#
# ##############################################
#
# def bind_to_shader(self, shader_program_interface):
#
# """ Bind the vertex array to the shader program interface attribute.
# """
#
# # Fixme: we cannot reuse the vbo
#
# self.bind()
# shader_program_interface.position.bind_to_buffer(self._positions_buffer)
# shader_program_interface.normal.bind_to_buffer(self._normals_buffer)
# shader_program_interface.colour.bind_to_buffer(self._colours_buffer)
# self.unbind()
#
# ##############################################
#
# def draw(self):
#
# """ Draw the vertex array as lines. """
#
# self.bind()
# GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3*self._number_of_items)
# self.unbind()
, which may include functions, classes, or code. Output only the next line. | return TriangleVertexArray((positions, normals, colours)) |
Continue the code snippet: <|code_start|>
####################################################################################################
logging.basicConfig(
format='\033[1;32m%(asctime)s\033[0m - \033[1;34m%(name)s.%(funcName)s\033[0m - \033[1;31m%(levelname)s\033[0m - %(message)s',
level=logging.INFO,
)
####################################################################################################
#
# GLFW Callbacks
#
@glfw.key_callback
def on_key(window, key, scancode, action, mods):
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.set_window_should_close(window, 1)
def error_callback(error, description):
raise NameError("{} {}".format(error, description))
####################################################################################################
# Initialize the GLFW library
if not glfw.init():
sys.exit()
glfw.set_error_callback(error_callback)
# Create a windowed mode window and its OpenGL context
<|code_end|>
. Use current file imports:
import logging
import sys
import PyGlfwCffi as glfw
import PyOpenGLng.Wrapper as GlWrapper
from PyOpenGLng.GlApi import ApiNumber
from PyOpenGLng.Tools.Timer import TimerContextManager
and context (classes, functions, or code) from other files:
# Path: PyOpenGLng/GlApi/ApiNumber.py
# class ApiNumber(object):
#
# """ This class implements a basic API number suitable for OpenGL.
#
# Use case::
#
# >>> api_number = ApiNumber('4.4')
# >>> str(api_number)
# '4.4'
# >>> ApiNumber('4.0') < ApiNumber('4.1')
# True
# >>> ApiNumber('4.0') <= ApiNumber('4.0')
# True
#
# """
#
# ##############################################
#
# def __init__(self, number):
#
# """ The argument *number* must be of the form "x.y". """
#
# try:
# self.major, self.minor = [int(x) for x in number.split('.')]
# except ValueError:
# # self.major, self.minor = int(number), 0
# raise NameError("Version number must be of the form x.y")
#
# ##############################################
#
# def __int__(self):
#
# return self.major * 1000 + self.minor
#
# ##############################################
#
# def __str__(self):
#
# return "%u.%u" % (self.major, self.minor)
#
# ##############################################
#
# def __le__(self, api_number):
#
# return int(self) <= int(api_number)
#
# ##############################################
#
# def __lt__(self, api_number):
#
# return int(self) < int(api_number)
#
# Path: PyOpenGLng/Tools/Timer.py
# class TimerContextManager(object):
#
# ##############################################
#
# def __init__(self, logger, title):
#
# self._logger = logger
# self._title = title
#
# ##############################################
#
# def __enter__(self):
#
# self._start = time.clock()
#
# ##############################################
#
# def __exit__(self, type_, value, traceback):
#
# dt = time.clock() - self._start
# self._logger.info("{} dt = {} s".format(self._title, dt))
. Output only the next line. | api_number = ApiNumber('2.1') |
Predict the next line after this snippet: <|code_start|>#
# GLFW Callbacks
#
@glfw.key_callback
def on_key(window, key, scancode, action, mods):
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.set_window_should_close(window, 1)
def error_callback(error, description):
raise NameError("{} {}".format(error, description))
####################################################################################################
# Initialize the GLFW library
if not glfw.init():
sys.exit()
glfw.set_error_callback(error_callback)
# Create a windowed mode window and its OpenGL context
api_number = ApiNumber('2.1')
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, api_number.major)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, api_number.minor)
glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
window = glfw.create_window(640, 480, "Hello World")
if not window:
glfw.terminate()
sys.exit()
# Create the OpenGL wrapper
<|code_end|>
using the current file's imports:
import logging
import sys
import PyGlfwCffi as glfw
import PyOpenGLng.Wrapper as GlWrapper
from PyOpenGLng.GlApi import ApiNumber
from PyOpenGLng.Tools.Timer import TimerContextManager
and any relevant context from other files:
# Path: PyOpenGLng/GlApi/ApiNumber.py
# class ApiNumber(object):
#
# """ This class implements a basic API number suitable for OpenGL.
#
# Use case::
#
# >>> api_number = ApiNumber('4.4')
# >>> str(api_number)
# '4.4'
# >>> ApiNumber('4.0') < ApiNumber('4.1')
# True
# >>> ApiNumber('4.0') <= ApiNumber('4.0')
# True
#
# """
#
# ##############################################
#
# def __init__(self, number):
#
# """ The argument *number* must be of the form "x.y". """
#
# try:
# self.major, self.minor = [int(x) for x in number.split('.')]
# except ValueError:
# # self.major, self.minor = int(number), 0
# raise NameError("Version number must be of the form x.y")
#
# ##############################################
#
# def __int__(self):
#
# return self.major * 1000 + self.minor
#
# ##############################################
#
# def __str__(self):
#
# return "%u.%u" % (self.major, self.minor)
#
# ##############################################
#
# def __le__(self, api_number):
#
# return int(self) <= int(api_number)
#
# ##############################################
#
# def __lt__(self, api_number):
#
# return int(self) < int(api_number)
#
# Path: PyOpenGLng/Tools/Timer.py
# class TimerContextManager(object):
#
# ##############################################
#
# def __init__(self, logger, title):
#
# self._logger = logger
# self._title = title
#
# ##############################################
#
# def __enter__(self):
#
# self._start = time.clock()
#
# ##############################################
#
# def __exit__(self, type_, value, traceback):
#
# dt = time.clock() - self._start
# self._logger.info("{} dt = {} s".format(self._title, dt))
. Output only the next line. | with TimerContextManager(logging, "GlWrapper.init"): |
Given the code snippet: <|code_start|> enum_name, enum_value = str(enum), int(enum)
# store enumerants and commands at the same level
setattr(self, enum_name, enum_value)
# store enumerants in a dedicated place
setattr(gl_enums, enum_name, enum_value)
self.enums = gl_enums
##############################################
def _reload_library(self, api_commands):
api_definition = ''
for command in api_commands.values():
prototype = command.prototype(with_size=False)
if 'GLDEBUGPROC' not in prototype and 'GLsync' not in prototype: # Fixme:
api_definition += prototype + ';\n'
ffi.cdef(api_definition, override=True)
##############################################
def _init_commands(self, api_commands):
self._reload_library(api_commands)
gl_commands = GlCommands()
for command in api_commands.values():
try:
command_name = str(command)
command_wrapper = GlCommandWrapper(self, command)
# store enumerants and commands at the same level
<|code_end|>
, generate the next line using the imports in this file:
import collections
import ctypes
import logging
import os
import subprocess
import sys
import types
import numpy as np
import PyOpenGLng.Config as Config
from cffi import FFI
from .PythonicWrapper import PythonicWrapper
and context (functions, classes, or occasionally code) from other files:
# Path: PyOpenGLng/Wrapper/PythonicWrapper.py
# class PythonicWrapper(object):
#
# _logger = _module_logger.getChild('PythonicWrapper')
#
# ##############################################
#
# def glGetActiveUniformBlockiv(self, program, index, pname):
#
# """ Query information about an active uniform block. """
#
# # Check index
# number_of_uniform_blocks = self.glGetProgramiv(program, self.GL_ACTIVE_UNIFORM_BLOCKS)
# # if not(0 <= index < number_of_uniform_blocks):
# if index < 0 or index >= number_of_uniform_blocks:
# raise IndexError('Index %s out of range 0 to %i' % (index, number_of_uniform_blocks -1))
#
# if pname != self.GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES:
# array_size = 1
# else:
# array_size = self.glGetActiveUniformBlockiv(program, index, self.GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS)
# params = np.zeros(array_size, dtype=np.int32)
#
# self.commands.glGetActiveUniformBlockiv(program, index, pname, params)
#
# if array_size > 1:
# return list(params)
# else:
# return params[0]
#
# ##############################################
#
# def glGetActiveUniformBlockName(self, program, index):
#
# """ Retrieve the name of an active uniform block. """
#
# number_of_uniform_blocks = self.glGetProgramiv(program, self.GL_ACTIVE_UNIFORM_BLOCKS)
# if index < 0 or index >= number_of_uniform_blocks:
# raise IndexError("Index %s out of range 0 to %i" % (index, number_of_uniform_blocks -1))
#
# max_name_length = self.glGetProgramiv(program, self.GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH)
# name, name_length = self.commands.glGetActiveUniformBlockName(program, index, max_name_length)
# return name
#
# ##############################################
#
# def glGetActiveUniformsiv(self, program, indices, pname):
#
# """ Returns information about several active uniform variables for the specified program
# object.
# """
#
# try:
# indices = list(indices)
# except TypeError:
# indices = (indices,)
#
# number_of_uniform_blocks = self.glGetProgramiv(program, self.GL_ACTIVE_UNIFORMS)
# for index in indices:
# if index < 0 or index >= number_of_uniform_blocks:
# raise IndexError('Index %s out of range 0 to %i' % (index, number_of_uniform_blocks -1))
#
# gl_indices = np.array(indices, dtype=np.uint32)
# params = np.zeros(len(indices), dtype=np.int32)
#
# self.commands.glGetActiveUniformsiv(program, len(indices), gl_indices, pname, params)
#
# if len(indices) > 1:
# return list(params)
# else:
# return params[0]
#
# ##############################################
#
# def glGetProgram(self, program, pname):
#
# self._logger.info("Use commands_dict")
#
# dtype, size = Getter.commands_dict['glGetProgram'][pname]
#
# command_wrapper = self.commands.glGetProgramiv
#
# # dtype is imposed by command
# # size is COMPSIZE
# # can we accelerate wrapper ??? overhead versus ctype pointer
# # pass size
# dtype, size = command_wrapper._getter[pname]
# data = np.zeros(size, dtype=dtype)
# command_wrapper(program, pname, data)
# data = data.tolist()
# if size == 1:
# return data[0]
# else:
# return data
#
# ##############################################
#
# def glGetProgramiv(self, program, pname):
#
# self._logger.info("Use commands_dict")
#
# command_wrapper = self.commands.glGetProgramiv
# # dtype is imposed by command
# # size is COMPSIZE
# # can we accelerate wrapper ??? overhead versus ctype pointer
# # pass size
# dtype, size = command_wrapper._getter[pname]
# data = np.zeros(size, dtype=dtype)
# command_wrapper(program, pname, data)
# data = data.tolist()
# if size == 1:
# return data[0]
# else:
# return data
#
# ##############################################
#
# def glGetShaderiv(self, program, pname):
#
# # Fixme: cf. infra
# data = np.zeros(1, dtype=np.int32)
# self.commands.glGetShaderiv(program, pname, data)
# return int(data[0])
#
# ##############################################
#
# def glGetString(self, *args, **kwargs):
#
# # Fixme:
# value = self.commands.glGetString(*args, **kwargs)
# if value is not None:
# return value.decode('ascii')
# else:
# return value
. Output only the next line. | if hasattr(PythonicWrapper, command_name): |
Using the 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class ConfigPath(object):
module_path = os.path.dirname(__file__)
##############################################
@staticmethod
def glsl(file_name):
return os.path.join(ConfigPath.module_path, 'glslv4', file_name)
####################################################################################################
<|code_end|>
, determine the next line of code. You have imports:
import os
from PyOpenGLng.HighLevelApi.Shader import GlShaderManager, GlShaderProgramInterface
and context (class names, function names, or code) available:
# Path: PyOpenGLng/HighLevelApi/Shader.py
# class GlShaderManager(with_metaclass(SingletonMetaClass, object)):
#
# """ This class provides a shader manager where each shader or program are identified by a name
# and the shader sources are loaded from files.
#
# The shaders or programs can be accessed using an attribute or a dictionary interface. For
# example to get the shader *fixed_fragment* we can use either::
#
# shader_manager.fixed_fragment
# shader_manager.['fixed_fragment']
#
# We can test if an identifier exists using::
#
# 'fixed_fragment' in shader_manager
# """
#
# # Fixme: -> attributeDictionaryInterface
#
# ##############################################
#
# def __init__(self):
#
# self._shaders = {}
# self._programs = {}
#
# ##############################################
#
# def __contains__(self, name):
#
# return name in self._shaders or name in self._programs
#
# ##############################################
#
# def __getattr__(self, name):
#
# item = self._programs.get(name, None)
# if item is None:
# item = self._shaders.get(name, None)
# if item is None:
# raise KeyError(name)
#
# return item
#
# ##############################################
#
# __getitem__ = __getattr__
#
# ##############################################
#
# def has_visual(self):
#
# return bool(GL.glCreateShader)
#
# ##############################################
#
# def load_from_file(self, shader_name, shader_file_name):
#
# """ Load a shader from a source file and compile it. This shader is identified by
# *shader_name*.
# """
#
# if shader_name in self:
# raise NameError("Shader %s is already defined" % (shader_name))
#
# shader = GlShader(file_name=shader_file_name)
# shader.compile()
# self._shaders[shader_name] = shader
#
# return shader
#
# ##############################################
#
# def link_program(self, program_name, shader_list,
# program_interface=None,
# shader_program_class=GlShaderProgram,
# shader_program_args=(),
# ):
#
# """ Link a program with the given list of shader names. This program is identified by
# *shader_name*. The argument *program_interface* can be used to set the program interface.
# """
#
# if program_name in self:
# raise NameError("Program %s is already defined" % (program_name))
#
# shader_program = shader_program_class(program_name, *shader_program_args)
# for shader_name in shader_list:
# shader_program.attach_shader(self[shader_name])
# # Fixme: move to link ?
# if program_interface is not None:
# shader_program.set_program_interface(program_interface)
# shader_program.link()
# if program_interface is not None:
# shader_program.set_uniform_block_bindings()
# self._programs[program_name] = shader_program
#
# return shader_program
#
# class GlShaderProgramInterface(object):
#
# """ This class defines a programming interface for a program.
# """
#
# ##############################################
#
# def __init__(self, uniform_blocks, attributes):
#
# self._init_uniform_blocks(uniform_blocks)
# self._init_attributes(attributes)
#
# ##############################################
#
# def _init_uniform_blocks(self, uniform_blocks):
#
# self.uniform_blocks = AttributeDictionaryInterface()
# for binding_point, name in enumerate(uniform_blocks):
# pair = GlShaderProgramInterfaceUniformBlock(name, binding_point)
# self.uniform_blocks._dictionary[name] = pair
#
# ##############################################
#
# def _init_attributes(self, attributes):
#
# self.attributes = AttributeDictionaryInterface()
# for location, name in enumerate(attributes):
# pair = GlShaderProgramInterfaceAttribute(name, location)
# self.attributes._dictionary[name] = pair
. Output only the next line. | shader_manager = GlShaderManager() |
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 this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
####################################################################################################
####################################################################################################
class ConfigPath(object):
module_path = os.path.dirname(__file__)
##############################################
@staticmethod
def glsl(file_name):
return os.path.join(ConfigPath.module_path, 'glslv4', file_name)
####################################################################################################
shader_manager = GlShaderManager()
<|code_end|>
using the current file's imports:
import os
from PyOpenGLng.HighLevelApi.Shader import GlShaderManager, GlShaderProgramInterface
and any relevant context from other files:
# Path: PyOpenGLng/HighLevelApi/Shader.py
# class GlShaderManager(with_metaclass(SingletonMetaClass, object)):
#
# """ This class provides a shader manager where each shader or program are identified by a name
# and the shader sources are loaded from files.
#
# The shaders or programs can be accessed using an attribute or a dictionary interface. For
# example to get the shader *fixed_fragment* we can use either::
#
# shader_manager.fixed_fragment
# shader_manager.['fixed_fragment']
#
# We can test if an identifier exists using::
#
# 'fixed_fragment' in shader_manager
# """
#
# # Fixme: -> attributeDictionaryInterface
#
# ##############################################
#
# def __init__(self):
#
# self._shaders = {}
# self._programs = {}
#
# ##############################################
#
# def __contains__(self, name):
#
# return name in self._shaders or name in self._programs
#
# ##############################################
#
# def __getattr__(self, name):
#
# item = self._programs.get(name, None)
# if item is None:
# item = self._shaders.get(name, None)
# if item is None:
# raise KeyError(name)
#
# return item
#
# ##############################################
#
# __getitem__ = __getattr__
#
# ##############################################
#
# def has_visual(self):
#
# return bool(GL.glCreateShader)
#
# ##############################################
#
# def load_from_file(self, shader_name, shader_file_name):
#
# """ Load a shader from a source file and compile it. This shader is identified by
# *shader_name*.
# """
#
# if shader_name in self:
# raise NameError("Shader %s is already defined" % (shader_name))
#
# shader = GlShader(file_name=shader_file_name)
# shader.compile()
# self._shaders[shader_name] = shader
#
# return shader
#
# ##############################################
#
# def link_program(self, program_name, shader_list,
# program_interface=None,
# shader_program_class=GlShaderProgram,
# shader_program_args=(),
# ):
#
# """ Link a program with the given list of shader names. This program is identified by
# *shader_name*. The argument *program_interface* can be used to set the program interface.
# """
#
# if program_name in self:
# raise NameError("Program %s is already defined" % (program_name))
#
# shader_program = shader_program_class(program_name, *shader_program_args)
# for shader_name in shader_list:
# shader_program.attach_shader(self[shader_name])
# # Fixme: move to link ?
# if program_interface is not None:
# shader_program.set_program_interface(program_interface)
# shader_program.link()
# if program_interface is not None:
# shader_program.set_uniform_block_bindings()
# self._programs[program_name] = shader_program
#
# return shader_program
#
# class GlShaderProgramInterface(object):
#
# """ This class defines a programming interface for a program.
# """
#
# ##############################################
#
# def __init__(self, uniform_blocks, attributes):
#
# self._init_uniform_blocks(uniform_blocks)
# self._init_attributes(attributes)
#
# ##############################################
#
# def _init_uniform_blocks(self, uniform_blocks):
#
# self.uniform_blocks = AttributeDictionaryInterface()
# for binding_point, name in enumerate(uniform_blocks):
# pair = GlShaderProgramInterfaceUniformBlock(name, binding_point)
# self.uniform_blocks._dictionary[name] = pair
#
# ##############################################
#
# def _init_attributes(self, attributes):
#
# self.attributes = AttributeDictionaryInterface()
# for location, name in enumerate(attributes):
# pair = GlShaderProgramInterfaceAttribute(name, location)
# self.attributes._dictionary[name] = pair
. Output only the next line. | basic_shader_program_interface = GlShaderProgramInterface(uniform_blocks=('viewport',), |
Given the code snippet: <|code_start|> for k in range(3):
positions[j+k] = struct.unpack('<fff', stream.read(12))
stream.read(2)
# struct.unpack('<H', stream.read(2))
# stream.seek(84)
# Center the solid
for i in range(3):
positions[:,i] -= .5*(positions[:,i].max() + positions[:,i].min())
print(positions[:,0].min(), positions[:,1].min(), positions[:,2].min())
print(positions[:,0].max(), positions[:,1].max(), positions[:,2].max())
# normal, 3 vertex
# dtype = np.dtype('12<f4, <u2')
# data = np.memmap(file_handle, mode='r', dtype=dtype, shape=number_of_triangles)
# print(data[0])
self.positions = positions
self.normals = normals
##############################################
def to_vertex_array(self):
# Fixme: here ?
colour = (1, 0, 0, 1)
self.colours = np.zeros((self.positions.shape[0], 4), dtype=np.float32)
self.colours[...] = colour
<|code_end|>
, generate the next line using the imports in this file:
import mmap
import struct
import numpy as np
from .PrimitiveVertexArray import TriangleVertexArray
from PyOpenGLng.Tools.EnumFactory import EnumFactory
and context (functions, classes, or occasionally code) from other files:
# Path: PyOpenGLng/HighLevelApi/PrimitiveVertexArray.py
# class TriangleVertexArray(GlVertexArrayObject):
#
# """ Base class to draw primitives as triangles. """
#
# # Fixme: 3d
#
# ##############################################
#
# def __init__(self, items=None):
#
# super(TriangleVertexArray, self).__init__()
#
# self._number_of_items = 0
# self._positions_buffer = GlArrayBuffer()
# self._normals_buffer = GlArrayBuffer()
# self._colours_buffer = GlArrayBuffer()
#
# if items is not None:
# self.set(*items)
#
# ##############################################
#
# def set(self, positions, normals, colours):
#
# """ Set the vertex array from an iterable of triangles. """
#
# self._number_of_items = positions.shape[0]
#
# # Fixme:
# # - set from high level primitive: slow
# # - set from Numpy array: fast but check for mistake
#
# # vertex = np.zeros((self._number_of_objects, 3), dtype='f') # dtype=np.float
#
# self._positions_buffer.set(positions)
# self._normals_buffer.set(normals)
# self._colours_buffer.set(colours)
#
# ##############################################
#
# def bind_to_shader(self, shader_program_interface):
#
# """ Bind the vertex array to the shader program interface attribute.
# """
#
# # Fixme: we cannot reuse the vbo
#
# self.bind()
# shader_program_interface.position.bind_to_buffer(self._positions_buffer)
# shader_program_interface.normal.bind_to_buffer(self._normals_buffer)
# shader_program_interface.colour.bind_to_buffer(self._colours_buffer)
# self.unbind()
#
# ##############################################
#
# def draw(self):
#
# """ Draw the vertex array as lines. """
#
# self.bind()
# GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3*self._number_of_items)
# self.unbind()
#
# Path: PyOpenGLng/Tools/EnumFactory.py
# def EnumFactory(enum_name, enum_tuple):
#
# """ Return an :class:`EnumMetaClass` instance, where *enum_name* is the class name and
# *enum_tuple* is an iterable of constant's names.
# """
#
# obj_dict = {}
# obj_dict['_size'] = len(enum_tuple)
# for value, name in enumerate(enum_tuple):
# obj_dict[name] = EnumConstant(name, value)
#
# return EnumMetaClass(enum_name, (), obj_dict)
. Output only the next line. | return TriangleVertexArray((self.positions, self.normals, self.colours)) |
Predict the next line for this snippet: <|code_start|>MAJOR version denotes backwards incompatible changes (old dnf won't work with
new transaction JSON).
MINOR version denotes extending the format without breaking backwards
compatibility (old dnf can work with new transaction JSON). Forwards
compatibility needs to be handled by being able to process the old format as
well as the new one.
"""
class TransactionError(dnf.exceptions.Error):
def __init__(self, msg):
super(TransactionError, self).__init__(msg)
class TransactionReplayError(dnf.exceptions.Error):
def __init__(self, filename, errors):
"""
:param filename: The name of the transaction file being replayed
:param errors: a list of error classes or a string with an error description
"""
# store args in case someone wants to read them from a caught exception
self.filename = filename
if isinstance(errors, (list, tuple)):
self.errors = errors
else:
self.errors = [errors]
if filename:
<|code_end|>
with the help of current file imports:
import libdnf
import hawkey
import dnf.exceptions
import json
from dnf.i18n import _
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may contain function names, class names, or code. Output only the next line. | msg = _('The following problems occurred while replaying the transaction from file "{filename}":').format(filename=filename) |
Here is a snippet: <|code_start|># This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Copyright 2004 Duke University
"""
Core DNF Errors.
"""
from __future__ import unicode_literals
class DeprecationWarning(DeprecationWarning):
# :api
pass
class Error(Exception):
# :api
"""Base Error. All other Errors thrown by DNF should inherit from this.
:api
"""
def __init__(self, value=None):
super(Error, self).__init__()
<|code_end|>
. Write the next line using the current file imports:
from dnf.i18n import ucd, _, P_
import dnf.util
import libdnf
import warnings
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may include functions, classes, or code. Output only the next line. | self.value = None if value is None else ucd(value) |
Given the code snippet: <|code_start|> return '\n'.join(errstrings)
def __str__(self):
return self.errmap2str(self.errmap)
class LockError(Error):
pass
class MarkingError(Error):
# :api
def __init__(self, value=None, pkg_spec=None):
"""Initialize the marking error instance."""
super(MarkingError, self).__init__(value)
self.pkg_spec = None if pkg_spec is None else ucd(pkg_spec)
def __str__(self):
string = super(MarkingError, self).__str__()
if self.pkg_spec:
string += ': ' + self.pkg_spec
return string
class MarkingErrors(Error):
# :api
def __init__(self, no_match_group_specs=(), error_group_specs=(), no_match_pkg_specs=(),
error_pkg_specs=(), module_depsolv_errors=()):
"""Initialize the marking error instance."""
<|code_end|>
, generate the next line using the imports in this file:
from dnf.i18n import ucd, _, P_
import dnf.util
import libdnf
import warnings
and context (functions, classes, or occasionally code) from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | msg = _("Problems in request:") |
Predict the next line for this snippet: <|code_start|> def __init__(self, value=None, pkg_spec=None):
"""Initialize the marking error instance."""
super(MarkingError, self).__init__(value)
self.pkg_spec = None if pkg_spec is None else ucd(pkg_spec)
def __str__(self):
string = super(MarkingError, self).__str__()
if self.pkg_spec:
string += ': ' + self.pkg_spec
return string
class MarkingErrors(Error):
# :api
def __init__(self, no_match_group_specs=(), error_group_specs=(), no_match_pkg_specs=(),
error_pkg_specs=(), module_depsolv_errors=()):
"""Initialize the marking error instance."""
msg = _("Problems in request:")
if (no_match_pkg_specs):
msg += "\n" + _("missing packages: ") + ", ".join(no_match_pkg_specs)
if (error_pkg_specs):
msg += "\n" + _("broken packages: ") + ", ".join(error_pkg_specs)
if (no_match_group_specs):
msg += "\n" + _("missing groups or modules: ") + ", ".join(no_match_group_specs)
if (error_group_specs):
msg += "\n" + _("broken groups or modules: ") + ", ".join(error_group_specs)
if (module_depsolv_errors):
msg_mod = dnf.util._format_resolve_problems(module_depsolv_errors[0])
if module_depsolv_errors[1] == \
libdnf.module.ModulePackageContainer.ModuleErrorType_ERROR_IN_DEFAULTS:
<|code_end|>
with the help of current file imports:
from dnf.i18n import ucd, _, P_
import dnf.util
import libdnf
import warnings
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may contain function names, class names, or code. Output only the next line. | msg += "\n" + "\n".join([P_('Modular dependency problem with Defaults:', |
Given snippet: <|code_start|>
def _terminal_messenger(tp='write', msg="", out=sys.stdout):
try:
if tp == 'write':
out.write(msg)
elif tp == 'flush':
out.flush()
elif tp == 'write_flush':
out.write(msg)
out.flush()
elif tp == 'print':
print(msg, file=out)
else:
raise ValueError('Unsupported type: ' + tp)
except IOError as e:
logger.critical('{}: {}'.format(type(e).__name__, ucd(e)))
pass
def _format_resolve_problems(resolve_problems):
"""
Format string about problems in resolve
:param resolve_problems: list with list of strings (output of goal.problem_rules())
:return: string
"""
msg = ""
count_problems = (len(resolve_problems) > 1)
for i, rs in enumerate(resolve_problems, start=1):
if count_problems:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .pycomp import PY3, basestring
from dnf.i18n import _, ucd
import argparse
import dnf
import dnf.callback
import dnf.const
import dnf.pycomp
import errno
import functools
import hawkey
import itertools
import locale
import logging
import os
import pwd
import shutil
import sys
import tempfile
import time
import libdnf.repo
import libdnf.transaction
import dbus
and context:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
which might include code, classes, or functions. Output only the next line. | msg += "\n " + _("Problem") + " %d: " % i |
Based on the snippet: <|code_start|> if s.startswith(prefix):
return s[len(prefix):]
return None
def touch(path, no_create=False):
"""Create an empty file if it doesn't exist or bump it's timestamps.
If no_create is True only bumps the timestamps.
"""
if no_create or os.access(path, os.F_OK):
return os.utime(path, None)
with open(path, 'a'):
pass
def _terminal_messenger(tp='write', msg="", out=sys.stdout):
try:
if tp == 'write':
out.write(msg)
elif tp == 'flush':
out.flush()
elif tp == 'write_flush':
out.write(msg)
out.flush()
elif tp == 'print':
print(msg, file=out)
else:
raise ValueError('Unsupported type: ' + tp)
except IOError as e:
<|code_end|>
, predict the immediate next line with the help of imports:
from .pycomp import PY3, basestring
from dnf.i18n import _, ucd
import argparse
import dnf
import dnf.callback
import dnf.const
import dnf.pycomp
import errno
import functools
import hawkey
import itertools
import locale
import logging
import os
import pwd
import shutil
import sys
import tempfile
import time
import libdnf.repo
import libdnf.transaction
import dbus
and context (classes, functions, sometimes code) from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | logger.critical('{}: {}'.format(type(e).__name__, ucd(e))) |
Predict the next line after this snippet: <|code_start|> return modules, nsvcap
return (), None
def _get_latest(self, module_list):
latest = None
if module_list:
latest = module_list[0]
for module in module_list[1:]:
if module.getVersionNum() > latest.getVersionNum():
latest = module
return latest
def _create_module_dict_and_enable(self, module_list, spec, enable=True):
moduleDict = {}
for module in module_list:
moduleDict.setdefault(
module.getName(), {}).setdefault(module.getStream(), []).append(module)
for moduleName, streamDict in moduleDict.items():
moduleState = self.base._moduleContainer.getModuleState(moduleName)
if len(streamDict) > 1:
if moduleState != STATE_DEFAULT and moduleState != STATE_ENABLED \
and moduleState != STATE_DISABLED:
streams_str = "', '".join(
sorted(streamDict.keys(), key=functools.cmp_to_key(self.base.sack.evr_cmp)))
msg = _("Argument '{argument}' matches {stream_count} streams ('{streams}') of "
"module '{module}', but none of the streams are enabled or "
"default").format(
argument=spec, stream_count=len(streamDict), streams=streams_str,
module=moduleName)
<|code_end|>
using the current file's imports:
from collections import OrderedDict
from dnf.module.exceptions import EnableMultipleStreamsException
from dnf.util import logger
from dnf.i18n import _, P_, ucd
import hawkey
import libdnf.smartcols
import libdnf.module
import dnf.selector
import dnf.exceptions
import functools
and any relevant context from other files:
# Path: dnf/module/exceptions.py
# class EnableMultipleStreamsException(dnf.exceptions.Error):
# def __init__(self, module_spec, value=None):
# if value is None:
# value = _("Cannot enable more streams from module '{}' at the same time").format(module_spec)
# super(EnableMultipleStreamsException, self).__init__(value)
#
# Path: dnf/util.py
# MAIN_PROG = argparse.ArgumentParser().prog if argparse.ArgumentParser().prog == "yum" else "dnf"
# MAIN_PROG_UPPER = MAIN_PROG.upper()
# def _parse_specs(namespace, values):
# def _urlopen_progress(url, conf, progress=None):
# def _urlopen(url, conf=None, repo=None, mode='w+b', **kwargs):
# def rtrim(s, r):
# def am_i_root():
# def clear_dir(path):
# def ensure_dir(dname):
# def split_path(path):
# def empty(iterable):
# def first(iterable):
# def first_not_none(iterable):
# def file_age(fn):
# def file_timestamp(fn):
# def get_effective_login():
# def get_in(dct, keys, not_found):
# def group_by_filter(fn, iterable):
# def splitter(acc, item):
# def insert_if(item, iterable, condition):
# def is_exhausted(iterator):
# def is_glob_pattern(pattern):
# def is_string_type(obj):
# def lazyattr(attrname):
# def get_decorated(fn):
# def cached_getter(obj):
# def mapall(fn, *seq):
# def normalize_time(timestamp):
# def on_ac_power():
# def on_metered_connection():
# def partition(pred, iterable):
# def rm_rf(path):
# def split_by(iterable, condition):
# def next_subsequence(it):
# def strip_prefix(s, prefix):
# def touch(path, no_create=False):
# def _terminal_messenger(tp='write', msg="", out=sys.stdout):
# def _format_resolve_problems(resolve_problems):
# def _te_nevra(te):
# def _log_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def _sync_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __init__(self, *args, **kwds):
# def __hash__(self):
# def __init__(self, iterable):
# def __getattr__(self, what):
# def fn(*args, **kwargs):
# def call_what(v):
# def __setattr__(self, what, val):
# def setter(item):
# def _make_lists(transaction):
# def _post_transaction_output(base, transaction, action_callback):
# def _tsi_or_pkg_nevra_cmp(item1, item2):
# def _name_unset_wrapper(input_name):
# class tmpdir(object):
# class Bunch(dict):
# class MultiCallList(list):
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | raise EnableMultipleStreamsException(moduleName, msg) |
Given the code snippet: <|code_start|>
STATE_DEFAULT = libdnf.module.ModulePackageContainer.ModuleState_DEFAULT
STATE_ENABLED = libdnf.module.ModulePackageContainer.ModuleState_ENABLED
STATE_DISABLED = libdnf.module.ModulePackageContainer.ModuleState_DISABLED
STATE_UNKNOWN = libdnf.module.ModulePackageContainer.ModuleState_UNKNOWN
MODULE_TABLE_HINT = _("\n\nHint: [d]efault, [e]nabled, [x]disabled, [i]nstalled")
MODULE_INFO_TABLE_HINT = _("\n\nHint: [d]efault, [e]nabled, [x]disabled, [i]nstalled, [a]ctive")
def _profile_comparison_key(profile):
return profile.getName()
class ModuleBase(object):
# :api
def __init__(self, base):
# :api
self.base = base
def enable(self, module_specs):
# :api
no_match_specs, error_specs, solver_errors, module_dicts = \
self._resolve_specs_enable_update_sack(module_specs)
for spec, (nsvcap, module_dict) in module_dicts.items():
if nsvcap.profile:
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from dnf.module.exceptions import EnableMultipleStreamsException
from dnf.util import logger
from dnf.i18n import _, P_, ucd
import hawkey
import libdnf.smartcols
import libdnf.module
import dnf.selector
import dnf.exceptions
import functools
and context (functions, classes, or occasionally code) from other files:
# Path: dnf/module/exceptions.py
# class EnableMultipleStreamsException(dnf.exceptions.Error):
# def __init__(self, module_spec, value=None):
# if value is None:
# value = _("Cannot enable more streams from module '{}' at the same time").format(module_spec)
# super(EnableMultipleStreamsException, self).__init__(value)
#
# Path: dnf/util.py
# MAIN_PROG = argparse.ArgumentParser().prog if argparse.ArgumentParser().prog == "yum" else "dnf"
# MAIN_PROG_UPPER = MAIN_PROG.upper()
# def _parse_specs(namespace, values):
# def _urlopen_progress(url, conf, progress=None):
# def _urlopen(url, conf=None, repo=None, mode='w+b', **kwargs):
# def rtrim(s, r):
# def am_i_root():
# def clear_dir(path):
# def ensure_dir(dname):
# def split_path(path):
# def empty(iterable):
# def first(iterable):
# def first_not_none(iterable):
# def file_age(fn):
# def file_timestamp(fn):
# def get_effective_login():
# def get_in(dct, keys, not_found):
# def group_by_filter(fn, iterable):
# def splitter(acc, item):
# def insert_if(item, iterable, condition):
# def is_exhausted(iterator):
# def is_glob_pattern(pattern):
# def is_string_type(obj):
# def lazyattr(attrname):
# def get_decorated(fn):
# def cached_getter(obj):
# def mapall(fn, *seq):
# def normalize_time(timestamp):
# def on_ac_power():
# def on_metered_connection():
# def partition(pred, iterable):
# def rm_rf(path):
# def split_by(iterable, condition):
# def next_subsequence(it):
# def strip_prefix(s, prefix):
# def touch(path, no_create=False):
# def _terminal_messenger(tp='write', msg="", out=sys.stdout):
# def _format_resolve_problems(resolve_problems):
# def _te_nevra(te):
# def _log_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def _sync_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __init__(self, *args, **kwds):
# def __hash__(self):
# def __init__(self, iterable):
# def __getattr__(self, what):
# def fn(*args, **kwargs):
# def call_what(v):
# def __setattr__(self, what, val):
# def setter(item):
# def _make_lists(transaction):
# def _post_transaction_output(base, transaction, action_callback):
# def _tsi_or_pkg_nevra_cmp(item1, item2):
# def _name_unset_wrapper(input_name):
# class tmpdir(object):
# class Bunch(dict):
# class MultiCallList(list):
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | logger.info(_("Ignoring unnecessary profile: '{}/{}'").format( |
Given snippet: <|code_start|># Copyright (C) 2017-2018 Red Hat, Inc.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
STATE_DEFAULT = libdnf.module.ModulePackageContainer.ModuleState_DEFAULT
STATE_ENABLED = libdnf.module.ModulePackageContainer.ModuleState_ENABLED
STATE_DISABLED = libdnf.module.ModulePackageContainer.ModuleState_DISABLED
STATE_UNKNOWN = libdnf.module.ModulePackageContainer.ModuleState_UNKNOWN
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import OrderedDict
from dnf.module.exceptions import EnableMultipleStreamsException
from dnf.util import logger
from dnf.i18n import _, P_, ucd
import hawkey
import libdnf.smartcols
import libdnf.module
import dnf.selector
import dnf.exceptions
import functools
and context:
# Path: dnf/module/exceptions.py
# class EnableMultipleStreamsException(dnf.exceptions.Error):
# def __init__(self, module_spec, value=None):
# if value is None:
# value = _("Cannot enable more streams from module '{}' at the same time").format(module_spec)
# super(EnableMultipleStreamsException, self).__init__(value)
#
# Path: dnf/util.py
# MAIN_PROG = argparse.ArgumentParser().prog if argparse.ArgumentParser().prog == "yum" else "dnf"
# MAIN_PROG_UPPER = MAIN_PROG.upper()
# def _parse_specs(namespace, values):
# def _urlopen_progress(url, conf, progress=None):
# def _urlopen(url, conf=None, repo=None, mode='w+b', **kwargs):
# def rtrim(s, r):
# def am_i_root():
# def clear_dir(path):
# def ensure_dir(dname):
# def split_path(path):
# def empty(iterable):
# def first(iterable):
# def first_not_none(iterable):
# def file_age(fn):
# def file_timestamp(fn):
# def get_effective_login():
# def get_in(dct, keys, not_found):
# def group_by_filter(fn, iterable):
# def splitter(acc, item):
# def insert_if(item, iterable, condition):
# def is_exhausted(iterator):
# def is_glob_pattern(pattern):
# def is_string_type(obj):
# def lazyattr(attrname):
# def get_decorated(fn):
# def cached_getter(obj):
# def mapall(fn, *seq):
# def normalize_time(timestamp):
# def on_ac_power():
# def on_metered_connection():
# def partition(pred, iterable):
# def rm_rf(path):
# def split_by(iterable, condition):
# def next_subsequence(it):
# def strip_prefix(s, prefix):
# def touch(path, no_create=False):
# def _terminal_messenger(tp='write', msg="", out=sys.stdout):
# def _format_resolve_problems(resolve_problems):
# def _te_nevra(te):
# def _log_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def _sync_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __init__(self, *args, **kwds):
# def __hash__(self):
# def __init__(self, iterable):
# def __getattr__(self, what):
# def fn(*args, **kwargs):
# def call_what(v):
# def __setattr__(self, what, val):
# def setter(item):
# def _make_lists(transaction):
# def _post_transaction_output(base, transaction, action_callback):
# def _tsi_or_pkg_nevra_cmp(item1, item2):
# def _name_unset_wrapper(input_name):
# class tmpdir(object):
# class Bunch(dict):
# class MultiCallList(list):
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
which might include code, classes, or functions. Output only the next line. | MODULE_TABLE_HINT = _("\n\nHint: [d]efault, [e]nabled, [x]disabled, [i]nstalled") |
Given the code snippet: <|code_start|> install_base_query = base_no_source_query.filter(nevra_strict=install_set_artifacts)
error_specs = []
# add hot-fix packages
hot_fix_repos = [i.id for i in self.base.repos.iter_enabled() if i.module_hotfixes]
hotfix_packages = base_no_source_query.filter(
reponame=hot_fix_repos, name=install_dict.keys())
install_base_query = install_base_query.union(hotfix_packages)
for pkg_name, set_specs in install_dict.items():
query = install_base_query.filter(name=pkg_name)
if not query:
# package can also be non-modular or part of another stream
query = base_no_source_query.filter(name=pkg_name)
if not query:
for spec in set_specs:
logger.error(_("Unable to resolve argument {}").format(spec))
logger.error(_("No match for package {}").format(pkg_name))
error_specs.extend(set_specs)
continue
self.base._goal.group_members.add(pkg_name)
sltr = dnf.selector.Selector(self.base.sack)
sltr.set(pkg=query)
self.base._goal.install(select=sltr, optional=(not strict))
return install_base_query, error_specs
def format_modular_solver_errors(errors):
msg = dnf.util._format_resolve_problems(errors)
return "\n".join(
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from dnf.module.exceptions import EnableMultipleStreamsException
from dnf.util import logger
from dnf.i18n import _, P_, ucd
import hawkey
import libdnf.smartcols
import libdnf.module
import dnf.selector
import dnf.exceptions
import functools
and context (functions, classes, or occasionally code) from other files:
# Path: dnf/module/exceptions.py
# class EnableMultipleStreamsException(dnf.exceptions.Error):
# def __init__(self, module_spec, value=None):
# if value is None:
# value = _("Cannot enable more streams from module '{}' at the same time").format(module_spec)
# super(EnableMultipleStreamsException, self).__init__(value)
#
# Path: dnf/util.py
# MAIN_PROG = argparse.ArgumentParser().prog if argparse.ArgumentParser().prog == "yum" else "dnf"
# MAIN_PROG_UPPER = MAIN_PROG.upper()
# def _parse_specs(namespace, values):
# def _urlopen_progress(url, conf, progress=None):
# def _urlopen(url, conf=None, repo=None, mode='w+b', **kwargs):
# def rtrim(s, r):
# def am_i_root():
# def clear_dir(path):
# def ensure_dir(dname):
# def split_path(path):
# def empty(iterable):
# def first(iterable):
# def first_not_none(iterable):
# def file_age(fn):
# def file_timestamp(fn):
# def get_effective_login():
# def get_in(dct, keys, not_found):
# def group_by_filter(fn, iterable):
# def splitter(acc, item):
# def insert_if(item, iterable, condition):
# def is_exhausted(iterator):
# def is_glob_pattern(pattern):
# def is_string_type(obj):
# def lazyattr(attrname):
# def get_decorated(fn):
# def cached_getter(obj):
# def mapall(fn, *seq):
# def normalize_time(timestamp):
# def on_ac_power():
# def on_metered_connection():
# def partition(pred, iterable):
# def rm_rf(path):
# def split_by(iterable, condition):
# def next_subsequence(it):
# def strip_prefix(s, prefix):
# def touch(path, no_create=False):
# def _terminal_messenger(tp='write', msg="", out=sys.stdout):
# def _format_resolve_problems(resolve_problems):
# def _te_nevra(te):
# def _log_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def _sync_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __init__(self, *args, **kwds):
# def __hash__(self):
# def __init__(self, iterable):
# def __getattr__(self, what):
# def fn(*args, **kwargs):
# def call_what(v):
# def __setattr__(self, what, val):
# def setter(item):
# def _make_lists(transaction):
# def _post_transaction_output(base, transaction, action_callback):
# def _tsi_or_pkg_nevra_cmp(item1, item2):
# def _name_unset_wrapper(input_name):
# class tmpdir(object):
# class Bunch(dict):
# class MultiCallList(list):
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | [P_('Modular dependency problem:', 'Modular dependency problems:', len(errors)), msg]) |
Predict the next line for this snippet: <|code_start|> else:
stream = self.base._moduleContainer.getDefaultStream(moduleName)
if not stream or stream not in streamDict:
raise EnableMultipleStreamsException(moduleName)
for key in sorted(streamDict.keys()):
if key == stream:
if enable:
self.base._moduleContainer.enable(moduleName, key)
continue
del streamDict[key]
elif enable:
for key in streamDict.keys():
self.base._moduleContainer.enable(moduleName, key)
assert len(streamDict) == 1
return moduleDict
def _resolve_specs_enable(self, module_specs):
no_match_specs = []
error_spec = []
module_dicts = {}
for spec in module_specs:
module_list, nsvcap = self._get_modules(spec)
if not module_list:
no_match_specs.append(spec)
continue
try:
module_dict = self._create_module_dict_and_enable(module_list, spec, True)
module_dicts[spec] = (nsvcap, module_dict)
except (RuntimeError, EnableMultipleStreamsException) as e:
error_spec.append(spec)
<|code_end|>
with the help of current file imports:
from collections import OrderedDict
from dnf.module.exceptions import EnableMultipleStreamsException
from dnf.util import logger
from dnf.i18n import _, P_, ucd
import hawkey
import libdnf.smartcols
import libdnf.module
import dnf.selector
import dnf.exceptions
import functools
and context from other files:
# Path: dnf/module/exceptions.py
# class EnableMultipleStreamsException(dnf.exceptions.Error):
# def __init__(self, module_spec, value=None):
# if value is None:
# value = _("Cannot enable more streams from module '{}' at the same time").format(module_spec)
# super(EnableMultipleStreamsException, self).__init__(value)
#
# Path: dnf/util.py
# MAIN_PROG = argparse.ArgumentParser().prog if argparse.ArgumentParser().prog == "yum" else "dnf"
# MAIN_PROG_UPPER = MAIN_PROG.upper()
# def _parse_specs(namespace, values):
# def _urlopen_progress(url, conf, progress=None):
# def _urlopen(url, conf=None, repo=None, mode='w+b', **kwargs):
# def rtrim(s, r):
# def am_i_root():
# def clear_dir(path):
# def ensure_dir(dname):
# def split_path(path):
# def empty(iterable):
# def first(iterable):
# def first_not_none(iterable):
# def file_age(fn):
# def file_timestamp(fn):
# def get_effective_login():
# def get_in(dct, keys, not_found):
# def group_by_filter(fn, iterable):
# def splitter(acc, item):
# def insert_if(item, iterable, condition):
# def is_exhausted(iterator):
# def is_glob_pattern(pattern):
# def is_string_type(obj):
# def lazyattr(attrname):
# def get_decorated(fn):
# def cached_getter(obj):
# def mapall(fn, *seq):
# def normalize_time(timestamp):
# def on_ac_power():
# def on_metered_connection():
# def partition(pred, iterable):
# def rm_rf(path):
# def split_by(iterable, condition):
# def next_subsequence(it):
# def strip_prefix(s, prefix):
# def touch(path, no_create=False):
# def _terminal_messenger(tp='write', msg="", out=sys.stdout):
# def _format_resolve_problems(resolve_problems):
# def _te_nevra(te):
# def _log_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def _sync_rpm_trans_with_swdb(rpm_transaction, swdb_transaction):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __init__(self, *args, **kwds):
# def __hash__(self):
# def __init__(self, iterable):
# def __getattr__(self, what):
# def fn(*args, **kwargs):
# def call_what(v):
# def __setattr__(self, what, val):
# def setter(item):
# def _make_lists(transaction):
# def _post_transaction_output(base, transaction, action_callback):
# def _tsi_or_pkg_nevra_cmp(item1, item2):
# def _name_unset_wrapper(input_name):
# class tmpdir(object):
# class Bunch(dict):
# class MultiCallList(list):
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may contain function names, class names, or code. Output only the next line. | logger.error(ucd(e)) |
Predict the next line for this snippet: <|code_start|>#
# Copyright (C) 2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
class DeplistCommand(RepoQueryCommand):
"""
The command is alias for 'dnf repoquery --deplist'
"""
aliases = ('deplist',)
<|code_end|>
with the help of current file imports:
from dnf.i18n import _
from dnf.cli.commands.repoquery import RepoQueryCommand
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may contain function names, class names, or code. Output only the next line. | summary = _("[deprecated, use repoquery --deplist] List package's dependencies and what packages provide them") |
Given the following code snippet before the placeholder: <|code_start|> 'next',
'clean']
self.tsflags = []
self.open = True
def __del__(self):
# Automatically close the rpm transaction when the reference is lost
self.close()
def close(self):
if self.open:
self.ts.closeDB()
self.ts = None
self.open = False
def dbMatch(self, *args, **kwds):
if 'patterns' in kwds:
patterns = kwds.pop('patterns')
else:
patterns = []
mi = self.ts.dbMatch(*args, **kwds)
for (tag, tp, pat) in patterns:
mi.pattern(tag, tp, pat)
return mi
def dbCookie(self):
# dbCookie() does not support lazy opening of rpm database.
# The following line opens the database if it is not already open.
if self.ts.openDB() != 0:
<|code_end|>
, predict the next line using imports from the current file:
from dnf.i18n import _
import logging
import rpm
and context including class names, function names, and sometimes code from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | _logger.error(_('The openDB() function cannot open rpm database.')) |
Here is a snippet: <|code_start|> # Mapping from email address to b64 encoded public key or NoKey in case of proven nonexistence
_cache = {}
# type: Dict[str, Union[str, NoKey]]
@staticmethod
def _cache_hit(key_union, input_key_string):
# type: (Union[str, NoKey], str) -> Validity
"""
Compare the key in case it was found in the cache.
"""
if key_union == input_key_string:
logger.debug("Cache hit, valid key")
return Validity.VALID
elif key_union is NoKey:
logger.debug("Cache hit, proven non-existence")
return Validity.PROVEN_NONEXISTENCE
else:
logger.debug("Key in cache: {}".format(key_union))
logger.debug("Input key : {}".format(input_key_string))
return Validity.REVOKED
@staticmethod
def _cache_miss(input_key):
# type: (KeyInfo) -> Validity
"""
In case the key was not found in the cache, create an Unbound context and contact the DNS
system
"""
try:
except ImportError as e:
<|code_end|>
. Write the next line using the current file imports:
from enum import Enum
from dnf.i18n import _
import base64
import hashlib
import logging
import re
import dnf.rpm
import dnf.exceptions
import unbound
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may include functions, classes, or code. Output only the next line. | msg = _("Configuration option 'gpgkey_dns_verification' requires " |
Given the following code snippet before the placeholder: <|code_start|># This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Copyright 2003 Duke University
from __future__ import print_function, absolute_import, unicode_literals
_logger = logging.getLogger('dnf')
_rpmkeys_binary = None
def _find_rpmkeys_binary():
global _rpmkeys_binary
if _rpmkeys_binary is None:
_rpmkeys_binary = which("rpmkeys")
<|code_end|>
, predict the next line using imports from the current file:
import os
import subprocess
import logging
from shutil import which
from dnf.i18n import _
and context including class names, function names, and sometimes code from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | _logger.debug(_('Using rpmkeys executable at %s to verify signatures'), |
Given snippet: <|code_start|>from __future__ import unicode_literals
logger = logging.getLogger('dnf')
class RepoReader(object):
def __init__(self, conf, opts):
self.conf = conf
self.opts = opts
def __iter__(self):
# get the repos from the main yum.conf file
for r in self._get_repos(self.conf.config_file_path):
yield r
# read .repo files from directories specified by conf.reposdir
repo_configs = []
for reposdir in self.conf.reposdir:
for path in glob.glob(os.path.join(reposdir, "*.repo")):
repo_configs.append(path)
# remove .conf suffix before calling the sort function
# also split the path so the separators are not treated as ordinary characters
repo_configs.sort(key=lambda x: dnf.util.split_path(x[:-5]))
for repofn in repo_configs:
try:
for r in self._get_repos(repofn):
yield r
except dnf.exceptions.ConfigError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dnf.i18n import _, ucd
import dnf.conf
import libdnf.conf
import dnf.exceptions
import dnf.repo
import glob
import logging
import os
and context:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
which might include code, classes, or functions. Output only the next line. | logger.warning(_("Warning: failed loading '%s', skipping."), |
Here is a snippet: <|code_start|> # Check the repo.id against the valid chars
invalid = dnf.repo.repo_id_invalid(substituted_id)
if invalid is not None:
if substituted_id != id_:
msg = _("Bad id for repo: {} ({}), byte = {} {}").format(substituted_id, id_,
substituted_id[invalid],
invalid)
else:
msg = _("Bad id for repo: {}, byte = {} {}").format(id_, id_[invalid], invalid)
raise dnf.exceptions.ConfigError(msg)
repo = dnf.repo.Repo(substituted_id, self.conf)
try:
repo._populate(parser, id_, repofn, dnf.conf.PRIO_REPOCONFIG)
except ValueError as e:
if substituted_id != id_:
msg = _("Repository '{}' ({}): Error parsing config: {}").format(substituted_id,
id_, e)
else:
msg = _("Repository '{}': Error parsing config: {}").format(id_, e)
raise dnf.exceptions.ConfigError(msg)
# Ensure that the repo name is set
if repo._get_priority('name') == dnf.conf.PRIO_DEFAULT:
if substituted_id != id_:
msg = _("Repository '{}' ({}) is missing name in configuration, using id.").format(
substituted_id, id_)
else:
msg = _("Repository '{}' is missing name in configuration, using id.").format(id_)
logger.warning(msg)
<|code_end|>
. Write the next line using the current file imports:
from dnf.i18n import _, ucd
import dnf.conf
import libdnf.conf
import dnf.exceptions
import dnf.repo
import glob
import logging
import os
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may include functions, classes, or code. Output only the next line. | repo.name = ucd(repo.name) |
Next line prediction: <|code_start|> for i in installed:
env = i.getCompsEnvironmentItem()
if not env:
continue
result.add(env.getEnvironmentId())
return result
def get(self, *patterns):
res = dnf.util.Bunch()
res.environments = []
res.groups = []
for pat in patterns:
envs = grps = []
if self.kinds & self.ENVIRONMENTS:
available = self.comps.environments_by_pattern(pat)
installed = self.history.env.search_by_pattern(pat)
envs = self._get_envs(available, installed)
res.environments.extend(envs)
if self.kinds & self.GROUPS:
available = self.comps.groups_by_pattern(pat)
installed = self.history.group.search_by_pattern(pat)
grps = self._get_groups(available, installed)
res.groups.extend(grps)
if not envs and not grps:
if self.status == self.INSTALLED:
msg = _("Module or Group '%s' is not installed.") % ucd(pat)
elif self.status == self.AVAILABLE:
msg = _("Module or Group '%s' is not available.") % ucd(pat)
else:
msg = _("Module or Group '%s' does not exist.") % ucd(pat)
<|code_end|>
. Use current file imports:
(import libdnf.transaction
import dnf.i18n
import dnf.util
import fnmatch
import gettext
import itertools
import libcomps
import locale
import logging
import operator
import re
import sys
from dnf.exceptions import CompsError
from dnf.i18n import _, ucd
from functools import reduce)
and context including class names, function names, or small code snippets from other files:
# Path: dnf/exceptions.py
# class CompsError(Error):
# # :api
# pass
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | raise CompsError(msg) |
Based on the snippet: <|code_start|> def _get_envs(self, available, installed):
result = set()
if self.status & self.AVAILABLE:
result.update({i.id for i in available})
if self.status & self.INSTALLED:
for i in installed:
env = i.getCompsEnvironmentItem()
if not env:
continue
result.add(env.getEnvironmentId())
return result
def get(self, *patterns):
res = dnf.util.Bunch()
res.environments = []
res.groups = []
for pat in patterns:
envs = grps = []
if self.kinds & self.ENVIRONMENTS:
available = self.comps.environments_by_pattern(pat)
installed = self.history.env.search_by_pattern(pat)
envs = self._get_envs(available, installed)
res.environments.extend(envs)
if self.kinds & self.GROUPS:
available = self.comps.groups_by_pattern(pat)
installed = self.history.group.search_by_pattern(pat)
grps = self._get_groups(available, installed)
res.groups.extend(grps)
if not envs and not grps:
if self.status == self.INSTALLED:
<|code_end|>
, predict the immediate next line with the help of imports:
import libdnf.transaction
import dnf.i18n
import dnf.util
import fnmatch
import gettext
import itertools
import libcomps
import locale
import logging
import operator
import re
import sys
from dnf.exceptions import CompsError
from dnf.i18n import _, ucd
from functools import reduce
and context (classes, functions, sometimes code) from other files:
# Path: dnf/exceptions.py
# class CompsError(Error):
# # :api
# pass
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | msg = _("Module or Group '%s' is not installed.") % ucd(pat) |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
logger = logging.getLogger("dnf")
# :api :binformat
CONDITIONAL = libdnf.transaction.CompsPackageType_CONDITIONAL
DEFAULT = libdnf.transaction.CompsPackageType_DEFAULT
MANDATORY = libdnf.transaction.CompsPackageType_MANDATORY
OPTIONAL = libdnf.transaction.CompsPackageType_OPTIONAL
ALL_TYPES = CONDITIONAL | DEFAULT | MANDATORY | OPTIONAL
def _internal_comps_length(comps):
collections = (comps.categories, comps.groups, comps.environments)
return reduce(operator.__add__, map(len, collections))
def _first_if_iterable(seq):
if seq is None:
return None
return dnf.util.first(seq)
def _by_pattern(pattern, case_sensitive, sqn):
"""Return items from sqn matching either exactly or glob-wise."""
<|code_end|>
with the help of current file imports:
import libdnf.transaction
import dnf.i18n
import dnf.util
import fnmatch
import gettext
import itertools
import libcomps
import locale
import logging
import operator
import re
import sys
from dnf.exceptions import CompsError
from dnf.i18n import _, ucd
from functools import reduce
and context from other files:
# Path: dnf/exceptions.py
# class CompsError(Error):
# # :api
# pass
#
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
, which may contain function names, class names, or code. Output only the next line. | pattern = dnf.i18n.ucd(pattern) |
Continue the code snippet: <|code_start|> self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
class ErrorTransactionDisplay(TransactionDisplay):
"""An RPMTransaction display that prints errors to standard output."""
def error(self, message):
super(ErrorTransactionDisplay, self).error(message)
dnf.util._terminal_messenger('print', message, sys.stderr)
class LoggingTransactionDisplay(TransactionDisplay):
'''
Base class for a RPMTransaction display callback class
'''
def __init__(self):
super(LoggingTransactionDisplay, self).__init__()
self.rpm_logger = logging.getLogger('dnf.rpm')
def error(self, message):
self.rpm_logger.error(message)
def filelog(self, package, action):
action_str = dnf.transaction.FILE_ACTIONS[action]
msg = '%s: %s' % (action_str, package)
self.rpm_logger.log(dnf.logging.SUBDEBUG, msg)
def scriptout(self, msgs):
if msgs:
<|code_end|>
. Use current file imports:
import libdnf.transaction
import dnf.callback
import dnf.transaction
import dnf.util
import rpm
import os
import logging
import sys
import tempfile
import traceback
import warnings
from dnf.i18n import _, ucd
and context (classes, functions, or code) from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | self.rpm_logger.info(ucd(msgs)) |
Given the following code snippet before the placeholder: <|code_start|># 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# The current implementation is storing to files in persistdir. Do not depend on
# specific files existing, instead use the persistor API. The underlying
# implementation can change, e.g. for one general file with a serialized dict of
# data etc.
from __future__ import absolute_import
from __future__ import unicode_literals
logger = logging.getLogger("dnf")
class JSONDB(object):
def _check_json_db(self, json_path):
if not os.path.isfile(json_path):
# initialize new db
dnf.util.ensure_dir(os.path.dirname(json_path))
self._write_json_db(json_path, [])
def _get_json_db(self, json_path, default=[]):
with open(json_path, 'r') as f:
content = f.read()
if content == "":
# empty file is invalid json format
<|code_end|>
, predict the next line using imports from the current file:
from dnf.i18n import _
import dnf.util
import errno
import fnmatch
import json
import logging
import os
import re
and context including class names, function names, and sometimes code from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
. Output only the next line. | logger.warning(_("%s is empty file"), json_path) |
Continue the code snippet: <|code_start|> lst_length = len(lst)
right_count = cols_count - 1
missing_items = -lst_length % right_count
if not lst_length:
lst = itertools.repeat('', right_count)
elif missing_items:
lst.extend(('',) * missing_items)
lst_iter = iter(lst)
return list(zip(left, *[lst_iter] * right_count))
class Output(object):
"""Main output class for the yum command line."""
GRP_PACKAGE_INDENT = ' ' * 3
FILE_PROVIDE_RE = re.compile(r'^\*{0,2}/')
def __init__(self, base, conf):
self.conf = conf
self.base = base
self.term = dnf.cli.term.Term()
self.progress = None
def _banner(self, col_data, row):
term_width = self.term.columns
rule = '%s' % '=' * term_width
header = self.fmtColumns(zip(row, col_data), ' ')
return rule, header, rule
def _col_widths(self, rows):
<|code_end|>
. Use current file imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context (classes, functions, or code) from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
. Output only the next line. | col_data = [dict() for _ in rows[0]] |
Given the code snippet: <|code_start|> """
name = ucd(name)
cols = self.term.columns - 2
name_len = exact_width(name)
if name_len >= (cols - 4):
beg = end = fill * 2
else:
beg = fill * ((cols - name_len) // 2)
end = fill * (cols - name_len - len(beg))
return "%s %s %s" % (beg, name, end)
def infoOutput(self, pkg, highlight=False):
"""Print information about the given package.
:param pkg: the package to print information about
:param highlight: highlighting options for the name of the
package
"""
def format_key_val(key, val):
return " ".join([fill_exact_width(key, 12, 12), ":", str(val)])
def format_key_val_fill(key, val):
return self.fmtKeyValFill(fill_exact_width(key, 12, 12) + " : ", val or "")
output_list = []
(hibeg, hiend) = self._highlight(highlight)
# Translators: This is abbreviated 'Name'. Should be no longer
# than 12 characters. You can use the full version if it is short
# enough in your language.
<|code_end|>
, generate the next line using the imports in this file:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context (functions, classes, or occasionally code) from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
. Output only the next line. | key = select_short_long(12, C_("short", "Name"), |
Given snippet: <|code_start|> for obspo in sorted(obsoletes):
appended = ' ' + _('replacing') + ' %s%s%s.%s %s\n'
appended %= (hibeg, obspo.name, hiend, obspo.arch, obspo.evr)
msg += appended
totalmsg = totalmsg + msg
if lines:
out.append(totalmsg)
out.append(_("""
Transaction Summary
%s
""") % ('=' * output_width))
summary_data = (
(_('Install'), len(list_bunch.installed) +
len(list_bunch.installed_group) +
len(list_bunch.installed_weak) +
len(list_bunch.installed_dep), 0),
(_('Upgrade'), len(list_bunch.upgraded), 0),
(_('Remove'), len(list_bunch.erased) + len(list_bunch.erased_dep) +
len(list_bunch.erased_clean), 0),
(_('Downgrade'), len(list_bunch.downgraded), 0),
(_('Skip'), len(skipped_conflicts) + len(skipped_broken), 0))
max_msg_action = 0
max_msg_count = 0
max_msg_pkgs = 0
max_msg_depcount = 0
for action, count, depcount in summary_data:
if not count and not depcount:
continue
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
which might include code, classes, or functions. Output only the next line. | msg_pkgs = P_('Package', 'Packages', count) |
Using the snippet: <|code_start|> continue
columns[d] += norm
total_width -= norm
# Split the remaining spaces among each column equally, except the
# last one. And put the rest into the remainder column
cols -= 1
norm = total_width // cols
for d in xrange(0, cols):
columns[d] += norm
columns[remainder_column] += total_width - (cols * norm)
total_width = 0
return columns
@staticmethod
def _fmt_column_align_width(width):
"""Returns tuple of (align_left, width)"""
if width < 0:
return (True, -width)
return (False, width)
def _col_data(self, col_data):
assert len(col_data) == 2 or len(col_data) == 3
if len(col_data) == 2:
(val, width) = col_data
hibeg = hiend = ''
if len(col_data) == 3:
(val, width, highlight) = col_data
(hibeg, hiend) = self._highlight(highlight)
<|code_end|>
, determine the next line of code. You have imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context (class names, function names, or code) available:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
. Output only the next line. | return (ucd(val), width, hibeg, hiend) |
Here is a snippet: <|code_start|> """
columns = list(columns)
total_width = len(msg)
data = []
for col_data in columns[:-1]:
(val, width, hibeg, hiend) = self._col_data(col_data)
if not width: # Don't count this column, invisible text
msg += u"%s"
data.append(val)
continue
(align_left, width) = self._fmt_column_align_width(width)
val_width = exact_width(val)
if val_width <= width:
# Don't use fill_exact_width() because it sucks performance
# wise for 1,000s of rows. Also allows us to use len(), when
# we can.
msg += u"%s%s%s%s "
if align_left:
data.extend([hibeg, val, " " * (width - val_width), hiend])
else:
data.extend([hibeg, " " * (width - val_width), val, hiend])
else:
msg += u"%s%s%s\n" + " " * (total_width + width + 1)
data.extend([hibeg, val, hiend])
total_width += width
total_width += 1
(val, width, hibeg, hiend) = self._col_data(columns[-1])
(align_left, width) = self._fmt_column_align_width(width)
<|code_end|>
. Write the next line using the current file imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
, which may include functions, classes, or code. Output only the next line. | val = fill_exact_width(val, width, left=align_left, |
Given the following code snippet before the placeholder: <|code_start|> columns = zip((envra, rid), columns, hi_cols)
print(self.fmtColumns(columns))
def simple_name_list(self, pkg):
"""Print a package as a line containing its name."""
print(ucd(pkg.name))
def simple_nevra_list(self, pkg):
"""Print a package as a line containing its NEVRA."""
print(ucd(pkg))
def fmtKeyValFill(self, key, val):
"""Return a key value pair in the common two column output
format.
:param key: the key to be formatted
:param val: the value associated with *key*
:return: the key value pair formatted in two columns for output
"""
keylen = exact_width(key)
cols = self.term.real_columns
if not cols:
cols = sys_maxsize
elif cols < 20:
cols = 20
nxt = ' ' * (keylen - 2) + ': '
if not val:
# textwrap.fill in case of empty val returns empty string
return key
val = ucd(val)
<|code_end|>
, predict the next line using imports from the current file:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context including class names, function names, and sometimes code from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
. Output only the next line. | ret = textwrap_fill(val, width=cols, initial_indent=key, |
Next line prediction: <|code_start|> # | four |
# ...than:
# |one two three|
# | f|
# |our |
# ...the later being what we get if we pre-allocate the last column, and
# thus. the space, due to "three" overflowing it's column by 2 chars.
if columns is None:
columns = [1] * (cols - 1)
columns.append(0)
# i'm not able to get real terminal width so i'm probably
# running in non interactive terminal (pipe to grep, redirect to file...)
# avoid splitting lines to enable filtering output
if not total_width:
full_columns = []
for d in xrange(0, cols):
col = data[d]
if col:
full_columns.append(col[-1][0])
else:
full_columns.append(columns[d] + 1)
full_columns[0] += len(indent)
# if possible, try to keep default width (usually 80 columns)
default_width = self.term.columns
if sum(full_columns) > default_width:
return full_columns
total_width = default_width
<|code_end|>
. Use current file imports:
(import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper)
and context including class names, function names, or small code snippets from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
. Output only the next line. | total_width -= (sum(columns) + (cols - 1) + exact_width(indent)) |
Predict the next line for this snippet: <|code_start|> """
name = ucd(name)
cols = self.term.columns - 2
name_len = exact_width(name)
if name_len >= (cols - 4):
beg = end = fill * 2
else:
beg = fill * ((cols - name_len) // 2)
end = fill * (cols - name_len - len(beg))
return "%s %s %s" % (beg, name, end)
def infoOutput(self, pkg, highlight=False):
"""Print information about the given package.
:param pkg: the package to print information about
:param highlight: highlighting options for the name of the
package
"""
def format_key_val(key, val):
return " ".join([fill_exact_width(key, 12, 12), ":", str(val)])
def format_key_val_fill(key, val):
return self.fmtKeyValFill(fill_exact_width(key, 12, 12) + " : ", val or "")
output_list = []
(hibeg, hiend) = self._highlight(highlight)
# Translators: This is abbreviated 'Name'. Should be no longer
# than 12 characters. You can use the full version if it is short
# enough in your language.
<|code_end|>
with the help of current file imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context from other files:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
, which may contain function names, class names, or code. Output only the next line. | key = select_short_long(12, C_("short", "Name"), |
Given snippet: <|code_start|> logger.debug(_('--> Finished dependency resolution'))
class CliKeyImport(dnf.callback.KeyImport):
def __init__(self, base, output):
self.base = base
self.output = output
def _confirm(self, id, userid, fingerprint, url, timestamp):
def short_id(id):
rj = '0' if dnf.pycomp.PY3 else b'0'
return id[-8:].rjust(8, rj)
msg = (_('Importing GPG key 0x%s:\n'
' Userid : "%s"\n'
' Fingerprint: %s\n'
' From : %s') %
(short_id(id), userid,
dnf.crypto._printable_fingerprint(fingerprint),
url.replace("file://", "")))
logger.critical("%s", msg)
if self.base.conf.assumeyes:
return True
if self.base.conf.assumeno:
return False
return self.output.userconfirm()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import fnmatch
import hawkey
import itertools
import libdnf.transaction
import logging
import operator
import pwd
import re
import sys
import time
import dnf.base
import dnf.callback
import dnf.cli.progress
import dnf.cli.term
import dnf.conf
import dnf.crypto
import dnf.i18n
import dnf.transaction
import dnf.util
import dnf.yum.misc
from dnf.cli.format import format_number, format_time
from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long
from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize
from dnf.yum.rpmtrans import TransactionDisplay
from dnf.db.history import MergedTransactionWrapper
and context:
# Path: dnf/i18n.py
# class UnicodeStream(object):
# def __init__(self, stream, encoding):
# def write(self, s):
# def __getattr__(self, name):
# def _full_ucd_support(encoding):
# def _guess_encoding():
# def setup_locale():
# def setup_stdout():
# def ucd_input(ucstring):
# def ucd(obj):
# def _exact_width_char(uchar):
# def chop_str(msg, chop=None):
# def exact_width(msg):
# def fill_exact_width(msg, fill, chop=None, left=True, prefix='', suffix=''):
# def textwrap_fill(text, width=70, initial_indent='', subsequent_indent=''):
# def _indent_at_beg(line):
# def select_short_long(width, msg_short, msg_long):
# def translation(name):
# def ucd_wrapper(fnc):
# def pgettext(context, message):
# _, P_ = translation("dnf")
# C_ = pgettext
#
# Path: dnf/yum/rpmtrans.py
# class TransactionDisplay(object):
# # :api
#
# def __init__(self):
# # :api
# pass
#
# # use constants from dnf.callback which are the official API
# PKG_CLEANUP = _add_deprecated_action("PKG_CLEANUP")
# PKG_DOWNGRADE = _add_deprecated_action("PKG_DOWNGRADE")
# PKG_REMOVE = _add_deprecated_action("PKG_REMOVE")
# PKG_ERASE = PKG_REMOVE
# PKG_INSTALL = _add_deprecated_action("PKG_INSTALL")
# PKG_OBSOLETE = _add_deprecated_action("PKG_OBSOLETE")
# PKG_REINSTALL = _add_deprecated_action("PKG_REINSTALL")
# PKG_UPGRADE = _add_deprecated_action("PKG_UPGRADE")
# PKG_VERIFY = _add_deprecated_action("PKG_VERIFY")
# TRANS_PREPARATION = _add_deprecated_action("TRANS_PREPARATION")
# PKG_SCRIPTLET = _add_deprecated_action("PKG_SCRIPTLET")
# TRANS_POST = _add_deprecated_action("TRANS_POST")
#
# def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
# """Report ongoing progress on a transaction item. :api
#
# :param package: a package being processed
# :param action: the action being performed
# :param ti_done: number of processed bytes of the transaction
# item being processed
# :param ti_total: total number of bytes of the transaction item
# being processed
# :param ts_done: number of actions processed in the whole
# transaction
# :param ts_total: total number of actions in the whole
# transaction
#
# """
# pass
#
# def scriptout(self, msgs):
# """Hook for reporting an rpm scriptlet output.
#
# :param msgs: the scriptlet output
# """
# pass
#
# def error(self, message):
# """Report an error that occurred during the transaction. :api"""
# pass
#
# def filelog(self, package, action):
# # check package object type - if it is a string - just output it
# """package is the same as in progress() - a package object or simple
# string action is also the same as in progress()"""
# pass
#
# def verify_tsi_package(self, pkg, count, total):
# # TODO: replace with verify_tsi?
# self.progress(pkg, dnf.transaction.PKG_VERIFY, 100, 100, count, total)
which might include code, classes, or functions. Output only the next line. | class CliTransactionDisplay(TransactionDisplay): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.