Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> def isBeatmap(fileName=None, content=None): if fileName is not None: with open(fileName, "rb") as f: firstLine = f.readline().decode("utf-8-sig").strip() elif content is not None: try: <|code_end|> . Write the next line using the current file imports: import os from common import generalUtils from common.log import logUtils as log from constants import exceptions from helpers import osuapiHelper from objects import glob and context from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/osuapiHelper.py # def osuApiRequest(request, params, getFirst=True): # def getOsuFileFromName(fileName): # def getOsuFileFromID(beatmapID): # URL = "{}/web/maps/{}".format(glob.conf["OSU_API_URL"], quote(fileName)) # URL = "{}/osu/{}".format(glob.conf["OSU_API_URL"], beatmapID) # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" , which may include functions, classes, or code. Output only the next line.
firstLine = content.decode("utf-8-sig").split("\n")[0].strip()
Based on the snippet: <|code_start|> MODULE_NAME = "ez" stats = { "latency": { gameModes.STD: { "classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1") }, gameModes.TAIKO: { "classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="taiko", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="taiko", relax="1") } }, <|code_end|> , predict the immediate next line with the help of imports: import contextlib import oppai from common.constants import gameModes, mods from common.log import logUtils as log from constants import exceptions from helpers import mapsHelper from objects import glob and context (classes, functions, sometimes code) from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" . Output only the next line.
"failures": {
Given the following code snippet before the placeholder: <|code_start|> MODULE_NAME = "ez" stats = { "latency": { gameModes.STD: { "classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1") }, gameModes.TAIKO: { "classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="taiko", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="taiko", relax="1") } }, "failures": { gameModes.STD: { "classic": glob.stats["pp_calc_failures"].labels(game_mode="std", relax="0"), "relax": glob.stats["pp_calc_failures"].labels(game_mode="std", relax="1") }, gameModes.TAIKO: { "classic": glob.stats["pp_calc_failures"].labels(game_mode="taiko", relax="0"), "relax": glob.stats["pp_calc_failures"].labels(game_mode="taiko", relax="1") } } <|code_end|> , predict the next line using imports from the current file: import contextlib import oppai from common.constants import gameModes, mods from common.log import logUtils as log from constants import exceptions from helpers import mapsHelper from objects import glob and context including class names, function names, and sometimes code from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" . Output only the next line.
}
Given the code snippet: <|code_start|> MODULE_NAME = "ez" stats = { "latency": { gameModes.STD: { "classic": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="std", relax="1") }, <|code_end|> , generate the next line using the imports in this file: import contextlib import oppai from common.constants import gameModes, mods from common.log import logUtils as log from constants import exceptions from helpers import mapsHelper from objects import glob and context (functions, classes, or occasionally code) from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" . Output only the next line.
gameModes.TAIKO: {
Predict the next line for this snippet: <|code_start|> stats = { "latency": { "classic":glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="1") }, "failures": { "classic": glob.stats["pp_calc_failures"].labels(game_mode="ctb", relax="0"), "relax": glob.stats["pp_calc_failures"].labels(game_mode="ctb", relax="1"), } <|code_end|> with the help of current file imports: import contextlib from common.log import logUtils as log from common.constants import gameModes, mods from constants import exceptions from helpers import mapsHelper from objects import glob from pp.catch_the_pp.osu_parser.beatmap import Beatmap as CalcBeatmap from pp.catch_the_pp.osu.ctb.difficulty import Difficulty from pp.catch_the_pp import ppCalc and context from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" , which may contain function names, class names, or code. Output only the next line.
}
Predict the next line for this snippet: <|code_start|> mapFile = mapsHelper.cachedMapPath(self.beatmap.beatmapID) mapsHelper.cacheMap(mapFile, self.beatmap) # TODO: Sanizite mods # Gamemode check if self.score is not None and self.score.gameMode != gameModes.CTB: raise exceptions.unsupportedGameModeException() # Calculate difficulty calcBeatmap = CalcBeatmap(mapFile) difficulty = Difficulty(beatmap=calcBeatmap, mods=self.unrelaxMods) self.stars = difficulty.star_rating # Calculate pp if self.tillerino: results = [] for acc in (1, 0.99, 0.98, 0.95): results.append(ppCalc.calculate_pp( diff=difficulty, accuracy=acc, combo=self.combo if self.combo >= 0 else calcBeatmap.max_combo, miss=self.misses )) self.pp = results else: # Accuracy check if self.accuracy > 1: raise ValueError("Accuracy must be between 0 and 1") self.pp = ppCalc.calculate_pp( <|code_end|> with the help of current file imports: import contextlib from common.log import logUtils as log from common.constants import gameModes, mods from constants import exceptions from helpers import mapsHelper from objects import glob from pp.catch_the_pp.osu_parser.beatmap import Beatmap as CalcBeatmap from pp.catch_the_pp.osu.ctb.difficulty import Difficulty from pp.catch_the_pp import ppCalc and context from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" , which may contain function names, class names, or code. Output only the next line.
diff=difficulty,
Next line prediction: <|code_start|>stats = { "latency": { "classic":glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="0"), "relax": glob.stats["pp_calc_latency_seconds"].labels(game_mode="ctb", relax="1") }, "failures": { "classic": glob.stats["pp_calc_failures"].labels(game_mode="ctb", relax="0"), "relax": glob.stats["pp_calc_failures"].labels(game_mode="ctb", relax="1"), } } class Cicciobello: def __init__(self, beatmap_, score_=None, accuracy=1, mods_=mods.NOMOD, combo=None, misses=0, tillerino=False): # Beatmap is always present self.beatmap = beatmap_ # If passed, set everything from score object self.score = None if score_ is not None: self.score = score_ self.accuracy = self.score.accuracy self.mods = self.score.mods self.combo = self.score.maxCombo self.misses = self.score.cMiss else: # Otherwise, set acc and mods from params (tillerino) self.accuracy = accuracy self.mods = mods_ self.combo = combo <|code_end|> . Use current file imports: (import contextlib from common.log import logUtils as log from common.constants import gameModes, mods from constants import exceptions from helpers import mapsHelper from objects import glob from pp.catch_the_pp.osu_parser.beatmap import Beatmap as CalcBeatmap from pp.catch_the_pp.osu.ctb.difficulty import Difficulty from pp.catch_the_pp import ppCalc) and context including class names, function names, or small code snippets from other files: # Path: constants/exceptions.py # class invalidArgumentsException(Exception): # class loginFailedException(Exception): # class userBannedException(Exception): # class userLockedException(Exception): # class noBanchoSessionException(Exception): # class osuApiFailException(Exception): # class fileNotFoundException(Exception): # class invalidBeatmapException(Exception): # class unsupportedGameModeException(Exception): # class beatmapTooLongException(Exception): # class need2FAException(Exception): # class noAPIDataError(Exception): # class scoreNotFoundError(Exception): # class ppCalcException(Exception): # def __init__(self, handler): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who): # def __init__(self, handler, who, ip): # def __init__(self, handler): # def __init__(self, handler, f): # def __init__(self, handler): # def __init__(self, handler, who, ip): # def __init__(self, exception): # # Path: helpers/mapsHelper.py # def isBeatmap(fileName=None, content=None): # def shouldDownloadMap(mapFile, _beatmap): # def cacheMap(mapFile, _beatmap): # def cachedMapPath(beatmap_id): # # Path: objects/glob.py # VERSION = f.read().strip() # VERSION = "Unknown" # ACHIEVEMENTS_VERSION = 1 # DATADOG_PREFIX = "lets" . Output only the next line.
if self.combo is None or self.combo < 0:
Given snippet: <|code_start|> class Data(): pass def _resolveRefs(symdict, arg): gens = _flatten(arg) data = Data() data.symdict = symdict v = _AttrRefTransformer(data) <|code_end|> , continue by predicting the next line. Consider current file imports: import ast import itertools from types import FunctionType from myhdl._util import _flatten from myhdl._enum import EnumType from myhdl._Signal import SignalType and context: # Path: myhdl/_Signal.py # def _isListOfSigs(obj): # def purge(self): # def __init__(self, sig): # def _toVerilog(self): # def _toVHDL(self): # def __init__(self, sig): # def _toVerilog(self): # def _toVHDL(self): # def posedge(sig): # def negedge(sig): # def Signal(val=None, delay=None): # def __init__(self, val=None): # def _clear(self): # def _update(self): # def val(self): # def next(self): # def next(self, val): # def posedge(self): # def negedge(self): # def max(self): # def min(self): # def driven(self): # def driven(self, val): # def read(self): # def read(self, val): # def _markRead(self): # def _markUsed(self): # def _setNextBool(self, val): # def _setNextInt(self, val): # def _setNextIntbv(self, val): # def _setNextNonmutable(self, val): # def _setNextMutable(self, val): # def _printVcdStr(self): # def _printVcdHex(self): # def _printVcdBit(self): # def _printVcdVec(self): # def __call__(self, left, right=None): # def __hash__(self): # def __bool__(self): # def __len__(self): # def __getitem__(self, key): # def __add__(self, other): # def __radd__(self, other): # def __sub__(self, other): # def __rsub__(self, other): # def __mul__(self, other): # def __rmul__(self, other): # def __truediv__(self, other): # def __rtruediv__(self, other): # def __floordiv__(self, other): # def __rfloordiv__(self, other): # def __mod__(self, other): # def __rmod__(self, other): # def __pow__(self, other): # def __rpow__(self, other): # def __lshift__(self, other): # def __rlshift__(self, other): # def __rshift__(self, other): # def __rrshift__(self, other): # def __and__(self, other): # def __rand__(self, other): # def __or__(self, other): # def __ror__(self, other): # def __xor__(self, other): # def __rxor__(self, other): # def __neg__(self): # def __pos__(self): # def __abs__(self): # def __invert__(self): # def __int__(self): # def __long__(self): # def __float__(self): # def __oct__(self): # def __hex__(self): # def __index__(self): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __getattr__(self, attr): # def __str__(self): # def __repr__(self): # def _toVerilog(self): # def _augm(self): # def __setitem__(self, key, val): # def assign(self, sig): # def genFunc(): # def toVHDL(): # def toVerilog(): # def __init__(self, val=None, delay=1): # def _update(self): # def _apply(self, next, timeStamp): # def delay(self): # def delay(self, delay): # def __init__(self, sig, next, timeStamp): # def apply(self): # class _WaiterList(list): # class _PosedgeWaiterList(_WaiterList): # class _NegedgeWaiterList(_WaiterList): # class _Signal(object): # class _DelayedSignal(_Signal): # class _SignalWrap(object): which might include code, classes, or functions. Output only the next line.
for gen in gens:
Given the following code snippet before the placeholder: <|code_start|> def test_auc_for_one_positive(): assert auc_for_one_positive(1, [0, 2]) == 0.5 assert auc_for_one_positive(1, [1]) == 0.5 assert auc_for_one_positive(3, [0]) == 1.0 assert auc_for_one_positive(0, [3]) == 0.0 <|code_end|> , predict the next line using imports from the current file: from hypothesis import given, strategies as st from pysaliency.numba_utils import auc_for_one_positive from pysaliency.roc import general_roc import numpy as np and context including class names, function names, and sometimes code from other files: # Path: pysaliency/numba_utils.py # def auc_for_one_positive(positive, negatives): # """ Computes the AUC score of one single positive sample agains many negatives. # # The result is equal to general_roc([positive], negatives)[0], but computes much # faster because one can save sorting the negatives. # """ # return _auc_for_one_positive(positive, np.asarray(negatives)) . Output only the next line.
@given(st.lists(st.floats(allow_nan=False, allow_infinity=False), min_size=1), st.floats(allow_nan=False, allow_infinity=False))
Given snippet: <|code_start|>from __future__ import print_function, division, absolute_import, unicode_literals def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None): xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst) <|code_end|> , continue by predicting the next line. Consider current file imports: from tqdm import tqdm from scipy.ndimage import gaussian_filter from scipy.special import logsumexp from .models import sample_from_logdensity from .tf_utils import gauss_blur import numpy as np import tensorflow as tf and context: # Path: pysaliency/models.py # def sample_from_logdensity(log_density, count=None, rst=None): # if count is None: # real_count = 1 # else: # real_count = count # # height, width = log_density.shape # flat_log_density = log_density.flatten(order='C') # samples = sample_from_logprobabilities(flat_log_density, size=real_count, rst=rst) # sample_xs = samples % width # sample_ys = samples // width # # if count is None: # return sample_xs[0], sample_ys[0] # else: # return np.asarray(sample_xs), np.asarray(sample_ys) # # Path: pysaliency/tf_utils.py # @slim.add_arg_scope # def gauss_blur(inputs, sigma, windowradius=5, mode='NEAREST', scope=None, # outputs_collections=None): # with tf.name_scope(scope, 'gauss_blur', [inputs, sigma, windowradius]) as sc: # # outputs = inputs # # for axis in [0, 1]: # # outputs = gaussian_convolution_along_axis(outputs, # axis=axis, # sigma=sigma, # windowradius=windowradius, # mode=mode) # return outputs # # return slim.utils.collect_named_outputs(outputs_collections, sc, outputs) which might include code, classes, or functions. Output only the next line.
ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image)
Given the code snippet: <|code_start|> assert skew(fixations_val.x) == approx(0.11714467225615313) assert skew(fixations_val.y) == approx(0.12631245881037118) assert skew(fixations_val.t) == approx(1.8301317514860862) assert skew(fixations_val.lengths) == approx(0.0) assert entropy(fixations_val.n) == approx(12.234936723301066) assert (fixations_val.n == 0).sum() == 259 @pytest.mark.slow @pytest.mark.download def test_SALICON_fixations_2017_mouse(tmpdir): real_location = str(tmpdir) location = tmpdir fixations_train, fixations_val = pysaliency.external_datasets._get_SALICON_fixations( location=real_location, name='SALICONbar', edition='2017', fixation_type='mouse') assert location.join('SALICONbar/fixations_train.hdf5').check() assert location.join('SALICONbar/fixations_val.hdf5').check() assert len(fixations_train.x) == 215286274 assert np.mean(fixations_train.x) == approx(314.91750797871686) assert np.mean(fixations_train.y) == approx(232.38085973332957) assert np.mean(fixations_train.t) == approx(2541.6537073654777) assert np.mean(fixations_train.lengths) == approx(0.0) assert np.std(fixations_train.x) == approx(138.09403491170718) <|code_end|> , generate the next line using the imports in this file: import pytest import unittest import numpy as np import pysaliency import pysaliency.external_datasets from pytest import approx from scipy.stats import kurtosis, skew from pysaliency.utils import remove_trailing_nans and context (functions, classes, or occasionally code) from other files: # Path: pysaliency/utils.py # def remove_trailing_nans(data): # """Filters a scanpath arrays to remove the ending part of nans.""" # for i in range(len(data)): # if np.all(np.isnan(data[i:])): # return data[:i] # return data . Output only the next line.
assert np.std(fixations_train.y) == approx(93.55417139372516)
Here is a snippet: <|code_start|> class TestPatchFile(TestWithData): def test_parsing(self): p = open('tests/test_quilt/patches/add_numbers.diff').read() patch = PatchFile(p) self.assertEqual(len(patch.diffs), 1) diff = patch.diffs[0] self.assertEqual(len(diff.hunks), 1) self.assertEqual(diff.source_filename, 'source.txt') self.assertEqual(diff.target_filename, 'source.txt') hunk = diff.hunks[0] self.assertEqual(hunk.source_start, 3) self.assertEqual(hunk.source_length, 6) self.assertEqual(hunk.target_start, 3) self.assertEqual(hunk.target_length, 8) def test_apply(self): location = os.path.join(self.data_path, 'patching') shutil.copytree('tests/test_quilt/source', location) p = open('tests/test_quilt/patches/add_numbers.diff').read() patch = PatchFile(p) patch.apply(location) self.assertTrue(filecmp.cmp(os.path.join(location, 'source.txt'), 'tests/test_quilt/target/source.txt', <|code_end|> . Write the next line using the current file imports: import os import shutil import filecmp import unittest from pysaliency.quilt import PatchFile, QuiltSeries from test_helpers import TestWithData, assertDirsEqual and context from other files: # Path: pysaliency/quilt.py # class PatchFile(object): # def __init__(self, patch): # self.diffs = [] # lines = patch.split('\n') # while lines: # index1 = lines.pop(0) # assert index1.startswith('Index: ') # index2 = lines.pop(0) # assert index2.startswith('==============') # diff = [] # diff.append(lines.pop(0)) # while lines and not lines[0].startswith('Index: '): # diff.append(lines.pop(0)) # diff_obj = Diff(diff) # self.diffs.append(diff_obj) # # def apply(self, location, verbose=True): # for diff in self.diffs: # if verbose: # print("Patching {}".format(diff.source_filename)) # diff.apply(location) # # class QuiltSeries(object): # def __init__(self, patches_location): # self.patches_location = patches_location # series = open(os.path.join(self.patches_location, 'series')).read() # self.patches = [] # self.patch_names = [] # for line in series.split('\n'): # if not line: # continue # patch_content = open(os.path.join(self.patches_location, line)).read() # self.patches.append(PatchFile(patch_content)) # self.patch_names.append(line) # # def apply(self, location, verbose=True): # for patch, name in zip(self.patches, self.patch_names): # if verbose: # print("Applying {}".format(name)) # patch.apply(location, verbose=verbose) , which may include functions, classes, or code. Output only the next line.
shallow=False))
Predict the next line after this snippet: <|code_start|> diff = patch.diffs[0] self.assertEqual(len(diff.hunks), 1) self.assertEqual(diff.source_filename, 'source.txt') self.assertEqual(diff.target_filename, 'source.txt') hunk = diff.hunks[0] self.assertEqual(hunk.source_start, 3) self.assertEqual(hunk.source_length, 6) self.assertEqual(hunk.target_start, 3) self.assertEqual(hunk.target_length, 8) def test_apply(self): location = os.path.join(self.data_path, 'patching') shutil.copytree('tests/test_quilt/source', location) p = open('tests/test_quilt/patches/add_numbers.diff').read() patch = PatchFile(p) patch.apply(location) self.assertTrue(filecmp.cmp(os.path.join(location, 'source.txt'), 'tests/test_quilt/target/source.txt', shallow=False)) class TestSeries(TestWithData): def test_parsing(self): series = QuiltSeries(os.path.join('tests', 'test_quilt', 'patches')) self.assertEqual(len(series.patches), 1) def test_apply(self): <|code_end|> using the current file's imports: import os import shutil import filecmp import unittest from pysaliency.quilt import PatchFile, QuiltSeries from test_helpers import TestWithData, assertDirsEqual and any relevant context from other files: # Path: pysaliency/quilt.py # class PatchFile(object): # def __init__(self, patch): # self.diffs = [] # lines = patch.split('\n') # while lines: # index1 = lines.pop(0) # assert index1.startswith('Index: ') # index2 = lines.pop(0) # assert index2.startswith('==============') # diff = [] # diff.append(lines.pop(0)) # while lines and not lines[0].startswith('Index: '): # diff.append(lines.pop(0)) # diff_obj = Diff(diff) # self.diffs.append(diff_obj) # # def apply(self, location, verbose=True): # for diff in self.diffs: # if verbose: # print("Patching {}".format(diff.source_filename)) # diff.apply(location) # # class QuiltSeries(object): # def __init__(self, patches_location): # self.patches_location = patches_location # series = open(os.path.join(self.patches_location, 'series')).read() # self.patches = [] # self.patch_names = [] # for line in series.split('\n'): # if not line: # continue # patch_content = open(os.path.join(self.patches_location, line)).read() # self.patches.append(PatchFile(patch_content)) # self.patch_names.append(line) # # def apply(self, location, verbose=True): # for patch, name in zip(self.patches, self.patch_names): # if verbose: # print("Applying {}".format(name)) # patch.apply(location, verbose=verbose) . Output only the next line.
location = os.path.join(self.data_path, 'patching')
Predict the next line after this snippet: <|code_start|>class ConstantSaliencyModel(pysaliency.Model): def _log_density(self, stimulus): return np.zeros((stimulus.shape[0], stimulus.shape[1])) - np.log(stimulus.shape[0]) - np.log(stimulus.shape[1]) class GaussianSaliencyModel(pysaliency.Model): def _log_density(self, stimulus): height = stimulus.shape[0] width = stimulus.shape[1] YS, XS = np.mgrid[:height, :width] r_squared = (XS-0.5*width)**2 + (YS-0.5*height)**2 size = np.sqrt(width**2+height**2) values = np.ones((stimulus.shape[0], stimulus.shape[1]))*np.exp(-0.5*(r_squared/size)) density = values / values.sum() return np.log(density) @pytest.fixture def fixation_trains(): xs_trains = [ [0, 1, 2], [2, 2], [1, 5, 3], [10]] ys_trains = [ [10, 11, 12], [12, 12], [21, 25, 33], [11]] ts_trains = [ <|code_end|> using the current file's imports: import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import ScikitLearnImageCrossValidationGenerator, ScikitLearnImageSubjectCrossValidationGenerator, \ RegularizedKernelDensityEstimator, fixations_to_scikit_learn from sklearn.model_selection import cross_val_score and any relevant context from other files: # Path: pysaliency/baseline_utils.py # class ScikitLearnImageCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # inds = self.fixations.n == n # if inds.sum(): # yield ~inds, inds # # def __len__(self): # return len(self.stimuli) # # class ScikitLearnImageSubjectCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # for s in range(self.fixations.subject_count): # image_inds = self.fixations.n == n # subject_inds = self.fixations.subjects == s # train_inds, test_inds = image_inds & ~subject_inds, image_inds & subject_inds # if test_inds.sum() == 0 or train_inds.sum() == 0: # #print("Skipping") # continue # yield train_inds, test_inds # # def __len__(self): # return len(set(zip(self.fixations.n, self.fixations.subjects))) # # class RegularizedKernelDensityEstimator(BaseEstimator): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # self.bandwidth = bandwidth # self.regularization = regularization # # def setup(self): # self.kde = KernelDensity(kernel='gaussian', bandwidth=self.bandwidth) # # height, width = self.shape # self.uniform_density = -np.log(width*height) # # self.kde_constant = np.log(1-self.regularization) # self.uniform_constant = np.log(self.regularization) # # def fit(self, X): # self.shape = X[0, 2:4] # self.setup() # self.kde.fit(X[:, 0:2]) # return self # # def score_samples(self, X): # kde_logliks = self.kde.score_samples(X[:, :2]) # # logliks = np.logaddexp( # self.kde_constant + kde_logliks, # self.uniform_constant + self.uniform_density # ) # return logliks # # def score(self, X): # return np.sum(self.score_samples(X)) # # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # if normalize is None: # xs = fixations.x # ys = fixations.y # data = [xs, ys] # if add_shape: # raise NotImplementedError() # else: # data = normalize_fixations(normalize, fixations, keep_aspect=keep_aspect, add_shape=add_shape, # verbose=verbose) # if add_stimulus_number: # data = list(data) + [fixations.n] # if add_fixation_number: # data = list(data) + [np.arange(len(fixations.n))] # return np.vstack(data).T.copy() . Output only the next line.
[0, 200, 600],
Next line prediction: <|code_start|> [False, False, False, False, False, True, True, True, False]), ([True, True, True, True, True, True, True, True, False], [False, False, False, False, False, False, False, False, True]) ] X = fixations_to_scikit_learn(fixation_trains, normalize=stimuli, add_shape=True) assert cross_val_score( RegularizedKernelDensityEstimator(bandwidth=0.1, regularization=0.1), X, cv=cv, verbose=0).sum() def test_image_subject_crossvalidation(stimuli, fixation_trains): gsmm = GaussianSaliencyModel() cv = ScikitLearnImageSubjectCrossValidationGenerator(stimuli, fixation_trains) assert unpack_crossval(cv) == [ ([False, False, False, True, True, False, False, False, False], [True, True, True, False, False, False, False, False, False]), ([True, True, True, False, False, False, False, False, False], [False, False, False, True, True, False, False, False, False]) ] X = fixations_to_scikit_learn(fixation_trains, normalize=stimuli, add_shape=True) assert cross_val_score( RegularizedKernelDensityEstimator(bandwidth=0.1, regularization=0.1), <|code_end|> . Use current file imports: (import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import ScikitLearnImageCrossValidationGenerator, ScikitLearnImageSubjectCrossValidationGenerator, \ RegularizedKernelDensityEstimator, fixations_to_scikit_learn from sklearn.model_selection import cross_val_score) and context including class names, function names, or small code snippets from other files: # Path: pysaliency/baseline_utils.py # class ScikitLearnImageCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # inds = self.fixations.n == n # if inds.sum(): # yield ~inds, inds # # def __len__(self): # return len(self.stimuli) # # class ScikitLearnImageSubjectCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # for s in range(self.fixations.subject_count): # image_inds = self.fixations.n == n # subject_inds = self.fixations.subjects == s # train_inds, test_inds = image_inds & ~subject_inds, image_inds & subject_inds # if test_inds.sum() == 0 or train_inds.sum() == 0: # #print("Skipping") # continue # yield train_inds, test_inds # # def __len__(self): # return len(set(zip(self.fixations.n, self.fixations.subjects))) # # class RegularizedKernelDensityEstimator(BaseEstimator): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # self.bandwidth = bandwidth # self.regularization = regularization # # def setup(self): # self.kde = KernelDensity(kernel='gaussian', bandwidth=self.bandwidth) # # height, width = self.shape # self.uniform_density = -np.log(width*height) # # self.kde_constant = np.log(1-self.regularization) # self.uniform_constant = np.log(self.regularization) # # def fit(self, X): # self.shape = X[0, 2:4] # self.setup() # self.kde.fit(X[:, 0:2]) # return self # # def score_samples(self, X): # kde_logliks = self.kde.score_samples(X[:, :2]) # # logliks = np.logaddexp( # self.kde_constant + kde_logliks, # self.uniform_constant + self.uniform_density # ) # return logliks # # def score(self, X): # return np.sum(self.score_samples(X)) # # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # if normalize is None: # xs = fixations.x # ys = fixations.y # data = [xs, ys] # if add_shape: # raise NotImplementedError() # else: # data = normalize_fixations(normalize, fixations, keep_aspect=keep_aspect, add_shape=add_shape, # verbose=verbose) # if add_stimulus_number: # data = list(data) + [fixations.n] # if add_fixation_number: # data = list(data) + [np.arange(len(fixations.n))] # return np.vstack(data).T.copy() . Output only the next line.
X,
Using the snippet: <|code_start|> [True, True, True, True, True, False, False, False, False]), ([True, True, True, True, True, False, False, False, True], [False, False, False, False, False, True, True, True, False]), ([True, True, True, True, True, True, True, True, False], [False, False, False, False, False, False, False, False, True]) ] X = fixations_to_scikit_learn(fixation_trains, normalize=stimuli, add_shape=True) assert cross_val_score( RegularizedKernelDensityEstimator(bandwidth=0.1, regularization=0.1), X, cv=cv, verbose=0).sum() def test_image_subject_crossvalidation(stimuli, fixation_trains): gsmm = GaussianSaliencyModel() cv = ScikitLearnImageSubjectCrossValidationGenerator(stimuli, fixation_trains) assert unpack_crossval(cv) == [ ([False, False, False, True, True, False, False, False, False], [True, True, True, False, False, False, False, False, False]), ([True, True, True, False, False, False, False, False, False], [False, False, False, True, True, False, False, False, False]) ] X = fixations_to_scikit_learn(fixation_trains, normalize=stimuli, add_shape=True) <|code_end|> , determine the next line of code. You have imports: import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import ScikitLearnImageCrossValidationGenerator, ScikitLearnImageSubjectCrossValidationGenerator, \ RegularizedKernelDensityEstimator, fixations_to_scikit_learn from sklearn.model_selection import cross_val_score and context (class names, function names, or code) available: # Path: pysaliency/baseline_utils.py # class ScikitLearnImageCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # inds = self.fixations.n == n # if inds.sum(): # yield ~inds, inds # # def __len__(self): # return len(self.stimuli) # # class ScikitLearnImageSubjectCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # for s in range(self.fixations.subject_count): # image_inds = self.fixations.n == n # subject_inds = self.fixations.subjects == s # train_inds, test_inds = image_inds & ~subject_inds, image_inds & subject_inds # if test_inds.sum() == 0 or train_inds.sum() == 0: # #print("Skipping") # continue # yield train_inds, test_inds # # def __len__(self): # return len(set(zip(self.fixations.n, self.fixations.subjects))) # # class RegularizedKernelDensityEstimator(BaseEstimator): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # self.bandwidth = bandwidth # self.regularization = regularization # # def setup(self): # self.kde = KernelDensity(kernel='gaussian', bandwidth=self.bandwidth) # # height, width = self.shape # self.uniform_density = -np.log(width*height) # # self.kde_constant = np.log(1-self.regularization) # self.uniform_constant = np.log(self.regularization) # # def fit(self, X): # self.shape = X[0, 2:4] # self.setup() # self.kde.fit(X[:, 0:2]) # return self # # def score_samples(self, X): # kde_logliks = self.kde.score_samples(X[:, :2]) # # logliks = np.logaddexp( # self.kde_constant + kde_logliks, # self.uniform_constant + self.uniform_density # ) # return logliks # # def score(self, X): # return np.sum(self.score_samples(X)) # # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # if normalize is None: # xs = fixations.x # ys = fixations.y # data = [xs, ys] # if add_shape: # raise NotImplementedError() # else: # data = normalize_fixations(normalize, fixations, keep_aspect=keep_aspect, add_shape=add_shape, # verbose=verbose) # if add_stimulus_number: # data = list(data) + [fixations.n] # if add_fixation_number: # data = list(data) + [np.arange(len(fixations.n))] # return np.vstack(data).T.copy() . Output only the next line.
assert cross_val_score(
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function, unicode_literals class ConstantSaliencyModel(pysaliency.Model): def _log_density(self, stimulus): return np.zeros((stimulus.shape[0], stimulus.shape[1])) - np.log(stimulus.shape[0]) - np.log(stimulus.shape[1]) class GaussianSaliencyModel(pysaliency.Model): def _log_density(self, stimulus): height = stimulus.shape[0] width = stimulus.shape[1] YS, XS = np.mgrid[:height, :width] r_squared = (XS-0.5*width)**2 + (YS-0.5*height)**2 size = np.sqrt(width**2+height**2) values = np.ones((stimulus.shape[0], stimulus.shape[1]))*np.exp(-0.5*(r_squared/size)) density = values / values.sum() return np.log(density) @pytest.fixture def fixation_trains(): xs_trains = [ [0, 1, 2], <|code_end|> with the help of current file imports: import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import ScikitLearnImageCrossValidationGenerator, ScikitLearnImageSubjectCrossValidationGenerator, \ RegularizedKernelDensityEstimator, fixations_to_scikit_learn from sklearn.model_selection import cross_val_score and context from other files: # Path: pysaliency/baseline_utils.py # class ScikitLearnImageCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # inds = self.fixations.n == n # if inds.sum(): # yield ~inds, inds # # def __len__(self): # return len(self.stimuli) # # class ScikitLearnImageSubjectCrossValidationGenerator(object): # def __init__(self, stimuli, fixations): # self.stimuli = stimuli # self.fixations = fixations # # def __iter__(self): # for n in range(len(self.stimuli)): # for s in range(self.fixations.subject_count): # image_inds = self.fixations.n == n # subject_inds = self.fixations.subjects == s # train_inds, test_inds = image_inds & ~subject_inds, image_inds & subject_inds # if test_inds.sum() == 0 or train_inds.sum() == 0: # #print("Skipping") # continue # yield train_inds, test_inds # # def __len__(self): # return len(set(zip(self.fixations.n, self.fixations.subjects))) # # class RegularizedKernelDensityEstimator(BaseEstimator): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # self.bandwidth = bandwidth # self.regularization = regularization # # def setup(self): # self.kde = KernelDensity(kernel='gaussian', bandwidth=self.bandwidth) # # height, width = self.shape # self.uniform_density = -np.log(width*height) # # self.kde_constant = np.log(1-self.regularization) # self.uniform_constant = np.log(self.regularization) # # def fit(self, X): # self.shape = X[0, 2:4] # self.setup() # self.kde.fit(X[:, 0:2]) # return self # # def score_samples(self, X): # kde_logliks = self.kde.score_samples(X[:, :2]) # # logliks = np.logaddexp( # self.kde_constant + kde_logliks, # self.uniform_constant + self.uniform_density # ) # return logliks # # def score(self, X): # return np.sum(self.score_samples(X)) # # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # if normalize is None: # xs = fixations.x # ys = fixations.y # data = [xs, ys] # if add_shape: # raise NotImplementedError() # else: # data = normalize_fixations(normalize, fixations, keep_aspect=keep_aspect, add_shape=add_shape, # verbose=verbose) # if add_stimulus_number: # data = list(data) + [fixations.n] # if add_fixation_number: # data = list(data) + [np.arange(len(fixations.n))] # return np.vstack(data).T.copy() , which may contain function names, class names, or code. Output only the next line.
[2, 2],
Predict the next line for this snippet: <|code_start|> ts_trains = [ [0, 200, 600], [100, 400], [50, 500, 900]] ns = [0, 0, 1] subjects = [0, 1, 1] return pysaliency.FixationTrains.from_fixation_trains(xs_trains, ys_trains, ts_trains, ns, subjects) @pytest.fixture def stimuli(): return pysaliency.Stimuli([np.random.randn(40, 40, 3), np.random.randn(40, 40, 3)]) def test_fixation_map(): fixations = np.array([ [0, 0], [1, 1], [1, 1], [1, 2], [1, 2], [2, 1]]) fixation_map = np.zeros((3, 3)) fill_fixation_map(fixation_map, fixations) np.testing.assert_allclose(fixation_map, np.array([ [1, 0, 0], [0, 2, 2], <|code_end|> with the help of current file imports: import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import fill_fixation_map, KDEGoldModel and context from other files: # Path: pysaliency/baseline_utils.py # def _normalize_fixations(orig_xs, orig_ys, orig_ns, sizes, new_xs, new_ys, real_widths, real_heights): # def normalize_fixations(stimuli, fixations, keep_aspect=False, add_shape=False, verbose=True): # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # def __init__(self, stimuli, fixations): # def __iter__(self): # def __len__(self): # def __init__(self, stimuli, fixations): # def __iter__(self): # def __len__(self): # def __init__(self, stimuli, fixations, chunks_per_image=10, random_seed=42): # def __iter__(self): # def __len__(self): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5, regularizing_log_likelihoods=None): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, nonfixations, bandwidth=1.0): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, keep_aspect=False, verbose=False, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps=1e-20, keep_aspect=False, verbose=False, grid_spacing=1, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, keep_aspect=False, **kwargs): # def _log_density(self, stimulus): # class ScikitLearnImageCrossValidationGenerator(object): # class ScikitLearnImageSubjectCrossValidationGenerator(object): # class ScikitLearnWithinImageCrossValidationGenerator(object): # class RegularizedKernelDensityEstimator(BaseEstimator): # class MixtureKernelDensityEstimator(BaseEstimator): # class AUCKernelDensityEstimator(BaseEstimator): # class GoldModel(Model): # class KDEGoldModel(Model): # class CrossvalidatedBaselineModel(Model): # class BaselineModel(Model): # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*y_factor, self.bandwidth*x_factor]) # ZZ = np.log(ZZ) # X = fixations_to_scikit_learn( # self.fixations[inds], normalize=self.stimuli, # keep_aspect=self.keep_aspect, add_shape=False, verbose=False) # XX, YY = np.meshgrid(xs, ys) # ZZ = scores # ZZ = np.logaddexp( # np.log(1 - self.eps) + scores, # np.log(self.eps) - np.log(height * width) # ) # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*shape[0], self.bandwidth*shape[1]]) # ZZ = np.log(ZZ) # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*y_factor, self.bandwidth*x_factor]) # ZZ = np.log(ZZ) , which may contain function names, class names, or code. Output only the next line.
[0, 1, 0]]))
Next line prediction: <|code_start|> [22, 5, 18]] ts_trains = [ [0, 200, 600], [100, 400], [50, 500, 900]] ns = [0, 0, 1] subjects = [0, 1, 1] return pysaliency.FixationTrains.from_fixation_trains(xs_trains, ys_trains, ts_trains, ns, subjects) @pytest.fixture def stimuli(): return pysaliency.Stimuli([np.random.randn(40, 40, 3), np.random.randn(40, 40, 3)]) def test_fixation_map(): fixations = np.array([ [0, 0], [1, 1], [1, 1], [1, 2], [1, 2], [2, 1]]) fixation_map = np.zeros((3, 3)) fill_fixation_map(fixation_map, fixations) np.testing.assert_allclose(fixation_map, np.array([ [1, 0, 0], <|code_end|> . Use current file imports: (import pytest import numpy as np import pysaliency from pysaliency.baseline_utils import fill_fixation_map, KDEGoldModel) and context including class names, function names, or small code snippets from other files: # Path: pysaliency/baseline_utils.py # def _normalize_fixations(orig_xs, orig_ys, orig_ns, sizes, new_xs, new_ys, real_widths, real_heights): # def normalize_fixations(stimuli, fixations, keep_aspect=False, add_shape=False, verbose=True): # def fixations_to_scikit_learn(fixations, normalize=None, keep_aspect=False, add_shape=False, # add_stimulus_number=False, # add_fixation_number=False, # verbose=True): # def __init__(self, stimuli, fixations): # def __iter__(self): # def __len__(self): # def __init__(self, stimuli, fixations): # def __iter__(self): # def __len__(self): # def __init__(self, stimuli, fixations, chunks_per_image=10, random_seed=42): # def __iter__(self): # def __len__(self): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, bandwidth=1.0, regularization = 1.0e-5, regularizing_log_likelihoods=None): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, nonfixations, bandwidth=1.0): # def setup(self): # def fit(self, X): # def score_samples(self, X): # def score(self, X): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, keep_aspect=False, verbose=False, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps=1e-20, keep_aspect=False, verbose=False, grid_spacing=1, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, **kwargs): # def _log_density(self, stimulus): # def __init__(self, stimuli, fixations, bandwidth, eps = 1e-20, keep_aspect=False, **kwargs): # def _log_density(self, stimulus): # class ScikitLearnImageCrossValidationGenerator(object): # class ScikitLearnImageSubjectCrossValidationGenerator(object): # class ScikitLearnWithinImageCrossValidationGenerator(object): # class RegularizedKernelDensityEstimator(BaseEstimator): # class MixtureKernelDensityEstimator(BaseEstimator): # class AUCKernelDensityEstimator(BaseEstimator): # class GoldModel(Model): # class KDEGoldModel(Model): # class CrossvalidatedBaselineModel(Model): # class BaselineModel(Model): # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*y_factor, self.bandwidth*x_factor]) # ZZ = np.log(ZZ) # X = fixations_to_scikit_learn( # self.fixations[inds], normalize=self.stimuli, # keep_aspect=self.keep_aspect, add_shape=False, verbose=False) # XX, YY = np.meshgrid(xs, ys) # ZZ = scores # ZZ = np.logaddexp( # np.log(1 - self.eps) + scores, # np.log(self.eps) - np.log(height * width) # ) # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*shape[0], self.bandwidth*shape[1]]) # ZZ = np.log(ZZ) # ZZ = np.zeros(shape) # ZZ = gaussian_filter(ZZ, [self.bandwidth*y_factor, self.bandwidth*x_factor]) # ZZ = np.log(ZZ) . Output only the next line.
[0, 2, 2],
Here is a snippet: <|code_start|> train_ts = np.vstack(train_ts) train_ns = np.hstack(train_ns) train_subjects = np.hstack(train_subjects) full_nonfixations = type(self)(train_xs, train_ys, train_ts, train_ns, train_subjects) self.full_nonfixations = full_nonfixations return full_nonfixations def generate_nonfixation_partners(self, seed=42): """Generate nonfixational distribution from this fixation object such that for every fixation in the original fixation object there is a corresponding fixation on the same image but on a different position that comes from some other fixation. This destroys the temporal ordering of the fixation trains.""" train_xs = self.train_xs.copy() train_ys = self.train_ys.copy() train_ts = self.train_ts.copy() train_ns = self.train_ns.copy() train_subjects = self.train_subjects.copy() rs = np.random.RandomState(seed) for train_index in range(len(train_ns)): n = train_ns[train_index] inds = np.nonzero(self.n != n)[0] length = (1 - np.isnan(train_xs[train_index])).sum() for i in range(length): new_fix_index = rs.choice(inds) train_xs[train_index][i] = self.x[new_fix_index] train_ys[train_index][i] = self.y[new_fix_index] <|code_end|> . Write the next line using the current file imports: import os import json import numpy as np import h5py import h5py import h5py import h5py from hashlib import sha1 from collections import Sequence from functools import wraps from weakref import WeakValueDictionary from six.moves import range as xrange from six import string_types from boltons.cacheutils import cached from imageio import imread from PIL import Image from tqdm import tqdm from .utils import LazyList, build_padded_2d_array and context from other files: # Path: pysaliency/utils.py # class LazyList(Sequence): # """ # A list-like class that is able to generate it's entries only # when needed. Entries can be cached. # # LayList implements `collections.Sequence` and therefore `__contains__`. # However, to use it, in the worst case all elements of the list have # to be generated. # # .. note:: # As `LazyList` stores the generator function, pickling it # will usually fail. To pickle a `LazyList`, use `dill`. # """ # def __init__(self, generator, length, cache=True, pickle_cache=False): # """ # Parameters # ---------- # # @type generator: callable # @param generator: A function that takes an integer `n` and returns the # `n`-th element of the list. # # @type length: int # @param length: The length of the list # # @type cache: bool, defaults to `True` # @param cache: Wether to cache the list items. # # @type pickle_cache: bool, defaults to `False` # @param pickle_cache: Whether the cache should be saved when # pickling the object. # """ # self.generator = generator # self.length = length # self.cache = cache # self.pickle_cache = pickle_cache # self._cache = {} # # def __len__(self): # return self.length # # def __getitem__(self, index): # if isinstance(index, slice): # return [self[i] for i in range(len(self))[index]] # elif isinstance(index, list): # return [self[i] for i in index] # else: # return self._getitem(index) # # def _getitem(self, index): # if not 0 <= index < self.length: # raise IndexError(index) # if index in self._cache: # return self._cache[index] # value = self.generator(index) # if self.cache: # self._cache[index] = value # return value # # def __getstate__(self): # # we don't want to save the cache # state = dict(self.__dict__) # if not self.pickle_cache: # state.pop('_cache') # return state # # def __setstate__(self, state): # if not '_cache' in state: # state['_cache'] = {} # self.__dict__ = dict(state) # # def build_padded_2d_array(arrays, max_length=None, padding_value=np.nan): # if max_length is None: # max_length = np.max([len(a) for a in arrays]) # # output = np.ones((len(arrays), max_length), dtype=np.asarray(arrays[0]).dtype) # output *= padding_value # for i, array in enumerate(arrays): # output[i, :len(array)] = array # # return output , which may include functions, classes, or code. Output only the next line.
train_ts[train_index][i] = self.t[new_fix_index]
Using the snippet: <|code_start|> """Return dictionary of optimization parameters from vector x. The non-optimization parameters will be taken from the initial values. if return_list==True, return a list instead of an dictionary""" params = self.param_values.copy() index = 0 for param_name in self.optimize: if not isinstance(self.param_values[param_name], np.ndarray) or len(self.param_values[param_name].shape) == 0: # Only scalar value params[param_name] = x[index] index += 1 else: shape = self.param_values[param_name].shape if len(shape) > 1: raise ValueError('Arrays with more than one dimension are not yet supported!') params[param_name] = x[index:index+shape[0]] index += shape[0] if return_list: return [params[key] for key in self.parameters] else: return params def build_vector(self, **kwargs): """Build a vector of the optimization parameters. The initial values will be taken unless you overwrite them using the keyword arguments""" params = self.param_values.copy() params.update(kwargs) vector_values = [params[key] for key in self.optimize] return np.hstack(vector_values) <|code_end|> , determine the next line of code. You have imports: import numpy as np import scipy.optimize from .jacobian import FunctionWithApproxJacobian and context (class names, function names, or code) available: # Path: pysaliency/optpy/jacobian.py # class FunctionWithApproxJacobian(object): # def __init__(self, func, epsilon, verbose=True): # self._func = func # self.epsilon = epsilon # self.value_cache = {} # self.verbose = verbose # # def __call__(self, x, *args, **kwargs): # key = tuple(x) # if not key in self.value_cache: # self.log('.') # value = self._func(x, *args, **kwargs) # if np.any(np.isnan(value)): # print("Warning! nan function value encountered at {0}".format(x)) # self.value_cache[key] = value # return self.value_cache[key] # # def func(self, x, *args, **kwargs): # if self.verbose: # print(x) # return self(x, *args, **kwargs) # # def log(self, msg): # if self.verbose: # sys.stdout.write(msg) # sys.stdout.flush() # # def jac(self, x, *args, **kwargs): # self.log('G[') # x0 = np.asfarray(x) # #print x0 # dxs = np.zeros((len(x0), len(x0) + 1)) # for i in range(len(x0)): # dxs[i, i + 1] = self.epsilon # results = [self(*(x0 + dxs[:, i], ) + args, **kwargs) for i in range(len(x0) + 1)] # jac = np.zeros([len(x0), len(np.atleast_1d(results[0]))]) # for i in range(len(x0)): # jac[i] = (results[i + 1] - results[0]) / self.epsilon # self.log(']') # return jac.transpose() . Output only the next line.
def get_length(self, param_name):
Using the snippet: <|code_start|> rst = np.random.RandomState(42) inds = [] k_fold = StratifiedKFold(n_splits=split_count, shuffle=random, random_state=rst) for i, (train_index, test_index) in enumerate(k_fold.split(X, labels)): if i in included_splits: inds.extend(test_index) stimuli, fixations = create_subset(stimuli, fixations, inds) return stimuli, fixations def create_train_folds(crossval_folds, val_folds, test_folds): all_folds = list(range(crossval_folds)) if isinstance(val_folds, int): val_folds = [val_folds] if isinstance(test_folds, int): test_folds = [test_folds] train_folds = [f for f in all_folds if not (f in val_folds or f in test_folds)] return train_folds, val_folds, test_folds def get_crossval_folds(crossval_folds, crossval_no, test_folds=1, val_folds=1): assert test_folds <= 1 if test_folds: _test_folds = [crossval_no] _val_folds = [(crossval_no - i - 1) % crossval_folds for i in range(val_folds)] <|code_end|> , determine the next line of code. You have imports: import numpy as np from boltons.iterutils import chunked from .datasets import create_subset from sklearn.model_selection import StratifiedKFold and context (class names, function names, or code) available: # Path: pysaliency/datasets.py # def create_subset(stimuli, fixations, stimuli_indices): # """Create subset of stimuli and fixations using only stimuli # with given indices. # """ # new_stimuli = stimuli[stimuli_indices] # if isinstance(fixations, FixationTrains): # fix_inds = np.in1d(fixations.train_ns, stimuli_indices) # new_fixations = fixations.filter_fixation_trains(fix_inds) # # index_list = list(stimuli_indices) # new_pos = {i: index_list.index(i) for i in index_list} # # new_fixation_train_ns = [new_pos[i] for i in new_fixations.train_ns] # new_fixations.train_ns = np.array(new_fixation_train_ns) # new_fixation_ns = [new_pos[i] for i in new_fixations.n] # new_fixations.n = np.array(new_fixation_ns) # else: # fix_inds = np.in1d(fixations.n, stimuli_indices) # new_fixations = fixations[fix_inds] # # index_list = list(stimuli_indices) # new_pos = {i: index_list.index(i) for i in index_list} # new_fixation_ns = [new_pos[i] for i in new_fixations.n] # new_fixations.n = np.array(new_fixation_ns) # # return new_stimuli, new_fixations . Output only the next line.
else:
Continue the code snippet: <|code_start|> def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None): xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst) ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image) return xs, ys, ns class DistributionSGD(torch.optim.Optimizer): """Extension of SGD that constraints the parameters to be nonegative and with fixed sum (e.g., a probability distribution)""" def __init__(self, params, lr=required): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) defaults = dict(lr=lr) super(DistributionSGD, self).__init__(params, defaults) @torch.no_grad() <|code_end|> . Use current file imports: import numpy as np import torch import torch.nn as nn from scipy.ndimage import gaussian_filter as sp_gaussian_filter from scipy.special import logsumexp from torch.optim.optimizer import required from tqdm import tqdm from .models import sample_from_logdensity from .torch_utils import gaussian_filter and context (classes, functions, or code) from other files: # Path: pysaliency/models.py # def sample_from_logdensity(log_density, count=None, rst=None): # if count is None: # real_count = 1 # else: # real_count = count # # height, width = log_density.shape # flat_log_density = log_density.flatten(order='C') # samples = sample_from_logprobabilities(flat_log_density, size=real_count, rst=rst) # sample_xs = samples % width # sample_ys = samples // width # # if count is None: # return sample_xs[0], sample_ys[0] # else: # return np.asarray(sample_xs), np.asarray(sample_ys) # # Path: pysaliency/torch_utils.py # def gaussian_filter(tensor, dim, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0): # if isinstance(dim, int): # dim = [dim] # # for k in dim: # tensor = gaussian_filter_1d( # tensor, # dim=k, # sigma=sigma, # truncate=truncate, # kernel_size=kernel_size, # padding_mode=padding_mode, # padding_value=padding_value, # ) # # return tensor . Output only the next line.
def step(self, closure=None):
Given the code snippet: <|code_start|> def sample_batch_fixations(log_density, fixations_per_image, batch_size, rst=None): xs, ys = sample_from_logdensity(log_density, fixations_per_image * batch_size, rst=rst) ns = np.repeat(np.arange(batch_size, dtype=int), repeats=fixations_per_image) return xs, ys, ns class DistributionSGD(torch.optim.Optimizer): """Extension of SGD that constraints the parameters to be nonegative and with fixed sum (e.g., a probability distribution)""" def __init__(self, params, lr=required): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) defaults = dict(lr=lr) <|code_end|> , generate the next line using the imports in this file: import numpy as np import torch import torch.nn as nn from scipy.ndimage import gaussian_filter as sp_gaussian_filter from scipy.special import logsumexp from torch.optim.optimizer import required from tqdm import tqdm from .models import sample_from_logdensity from .torch_utils import gaussian_filter and context (functions, classes, or occasionally code) from other files: # Path: pysaliency/models.py # def sample_from_logdensity(log_density, count=None, rst=None): # if count is None: # real_count = 1 # else: # real_count = count # # height, width = log_density.shape # flat_log_density = log_density.flatten(order='C') # samples = sample_from_logprobabilities(flat_log_density, size=real_count, rst=rst) # sample_xs = samples % width # sample_ys = samples // width # # if count is None: # return sample_xs[0], sample_ys[0] # else: # return np.asarray(sample_xs), np.asarray(sample_ys) # # Path: pysaliency/torch_utils.py # def gaussian_filter(tensor, dim, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0): # if isinstance(dim, int): # dim = [dim] # # for k in dim: # tensor = gaussian_filter_1d( # tensor, # dim=k, # sigma=sigma, # truncate=truncate, # kernel_size=kernel_size, # padding_mode=padding_mode, # padding_value=padding_value, # ) # # return tensor . Output only the next line.
super(DistributionSGD, self).__init__(params, defaults)
Using the snippet: <|code_start|> def test_fixation_sampling(): class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel): def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): return x_hist[-1] + 1, y_hist[-1] + 1, t_hist[-1] + 1 model = SamplingModel() xs, ys, ts = model.sample_scanpath(np.zeros((40, 40, 3)), [0], [1], [2], 4) assert xs == [0, 1, 2, 3, 4] assert ys == [1, 2, 3, 4, 5] assert ts == [2, 3, 4, 5, 6] def test_scanpath_sampling(): class SamplingModel(ScanpathSamplingModelMixin, GaussianSaliencyMapModel): def sample_scanpath(self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None): return ( <|code_end|> , determine the next line of code. You have imports: import numpy as np from pysaliency.saliency_map_models import GaussianSaliencyMapModel from pysaliency.sampling_models import SamplingModelMixin, ScanpathSamplingModelMixin and context (class names, function names, or code) available: # Path: pysaliency/saliency_map_models.py # class GaussianSaliencyMapModel(SaliencyMapModel): # """Gaussian saliency map model with given width""" # def __init__(self, width=0.5, center_x=0.5, center_y=0.5, **kwargs): # super(GaussianSaliencyMapModel, self).__init__(**kwargs) # self.width = width # self.center_x = center_x # self.center_y = center_y # # def _saliency_map(self, stimulus): # height = stimulus.shape[0] # width = stimulus.shape[1] # YS, XS = np.mgrid[:height, :width].astype(float) # XS /= width # YS /= height # XS -= self.center_x # YS -= self.center_y # r_squared = XS**2 + YS**2 # return np.ones((stimulus.shape[0], stimulus.shape[1]))*np.exp(-0.5*r_squared/(self.width)**2) # # Path: pysaliency/sampling_models.py # class SamplingModelMixin(object): # """A sampling model is supports sampling fixations and whole scanpaths.""" # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # """return xs, ys, ts""" # xs = list(remove_trailing_nans(x_hist)) # ys = list(remove_trailing_nans(y_hist)) # ts = list(remove_trailing_nans(t_hist)) # if not len(xs) == len(ys) == len(ts): # raise ValueError("Histories for x, y and t have to be the same length") # # for i in range(samples): # x, y, t = self.sample_fixation(stimulus, xs, ys, ts, attributes=attributes, verbose=verbose, rst=rst) # xs.append(x) # ys.append(y) # ts.append(t) # # return xs, ys, ts # # @abstractmethod # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # """return x, y, t""" # raise NotImplementedError() # # class ScanpathSamplingModelMixin(SamplingModelMixin): # """A sampling model which only has to implement sample_scanpath instead of sample_fixation""" # @abstractmethod # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # raise NotImplementedError() # # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # samples = 1 # xs, ys, ts = self.sample_scanpath(stimulus, x_hist, y_hist, t_hist, samples, attributes=attributes, # verbose=verbose, rst=rst) # return xs[-1], ys[-1], ts[-1] . Output only the next line.
list(x_hist) + [x_hist[-1]] * samples,
Next line prediction: <|code_start|> def test_fixation_sampling(): class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel): def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): <|code_end|> . Use current file imports: (import numpy as np from pysaliency.saliency_map_models import GaussianSaliencyMapModel from pysaliency.sampling_models import SamplingModelMixin, ScanpathSamplingModelMixin) and context including class names, function names, or small code snippets from other files: # Path: pysaliency/saliency_map_models.py # class GaussianSaliencyMapModel(SaliencyMapModel): # """Gaussian saliency map model with given width""" # def __init__(self, width=0.5, center_x=0.5, center_y=0.5, **kwargs): # super(GaussianSaliencyMapModel, self).__init__(**kwargs) # self.width = width # self.center_x = center_x # self.center_y = center_y # # def _saliency_map(self, stimulus): # height = stimulus.shape[0] # width = stimulus.shape[1] # YS, XS = np.mgrid[:height, :width].astype(float) # XS /= width # YS /= height # XS -= self.center_x # YS -= self.center_y # r_squared = XS**2 + YS**2 # return np.ones((stimulus.shape[0], stimulus.shape[1]))*np.exp(-0.5*r_squared/(self.width)**2) # # Path: pysaliency/sampling_models.py # class SamplingModelMixin(object): # """A sampling model is supports sampling fixations and whole scanpaths.""" # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # """return xs, ys, ts""" # xs = list(remove_trailing_nans(x_hist)) # ys = list(remove_trailing_nans(y_hist)) # ts = list(remove_trailing_nans(t_hist)) # if not len(xs) == len(ys) == len(ts): # raise ValueError("Histories for x, y and t have to be the same length") # # for i in range(samples): # x, y, t = self.sample_fixation(stimulus, xs, ys, ts, attributes=attributes, verbose=verbose, rst=rst) # xs.append(x) # ys.append(y) # ts.append(t) # # return xs, ys, ts # # @abstractmethod # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # """return x, y, t""" # raise NotImplementedError() # # class ScanpathSamplingModelMixin(SamplingModelMixin): # """A sampling model which only has to implement sample_scanpath instead of sample_fixation""" # @abstractmethod # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # raise NotImplementedError() # # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # samples = 1 # xs, ys, ts = self.sample_scanpath(stimulus, x_hist, y_hist, t_hist, samples, attributes=attributes, # verbose=verbose, rst=rst) # return xs[-1], ys[-1], ts[-1] . Output only the next line.
return x_hist[-1] + 1, y_hist[-1] + 1, t_hist[-1] + 1
Predict the next line after this snippet: <|code_start|> def test_fixation_sampling(): class SamplingModel(SamplingModelMixin, GaussianSaliencyMapModel): def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): return x_hist[-1] + 1, y_hist[-1] + 1, t_hist[-1] + 1 model = SamplingModel() xs, ys, ts = model.sample_scanpath(np.zeros((40, 40, 3)), [0], [1], [2], 4) assert xs == [0, 1, 2, 3, 4] assert ys == [1, 2, 3, 4, 5] assert ts == [2, 3, 4, 5, 6] def test_scanpath_sampling(): class SamplingModel(ScanpathSamplingModelMixin, GaussianSaliencyMapModel): def sample_scanpath(self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None): return ( list(x_hist) + [x_hist[-1]] * samples, list(y_hist) + [y_hist[-1]] * samples, list(t_hist) + [t_hist[-1]] * samples ) model = SamplingModel() <|code_end|> using the current file's imports: import numpy as np from pysaliency.saliency_map_models import GaussianSaliencyMapModel from pysaliency.sampling_models import SamplingModelMixin, ScanpathSamplingModelMixin and any relevant context from other files: # Path: pysaliency/saliency_map_models.py # class GaussianSaliencyMapModel(SaliencyMapModel): # """Gaussian saliency map model with given width""" # def __init__(self, width=0.5, center_x=0.5, center_y=0.5, **kwargs): # super(GaussianSaliencyMapModel, self).__init__(**kwargs) # self.width = width # self.center_x = center_x # self.center_y = center_y # # def _saliency_map(self, stimulus): # height = stimulus.shape[0] # width = stimulus.shape[1] # YS, XS = np.mgrid[:height, :width].astype(float) # XS /= width # YS /= height # XS -= self.center_x # YS -= self.center_y # r_squared = XS**2 + YS**2 # return np.ones((stimulus.shape[0], stimulus.shape[1]))*np.exp(-0.5*r_squared/(self.width)**2) # # Path: pysaliency/sampling_models.py # class SamplingModelMixin(object): # """A sampling model is supports sampling fixations and whole scanpaths.""" # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # """return xs, ys, ts""" # xs = list(remove_trailing_nans(x_hist)) # ys = list(remove_trailing_nans(y_hist)) # ts = list(remove_trailing_nans(t_hist)) # if not len(xs) == len(ys) == len(ts): # raise ValueError("Histories for x, y and t have to be the same length") # # for i in range(samples): # x, y, t = self.sample_fixation(stimulus, xs, ys, ts, attributes=attributes, verbose=verbose, rst=rst) # xs.append(x) # ys.append(y) # ts.append(t) # # return xs, ys, ts # # @abstractmethod # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # """return x, y, t""" # raise NotImplementedError() # # class ScanpathSamplingModelMixin(SamplingModelMixin): # """A sampling model which only has to implement sample_scanpath instead of sample_fixation""" # @abstractmethod # def sample_scanpath( # self, stimulus, x_hist, y_hist, t_hist, samples, attributes=None, verbose=False, rst=None # ): # raise NotImplementedError() # # def sample_fixation(self, stimulus, x_hist, y_hist, t_hist, attributes=None, verbose=False, rst=None): # samples = 1 # xs, ys, ts = self.sample_scanpath(stimulus, x_hist, y_hist, t_hist, samples, attributes=attributes, # verbose=verbose, rst=rst) # return xs[-1], ys[-1], ts[-1] . Output only the next line.
x, y, t = model.sample_fixation(np.zeros((40, 40, 3)), [0], [1], [2])
Next line prediction: <|code_start|> dataset_config_schema = Schema({ 'stimuli': str, 'fixations': str, Optional('filters', default=[]): [{ 'type': str, Optional('parameters', default={}): dict, }], }) def load_dataset_from_config(config): config = dataset_config_schema.validate(config) stimuli = read_hdf5(config['stimuli']) fixations = read_hdf5(config['fixations']) for filter_config in config['filters']: stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config) return stimuli, fixations <|code_end|> . Use current file imports: (from .datasets import read_hdf5 from .filter_datasets import ( filter_fixations_by_number, filter_stimuli_by_number, filter_stimuli_by_size, train_split, validation_split, test_split ) from schema import Schema, Optional) and context including class names, function names, or small code snippets from other files: # Path: pysaliency/datasets.py # def read_hdf5(source): # if isinstance(source, str): # return _read_hdf5_from_file(source) # # data_type = decode_string(source.attrs['type']) # # if data_type == 'Fixations': # return Fixations.read_hdf5(source) # elif data_type == 'FixationTrains': # return FixationTrains.read_hdf5(source) # elif data_type == 'Stimuli': # return Stimuli.read_hdf5(source) # elif data_type == 'FileStimuli': # return FileStimuli.read_hdf5(source) # else: # raise ValueError("Invalid HDF content type:", data_type) # # Path: pysaliency/filter_datasets.py # def filter_fixations_by_number(fixations, intervals): # intervals = _check_intervals(intervals, type=int) # inds = np.zeros_like(fixations.x, dtype=bool) # # for n1, n2 in intervals: # _inds = np.logical_and(fixations.lengths >= n1, fixations.lengths < n2) # inds = np.logical_or(inds, _inds) # # return fixations[inds] # # def filter_stimuli_by_number(stimuli, fixations, intervals): # intervals = _check_intervals(intervals, type=int) # mask = np.zeros(len(stimuli), dtype=bool) # # for n1, n2 in intervals: # mask[n1:n2] = True # # indices = list(np.nonzero(mask)[0]) # # return create_subset(stimuli, fixations, indices) # # def filter_stimuli_by_size(stimuli, fixations, size=None, sizes=None): # if size is not None: # sizes = [size] # sizes = [tuple(size) for size in sizes] # # indices = [i for i in range(len(stimuli)) if stimuli.sizes[i] in sizes] # # return create_subset(stimuli, fixations, indices) # # def train_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='train', stratified_attributes=stratified_attributes) # # def validation_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='val', stratified_attributes=stratified_attributes) # # def test_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='test', stratified_attributes=stratified_attributes) . Output only the next line.
def apply_dataset_filter_config(stimuli, fixations, filter_config):
Given the code snippet: <|code_start|>def load_dataset_from_config(config): config = dataset_config_schema.validate(config) stimuli = read_hdf5(config['stimuli']) fixations = read_hdf5(config['fixations']) for filter_config in config['filters']: stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config) return stimuli, fixations def apply_dataset_filter_config(stimuli, fixations, filter_config): filter_dict = { 'filter_fixations_by_number': add_stimuli_argument(filter_fixations_by_number), 'filter_stimuli_by_number': filter_stimuli_by_number, 'filter_stimuli_by_size': filter_stimuli_by_size, 'train_split': train_split, 'validation_split': validation_split, 'test_split': test_split, } if filter_config['type'] not in filter_dict: raise ValueError("Invalid filter name: {}".format(filter_config['type'])) filter_fn = filter_dict[filter_config['type']] return filter_fn(stimuli, fixations, **filter_config['parameters']) def add_stimuli_argument(fn): <|code_end|> , generate the next line using the imports in this file: from .datasets import read_hdf5 from .filter_datasets import ( filter_fixations_by_number, filter_stimuli_by_number, filter_stimuli_by_size, train_split, validation_split, test_split ) from schema import Schema, Optional and context (functions, classes, or occasionally code) from other files: # Path: pysaliency/datasets.py # def read_hdf5(source): # if isinstance(source, str): # return _read_hdf5_from_file(source) # # data_type = decode_string(source.attrs['type']) # # if data_type == 'Fixations': # return Fixations.read_hdf5(source) # elif data_type == 'FixationTrains': # return FixationTrains.read_hdf5(source) # elif data_type == 'Stimuli': # return Stimuli.read_hdf5(source) # elif data_type == 'FileStimuli': # return FileStimuli.read_hdf5(source) # else: # raise ValueError("Invalid HDF content type:", data_type) # # Path: pysaliency/filter_datasets.py # def filter_fixations_by_number(fixations, intervals): # intervals = _check_intervals(intervals, type=int) # inds = np.zeros_like(fixations.x, dtype=bool) # # for n1, n2 in intervals: # _inds = np.logical_and(fixations.lengths >= n1, fixations.lengths < n2) # inds = np.logical_or(inds, _inds) # # return fixations[inds] # # def filter_stimuli_by_number(stimuli, fixations, intervals): # intervals = _check_intervals(intervals, type=int) # mask = np.zeros(len(stimuli), dtype=bool) # # for n1, n2 in intervals: # mask[n1:n2] = True # # indices = list(np.nonzero(mask)[0]) # # return create_subset(stimuli, fixations, indices) # # def filter_stimuli_by_size(stimuli, fixations, size=None, sizes=None): # if size is not None: # sizes = [size] # sizes = [tuple(size) for size in sizes] # # indices = [i for i in range(len(stimuli)) if stimuli.sizes[i] in sizes] # # return create_subset(stimuli, fixations, indices) # # def train_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='train', stratified_attributes=stratified_attributes) # # def validation_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='val', stratified_attributes=stratified_attributes) # # def test_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='test', stratified_attributes=stratified_attributes) . Output only the next line.
def wrapped(stimuli, fixations, **kwargs):
Using the snippet: <|code_start|> dataset_config_schema = Schema({ 'stimuli': str, 'fixations': str, Optional('filters', default=[]): [{ 'type': str, Optional('parameters', default={}): dict, }], }) def load_dataset_from_config(config): config = dataset_config_schema.validate(config) stimuli = read_hdf5(config['stimuli']) fixations = read_hdf5(config['fixations']) for filter_config in config['filters']: stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config) <|code_end|> , determine the next line of code. You have imports: from .datasets import read_hdf5 from .filter_datasets import ( filter_fixations_by_number, filter_stimuli_by_number, filter_stimuli_by_size, train_split, validation_split, test_split ) from schema import Schema, Optional and context (class names, function names, or code) available: # Path: pysaliency/datasets.py # def read_hdf5(source): # if isinstance(source, str): # return _read_hdf5_from_file(source) # # data_type = decode_string(source.attrs['type']) # # if data_type == 'Fixations': # return Fixations.read_hdf5(source) # elif data_type == 'FixationTrains': # return FixationTrains.read_hdf5(source) # elif data_type == 'Stimuli': # return Stimuli.read_hdf5(source) # elif data_type == 'FileStimuli': # return FileStimuli.read_hdf5(source) # else: # raise ValueError("Invalid HDF content type:", data_type) # # Path: pysaliency/filter_datasets.py # def filter_fixations_by_number(fixations, intervals): # intervals = _check_intervals(intervals, type=int) # inds = np.zeros_like(fixations.x, dtype=bool) # # for n1, n2 in intervals: # _inds = np.logical_and(fixations.lengths >= n1, fixations.lengths < n2) # inds = np.logical_or(inds, _inds) # # return fixations[inds] # # def filter_stimuli_by_number(stimuli, fixations, intervals): # intervals = _check_intervals(intervals, type=int) # mask = np.zeros(len(stimuli), dtype=bool) # # for n1, n2 in intervals: # mask[n1:n2] = True # # indices = list(np.nonzero(mask)[0]) # # return create_subset(stimuli, fixations, indices) # # def filter_stimuli_by_size(stimuli, fixations, size=None, sizes=None): # if size is not None: # sizes = [size] # sizes = [tuple(size) for size in sizes] # # indices = [i for i in range(len(stimuli)) if stimuli.sizes[i] in sizes] # # return create_subset(stimuli, fixations, indices) # # def train_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='train', stratified_attributes=stratified_attributes) # # def validation_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='val', stratified_attributes=stratified_attributes) # # def test_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='test', stratified_attributes=stratified_attributes) . Output only the next line.
return stimuli, fixations
Given the code snippet: <|code_start|> dataset_config_schema = Schema({ 'stimuli': str, 'fixations': str, Optional('filters', default=[]): [{ 'type': str, Optional('parameters', default={}): dict, }], }) def load_dataset_from_config(config): config = dataset_config_schema.validate(config) stimuli = read_hdf5(config['stimuli']) fixations = read_hdf5(config['fixations']) for filter_config in config['filters']: stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config) <|code_end|> , generate the next line using the imports in this file: from .datasets import read_hdf5 from .filter_datasets import ( filter_fixations_by_number, filter_stimuli_by_number, filter_stimuli_by_size, train_split, validation_split, test_split ) from schema import Schema, Optional and context (functions, classes, or occasionally code) from other files: # Path: pysaliency/datasets.py # def read_hdf5(source): # if isinstance(source, str): # return _read_hdf5_from_file(source) # # data_type = decode_string(source.attrs['type']) # # if data_type == 'Fixations': # return Fixations.read_hdf5(source) # elif data_type == 'FixationTrains': # return FixationTrains.read_hdf5(source) # elif data_type == 'Stimuli': # return Stimuli.read_hdf5(source) # elif data_type == 'FileStimuli': # return FileStimuli.read_hdf5(source) # else: # raise ValueError("Invalid HDF content type:", data_type) # # Path: pysaliency/filter_datasets.py # def filter_fixations_by_number(fixations, intervals): # intervals = _check_intervals(intervals, type=int) # inds = np.zeros_like(fixations.x, dtype=bool) # # for n1, n2 in intervals: # _inds = np.logical_and(fixations.lengths >= n1, fixations.lengths < n2) # inds = np.logical_or(inds, _inds) # # return fixations[inds] # # def filter_stimuli_by_number(stimuli, fixations, intervals): # intervals = _check_intervals(intervals, type=int) # mask = np.zeros(len(stimuli), dtype=bool) # # for n1, n2 in intervals: # mask[n1:n2] = True # # indices = list(np.nonzero(mask)[0]) # # return create_subset(stimuli, fixations, indices) # # def filter_stimuli_by_size(stimuli, fixations, size=None, sizes=None): # if size is not None: # sizes = [size] # sizes = [tuple(size) for size in sizes] # # indices = [i for i in range(len(stimuli)) if stimuli.sizes[i] in sizes] # # return create_subset(stimuli, fixations, indices) # # def train_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='train', stratified_attributes=stratified_attributes) # # def validation_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='val', stratified_attributes=stratified_attributes) # # def test_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='test', stratified_attributes=stratified_attributes) . Output only the next line.
return stimuli, fixations
Given snippet: <|code_start|> config = dataset_config_schema.validate(config) stimuli = read_hdf5(config['stimuli']) fixations = read_hdf5(config['fixations']) for filter_config in config['filters']: stimuli, fixations = apply_dataset_filter_config(stimuli, fixations, filter_config) return stimuli, fixations def apply_dataset_filter_config(stimuli, fixations, filter_config): filter_dict = { 'filter_fixations_by_number': add_stimuli_argument(filter_fixations_by_number), 'filter_stimuli_by_number': filter_stimuli_by_number, 'filter_stimuli_by_size': filter_stimuli_by_size, 'train_split': train_split, 'validation_split': validation_split, 'test_split': test_split, } if filter_config['type'] not in filter_dict: raise ValueError("Invalid filter name: {}".format(filter_config['type'])) filter_fn = filter_dict[filter_config['type']] return filter_fn(stimuli, fixations, **filter_config['parameters']) def add_stimuli_argument(fn): def wrapped(stimuli, fixations, **kwargs): <|code_end|> , continue by predicting the next line. Consider current file imports: from .datasets import read_hdf5 from .filter_datasets import ( filter_fixations_by_number, filter_stimuli_by_number, filter_stimuli_by_size, train_split, validation_split, test_split ) from schema import Schema, Optional and context: # Path: pysaliency/datasets.py # def read_hdf5(source): # if isinstance(source, str): # return _read_hdf5_from_file(source) # # data_type = decode_string(source.attrs['type']) # # if data_type == 'Fixations': # return Fixations.read_hdf5(source) # elif data_type == 'FixationTrains': # return FixationTrains.read_hdf5(source) # elif data_type == 'Stimuli': # return Stimuli.read_hdf5(source) # elif data_type == 'FileStimuli': # return FileStimuli.read_hdf5(source) # else: # raise ValueError("Invalid HDF content type:", data_type) # # Path: pysaliency/filter_datasets.py # def filter_fixations_by_number(fixations, intervals): # intervals = _check_intervals(intervals, type=int) # inds = np.zeros_like(fixations.x, dtype=bool) # # for n1, n2 in intervals: # _inds = np.logical_and(fixations.lengths >= n1, fixations.lengths < n2) # inds = np.logical_or(inds, _inds) # # return fixations[inds] # # def filter_stimuli_by_number(stimuli, fixations, intervals): # intervals = _check_intervals(intervals, type=int) # mask = np.zeros(len(stimuli), dtype=bool) # # for n1, n2 in intervals: # mask[n1:n2] = True # # indices = list(np.nonzero(mask)[0]) # # return create_subset(stimuli, fixations, indices) # # def filter_stimuli_by_size(stimuli, fixations, size=None, sizes=None): # if size is not None: # sizes = [size] # sizes = [tuple(size) for size in sizes] # # indices = [i for i in range(len(stimuli)) if stimuli.sizes[i] in sizes] # # return create_subset(stimuli, fixations, indices) # # def train_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='train', stratified_attributes=stratified_attributes) # # def validation_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='val', stratified_attributes=stratified_attributes) # # def test_split(stimuli, fixations, crossval_folds, fold_no, val_folds=1, test_folds=1, random=True, stratified_attributes=None): # return crossval_split(stimuli, fixations, crossval_folds, fold_no, val_folds=val_folds, test_folds=test_folds, random=random, split='test', stratified_attributes=stratified_attributes) which might include code, classes, or functions. Output only the next line.
new_fixations = fn(fixations, **kwargs)
Continue the code snippet: <|code_start|> DURATION_PATTERN = r'^((?P<hours>\d+)h)?((?P<minutes>\d+)m)?((?P<seconds>\d+)s)?$' TIME_FORMAT = r'%Y-%m-%dT%H:%M:%S%z' def utcnow() -> datetime.datetime: return datetime.datetime.now(datetime.timezone.utc) def parse_duration_to_time(duration: str) -> datetime.datetime: match = re.match(DURATION_PATTERN, duration) if match is None: raise ValueError( f"Unknown duration format {duration!r}. Try something like '1h2m3s'.", ) delta = datetime.timedelta( hours=int(match['hours'] or 0), minutes=int(match['minutes'] or 0), seconds=int(match['seconds'] or 0), <|code_end|> . Use current file imports: import re import argparse import datetime from django.core.management.base import BaseCommand, CommandError from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithPause and context (classes, functions, or code) from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithPause(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def pause(self, queue: QueueName, until: datetime.datetime) -> None: # raise NotImplementedError() # # @abstractmethod # def is_paused(self, queue: QueueName) -> bool: # raise NotImplementedError() . Output only the next line.
)
Predict the next line after this snippet: <|code_start|> DURATION_PATTERN = r'^((?P<hours>\d+)h)?((?P<minutes>\d+)m)?((?P<seconds>\d+)s)?$' TIME_FORMAT = r'%Y-%m-%dT%H:%M:%S%z' def utcnow() -> datetime.datetime: return datetime.datetime.now(datetime.timezone.utc) def parse_duration_to_time(duration: str) -> datetime.datetime: match = re.match(DURATION_PATTERN, duration) if match is None: raise ValueError( f"Unknown duration format {duration!r}. Try something like '1h2m3s'.", ) <|code_end|> using the current file's imports: import re import argparse import datetime from django.core.management.base import BaseCommand, CommandError from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithPause and any relevant context from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithPause(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def pause(self, queue: QueueName, until: datetime.datetime) -> None: # raise NotImplementedError() # # @abstractmethod # def is_paused(self, queue: QueueName) -> bool: # raise NotImplementedError() . Output only the next line.
delta = datetime.timedelta(
Here is a snippet: <|code_start|> def utcnow() -> datetime.datetime: return datetime.datetime.now(datetime.timezone.utc) def parse_duration_to_time(duration: str) -> datetime.datetime: match = re.match(DURATION_PATTERN, duration) if match is None: raise ValueError( f"Unknown duration format {duration!r}. Try something like '1h2m3s'.", ) delta = datetime.timedelta( hours=int(match['hours'] or 0), minutes=int(match['minutes'] or 0), seconds=int(match['seconds'] or 0), ) return utcnow() + delta def parse_time(date_string: str) -> datetime.datetime: return datetime.datetime.strptime(date_string, TIME_FORMAT) class Command(BaseCommand): help = """ Command to pause work on a redis-backed queue. New jobs can still be added to the queue, however no jobs will be pulled off <|code_end|> . Write the next line using the current file imports: import re import argparse import datetime from django.core.management.base import BaseCommand, CommandError from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithPause and context from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithPause(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def pause(self, queue: QueueName, until: datetime.datetime) -> None: # raise NotImplementedError() # # @abstractmethod # def is_paused(self, queue: QueueName) -> bool: # raise NotImplementedError() , which may include functions, classes, or code. Output only the next line.
the queue for processing.
Based on the snippet: <|code_start|> if TYPE_CHECKING: TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' class Job: def __init__( self, path: str, args: Tuple[Any, ...], kwargs: Dict[str, Any], timeout: Optional[int] = None, sigkill_on_stop: bool = False, ) -> None: self.path = path self.args = args self.kwargs = kwargs <|code_end|> , predict the immediate next line with the help of imports: import sys import json import time import datetime import warnings from typing import Any, Dict, Tuple, Callable, Optional, TYPE_CHECKING from django.db import transaction from .types import QueueName, WorkerNumber from .utils import get_path, get_middleware from .task import TaskWrapper and context (classes, functions, sometimes code) from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_path(path: str) -> Any: # module_name, attr = path.rsplit('.', 1) # # module = importlib.import_module(module_name) # # return getattr(module, attr) # # @lru_cache() # def get_middleware() -> List[Any]: # middleware = [] # # for path in app_settings.MIDDLEWARE: # try: # middleware.append(get_path(path)()) # except MiddlewareNotUsed: # pass # # return middleware . Output only the next line.
self.timeout = timeout
Here is a snippet: <|code_start|> self.sigkill_on_stop = sigkill_on_stop self.created_time = datetime.datetime.utcnow() self._json = None # type: Optional[str] def __repr__(self) -> str: return "<Job: {}(*{!r}, **{!r}) @ {}>".format( self.path, self.args, self.kwargs, self.created_time_str, ) @classmethod def from_json(cls, val: str) -> 'Job': as_dict = json.loads(val) # Historic jobs won't have a created_time, so have a default created_time = as_dict.pop('created_time', None) job = cls(**as_dict) if created_time is not None: job.created_time = datetime.datetime.strptime( created_time, TIME_FORMAT, ) # Ensures that Job.from_json(x).to_json() == x job._json = val <|code_end|> . Write the next line using the current file imports: import sys import json import time import datetime import warnings from typing import Any, Dict, Tuple, Callable, Optional, TYPE_CHECKING from django.db import transaction from .types import QueueName, WorkerNumber from .utils import get_path, get_middleware from .task import TaskWrapper and context from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_path(path: str) -> Any: # module_name, attr = path.rsplit('.', 1) # # module = importlib.import_module(module_name) # # return getattr(module, attr) # # @lru_cache() # def get_middleware() -> List[Any]: # middleware = [] # # for path in app_settings.MIDDLEWARE: # try: # middleware.append(get_path(path)()) # except MiddlewareNotUsed: # pass # # return middleware , which may include functions, classes, or code. Output only the next line.
return job
Next line prediction: <|code_start|> TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' class Job: def __init__( self, path: str, args: Tuple[Any, ...], kwargs: Dict[str, Any], timeout: Optional[int] = None, sigkill_on_stop: bool = False, ) -> None: self.path = path self.args = args self.kwargs = kwargs self.timeout = timeout self.sigkill_on_stop = sigkill_on_stop self.created_time = datetime.datetime.utcnow() self._json = None # type: Optional[str] def __repr__(self) -> str: return "<Job: {}(*{!r}, **{!r}) @ {}>".format( self.path, self.args, self.kwargs, self.created_time_str, ) <|code_end|> . Use current file imports: (import sys import json import time import datetime import warnings from typing import Any, Dict, Tuple, Callable, Optional, TYPE_CHECKING from django.db import transaction from .types import QueueName, WorkerNumber from .utils import get_path, get_middleware from .task import TaskWrapper) and context including class names, function names, or small code snippets from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_path(path: str) -> Any: # module_name, attr = path.rsplit('.', 1) # # module = importlib.import_module(module_name) # # return getattr(module, attr) # # @lru_cache() # def get_middleware() -> List[Any]: # middleware = [] # # for path in app_settings.MIDDLEWARE: # try: # middleware.append(get_path(path)()) # except MiddlewareNotUsed: # pass # # return middleware . Output only the next line.
@classmethod
Predict the next line for this snippet: <|code_start|> if TYPE_CHECKING: TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' class Job: def __init__( <|code_end|> with the help of current file imports: import sys import json import time import datetime import warnings from typing import Any, Dict, Tuple, Callable, Optional, TYPE_CHECKING from django.db import transaction from .types import QueueName, WorkerNumber from .utils import get_path, get_middleware from .task import TaskWrapper and context from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_path(path: str) -> Any: # module_name, attr = path.rsplit('.', 1) # # module = importlib.import_module(module_name) # # return getattr(module, attr) # # @lru_cache() # def get_middleware() -> List[Any]: # middleware = [] # # for path in app_settings.MIDDLEWARE: # try: # middleware.append(get_path(path)()) # except MiddlewareNotUsed: # pass # # return middleware , which may contain function names, class names, or code. Output only the next line.
self,
Predict the next line for this snippet: <|code_start|> class Command(BaseCommand): help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name def add_arguments(self, parser: CommandParser) -> None: parser.add_argument( 'queue', action='store', help="The queue to deduplicate", ) def handle(self, queue: QueueName, **options: Any) -> None: backend = get_backend(queue) if not isinstance(backend, BackendWithDeduplicate): raise CommandError( "Configured backend '{}.{}' doesn't support deduplication".format( type(backend).__module__, type(backend).__name__, ), ) original_size, new_size = backend.deduplicate( queue, progress_logger=self.get_progress_logger(), ) if original_size == new_size: self.stdout.write( <|code_end|> with the help of current file imports: from typing import Any, TypeVar from django.core.management.base import ( BaseCommand, CommandError, CommandParser, ) from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithDeduplicate from ...progress_logger import ProgressLogger import tqdm and context from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithDeduplicate(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def deduplicate( # self, # queue: QueueName, # *, # progress_logger: ProgressLogger = NULL_PROGRESS_LOGGER # ) -> Tuple[int, int]: # raise NotImplementedError() # # Path: django_lightweight_queue/progress_logger.py # T = TypeVar('T') # NULL_PROGRESS_LOGGER = ProgressLogger(lambda x: None, lambda x: x) , which may contain function names, class names, or code. Output only the next line.
"No duplicate jobs detected (queue length remains {})".format(
Based on the snippet: <|code_start|>class Command(BaseCommand): help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name def add_arguments(self, parser: CommandParser) -> None: parser.add_argument( 'queue', action='store', help="The queue to deduplicate", ) def handle(self, queue: QueueName, **options: Any) -> None: backend = get_backend(queue) if not isinstance(backend, BackendWithDeduplicate): raise CommandError( "Configured backend '{}.{}' doesn't support deduplication".format( type(backend).__module__, type(backend).__name__, ), ) original_size, new_size = backend.deduplicate( queue, progress_logger=self.get_progress_logger(), ) if original_size == new_size: self.stdout.write( "No duplicate jobs detected (queue length remains {})".format( original_size, <|code_end|> , predict the immediate next line with the help of imports: from typing import Any, TypeVar from django.core.management.base import ( BaseCommand, CommandError, CommandParser, ) from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithDeduplicate from ...progress_logger import ProgressLogger import tqdm and context (classes, functions, sometimes code) from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithDeduplicate(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def deduplicate( # self, # queue: QueueName, # *, # progress_logger: ProgressLogger = NULL_PROGRESS_LOGGER # ) -> Tuple[int, int]: # raise NotImplementedError() # # Path: django_lightweight_queue/progress_logger.py # T = TypeVar('T') # NULL_PROGRESS_LOGGER = ProgressLogger(lambda x: None, lambda x: x) . Output only the next line.
),
Continue the code snippet: <|code_start|> T = TypeVar('T') class Command(BaseCommand): help = "Command to deduplicate tasks in a redis-backed queue" # noqa:A003 # inherited name def add_arguments(self, parser: CommandParser) -> None: parser.add_argument( 'queue', action='store', help="The queue to deduplicate", ) def handle(self, queue: QueueName, **options: Any) -> None: backend = get_backend(queue) if not isinstance(backend, BackendWithDeduplicate): raise CommandError( <|code_end|> . Use current file imports: from typing import Any, TypeVar from django.core.management.base import ( BaseCommand, CommandError, CommandParser, ) from ...types import QueueName from ...utils import get_backend from ...backends.base import BackendWithDeduplicate from ...progress_logger import ProgressLogger import tqdm and context (classes, functions, or code) from other files: # Path: django_lightweight_queue/types.py # class Logger(Protocol): # def log( # self, # level: int, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def debug( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def info( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def warning( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def error( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # def exception( # self, # msg: str, # *args: Any, # exc_info: _ExcInfoType = ..., # stack_info: bool = ..., # extra: Optional[Dict[str, Any]] = ..., # **kwargs: Any # ) -> None: # # Path: django_lightweight_queue/utils.py # @lru_cache() # def get_backend(queue: QueueName) -> 'BaseBackend': # return get_path(app_settings.BACKEND_OVERRIDES.get( # queue, # app_settings.BACKEND, # ))() # # Path: django_lightweight_queue/backends/base.py # class BackendWithDeduplicate(BaseBackend, metaclass=ABCMeta): # @abstractmethod # def deduplicate( # self, # queue: QueueName, # *, # progress_logger: ProgressLogger = NULL_PROGRESS_LOGGER # ) -> Tuple[int, int]: # raise NotImplementedError() # # Path: django_lightweight_queue/progress_logger.py # T = TypeVar('T') # NULL_PROGRESS_LOGGER = ProgressLogger(lambda x: None, lambda x: x) . Output only the next line.
"Configured backend '{}.{}' doesn't support deduplication".format(
Given snippet: <|code_start|> args: Tuple[Any, ...] = ('args',), kwargs: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, sigkill_on_stop: bool = False, created_time: Optional[datetime.datetime] = None, ) -> Job: if created_time is None: created_time = self.start_time job = Job(path, args, kwargs or {}, timeout, sigkill_on_stop) job.created_time = created_time return job def setUp(self) -> None: super(JobTests, self).setUp() self.start_time = datetime.datetime.utcnow() def test_identity_same_created_time(self) -> None: job1 = self.create_job( created_time=datetime.datetime(2018, 1, 1), ) job2 = self.create_job( created_time=datetime.datetime(2018, 1, 1), ) self.assertEqual( job1.identity_without_created(), job2.identity_without_created(), <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import unittest from typing import Any, Dict, Tuple, Optional from django_lightweight_queue.job import Job and context: # Path: django_lightweight_queue/job.py # class Job: # def __init__( # self, # path: str, # args: Tuple[Any, ...], # kwargs: Dict[str, Any], # timeout: Optional[int] = None, # sigkill_on_stop: bool = False, # ) -> None: # self.path = path # self.args = args # self.kwargs = kwargs # self.timeout = timeout # self.sigkill_on_stop = sigkill_on_stop # self.created_time = datetime.datetime.utcnow() # # self._json = None # type: Optional[str] # # def __repr__(self) -> str: # return "<Job: {}(*{!r}, **{!r}) @ {}>".format( # self.path, # self.args, # self.kwargs, # self.created_time_str, # ) # # @classmethod # def from_json(cls, val: str) -> 'Job': # as_dict = json.loads(val) # # # Historic jobs won't have a created_time, so have a default # created_time = as_dict.pop('created_time', None) # # job = cls(**as_dict) # if created_time is not None: # job.created_time = datetime.datetime.strptime( # created_time, # TIME_FORMAT, # ) # # # Ensures that Job.from_json(x).to_json() == x # job._json = val # # return job # # @property # def created_time_str(self) -> str: # return self.created_time.strftime(TIME_FORMAT) # # def run(self, *, queue: QueueName, worker_num: WorkerNumber) -> bool: # """ # `queue` and `worker_num` arguments are required for context only and do # not change the behaviour of job execution. # """ # # start = time.time() # # middleware = get_middleware() # # for instance in middleware: # if hasattr(instance, 'process_job'): # instance.process_job(self, queue, worker_num) # # try: # task = self.get_task_instance() # # if task.atomic: # with transaction.atomic(): # result = task.fn(*self.args, **self.kwargs) # else: # result = task.fn(*self.args, **self.kwargs) # # time_taken = time.time() - start # # for instance in reversed(middleware): # if hasattr(instance, 'process_result'): # instance.process_result(self, result, time_taken) # except Exception: # time_taken = time.time() - start # # exc_info = sys.exc_info() # # for instance in reversed(middleware): # if hasattr(instance, 'process_exception'): # try: # instance.process_exception(self, time_taken, *exc_info) # except Exception: # pass # # return False # # return True # # def validate(self) -> None: # # Ensure these execute without exception so that we cannot enqueue # # things that are impossible to dequeue. # self.get_task_instance() # self.to_json() # # def get_task_instance(self) -> 'TaskWrapper[Callable[..., Any]]': # return get_path(self.path) # # def get_fn(self) -> 'TaskWrapper[Callable[..., Any]]': # warnings.warn( # "Job.get_fn is deprecated, call Job.get_task_instance instead.", # DeprecationWarning, # ) # return self.get_task_instance() # # def as_dict(self) -> Dict[str, Any]: # return { # 'path': self.path, # 'args': self.args, # 'kwargs': self.kwargs, # 'timeout': self.timeout, # 'sigkill_on_stop': self.sigkill_on_stop, # 'created_time': self.created_time_str, # } # # def to_json(self) -> str: # if self._json is None: # self._json = json.dumps(self.as_dict()) # return self._json # # def identity_without_created(self) -> str: # """Returns an object which can be used to identify equivalent jobs""" # self_dict = self.as_dict() # del self_dict['created_time'] # return json.dumps(self_dict, sort_keys=True) which might include code, classes, or functions. Output only the next line.
"Identities should match",
Next line prediction: <|code_start|>def update_pk_argument(field_name, rdtype): def add_update_pk_argument(parser, **kwargs): parser.add_argument( '--pk', required=True, default=None, type=int, dest='pk', help="The database integer primary key (id) of the " "{0} you are updating.".format(rdtype) ) return parser def extract_pk(nas): return _extract_pk(nas, field_name) return add_update_pk_argument, extract_pk, lambda: None def detail_pk_argument(field_name, rdtype): def add_detail_pk_argument(parser, **kwargs): parser.add_argument( '--pk', required=True, default=None, type=int, dest='pk', help="The database integer primary key (id) of the " "{0} you are getting detail about.".format(rdtype) ) return parser def extract_pk(nas): return _extract_pk(nas, field_name) return add_detail_pk_argument, extract_pk, lambda: None <|code_end|> . Use current file imports: (from invtool.tests.test_data import TEST_DESCRIPTION, TEST_STR from datetime import datetime import argparse) and context including class names, function names, or small code snippets from other files: # Path: invtool/tests/test_data.py # TEST_DESCRIPTION = '"This is a description"' # # TEST_STR = lambda: random_str() . Output only the next line.
def delete_pk_argument(field_name, rdtype):
Here is a snippet: <|code_start|> def build_extractor(field_name, nas_name): def extractor(nas): if not getattr(nas, nas_name): return {} data = {field_name: getattr(nas, nas_name)} return data return extractor def extract_pk(nas, field_name): return {field_name: getattr(nas, field_name)} def write_num_argument(parser, name, dest, help_text, required=False): parser.add_argument( '--{0}'.format(name), default=None, type=int, dest=dest, help=help_text, required=required ) return parser def _extract_pk(nas, field_name): return {field_name: nas.pk} <|code_end|> . Write the next line using the current file imports: from invtool.tests.test_data import TEST_DESCRIPTION, TEST_STR from datetime import datetime import argparse and context from other files: # Path: invtool/tests/test_data.py # TEST_DESCRIPTION = '"This is a description"' # # TEST_STR = lambda: random_str() , which may include functions, classes, or code. Output only the next line.
def update_pk_argument(field_name, rdtype):
Given the following code snippet before the placeholder: <|code_start|> __import__(d) def do_dispatch(args, IN=sys.stdin): inv_parser = argparse.ArgumentParser(prog='invtool') format_group = inv_parser.add_mutually_exclusive_group() format_group.add_argument( '--json', default=False, dest='p_json', action='store_true', help="Format the output as JSON" ) format_group.add_argument( '--silent', default=False, dest='p_silent', action='store_true', help="Silence all stdout and stderr" ) format_group.add_argument( '--debug', default=False, dest='DEBUG', action='store_true', help="Print stuff" ) format_group.add_argument( '--pk-only', default=False, dest='p_pk_only', action='store_true', help="If an object was just update/created print the primary key" "of that object otherwise print nothing. No new line is printed." ) base_parser = inv_parser.add_subparsers(dest='dtype') # Build parsers. Parses should register arguments. for d in registrar.dispatches: d.build_parser(base_parser) <|code_end|> , predict the next line using imports from the current file: import argparse import simplejson as json import sys from invtool.lib.registrar import registrar from invtool.dispatch import dispatch and context including class names, function names, and sometimes code from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/dispatch.py # def dispatch(nas): # for dispatch in registrar.dispatches: # if dispatch.dtype.lower() == nas.dtype.lower(): # return dispatch.route(nas) . Output only the next line.
nas = inv_parser.parse_args(args)
Continue the code snippet: <|code_start|> 'invtool.kv.kv_sreg_dispatch', 'invtool.system_dispatch', 'invtool.csv_dispatch', 'invtool.ba_dispatch', 'invtool.sreg_dispatch', 'invtool.decommission_dispatch', 'invtool.service_dispatch' ] for d in enabled_dispatches: __import__(d) def do_dispatch(args, IN=sys.stdin): inv_parser = argparse.ArgumentParser(prog='invtool') format_group = inv_parser.add_mutually_exclusive_group() format_group.add_argument( '--json', default=False, dest='p_json', action='store_true', help="Format the output as JSON" ) format_group.add_argument( '--silent', default=False, dest='p_silent', action='store_true', help="Silence all stdout and stderr" ) format_group.add_argument( '--debug', default=False, dest='DEBUG', action='store_true', help="Print stuff" ) format_group.add_argument( <|code_end|> . Use current file imports: import argparse import simplejson as json import sys from invtool.lib.registrar import registrar from invtool.dispatch import dispatch and context (classes, functions, or code) from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/dispatch.py # def dispatch(nas): # for dispatch in registrar.dispatches: # if dispatch.dtype.lower() == nas.dtype.lower(): # return dispatch.route(nas) . Output only the next line.
'--pk-only', default=False, dest='p_pk_only', action='store_true',
Next line prediction: <|code_start|> parser.add_argument( '--domain', default=None, type=str, dest='domain', help="The domain a record is in.", required=False) def domain_argument(field_name): def extract_domain(nas): data = {} if nas.domain: data.update({field_name: nas.domain}) return data def test_data(): return 'domain', TEST_DOMAIN return _add_domain_argument, extract_domain, test_data def _add_label_argument(parser, required=True): parser.add_argument( '--label', default="", type=str, dest='label', help="The first label in the fqdn. If label is ommited then '' is " "used and is analigouse to using '@' in a zone file (the record " "will get it's domain's name as it's fqdn).", required=False ) def fqdn_argument(field_name, rdtype): # We need rdtype because SRV requires a '_' to prefix it's test data def add_fqdn_argument(parser, required=True): <|code_end|> . Use current file imports: (from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME )) and context including class names, function names, or small code snippets from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
parser.add_argument(
Given the code snippet: <|code_start|> "used and is analigouse to using '@' in a zone file (the record " "will get it's domain's name as it's fqdn).", required=False ) def fqdn_argument(field_name, rdtype): # We need rdtype because SRV requires a '_' to prefix it's test data def add_fqdn_argument(parser, required=True): parser.add_argument( '--fqdn', default="", type=str, dest='fqdn', help="The FQDN of the record being created. If you use this " "option you cannot use label or domain", required=required ) def test_data(): if rdtype == "CNAME": # Make the target different so avoid cname loop errors return 'fqdn', "A" + TEST_FQDN if rdtype == "SRV": return 'fqdn', "_" + TEST_FQDN else: return 'fqdn', TEST_FQDN return add_fqdn_argument, build_extractor(field_name, 'fqdn'), test_data def system_argument(field_name): display_name = field_name.replace('_', '-') def add_system_argument(parser, required=True): <|code_end|> , generate the next line using the imports in this file: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context (functions, classes, or occasionally code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
parser.add_argument(
Next line prediction: <|code_start|> '--ip', default=None, type=str, dest='ip', help="A string representation of an IP address.", required=required ) def test_data(): if ip_type == '4': return 'ip', TEST_IPv4() elif ip_type == '6': return 'ip', TEST_IPv6() return add_ip_argument, build_extractor(field_name, 'ip'), test_data def target_argument(field_name): def add_target_arg(parser, required=True): parser.add_argument( '--target', default=None, type=str, dest='target', help="The target name of a record", required=required ) def test_data(): return 'target', TEST_FQDN return add_target_arg, build_extractor(field_name, 'target'), test_data def name_argument(field_name, prefix='nic'): def add_com_arg(parser, required=False, **kwargs): parser.add_argument( <|code_end|> . Use current file imports: (from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME )) and context including class names, function names, or small code snippets from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
'--{0}'.format('name'), type=str,
Here is a snippet: <|code_start|> def add_text_argument(parser, required=True): parser.add_argument( '--text', default=None, type=str, dest='text', help="The text data.", required=required ) def test_data(): return 'text', TEST_TEXT return add_text_argument, build_extractor(field_name, 'text'), test_data def ttl_argument(field_name): def add_ttl_argument(parser, **kwargs): write_num_argument( parser, 'ttl', 'ttl', "The ttl of a record.", required=False ) def extract_ttl(nas): data = {} if nas.ttl: data['ttl'] = nas.ttl return data def test_data(): return 'ttl', TEST_TTL return add_ttl_argument, build_extractor(field_name, 'ttl'), test_data <|code_end|> . Write the next line using the current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() , which may include functions, classes, or code. Output only the next line.
def key_argument(field_name):
Predict the next line after this snippet: <|code_start|> def view_arguments(field_name): def add_view_arguments(parser, required=False): pri_group = parser.add_mutually_exclusive_group() pri_group.add_argument('--no-private', default=False, action='store_true', dest='no_private', help="Disable private view.", required=required) pri_group.add_argument('--private', default=False, action='store_true', dest='private', help="Enabled private view.", required=False) pub_group = parser.add_mutually_exclusive_group() pub_group.add_argument('--no-public', default=False, action='store_true', dest='no_public', help="Disable public view.", required=required) <|code_end|> using the current file's imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and any relevant context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
pub_group.add_argument('--public', default=False, action='store_true',
Predict the next line for this snippet: <|code_start|> action='store_true', dest='no_public', help="Disable public view.", required=required) pub_group.add_argument('--public', default=False, action='store_true', dest='public', help="Enabled public view.", required=False) def extract_views(nas): views = [] if nas.no_private: views.append('no-private') elif nas.private: views.append('private') if nas.no_public: views.append('no-public') elif nas.public: views.append('public') data = {field_name: views} return data def test_data(): return '', '--no-public --private' return add_view_arguments, extract_views, test_data def _add_domain_argument(parser, required=True): parser.add_argument( '--domain', default=None, type=str, dest='domain', <|code_end|> with the help of current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() , which may contain function names, class names, or code. Output only the next line.
help="The domain a record is in.", required=False)
Continue the code snippet: <|code_start|> pri_group.add_argument('--no-private', default=False, action='store_true', dest='no_private', help="Disable private view.", required=required) pri_group.add_argument('--private', default=False, action='store_true', dest='private', help="Enabled private view.", required=False) pub_group = parser.add_mutually_exclusive_group() pub_group.add_argument('--no-public', default=False, action='store_true', dest='no_public', help="Disable public view.", required=required) pub_group.add_argument('--public', default=False, action='store_true', dest='public', help="Enabled public view.", required=False) def extract_views(nas): views = [] if nas.no_private: views.append('no-private') elif nas.private: views.append('private') if nas.no_public: views.append('no-public') elif nas.public: views.append('public') <|code_end|> . Use current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context (classes, functions, or code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
data = {field_name: views}
Based on the snippet: <|code_start|> help="Disable private view.", required=required) pri_group.add_argument('--private', default=False, action='store_true', dest='private', help="Enabled private view.", required=False) pub_group = parser.add_mutually_exclusive_group() pub_group.add_argument('--no-public', default=False, action='store_true', dest='no_public', help="Disable public view.", required=required) pub_group.add_argument('--public', default=False, action='store_true', dest='public', help="Enabled public view.", required=False) def extract_views(nas): views = [] if nas.no_private: views.append('no-private') elif nas.private: views.append('private') if nas.no_public: views.append('no-public') elif nas.public: views.append('public') data = {field_name: views} return data <|code_end|> , predict the immediate next line with the help of imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context (classes, functions, sometimes code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
def test_data():
Given the following code snippet before the placeholder: <|code_start|> if nas.ttl: data['ttl'] = nas.ttl return data def test_data(): return 'ttl', TEST_TTL return add_ttl_argument, build_extractor(field_name, 'ttl'), test_data def key_argument(field_name): def add_key_argument(parser, required=True): parser.add_argument( '--key', default=None, type=str, dest='sshfp_key', help="The key data.", required=required ) def algorithm_argument(field_name): def add_algorithm_argument(parser, required=True): parser.add_argument( '--algo', metavar="algorithm type", type=str, dest='algorith_type', choices=['RSA', 'DSS'], help="The Algorithm type. See RFC 4255.", required=required ) return parser def fingerprint_argument(field_name): def add_fingerprint_argument(parser, required=False): <|code_end|> , predict the next line using imports from the current file: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context including class names, function names, and sometimes code from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
parser.add_argument(
Given snippet: <|code_start|> parser, 'ttl', 'ttl', "The ttl of a record.", required=False ) def extract_ttl(nas): data = {} if nas.ttl: data['ttl'] = nas.ttl return data def test_data(): return 'ttl', TEST_TTL return add_ttl_argument, build_extractor(field_name, 'ttl'), test_data def key_argument(field_name): def add_key_argument(parser, required=True): parser.add_argument( '--key', default=None, type=str, dest='sshfp_key', help="The key data.", required=required ) def algorithm_argument(field_name): def add_algorithm_argument(parser, required=True): parser.add_argument( '--algo', metavar="algorithm type", type=str, dest='algorith_type', choices=['RSA', 'DSS'], help="The Algorithm type. See RFC 4255.", required=required ) <|code_end|> , continue by predicting the next line. Consider current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and context: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() which might include code, classes, or functions. Output only the next line.
return parser
Predict the next line after this snippet: <|code_start|> def name_argument(field_name, prefix='nic'): def add_com_arg(parser, required=False, **kwargs): parser.add_argument( '--{0}'.format('name'), type=str, dest='name', help="A short name", required=required ) def test_data(): return 'name', TEST_INAME(prefix=prefix) # Reuse this test data return add_com_arg, build_extractor(field_name, 'name'), test_data def text_argument(field_name): def add_text_argument(parser, required=True): parser.add_argument( '--text', default=None, type=str, dest='text', help="The text data.", required=required ) def test_data(): return 'text', TEST_TEXT return add_text_argument, build_extractor(field_name, 'text'), test_data def ttl_argument(field_name): <|code_end|> using the current file's imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME ) and any relevant context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
def add_ttl_argument(parser, **kwargs):
Next line prediction: <|code_start|> def add_fqdn_argument(parser, required=True): parser.add_argument( '--fqdn', default="", type=str, dest='fqdn', help="The FQDN of the record being created. If you use this " "option you cannot use label or domain", required=required ) def test_data(): if rdtype == "CNAME": # Make the target different so avoid cname loop errors return 'fqdn', "A" + TEST_FQDN if rdtype == "SRV": return 'fqdn', "_" + TEST_FQDN else: return 'fqdn', TEST_FQDN return add_fqdn_argument, build_extractor(field_name, 'fqdn'), test_data def system_argument(field_name): display_name = field_name.replace('_', '-') def add_system_argument(parser, required=True): parser.add_argument( '--{0}'.format(display_name), default="", type=str, dest=field_name, help="The hostname of the system this " "registration is associated with", required=True ) def test_data(): <|code_end|> . Use current file imports: (from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import ( TEST_DOMAIN, TEST_FQDN, TEST_IPv4, TEST_IPv6, TEST_TTL, TEST_PORT, TEST_WEIGHT, TEST_PRIORITY, TEST_TEXT, TEST_INAME )) and context including class names, function names, or small code snippets from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # def random_str(length=10): # N = 32 # TEST_DOMAIN = ( # ''.join( # random.choice(string.ascii_uppercase + string.digits) # for x in range(N)) + ".foo.bar.test_domain.lab1.mozilla.net" # ) # TEST_FQDN = "testfqdn." + TEST_DOMAIN # TEST_DESCRIPTION = '"This is a description"' # TEST_TTL = "9999" # TEST_PORT = "8888" # TEST_WEIGHT = "7777" # TEST_PRIORITY = "5555" # TEST_TEXT = "FOO 'BAR' baz" # TEST_INAME = lambda prefix='eth': prefix + str(random.randint(0, 255)) # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) # TEST_STR = lambda: random_str() . Output only the next line.
return 'system-hostname', 'toolsdev1.dmz.scl3.mozilla.com'
Next line prediction: <|code_start|> def name_argument(field_name, required=False): def add_name_arg(parser, required=required, **kwargs): parser.add_argument( '--{0}'.format(field_name), type=str, dest=field_name, help="A name.", required=required ) <|code_end|> . Use current file imports: (from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import TEST_NAME, TEST_PORT, TEST_NETWORK) and context including class names, function names, or small code snippets from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # # TEST_PORT = "8888" # # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) . Output only the next line.
def test_data():
Predict the next line for this snippet: <|code_start|> ) def extract_arg(nas): data = {} if nas.vlan: data = {field_name: nas.vlan} return data def test_data(): # vlan will need to be evaluated in at test time return 'vlan-pk', '{{ vlan }}' return add_argument, extract_arg, test_data def site_argument(field_name): def add_argument(parser, required=False): parser.add_argument( '--site-pk', type=str, dest='site', required=required, help="The pk of a site" ) def extract_arg(nas): data = {} if nas.site: data = {field_name: nas.site} return data def test_data(): # site need to be evaluated in at test time <|code_end|> with the help of current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import TEST_NAME, TEST_PORT, TEST_NETWORK and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # # TEST_PORT = "8888" # # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) , which may contain function names, class names, or code. Output only the next line.
return 'site-pk', '{{ site }}'
Continue the code snippet: <|code_start|> parser.add_argument( '--{0}'.format(field_name), type=str, dest=field_name, help="A name.", required=required ) def test_data(): return field_name, TEST_NAME() # Reuse this test data return add_name_arg, build_extractor(field_name, field_name), test_data def number_argument(field_name, required=False): def add_number_argument(parser, required=required): write_num_argument( parser, field_name, field_name, "A number number.", required=required ) def test_data(): return field_name, TEST_PORT return ( add_number_argument, build_extractor(field_name, field_name), test_data ) def network_str_argument(field_name, required=False): <|code_end|> . Use current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import TEST_NAME, TEST_PORT, TEST_NETWORK and context (classes, functions, or code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # # TEST_PORT = "8888" # # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) . Output only the next line.
def add_network_argument(parser, required=required):
Predict the next line for this snippet: <|code_start|> def name_argument(field_name, required=False): def add_name_arg(parser, required=required, **kwargs): parser.add_argument( '--{0}'.format(field_name), type=str, dest=field_name, help="A name.", required=required ) def test_data(): return field_name, TEST_NAME() # Reuse this test data return add_name_arg, build_extractor(field_name, field_name), test_data def number_argument(field_name, required=False): def add_number_argument(parser, required=required): write_num_argument( parser, field_name, field_name, "A number number.", required=required ) <|code_end|> with the help of current file imports: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import TEST_NAME, TEST_PORT, TEST_NETWORK and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # # TEST_PORT = "8888" # # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) , which may contain function names, class names, or code. Output only the next line.
def test_data():
Given the code snippet: <|code_start|> return data return extractor return ( add_network_argument, build_extractor('network_str', 'network_str'), test_data ) def vlan_argument(field_name): def add_argument(parser, required=False): parser.add_argument( '--vlan-pk', type=str, dest='vlan', required=required, help="The pk of a vlan" ) def extract_arg(nas): data = {} if nas.vlan: data = {field_name: nas.vlan} return data def test_data(): # vlan will need to be evaluated in at test time return 'vlan-pk', '{{ vlan }}' return add_argument, extract_arg, test_data <|code_end|> , generate the next line using the imports in this file: from invtool.lib.options import build_extractor, write_num_argument from invtool.tests.test_data import TEST_NAME, TEST_PORT, TEST_NETWORK and context (functions, classes, or occasionally code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def write_num_argument(parser, name, dest, help_text, required=False): # parser.add_argument( # '--{0}'.format(name), default=None, type=int, # dest=dest, help=help_text, required=required # ) # return parser # # Path: invtool/tests/test_data.py # TEST_NAME = lambda: 'whap{0}{1}foo'.format( # random.randint(0, 255), random.randint(0, 255) # ) # # TEST_PORT = "8888" # # TEST_NETWORK = '10.0.{0}.{1}/27'.format( # random.randint(0, 255), random.randint(0, 255) # ) . Output only the next line.
def site_argument(field_name):
Using the snippet: <|code_start|> extractor = build_extractor(field_name, field_name) return add_group_argument, extractor, test_data def mac_argument(field_name): def add_com_arg(parser, required=True, **kwargs): parser.add_argument( '--{0}'.format(field_name), default="", type=str, dest='mac', help="Mac Address", required=required ) def test_data(): return field_name, TEST_MAC() return add_com_arg, build_extractor(field_name, field_name), test_data def enable_dhcp_argument(field_name): def add_enable_dhcp_argument(parser, required=False): dhcp_group = parser.add_mutually_exclusive_group() dhcp_group.add_argument( '--no-dhcp', default=False, action='store_false', dest='enable_dhcp', help="Disable dhcp.", required=required ) dhcp_group.add_argument( '--dhcp', default=True, action='store_true', dest='enable_dhcp', help="Enabled dhcp (True by default).", required=required <|code_end|> , determine the next line of code. You have imports: from invtool.lib.options import build_extractor from invtool.tests.test_data import TEST_MAC and context (class names, function names, or code) available: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # Path: invtool/tests/test_data.py # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) . Output only the next line.
)
Here is a snippet: <|code_start|> help="Enabled dhcp (True by default).", required=required ) def test_data(): return '', '--no-dhcp' extractor = build_extractor(field_name, 'enable_dhcp') return add_enable_dhcp_argument, extractor, test_data def sreg_argument(field_name): def add_sreg_argument(parser, required=False): group = parser.add_mutually_exclusive_group() group.add_argument( '--sreg-pk', type=str, dest='sreg_pk', default=False, required=required, help="The pk of a registration" ) group.add_argument( '--sreg-url', type=str, dest='sreg_url', default=False, required=required, help="The RESTful url of a registration" ) def extract_sreg(nas): if nas.sreg_pk: sreg = nas.sreg_pk elif nas.sreg_url: sreg = nas.sreg_pk else: raise Exception('sreg is required') <|code_end|> . Write the next line using the current file imports: from invtool.lib.options import build_extractor from invtool.tests.test_data import TEST_MAC and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # Path: invtool/tests/test_data.py # TEST_MAC = lambda: '{0}{0}:{1}{1}:{2}{2}:{3}{3}:{4}{4}:{5}{5}'.format( # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9), # random.randint(0, 9) # ) , which may include functions, classes, or code. Output only the next line.
data = {field_name: sreg}
Based on the snippet: <|code_start|> nas, resp_msg, "http_status: 202 (Accepted)" ) elif resp.status_code == 200: return 0, self.format_response( nas, resp_msg, "http_status: 200 (Success)" ) elif resp.status_code == 401: return 1, [ "Auth Failure! Check your password, or update your keychain " "using inv-tool/scripts/reset_keychain.py" ] else: resp_list = [] resp_list.append("Client didn't understand the response.") resp_list.append( "CLIENT ERROR! (Please email this output to a code monkey)" ) return self.error_out(nas, data, resp, resp_list=resp_list) def get_errors(self, resp_msg): messages = json.loads(resp_msg, 'unicode') errors = [] for error, msg in messages.iteritems(): if error == '__all__': error = "Object Error" if isinstance(msg, list): errors.append("Error: {0} {1}".format(error, ', '.join(msg))) else: errors.append("Error: {0} {1}".format(error, msg)) <|code_end|> , predict the immediate next line with the help of imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context (classes, functions, sometimes code) from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
return 1, errors
Given the following code snippet before the placeholder: <|code_start|> return self.action(nas, url, requests.post, data) def action(self, nas, url, method, data, form_encode=True): headers = {'content-type': 'application/json'} if form_encode: wire_data = json.dumps(data, indent=2) else: wire_data = data if nas.DEBUG: sys.stderr.write('method: {0}\nurl: {1}\nparams:{2}\n'.format( method.__name__, url, json.dumps(data, indent=2) )) resp = method(url, headers=headers, data=wire_data, auth=auth()) return self.handle_resp(nas, data, resp) def get_create_data(self, nas): data = {} for add_arg, extract_arg, test_method in self.create_args: data.update(extract_arg(nas)) return data def get_update_data(self, nas): data = {} for add_arg, extract_arg, test_method in self.update_args: data.update(extract_arg(nas)) return data class ObjectDispatch(Dispatch): # Handy base class <|code_end|> , predict the next line using imports from the current file: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context including class names, function names, and sometimes code from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
object_url = None # fill me in
Here is a snippet: <|code_start|> ) elif resp.status_code == 202: return 0, self.format_response( nas, resp_msg, "http_status: 202 (Accepted)" ) elif resp.status_code == 200: return 0, self.format_response( nas, resp_msg, "http_status: 200 (Success)" ) elif resp.status_code == 401: return 1, [ "Auth Failure! Check your password, or update your keychain " "using inv-tool/scripts/reset_keychain.py" ] else: resp_list = [] resp_list.append("Client didn't understand the response.") resp_list.append( "CLIENT ERROR! (Please email this output to a code monkey)" ) return self.error_out(nas, data, resp, resp_list=resp_list) def get_errors(self, resp_msg): messages = json.loads(resp_msg, 'unicode') errors = [] for error, msg in messages.iteritems(): if error == '__all__': error = "Object Error" if isinstance(msg, list): errors.append("Error: {0} {1}".format(error, ', '.join(msg))) <|code_end|> . Write the next line using the current file imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) , which may include functions, classes, or code. Output only the next line.
else:
Next line prediction: <|code_start|> return 1, resp_list def delete(self, nas): url = "{0}{1}?format=json".format(REMOTE, self.delete_url(nas)) headers = {'content-type': 'application/json'} resp = requests.delete(url, headers=headers, auth=auth()) return self.handle_resp(nas, {}, resp) def detail(self, nas): url = "{0}{1}?format=json".format(REMOTE, self.detail_url(nas)) headers = {'content-type': 'application/json'} if nas.DEBUG: sys.stderr.write('method: {0}\nurl: {1}\nparams:{2}\n'.format( 'get', url, {} )) resp = requests.get(url, headers=headers, auth=auth()) return self.handle_resp(nas, {}, resp) def update(self, nas): data = self.get_update_data(nas) # Dispatch defined Hook url = "{0}{1}".format(REMOTE, self.update_url(nas)) return self.action(nas, url, requests.patch, data) def create(self, nas): data = self.get_create_data(nas) # Dispatch defined Hook url = "{0}{1}".format(REMOTE, self.create_url(nas)) return self.action(nas, url, requests.post, data) def action(self, nas, url, method, data, form_encode=True): headers = {'content-type': 'application/json'} <|code_end|> . Use current file imports: ( import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser )) and context including class names, function names, or small code snippets from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
if form_encode:
Predict the next line after this snippet: <|code_start|> "Auth Failure! Check your password, or update your keychain " "using inv-tool/scripts/reset_keychain.py" ] else: resp_list = [] resp_list.append("Client didn't understand the response.") resp_list.append( "CLIENT ERROR! (Please email this output to a code monkey)" ) return self.error_out(nas, data, resp, resp_list=resp_list) def get_errors(self, resp_msg): messages = json.loads(resp_msg, 'unicode') errors = [] for error, msg in messages.iteritems(): if error == '__all__': error = "Object Error" if isinstance(msg, list): errors.append("Error: {0} {1}".format(error, ', '.join(msg))) else: errors.append("Error: {0} {1}".format(error, msg)) return 1, errors def get_resp_dict(self, resp): if resp.text: # Tasty pie returns json that is unicode. Thats ok. msg = json.loads(resp.text, 'unicode') else: msg = {'message': 'No message from server'} <|code_end|> using the current file's imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and any relevant context from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
msg['http_status'] = resp.status_code
Here is a snippet: <|code_start|> self.dtype, help="Interface for {0}s".format(self.dtype), add_help=True ) action_parser = record_base_parser.add_subparsers( help="{0} actions".format(self.dtype), dest='action' ) build_create_parser(self, action_parser) build_update_parser(self, action_parser) build_delete_parser(self, action_parser) build_detail_parser(self, action_parser) # TODO, dedup this code def delete_url(self, nas): return self.object_url.format( API_MAJOR_VERSION, self.resource_name, nas.pk ) def detail_url(self, nas): return self.object_url.format( API_MAJOR_VERSION, self.resource_name, nas.pk ) def update_url(self, nas): return self.object_url.format( API_MAJOR_VERSION, self.resource_name, nas.pk ) def create_url(self, nas): <|code_end|> . Write the next line using the current file imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) , which may include functions, classes, or code. Output only the next line.
return self.object_list_url.format(
Continue the code snippet: <|code_start|> # Bad Request if nas.p_json: if resp_msg: return 1, [json.dumps(resp_msg, indent=2)] else: return 1, [json.dumps({'errors': resp.content}, indent=2)] else: if 'error_messages' in resp_msg: return self.get_errors(resp_msg['error_messages']) elif 'errors' in resp_msg: return 1, [resp_msg['errors']] elif 'message' in resp_msg: return 1, [resp_msg['message']] elif resp.content: return 1, ['errors: {0}'.format(resp.content)] else: return 1, ["http_status: 400 (bad request)"] elif resp.status_code == 201: return 0, self.format_response( nas, resp_msg, "http_status: 201 (created)" ) elif resp.status_code == 202: return 0, self.format_response( nas, resp_msg, "http_status: 202 (Accepted)" ) elif resp.status_code == 200: return 0, self.format_response( nas, resp_msg, "http_status: 200 (Success)" ) <|code_end|> . Use current file imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context (classes, functions, or code) from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
elif resp.status_code == 401:
Based on the snippet: <|code_start|>try: except ImportError: class Dispatch(object): def format_response(self, nas, resp_msg, user_msg): resp_list = [] if nas.p_json: resp_list.append(json.dumps(resp_msg, indent=2)) else: resp_list.append(user_msg) for k, v in resp_msg.iteritems(): resp_list.append("{0}: {1}".format(k, v)) return resp_list def handle_resp(self, nas, data, resp): try: resp_msg = self.get_resp_dict(resp) except json.decoder.JSONDecodeError: resp_msg = {} <|code_end|> , predict the immediate next line with the help of imports: import simplejson as json import json import sys import requests from gettext import gettext as _ from invtool.lib.registrar import registrar from invtool.lib.config import REMOTE, auth, API_MAJOR_VERSION from invtool.lib.parser import ( build_create_parser, build_update_parser, build_delete_parser, build_detail_parser ) and context (classes, functions, sometimes code) from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/lib/config.py # REMOTE = "http{0}://{1}{2}".format( # 's' if dev != 'True' else '', # host, # '' if port == '80' else ':' + port # ) # # def auth(): # global authcache # if authcache is False: # authcache = _realauth() # # return authcache # # API_MAJOR_VERSION = 1 # # Path: invtool/lib/parser.py # def build_create_parser(dispatch, action_parser, help=''): # if not help: # help = "Create a(n) {0} record".format(dispatch.dtype) # create_parser = action_parser.add_parser('create', help=help) # for add_arg, extract_arg, test_method in dispatch.create_args: # add_arg(create_parser) # # def build_update_parser(dispatch, action_parser, help=''): # if not help: # help = "Update a(n) {0}".format(dispatch.dtype) # update_parser = action_parser.add_parser('update', help=help) # for add_arg, extract_arg, test_method in dispatch.update_args: # add_arg(update_parser, required=False) # # def build_delete_parser(dispatch, action_parser, help=''): # if not help: # help = "Delete a(n) {0}".format(dispatch.dtype) # delete_parser = action_parser.add_parser('delete', help=help) # for add_arg, extract_arg, test_method in dispatch.delete_args: # add_arg(delete_parser) # # def build_detail_parser(dispatch, action_parser, help=''): # if not help: # help = "Detail a(n) {0}".format(dispatch.dtype) # detail_parser = action_parser.add_parser('detail', help=help) # for add_arg, extract_arg, test_method in dispatch.detail_args: # add_arg(detail_parser) . Output only the next line.
if resp.status_code == 404:
Predict the next line for this snippet: <|code_start|> def test_search(): expected_status, command = commands[0] ret, errors, rc = call_to_json(command) if errors: self.fail(errors) self.assertEqual(0, rc) self.assertTrue('http_status' in ret) self.assertEqual(ret['http_status'], expected_status) test_search() # Range def test_range(): expected_status, command = commands[1] ret, errors, rc = call_to_json(command) if errors: self.fail(errors) self.assertEqual(0, rc) self.assertTrue('http_status' in ret) self.assertEqual(ret['http_status'], expected_status) test_range() # CSV export <|code_end|> with the help of current file imports: import unittest import simplejson as json import json from invtool.tests.utils import call_to_json, EXEC and context from other files: # Path: invtool/tests/utils.py # def call_to_json(command_str): # """ # Given a string, this function will shell out, execute the command # and parse the json returned by that command # """ # print command_str # p = subprocess.Popen(shlex.split(command_str), # stderr=subprocess.PIPE, stdout=subprocess.PIPE) # stdout, stderr = p.communicate() # if stderr: # return None, stderr, p.returncode # # stdout = stdout.replace('u\'', '"').replace('\'', '"').strip('\n') # try: # return json.loads(stdout, 'unicode'), None, p.returncode # except json.decoder.JSONDecodeError, e: # return (None, # "Ret was: {0}. Got error: {1}".format(stdout, str(e)), # p.returncode) # # EXEC = "./inv --json" , which may contain function names, class names, or code. Output only the next line.
def test_csv_export():
Based on the snippet: <|code_start|> expected_status, command = commands[1] ret, errors, rc = call_to_json(command) if errors: self.fail(errors) self.assertEqual(0, rc) self.assertTrue('http_status' in ret) self.assertEqual(ret['http_status'], expected_status) test_range() # CSV export def test_csv_export(): expected_status, command = commands[2] ret, errors, rc = call_to_json(command) if errors: self.fail(errors) self.assertEqual(0, rc) self.assertTrue('http_status' in ret) self.assertEqual(ret['http_status'], expected_status) test_csv_export() test_name = "test_{0}".format('search') place_holder.__name__ = test_name <|code_end|> , predict the immediate next line with the help of imports: import unittest import simplejson as json import json from invtool.tests.utils import call_to_json, EXEC and context (classes, functions, sometimes code) from other files: # Path: invtool/tests/utils.py # def call_to_json(command_str): # """ # Given a string, this function will shell out, execute the command # and parse the json returned by that command # """ # print command_str # p = subprocess.Popen(shlex.split(command_str), # stderr=subprocess.PIPE, stdout=subprocess.PIPE) # stdout, stderr = p.communicate() # if stderr: # return None, stderr, p.returncode # # stdout = stdout.replace('u\'', '"').replace('\'', '"').strip('\n') # try: # return json.loads(stdout, 'unicode'), None, p.returncode # except json.decoder.JSONDecodeError, e: # return (None, # "Ret was: {0}. Got error: {1}".format(stdout, str(e)), # p.returncode) # # EXEC = "./inv --json" . Output only the next line.
setattr(_TestCase, test_name, place_holder)
Given the code snippet: <|code_start|>try: except ImportError: class DispatchSystem(CoreDispatch): object_url = "/en-US/core/api/v1_core/{1}/{2}/" <|code_end|> , generate the next line using the imports in this file: import simplejson as json import json # noqa from invtool.lib.registrar import registrar from invtool.core_dispatch import CoreDispatch from invtool.lib.config import API_MAJOR_VERSION from invtool.lib.options import ( comment_argument, general_argument, datetime_argument, date_argument ) from invtool.lib.system_options import ( foreign_key_argument, hostname_argument, notes_argument, system_pk_argument, new_hostname_argument ) and context (functions, classes, or occasionally code) from other files: # Path: invtool/lib/registrar.py # class Registrar(): # def register(self, dispatch): # # Path: invtool/core_dispatch.py # class CoreDispatch(ObjectDispatch): # object_url = "/en-US/core/api/v1_core/{1}/{2}/" # object_list_url = "/en-US/core/api/v1_core/{1}/" # # Path: invtool/lib/config.py # API_MAJOR_VERSION = 1 # # Path: invtool/lib/options.py # def comment_argument(field_name): # def add_com_arg(parser, **kwargs): # parser.add_argument( # '--comment', default="", type=str, # dest='comment', help="Use this to record why a change is " # "being made", required=False # ) # # def test_data(): # return 'comment', TEST_DESCRIPTION # Reuse this test data # # return add_com_arg, build_extractor(field_name, 'comment'), test_data # # def general_argument(field_name, help, type=lambda x: x, test_data=None): # real_fname = field_name.replace('-', '_') # # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--{0}'.format(field_name), default="", type=str, # dest=real_fname, required=False, help=help # ) # # if test_data is None: # def test_data_fun(): # return field_name, TEST_STR() # Reuse this test data # else: # test_data_fun = test_data # # return add_srt_arg, build_extractor(real_fname, real_fname), test_data_fun # # def datetime_argument(field_name, help): # def parse_datetime(date_str): # try: # datetime.strptime(date_str, '%Y-%m-%dT%M:%H') # except ValueError: # raise argparse.ArgumentTypeError( # '{0} is not in the format yyyy-mm-ddThh-mm (iso-8601)'.format( # date_str) # ) # # def test_data_fun(): # return field_name, '2013-02-02T11:11' # # return general_argument( # field_name, help, type=parse_datetime, test_data=test_data_fun # ) # # def date_argument(field_name, help): # def parse_date(date_str): # try: # datetime.strptime(date_str, '%Y-%m-%d') # except ValueError: # raise argparse.ArgumentTypeError( # '{0} is not in the format yyyy-mm-dd'.format( # date_str) # ) # # def test_data_fun(): # return field_name, '2013-02-02' # # return general_argument( # field_name, help, type=parse_date, test_data=test_data_fun # ) # # Path: invtool/lib/system_options.py # def foreign_key_argument(field_name, help): # real_fname = field_name.replace('-', '_') # # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--{0}-pk'.format(field_name), default="", type=str, # dest=real_fname, required=False, help=help # ) # # def test_data(): # return '', '' # # return add_srt_arg, build_extractor(real_fname, real_fname), test_data # # def hostname_argument(field_name, help): # return general_argument(field_name, help) # # def notes_argument(field_name, help): # """ # Work around for systems calling it 'Notes' and everything else calling it # 'Description'. # """ # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--description', default="", type=str, dest='notes', # required=False, help=help # ) # # def test_data(): # return 'description', 'asdfasdf' # # return add_srt_arg, build_extractor('notes', 'notes'), test_data # # def system_pk_argument(action='updating'): # def add_pk_arg(parser, **kwargs): # arg_g = parser.add_mutually_exclusive_group(required=True) # arg_g.add_argument( # '--hostname', type=str, dest='pk', # help='The hostname of a system you are {0}'.format(action) # ) # arg_g.add_argument( # '--pk', type=str, dest='pk', # help='The integer primary key of a system you are ' # '{0}'.format(action) # ) # # def extract_pk(nas): # if nas.hostname: # return {'pk': nas.hostname} # else: # return {'pk': nas.pk} # # return add_pk_arg, build_extractor('hostname', 'hostname'), lambda: None # # def new_hostname_argument(): # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--new-hostname', default="", type=str, # dest='hostname', required=False, help='If you are changing the ' # 'hostname of an existing system specify it with --hostname and ' # 'use this option to assign a new hostname' # ) # # def test_data(): # return 'new-hostname', TEST_STR() # # return add_srt_arg, build_extractor('hostname', 'hostname'), test_data . Output only the next line.
object_list_url = "/en-US/core/api/v1_core/{1}/"
Here is a snippet: <|code_start|> def foreign_key_argument(field_name, help): real_fname = field_name.replace('-', '_') def add_srt_arg(parser, **kwargs): parser.add_argument( '--{0}-pk'.format(field_name), default="", type=str, dest=real_fname, required=False, help=help ) def test_data(): return '', '' return add_srt_arg, build_extractor(real_fname, real_fname), test_data def hostname_argument(field_name, help): return general_argument(field_name, help) def new_hostname_argument(): def add_srt_arg(parser, **kwargs): parser.add_argument( '--new-hostname', default="", type=str, <|code_end|> . Write the next line using the current file imports: from invtool.lib.options import build_extractor, general_argument from invtool.tests.test_data import TEST_STR and context from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def general_argument(field_name, help, type=lambda x: x, test_data=None): # real_fname = field_name.replace('-', '_') # # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--{0}'.format(field_name), default="", type=str, # dest=real_fname, required=False, help=help # ) # # if test_data is None: # def test_data_fun(): # return field_name, TEST_STR() # Reuse this test data # else: # test_data_fun = test_data # # return add_srt_arg, build_extractor(real_fname, real_fname), test_data_fun # # Path: invtool/tests/test_data.py # TEST_STR = lambda: random_str() , which may include functions, classes, or code. Output only the next line.
dest='hostname', required=False, help='If you are changing the '
Given the code snippet: <|code_start|> def foreign_key_argument(field_name, help): real_fname = field_name.replace('-', '_') def add_srt_arg(parser, **kwargs): parser.add_argument( '--{0}-pk'.format(field_name), default="", type=str, dest=real_fname, required=False, help=help ) def test_data(): return '', '' return add_srt_arg, build_extractor(real_fname, real_fname), test_data def hostname_argument(field_name, help): return general_argument(field_name, help) def new_hostname_argument(): def add_srt_arg(parser, **kwargs): parser.add_argument( '--new-hostname', default="", type=str, <|code_end|> , generate the next line using the imports in this file: from invtool.lib.options import build_extractor, general_argument from invtool.tests.test_data import TEST_STR and context (functions, classes, or occasionally code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def general_argument(field_name, help, type=lambda x: x, test_data=None): # real_fname = field_name.replace('-', '_') # # def add_srt_arg(parser, **kwargs): # parser.add_argument( # '--{0}'.format(field_name), default="", type=str, # dest=real_fname, required=False, help=help # ) # # if test_data is None: # def test_data_fun(): # return field_name, TEST_STR() # Reuse this test data # else: # test_data_fun = test_data # # return add_srt_arg, build_extractor(real_fname, real_fname), test_data_fun # # Path: invtool/tests/test_data.py # TEST_STR = lambda: random_str() . Output only the next line.
dest='hostname', required=False, help='If you are changing the '
Given the code snippet: <|code_start|> def update_pk_argument(field_name, dtype): display_name = field_name.replace('_', '-') def add_update_pk_argument(parser, **kwargs): parser.add_argument( '--{0}'.format(display_name), required=True, default=None, type=int, dest=field_name, help="The database id of " "the {0} KV being updated.".format(dtype) ) return parser def _extract_pk(nas): return extract_pk(nas, field_name) def test_data(): # kv_pk will need to be evaluated in at test time return display_name, '{{ kv_pk }}' <|code_end|> , generate the next line using the imports in this file: from invtool.lib.options import build_extractor, extract_pk and context (functions, classes, or occasionally code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def extract_pk(nas, field_name): # return {field_name: getattr(nas, field_name)} . Output only the next line.
return add_update_pk_argument, _extract_pk, test_data
Based on the snippet: <|code_start|>def detail_pk_argument(field_name, dtype): display_name = field_name.replace('_', '-') def add_detail_pk_argument(parser, **kwargs): parser.add_argument( '--{0}'.format(display_name), required=True, default=None, type=int, dest=field_name, help="database id of the " "Key Value.".format(dtype) ) return parser def _extract_pk(nas): return extract_pk(nas, field_name) def test_data(): # kv_pk will need to be evaluated in at test time return display_name, '{{ kv_pk }}' return add_detail_pk_argument, _extract_pk, test_data def kvlist_pk_argument(field_name, dtype): display_name = field_name.replace('_', '-') def add_detail_pk_argument(parser, **kwargs): parser.add_argument( '--{0}'.format(display_name), required=True, default=None, type=int, dest=field_name, help="database id of the " "object who's Key Value " "store will be returned.".format(dtype) ) <|code_end|> , predict the immediate next line with the help of imports: from invtool.lib.options import build_extractor, extract_pk and context (classes, functions, sometimes code) from other files: # Path: invtool/lib/options.py # def build_extractor(field_name, nas_name): # def extractor(nas): # if not getattr(nas, nas_name): # return {} # data = {field_name: getattr(nas, nas_name)} # return data # return extractor # # def extract_pk(nas, field_name): # return {field_name: getattr(nas, field_name)} . Output only the next line.
return parser
Here is a snippet: <|code_start|> class MockTunnelled: def __init__(self, base_cmd: list, target: str): pass def command(self, cmd, **kwargs): return b'' def copy_file(self, src, dst): pass @contextmanager <|code_end|> . Write the next line using the current file imports: import functools import json import dcos_launch import dcos_launch.cli import dcos_launch.config import dcos_launch.onprem import dcos_launch.platforms import dcos_test_utils import dcos_test_utils.ssh_client import pytest from collections import namedtuple from contextlib import contextmanager from dcos_launch.util import get_temp_config_path, stub from dcos_test_utils.helpers import Host and context from other files: # Path: dcos_launch/util.py # def get_temp_config_path(tmpdir, name, update: dict = None): # config = yaml.load( # pkg_resources.resource_string(dcos_launch.__name__, 'sample_configs/{}'.format(name)).decode('utf-8')) # if update is not None: # config.update(update) # new_config_path = tmpdir.join('my_config.yaml') # new_config_path.write(yaml.dump(config)) # return str(new_config_path) # # def stub(output): # def accept_any_args(*args, **kwargs): # return output # return accept_any_args , which may include functions, classes, or code. Output only the next line.
def mocked_context(*args, **kwargs):
Based on the snippet: <|code_start|> @pytest.fixture def aws_onprem_with_extra_volumes_config_path(tmpdir, mocked_aws_cfstack_bare_cluster): return get_temp_config_path(tmpdir, 'aws-onprem-with-extra-volumes.yaml') @pytest.fixture def aws_onprem_with_extra_iam_config_path(tmpdir, mocked_aws_cfstack_bare_cluster): return get_temp_config_path(tmpdir, 'aws-onprem-with-extra-iam.yaml') @pytest.fixture def aws_onprem_enterprise_config_path(tmpdir, mocked_aws_cfstack_bare_cluster): return get_temp_config_path(tmpdir, 'aws-onprem-enterprise-with-helper.yaml') @pytest.fixture def mock_genconf_dir(tmpdir): """ For testing genconf_dir and providing onprem configuration via a local genconf dir. Similarly, the DC/OS config can be provided by a 'dcos_config' field in the dcos-launch config.yaml or it can be provided in a (native) genconf/config.yaml """ genconf_dir = tmpdir.join('genconf') genconf_dir.ensure(dir=True) genconf_dir.join('config.yaml').write(""" --- cluster_name: My Awesome DC/OS resolvers: - 8.8.4.4 <|code_end|> , predict the immediate next line with the help of imports: import functools import json import dcos_launch import dcos_launch.cli import dcos_launch.config import dcos_launch.onprem import dcos_launch.platforms import dcos_test_utils import dcos_test_utils.ssh_client import pytest from collections import namedtuple from contextlib import contextmanager from dcos_launch.util import get_temp_config_path, stub from dcos_test_utils.helpers import Host and context (classes, functions, sometimes code) from other files: # Path: dcos_launch/util.py # def get_temp_config_path(tmpdir, name, update: dict = None): # config = yaml.load( # pkg_resources.resource_string(dcos_launch.__name__, 'sample_configs/{}'.format(name)).decode('utf-8')) # if update is not None: # config.update(update) # new_config_path = tmpdir.join('my_config.yaml') # new_config_path.write(yaml.dump(config)) # return str(new_config_path) # # def stub(output): # def accept_any_args(*args, **kwargs): # return output # return accept_any_args . Output only the next line.
- 8.8.8.8
Given the following code snippet before the placeholder: <|code_start|> app_name = 'admin' urlpatterns = [ url(r'^$', views.NodeSearchView.as_view(), name='search'), url(r'^flagged_spam$', views.NodeFlaggedSpamList.as_view(), name='flagged-spam'), url(r'^known_spam$', views.NodeKnownSpamList.as_view(), name='known-spam'), url(r'^known_ham$', views.NodeKnownHamList.as_view(), name='known-ham'), url(r'^doi_backlog_list/$', views.DoiBacklogListView.as_view(), name='doi-backlog-list'), url(r'^registration_list/$', views.RegistrationListView.as_view(), name='registrations'), url(r'^stuck_registration_list/$', views.StuckRegistrationListView.as_view(), name='stuck-registrations'), url(r'^ia_backlog_list/$', views.RegistrationBacklogListView.as_view(), name='ia-backlog-list'), url(r'^(?P<guid>[a-z0-9]+)/$', views.NodeView.as_view(), name='node'), url(r'^(?P<guid>[a-z0-9]+)/logs/$', views.AdminNodeLogView.as_view(), name='node-logs'), url(r'^(?P<guid>[a-z0-9]+)/schema_responses/$', views.AdminNodeSchemaResponseView.as_view(), name='schema-responses'), url(r'^(?P<guid>[a-z0-9]+)/update_embargo/$', views.RegistrationUpdateEmbargoView.as_view(), name='update-embargo'), url(r'^(?P<guid>[a-z0-9]+)/remove/$', views.NodeDeleteView.as_view(), name='remove'), url(r'^(?P<guid>[a-z0-9]+)/restore/$', views.NodeDeleteView.as_view(), name='restore'), url(r'^(?P<guid>[a-z0-9]+)/confirm_spam/$', views.NodeConfirmSpamView.as_view(), name='confirm-spam'), url(r'^(?P<guid>[a-z0-9]+)/confirm_ham/$', views.NodeConfirmHamView.as_view(), name='confirm-ham'), url(r'^(?P<guid>[a-z0-9]+)/confirm_unflag/$', views.NodeConfirmUnflagView.as_view(), name='confirm-unflag'), url(r'^(?P<guid>[a-z0-9]+)/reindex_share_node/$', views.NodeReindexShare.as_view(), name='reindex-share-node'), url(r'^(?P<guid>[a-z0-9]+)/reindex_elastic_node/$', views.NodeReindexElastic.as_view(), name='reindex-elastic-node'), url(r'^(?P<guid>[a-z0-9]+)/restart_stuck_registrations/$', views.RestartStuckRegistrationsView.as_view(), <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import url from admin.nodes import views and context including class names, function names, and sometimes code from other files: # Path: admin/nodes/views.py # class NodeMixin(PermissionRequiredMixin): # class NodeView(NodeMixin, GuidView): # class NodeSearchView(PermissionRequiredMixin, FormView): # class NodeRemoveContributorView(NodeMixin, View): # class NodeDeleteView(NodeMixin, TemplateView): # class AdminNodeLogView(NodeMixin, ListView): # class AdminNodeSchemaResponseView(NodeMixin, ListView): # class RegistrationListView(PermissionRequiredMixin, ListView): # class StuckRegistrationListView(RegistrationListView): # class RegistrationBacklogListView(RegistrationListView): # class DoiBacklogListView(RegistrationListView): # class RegistrationUpdateEmbargoView(NodeMixin, View): # class NodeSpamList(PermissionRequiredMixin, ListView): # class NodeFlaggedSpamList(NodeSpamList, View): # class NodeKnownSpamList(NodeSpamList): # class NodeKnownHamList(NodeSpamList): # class NodeConfirmSpamView(NodeMixin, View): # class NodeConfirmHamView(NodeMixin, View): # class NodeConfirmUnflagView(NodeMixin, View): # class NodeReindexShare(NodeMixin, View): # class NodeReindexElastic(NodeMixin, View): # class NodeModifyStorageUsage(NodeMixin, View): # class NodeRecalculateStorage(NodeMixin, View): # class NodeMakePrivate(NodeMixin, View): # class NodeMakePublic(NodeMixin, View): # class RestartStuckRegistrationsView(NodeMixin, TemplateView): # class RemoveStuckRegistrationsView(NodeMixin, TemplateView): # def get_object(self): # def get_success_url(self): # def get_context_data(self, **kwargs): # def form_valid(self, form): # def post(self, request, *args, **kwargs): # def add_contributor_removed_log(self, node, user): # def post(self, request, *args, **kwargs): # def get_queryset(self): # def get_context_data(self, **kwargs): # def get_queryset(self): # def get_context_data(self, **kwargs): # def get_queryset(self): # def get_context_data(self, **kwargs): # def get_queryset(self): # def get_queryset(self): # def get_queryset(self): # def post(self, request, *args, **kwargs): # def get_queryset(self): # def get_context_data(self, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # SPAM_STATE = SpamStatus.UNKNOWN # SPAM_STATE = SpamStatus.FLAGGED # SPAM_STATE = SpamStatus.SPAM # SPAM_STATE = SpamStatus.HAM . Output only the next line.
name='restart-stuck-registrations'),
Predict the next line after this snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), When( custom_storage_usage_limit_public__gt=0, <|code_end|> using the current file's imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and any relevant context from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
then=F('custom_storage_usage_limit_public'),
Next line prediction: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( <|code_end|> . Use current file imports: (import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify) and context including class names, function names, or small code snippets from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
guid=F('guids___id'),
Using the snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), When( custom_storage_usage_limit_public__gt=0, then=F('custom_storage_usage_limit_public'), ), output_field=IntegerField() ), private_cap=Case( When( custom_storage_usage_limit_private=None, then=settings.STORAGE_LIMIT_PRIVATE, ), <|code_end|> , determine the next line of code. You have imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (class names, function names, or code) available: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
When(
Using the snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( <|code_end|> , determine the next line of code. You have imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (class names, function names, or code) available: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
guids___id=self.kwargs['guid']
Continue the code snippet: <|code_start|> def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), When( custom_storage_usage_limit_public__gt=0, then=F('custom_storage_usage_limit_public'), ), output_field=IntegerField() ), private_cap=Case( When( custom_storage_usage_limit_private=None, then=settings.STORAGE_LIMIT_PRIVATE, ), When( custom_storage_usage_limit_private__gt=0, then=F('custom_storage_usage_limit_private'), ), output_field=IntegerField() ) ).get() <|code_end|> . Use current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (classes, functions, or code) from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
def get_success_url(self):
Given the code snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] <|code_end|> , generate the next line using the imports in this file: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (functions, classes, or occasionally code) from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
).annotate(
Given snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] <|code_end|> , continue by predicting the next line. Consider current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 which might include code, classes, or functions. Output only the next line.
).annotate(
Here is a snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), When( custom_storage_usage_limit_public__gt=0, then=F('custom_storage_usage_limit_public'), ), <|code_end|> . Write the next line using the current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 , which may include functions, classes, or code. Output only the next line.
output_field=IntegerField()
Continue the code snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), <|code_end|> . Use current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (classes, functions, or code) from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
When(
Here is a snippet: <|code_start|> class NodeMixin(PermissionRequiredMixin): def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] <|code_end|> . Write the next line using the current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 , which may include functions, classes, or code. Output only the next line.
).annotate(
Continue the code snippet: <|code_start|> def get_object(self): return AbstractNode.objects.filter( guids___id=self.kwargs['guid'] ).annotate( guid=F('guids___id'), public_cap=Case( When( custom_storage_usage_limit_public=None, then=settings.STORAGE_LIMIT_PUBLIC, ), When( custom_storage_usage_limit_public__gt=0, then=F('custom_storage_usage_limit_public'), ), output_field=IntegerField() ), private_cap=Case( When( custom_storage_usage_limit_private=None, then=settings.STORAGE_LIMIT_PRIVATE, ), When( custom_storage_usage_limit_private__gt=0, then=F('custom_storage_usage_limit_private'), ), output_field=IntegerField() ) ).get() def get_success_url(self): <|code_end|> . Use current file imports: import pytz from datetime import datetime from framework import status from django.utils import timezone from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import NoReverseMatch from django.db.models import F, Case, When, IntegerField from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from django.views.generic import ( View, FormView, ListView, TemplateView, ) from django.shortcuts import redirect, reverse from django.urls import reverse_lazy from admin.base.utils import change_embargo_date, validate_embargo_date from admin.base.views import GuidView from admin.base.forms import GuidForm from api.share.utils import update_share from api.caching.tasks import update_storage_usage_cache from osf.exceptions import NodeStateError from osf.models import ( OSFUser, NodeLog, AbstractNode, Registration, SpamStatus ) from osf.models.admin_log_entry import ( update_admin_log, NODE_REMOVED, NODE_RESTORED, CONTRIBUTOR_REMOVED, CONFIRM_SPAM, CONFIRM_HAM, UNFLAG_SPAM, REINDEX_SHARE, REINDEX_ELASTIC, ) from website import settings, search from osf.management.commands.force_archive import archive, verify and context (classes, functions, or code) from other files: # Path: admin/base/utils.py # def change_embargo_date(registration, user, end_date): # """Update the embargo period of a registration # :param registration: Registration that is being updated # :param user: osf_admin that is updating a registration # :param end_date: Date when the registration should be made public # """ # # validate_embargo_date(registration, user, end_date) # # if registration.embargo: # registration.embargo.end_date = end_date # else: # registration._initiate_embargo( # user, # end_date, # for_existing_registration=True, # notify_initiator_on_complete=False # ) # # registration.is_public = False # # registration.embargo.save() # registration.save() # # update_admin_log( # user_id=user.id, # object_id=registration.id, # object_repr='Registration', # message='User {} changed the embargo end date of {} to {}.'.format( # user.pk, registration.pk, end_date # ), # action_flag=EMBARGO_UPDATED # ) # # def validate_embargo_date(registration, user, end_date): # if not user.has_perm('osf.change_node'): # raise PermissionDenied('Only osf_admins may update a registration embargo.') # if end_date - registration.registered_date >= settings.EMBARGO_END_DATE_MAX: # raise ValidationError('Registrations can only be embargoed for up to four years.') # elif end_date < timezone.now(): # raise ValidationError('Embargo end date must be in the future.') # # Path: osf/models/admin_log_entry.py # def update_admin_log(user_id, object_id, object_repr, message, action_flag=UNKNOWN): # AdminLogEntry.objects.log_action( # user_id=user_id, # content_type_id=None, # object_id=object_id, # object_repr=object_repr, # change_message=message, # action_flag=action_flag # ) # # NODE_REMOVED = 30 # # NODE_RESTORED = 31 # # CONTRIBUTOR_REMOVED = 32 # # CONFIRM_SPAM = 20 # # CONFIRM_HAM = 21 # # UNFLAG_SPAM = 22 # # REINDEX_SHARE = 50 # # REINDEX_ELASTIC = 51 . Output only the next line.
return reverse('nodes:node', kwargs={'guid': self.kwargs['guid']})
Given the code snippet: <|code_start|> @pytest.fixture() def header_row(self, question_headers, metadata_headers): return [*metadata_headers, *question_headers] @pytest.fixture() def subjects_list(self, provider_subjects): return [subject.text for subject in provider_subjects] @pytest.fixture() def valid_row(self, subjects_list): subjects_text = (';').join(subjects_list) return make_row({'Subjects': subjects_text}) def test_csv_parsed(self, header_row, open_ended_schema, subjects_list, registration_provider, valid_row): test_csv = write_csv(header_row, {'Title': open_ended_schema._id}, valid_row) upload = BulkRegistrationUpload(test_csv, registration_provider._id) assert upload.is_validated is False upload.validate() parsed = upload.get_parsed() assert upload.is_validated is True assert upload.errors == [] assert 'registrations' in parsed assert 'csv_raw' in parsed['registrations'][0] assert 'csv_parsed' in parsed['registrations'][0] assert_parsed(parsed['registrations'][0]['csv_parsed'], { 'Title': 'Test title', 'Description': 'Test description', 'Admin Contributors': [{'full_name': 'jane doe', 'email': 'jane.doe@email.com'}, {'full_name': 'joan doe', 'email': 'joan.doe@email.com'}], 'Read-Write Contributors': [], 'Read-Only Contributors': [], <|code_end|> , generate the next line using the imports in this file: import csv import io import pytest import string from nose.tools import assert_equal, assert_true from rest_framework.exceptions import NotFound from osf_tests.factories import SubjectFactory from osf.models import RegistrationSchema, RegistrationProvider from osf.registrations.utils import (BulkRegistrationUpload, InvalidHeadersError, FileUploadNotSupportedError, DuplicateHeadersError, get_excel_column_name, Store, CategoryField, LicenseField, ContributorField, MAX_EXCEL_COLUMN_NUMBER, METADATA_FIELDS) and context (functions, classes, or occasionally code) from other files: # Path: osf_tests/factories.py # class SubjectFactory(DjangoModelFactory): # text = factory.Sequence(lambda n: 'Example Subject #{}'.format(n)) # # class Meta: # model = models.Subject # # @classmethod # def _create(cls, target_class, parent=None, provider=None, bepress_subject=None, *args, **kwargs): # provider = provider or models.PreprintProvider.objects.first() or PreprintProviderFactory(_id='osf') # if provider._id != 'osf' and not bepress_subject: # osf = models.PreprintProvider.load('osf') or PreprintProviderFactory(_id='osf') # bepress_subject = SubjectFactory(provider=osf) # try: # ret = super()._create(target_class, parent=parent, provider=provider, bepress_subject=bepress_subject, *args, **kwargs) # except (IntegrityError, ValidationError): # ret = models.Subject.objects.get(text=kwargs['text']) # if parent: # ret.parent = parent # return ret . Output only the next line.
'Bibliographic Contributors': [{'full_name': 'jane doe', 'email': 'jane.doe@email.com'}, {'full_name': 'joan doe', 'email': 'joan.doe@email.com'}],
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__file__) increment = 100000 # Dict to map original schema formats to schema block types FORMAT_TYPE_TO_TYPE_MAP = { ('multiselect', 'choose'): 'multi-select-input', (None, 'multiselect'): 'multi-select-input', (None, 'choose'): 'single-select-input', ('osf-upload-open', 'osf-upload'): 'file-input', ('osf-upload-toggle', 'osf-upload'): 'file-input', ('singleselect', 'choose'): 'single-select-input', ('text', 'string'): 'short-text-input', ('textarea', 'osf-author-import'): 'contributors-input', ('textarea', None): 'long-text-input', ('textarea', 'string'): 'long-text-input', ('textarea-lg', None): 'long-text-input', ('textarea-lg', 'string'): 'long-text-input', ('textarea-xl', 'string'): 'long-text-input', } <|code_end|> , predict the next line using imports from the current file: from past.builtins import basestring from math import ceil from contextlib import contextmanager from django.apps import apps from django.db import connection from django.db.migrations.operations.base import Operation from osf.models.base import generate_object_id from osf.utils.sanitize import strip_html, unescape_entities from website import settings from website.project.metadata.schemas import get_osf_meta_schemas from osf.models import NodeLicense from osf.models import NodeLicense from osf.models import RegistrationSchema from osf.models import RegistrationSchemaBlock import os import itertools import builtins import json import logging import warnings and context including class names, function names, and sometimes code from other files: # Path: website/project/metadata/schemas.py # def get_osf_meta_schemas(): # """Returns the current contents of all known schema files.""" # schemas = [ # ensure_schema_structure(from_json(json_filename)) # for json_filename in OSF_META_SCHEMA_FILES # ] # return schemas . Output only the next line.
def get_osf_models():
Here is a snippet: <|code_start|> @pytest.mark.django_db class TestRegistrationBulkUploadJob: @pytest.fixture() def payload_hash(self): return str(uuid.uuid4()).replace('-', '') @pytest.fixture() def initiator(self): return UserFactory() @pytest.fixture() def schema(self): return get_default_metaschema() @pytest.fixture() def provider(self): return RegistrationProviderFactory() def test_job_creation(self, payload_hash, initiator, provider, schema): <|code_end|> . Write the next line using the current file imports: import uuid import pytest from django.db.utils import IntegrityError from osf.models import RegistrationBulkUploadJob from osf.models.registration_bulk_upload_job import JobState from osf_tests.factories import UserFactory, RegistrationProviderFactory, get_default_metaschema and context from other files: # Path: osf/models/registration_bulk_upload_job.py # class JobState(IntEnum): # """Defines the six states of registration bulk upload jobs. # """ # # PENDING = 0 # Database preparation is in progress # INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up # PICKED_UP = 2 # Registration creation is in progress # DONE_FULL = 3 # All (draft) registrations have been successfully created # DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process # DONE_ERROR = 5 # All (draft) registrations have failed # # Path: osf_tests/factories.py # class UserFactory(DjangoModelFactory): # # TODO: Change this to only generate long names and see what breaks # fullname = factory.Sequence(lambda n: 'Freddie Mercury{0}'.format(n)) # # username = factory.LazyFunction(fake_email) # password = factory.PostGenerationMethodCall('set_password', # 'queenfan86') # is_registered = True # date_confirmed = factory.Faker('date_time_this_decade', tzinfo=pytz.utc) # merged_by = None # verification_key = None # # class Meta: # model = models.OSFUser # # @classmethod # def _build(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._build(target_class, *args, **kwargs) # if emails: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @classmethod # def _create(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._create(target_class, *args, **kwargs) # if emails and not instance.pk: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @factory.post_generation # def set_names(self, create, extracted): # parsed = impute_names_model(self.fullname) # for key, value in parsed.items(): # setattr(self, key, value) # # @factory.post_generation # def set_emails(self, create, extracted): # if not self.emails.filter(address=self.username).exists(): # if not self.id: # if create: # # Perform implicit save to populate M2M # self.save(clean=False) # else: # # This might lead to strange behavior # return # self.emails.create(address=str(self.username).lower()) # # class RegistrationProviderFactory(DjangoModelFactory): # name = factory.Faker('company') # description = factory.Faker('bs') # external_url = factory.Faker('url') # access_token = factory.Faker('bs') # share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n)) # # class Meta: # model = models.RegistrationProvider # # @classmethod # def _create(cls, *args, **kwargs): # user = kwargs.pop('creator', None) # _id = kwargs.pop('_id', None) # try: # obj = cls._build(*args, **kwargs) # except IntegrityError as e: # # This is to ensure legacy tests don't fail when their _ids aren't unique # if _id == models.RegistrationProvider.default__id: # pass # else: # raise e # if _id and _id != 'osf': # obj._id = _id # # obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection # obj.save() # return obj # # def get_default_metaschema(): # """This needs to be a method so it gets called after the test database is set up""" # return models.RegistrationSchema.objects.first() , which may include functions, classes, or code. Output only the next line.
upload_job = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema)
Continue the code snippet: <|code_start|> return str(uuid.uuid4()).replace('-', '') @pytest.fixture() def initiator(self): return UserFactory() @pytest.fixture() def schema(self): return get_default_metaschema() @pytest.fixture() def provider(self): return RegistrationProviderFactory() def test_job_creation(self, payload_hash, initiator, provider, schema): upload_job = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema) upload_job.save() upload_job.reload() assert upload_job.payload_hash == payload_hash assert upload_job.initiator == initiator assert upload_job.schema == schema assert upload_job.provider == provider assert upload_job.state == JobState.PENDING assert upload_job.email_sent is None def test_job_uniqueness(self, payload_hash, initiator, provider, schema): upload_job_1 = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema) upload_job_1.save() upload_job_2 = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema) <|code_end|> . Use current file imports: import uuid import pytest from django.db.utils import IntegrityError from osf.models import RegistrationBulkUploadJob from osf.models.registration_bulk_upload_job import JobState from osf_tests.factories import UserFactory, RegistrationProviderFactory, get_default_metaschema and context (classes, functions, or code) from other files: # Path: osf/models/registration_bulk_upload_job.py # class JobState(IntEnum): # """Defines the six states of registration bulk upload jobs. # """ # # PENDING = 0 # Database preparation is in progress # INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up # PICKED_UP = 2 # Registration creation is in progress # DONE_FULL = 3 # All (draft) registrations have been successfully created # DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process # DONE_ERROR = 5 # All (draft) registrations have failed # # Path: osf_tests/factories.py # class UserFactory(DjangoModelFactory): # # TODO: Change this to only generate long names and see what breaks # fullname = factory.Sequence(lambda n: 'Freddie Mercury{0}'.format(n)) # # username = factory.LazyFunction(fake_email) # password = factory.PostGenerationMethodCall('set_password', # 'queenfan86') # is_registered = True # date_confirmed = factory.Faker('date_time_this_decade', tzinfo=pytz.utc) # merged_by = None # verification_key = None # # class Meta: # model = models.OSFUser # # @classmethod # def _build(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._build(target_class, *args, **kwargs) # if emails: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @classmethod # def _create(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._create(target_class, *args, **kwargs) # if emails and not instance.pk: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @factory.post_generation # def set_names(self, create, extracted): # parsed = impute_names_model(self.fullname) # for key, value in parsed.items(): # setattr(self, key, value) # # @factory.post_generation # def set_emails(self, create, extracted): # if not self.emails.filter(address=self.username).exists(): # if not self.id: # if create: # # Perform implicit save to populate M2M # self.save(clean=False) # else: # # This might lead to strange behavior # return # self.emails.create(address=str(self.username).lower()) # # class RegistrationProviderFactory(DjangoModelFactory): # name = factory.Faker('company') # description = factory.Faker('bs') # external_url = factory.Faker('url') # access_token = factory.Faker('bs') # share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n)) # # class Meta: # model = models.RegistrationProvider # # @classmethod # def _create(cls, *args, **kwargs): # user = kwargs.pop('creator', None) # _id = kwargs.pop('_id', None) # try: # obj = cls._build(*args, **kwargs) # except IntegrityError as e: # # This is to ensure legacy tests don't fail when their _ids aren't unique # if _id == models.RegistrationProvider.default__id: # pass # else: # raise e # if _id and _id != 'osf': # obj._id = _id # # obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection # obj.save() # return obj # # def get_default_metaschema(): # """This needs to be a method so it gets called after the test database is set up""" # return models.RegistrationSchema.objects.first() . Output only the next line.
with pytest.raises(IntegrityError):
Based on the snippet: <|code_start|> @pytest.mark.django_db class TestRegistrationBulkUploadJob: @pytest.fixture() def payload_hash(self): return str(uuid.uuid4()).replace('-', '') @pytest.fixture() def initiator(self): return UserFactory() @pytest.fixture() def schema(self): return get_default_metaschema() @pytest.fixture() def provider(self): return RegistrationProviderFactory() def test_job_creation(self, payload_hash, initiator, provider, schema): upload_job = RegistrationBulkUploadJob.create(payload_hash, initiator, provider, schema) upload_job.save() upload_job.reload() assert upload_job.payload_hash == payload_hash <|code_end|> , predict the immediate next line with the help of imports: import uuid import pytest from django.db.utils import IntegrityError from osf.models import RegistrationBulkUploadJob from osf.models.registration_bulk_upload_job import JobState from osf_tests.factories import UserFactory, RegistrationProviderFactory, get_default_metaschema and context (classes, functions, sometimes code) from other files: # Path: osf/models/registration_bulk_upload_job.py # class JobState(IntEnum): # """Defines the six states of registration bulk upload jobs. # """ # # PENDING = 0 # Database preparation is in progress # INITIALIZED = 1 # Database preparation has been finished and is ready to be picked up # PICKED_UP = 2 # Registration creation is in progress # DONE_FULL = 3 # All (draft) registrations have been successfully created # DONE_PARTIAL = 4 # Some (draft) registrations have failed the creation creation process # DONE_ERROR = 5 # All (draft) registrations have failed # # Path: osf_tests/factories.py # class UserFactory(DjangoModelFactory): # # TODO: Change this to only generate long names and see what breaks # fullname = factory.Sequence(lambda n: 'Freddie Mercury{0}'.format(n)) # # username = factory.LazyFunction(fake_email) # password = factory.PostGenerationMethodCall('set_password', # 'queenfan86') # is_registered = True # date_confirmed = factory.Faker('date_time_this_decade', tzinfo=pytz.utc) # merged_by = None # verification_key = None # # class Meta: # model = models.OSFUser # # @classmethod # def _build(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._build(target_class, *args, **kwargs) # if emails: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @classmethod # def _create(cls, target_class, *args, **kwargs): # emails = kwargs.pop('emails', []) # instance = super(DjangoModelFactory, cls)._create(target_class, *args, **kwargs) # if emails and not instance.pk: # # Save for M2M population # instance.set_unusable_password() # instance.save() # for email in emails: # instance.emails.create(address=email) # return instance # # @factory.post_generation # def set_names(self, create, extracted): # parsed = impute_names_model(self.fullname) # for key, value in parsed.items(): # setattr(self, key, value) # # @factory.post_generation # def set_emails(self, create, extracted): # if not self.emails.filter(address=self.username).exists(): # if not self.id: # if create: # # Perform implicit save to populate M2M # self.save(clean=False) # else: # # This might lead to strange behavior # return # self.emails.create(address=str(self.username).lower()) # # class RegistrationProviderFactory(DjangoModelFactory): # name = factory.Faker('company') # description = factory.Faker('bs') # external_url = factory.Faker('url') # access_token = factory.Faker('bs') # share_source = factory.Sequence(lambda n: 'share source #{0}'.format(n)) # # class Meta: # model = models.RegistrationProvider # # @classmethod # def _create(cls, *args, **kwargs): # user = kwargs.pop('creator', None) # _id = kwargs.pop('_id', None) # try: # obj = cls._build(*args, **kwargs) # except IntegrityError as e: # # This is to ensure legacy tests don't fail when their _ids aren't unique # if _id == models.RegistrationProvider.default__id: # pass # else: # raise e # if _id and _id != 'osf': # obj._id = _id # # obj._creator = user or models.OSFUser.objects.first() or UserFactory() # Generates primary_collection # obj.save() # return obj # # def get_default_metaschema(): # """This needs to be a method so it gets called after the test database is set up""" # return models.RegistrationSchema.objects.first() . Output only the next line.
assert upload_job.initiator == initiator