Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|> shader._reportInactive = ori
def _setObjectUniforms(shader, params):
"""
@type shader: Shader
"""
paramsList = []
ori = shader._reportInactive
shader._reportInactive = False
paramsList.append(("Model", params.model))
paramsList.append(("ModelView", params.ModelView))
paramsList.append(("ModelViewProjection", params.ModelViewProjection))
paramsList.append(("ModelProjection", params.ModelProjection))
paramsList.append(("ModelInverse", params.ModelInverse))
paramsList.append(("ModelInverseTranspose", params.ModelInverseTranspose))
paramsList.append(("ModelViewInverse", params.ModelViewInverse))
paramsList.append(("ModelViewInverseTranspose", params.ModelViewInverseTranspose))
paramsList.append(("NormalMatrix", params.NormalMatrix))
paramsList.append(("HasBones", params.hasBones))
shader.setUniformsList(paramsList)
shader._reportInactive = ori
def _setMaterialShaderProperties(shader, props):
paramsList = []
for p in props:
<|code_end|>
. Use current file imports:
from collections import OrderedDict, defaultdict
from abc import ABCMeta
from cycgkit.cgtypes import vec3, vec4
from e3d.model_management.MaterialClass import ShaderProperty
and context (classes, functions, or code) from other files:
# Path: e3d/model_management/MaterialClass.py
# class ShaderProperty:
# def __init__(self, nameInShader, val):
# self.nameInShader = nameInShader
# self._val = val
#
# def getVal(self):
# pass
. Output only the next line. | assert isinstance(p, ShaderProperty) |
Based on the snippet: <|code_start|> self._barColor = barColor or style.activeColor
styleHint = style.buttonStyleHint
if color is None:
color = style.backgroundColor
super(ProgressBar, self).__init__(left, top, width, height, parent, pinning, color, ID, None, rotation, style)
if styleHint in (StyleHintsEnum.Raised, StyleHintsEnum.Sunken):
self.gradientType = GradientTypesEnum.Horizontal
else:
self.gradientType = GradientTypesEnum.noGradient
self.borderColor = style.borderColor
borderSize = style.borderSize
self._label = Label(borderSize, borderSize, width - (borderSize * 2), str(value), self,
pinning=PinningEnum.TopLeftRight, ID=self.ID + '_label',
outlineLength=OutlineLenghtEnum.NoOutline)
label = self._label
label.borderSize = 0
label.color = vec4(0)
x, y, z = self.getAlignedPosition(label.size, self.size, self.borderSize, hAlign=self._hTextAlign)
label.top = y
label.vTextAlign = Align2DEnum.Center
self._styleHint = styleHint
barStyle = style._copy()
barStyle.baseColor = self._barColor
self._backgroundSize = 0
bsize = self._backgroundSize
dbsize = bsize * 2
<|code_end|>
, predict the immediate next line with the help of imports:
from .LabelClass import *
from .TextEnums import FontWeightEnum
from ..Colors import *
from .Styling import *
from .PanelClass import Panel
from ..commonValues import scaleNumber
and context (classes, functions, sometimes code) from other files:
# Path: e3d/gui/TextEnums.py
# class FontWeightEnum(object):
# Light = .4
# Normal = .6
# Bold = .9
#
# Path: e3d/gui/PanelClass.py
# class Panel(BaseControl):
# """
# Flat container for Gui objects.
#
# @rtype : Panel
# """
#
# def __init__(self, left, top, width, height, parent, pinning=PinningEnum.TopLeft, color=None, ID=None,
# imgID=None, rotation=None, style=None):
# style = style or DefaultStyle(color)
# if color is None:
# color = style.backgroundColor
# super(Panel, self).__init__(left, top, width, height, parent, pinning, color, ID, imgID, rotation,
# style)
# self._passEventDown = True
#
# Path: e3d/commonValues.py
# def scaleNumber(val, src, dst):
# """
# http://stackoverflow.com/a/4155197
#
# Scale the given value from the scale of src to the scale of dst.
#
# @rtype : int
# @type dst: list
# @type src: list
# @type val: int
#
# Examples:
# >> scaleNumber(0, (0.0, 99.0), (-1.0, 1.0))
# -1.0
# >> scaleNumber(99, (0.0, 99.0), (-1.0, 1.0))
# 1
# >> scaleNumber(1, (0.0, 2.0), (0.0, 1.0))
# 0.5
# """
# try:
# return ((val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
# except ZeroDivisionError:
# return dst[1] / 2.0
. Output only the next line. | self._pbar = Panel(bsize, bsize, (self.width - dbsize) * (value / 100.0), self.height - dbsize, self, |
Predict the next line for this snippet: <|code_start|>
def _setFont(self, fontID):
self._label.fontID = fontID
def _getFont(self):
return self._label.fontID
fontID = property(_getFont, _setFont)
def _reStyle(self):
super(ProgressBar, self)._reStyle()
barStyle = self.style._copy()
self._pbar.style = barStyle
self._pbar.borderSize = 0
self._buildColors()
@property
def value(self):
return self._value
@value.setter
def value(self, val):
self._dirty = True
self._value = val
self._buildValues()
def _getPercentage(self):
maximum = self.maximum
minimum = self.minimum
value = self._clampValue()
<|code_end|>
with the help of current file imports:
from .LabelClass import *
from .TextEnums import FontWeightEnum
from ..Colors import *
from .Styling import *
from .PanelClass import Panel
from ..commonValues import scaleNumber
and context from other files:
# Path: e3d/gui/TextEnums.py
# class FontWeightEnum(object):
# Light = .4
# Normal = .6
# Bold = .9
#
# Path: e3d/gui/PanelClass.py
# class Panel(BaseControl):
# """
# Flat container for Gui objects.
#
# @rtype : Panel
# """
#
# def __init__(self, left, top, width, height, parent, pinning=PinningEnum.TopLeft, color=None, ID=None,
# imgID=None, rotation=None, style=None):
# style = style or DefaultStyle(color)
# if color is None:
# color = style.backgroundColor
# super(Panel, self).__init__(left, top, width, height, parent, pinning, color, ID, imgID, rotation,
# style)
# self._passEventDown = True
#
# Path: e3d/commonValues.py
# def scaleNumber(val, src, dst):
# """
# http://stackoverflow.com/a/4155197
#
# Scale the given value from the scale of src to the scale of dst.
#
# @rtype : int
# @type dst: list
# @type src: list
# @type val: int
#
# Examples:
# >> scaleNumber(0, (0.0, 99.0), (-1.0, 1.0))
# -1.0
# >> scaleNumber(99, (0.0, 99.0), (-1.0, 1.0))
# 1
# >> scaleNumber(1, (0.0, 2.0), (0.0, 1.0))
# 0.5
# """
# try:
# return ((val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
# except ZeroDivisionError:
# return dst[1] / 2.0
, which may contain function names, class names, or code. Output only the next line. | value = scaleNumber(value, (minimum, maximum), (0, 100)) |
Based on the snippet: <|code_start|> if not att.startswith('_'):
vals[att] = getattr(self, att)
dump(vals, file, indent=4)
@staticmethod
def readFromFile(path):
style = DefaultStyle()
with open(path) as file:
vals = load(file)
for att in vals.keys:
setattr(style, att, vals[att])
return style
@property
def baseColor(self):
return self._baseColor
@baseColor.setter
def baseColor(self, value):
baseColor = vec4(value)
self._baseColor = value
self.backgroundColor = vec4(baseColor)
self.fontColor = WHITE
self.fontOutlineColor = BLUE
self.fontSize = 10
self.borderSize = 1
self.borderColor = fromRGB1_A(baseColor / 4.0, 1)
self.focusBorderColor = ORANGE
self.hoverBorderColor = GREEN
<|code_end|>
, predict the immediate next line with the help of imports:
from ...Colors import *
from ..BaseControlClass import GradientTypesEnum
from copy import copy
from json import dump, load
and context (classes, functions, sometimes code) from other files:
# Path: e3d/gui/BaseControlClass.py
# class GradientTypesEnum(object):
# noGradient = -1
# Vertical = 0
# Horizontal = 1
# RightCorner = 2
# LeftCorner = 3
# CenterVertical = 4
# CenterHorizontal = 5
# Diagonal1 = 6
# Diagonal2 = 7
# Radial = 8
. Output only the next line. | self.gradientType = GradientTypesEnum.noGradient |
Given the code snippet: <|code_start|> # if any duplicate vertices are found in a Face3
# we have to remove the face as nothing can be saved
for n in range(3):
if indices[n] == indices[(n + 1) % 3]:
dupIndex = n
faceIndicesToRemove.append(i)
break
for i in range(len(faceIndicesToRemove) - 1, 0, -1):
# for ( i = faceIndicesToRemove.length - 1 i >= 0 i -- ):
idx = faceIndicesToRemove[i]
self.faces.pop(idx)
# for j in range(len(self.faceVertexUvs)):
self.faceVertexUvs.pop(idx)
# Use unique set of vertices
diff = len(self.vertices) - len(unique)
self.vertices = unique
return diff
def addGroup(self, start, count):
self.groups.append({'start': start, 'count': count})
return self
def setIndex(self, indices):
for v in indices:
<|code_end|>
, generate the next line using the imports in this file:
from cycgkit.cgtypes import vec3, mat4
from uuid import uuid1
from .face3 import Face3
import math
and context (functions, classes, or occasionally code) from other files:
# Path: e3d/model_management/pygeom/face3.py
# class Face3:
# def __init__(self, a, b, c, normals=None):
# if normals is None:
# normals = []
# self.a = a
# self.b = b
# self.c = c
# self.vertexNormals = normals
# self.normal = vec3()
#
# def abcVec3(self):
# return vec3(self.a, self.b, self.c)
#
# def __repr__(self):
# return '{},{},{}'.format(self.a, self.b, self.c)
. Output only the next line. | self.faces.append(Face3(v.x, v.y, v.z)) |
Predict the next line for this snippet: <|code_start|>
class Communicator(object):
def __init__(self):
self._inQueue = Queue()
self._outQueue = Queue()
def _readTask(self):
try:
task = self._inQueue.get_nowait()
except Empty:
return
if not isinstance(task, Task):
self._engine.log('server sent data with wrong type. Ignored.', logLevelsEnum.warning)
else:
return task
def _sendTask(self, task, wait=False):
if not isinstance(task, Task):
raise TypeError('task must be of type \'Task\'')
try:
if wait:
self._outQueue.put(task, timeout=1)
else:
self._outQueue.put_nowait(task)
except Full:
self._engine.log('out queue is full. Missed data!', logLevelsEnum.warning)
<|code_end|>
with the help of current file imports:
from sys import platform
from multiprocessing.dummy import Process, Queue
from multiprocessing import Process, Queue
from queue import Full, Empty
from Queue import Full, Empty
from .._baseManager import BaseManager
from ..Logging import logLevelsEnum
and context from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/Logging.py
# class logLevelsEnum(object):
# debug = 0
# info = 1
# warning = 2
# error = 3
, which may contain function names, class names, or code. Output only the next line. | class ParallelClient(BaseManager, Communicator): |
Next line prediction: <|code_start|> Error = 'Error'
RawData = 'RawData'
NewTask = 'NewTask'
TaskResult = 'TaskResult'
Custom = 'Custom'
Finish = 'Finish'
class Task(object):
def __init__(self, taskType, data, name=''):
self.taskType = taskType
self.data = data
self.name = name
def __repr__(self):
return self.taskType + '-' + self.name
class Communicator(object):
def __init__(self):
self._inQueue = Queue()
self._outQueue = Queue()
def _readTask(self):
try:
task = self._inQueue.get_nowait()
except Empty:
return
if not isinstance(task, Task):
<|code_end|>
. Use current file imports:
(from sys import platform
from multiprocessing.dummy import Process, Queue
from multiprocessing import Process, Queue
from queue import Full, Empty
from Queue import Full, Empty
from .._baseManager import BaseManager
from ..Logging import logLevelsEnum)
and context including class names, function names, or small code snippets from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/Logging.py
# class logLevelsEnum(object):
# debug = 0
# info = 1
# warning = 2
# error = 3
. Output only the next line. | self._engine.log('server sent data with wrong type. Ignored.', logLevelsEnum.warning) |
Predict the next line for this snippet: <|code_start|>
if __name__ == '__main__':
desc = PluginDescription('My Test Plugin', 'JR-García', 'some@example.com', 'Dummy plugin to test '
'plugin creation')
pluginFolderPath = './plugins/MyTestPlugin'
desc.saveToDisk(pluginFolderPath)
<|code_end|>
with the help of current file imports:
from e3d.plugin_management.PluginHandlers import PluginDescription, packPluginFromFolder
and context from other files:
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# def packPluginFromFolder(folderPath):
# folderPath = path.abspath(folderPath)
# if not path.exists(folderPath):
# raise FileNotFoundError('the folder does not exist.')
# if not path.isdir(folderPath):
# raise NotADirectoryError('folderPath must be a directory with files.')
#
# parentFolder = path.abspath(path.join(folderPath, path.pardir))
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
#
# zipTitle = folderPath
# finalName = zipTitle + PLUGINEXTENSION
# make_archive(zipTitle, 'gztar', folderPath, './')
# os.rename(zipTitle + '.tar.gz', finalName)
, which may contain function names, class names, or code. Output only the next line. | packPluginFromFolder(pluginFolderPath) |
Predict the next line for this snippet: <|code_start|> @staticmethod
def calculatePlanarUVS(groupedVertices, normal):
if isinstance(normal, list):
if normal.__len__() > 1:
normal = vec3(normal[0])
else:
normal = vec3(normal)
uvs = []
bbox = BoundingBox()
M = mat3.fromToRotation(normal, vec3(0, 0, 1))
newverts = []
for v in groupedVertices:
faceverts = []
for vv in v:
ver = M * vec3(vv)
faceverts.append(ver)
newverts.append(faceverts)
for v in newverts:
for vv in v:
bbox.addPoint(vv)
src1, src2 = bbox.getBounds()
srcU = [src1.x, src2.x]
srcV = [src1.y, src2.y]
for v in newverts:
for ver in v:
<|code_end|>
with the help of current file imports:
from collections import defaultdict
from cycgkit.cgtypes import *
from cycgkit.boundingbox import BoundingBox
from numpy import arccos, arctan2, array, float32, ndarray, pi, sqrt, uint32
from ..commonValues import scaleNumber
import numpy as np
and context from other files:
# Path: e3d/commonValues.py
# def scaleNumber(val, src, dst):
# """
# http://stackoverflow.com/a/4155197
#
# Scale the given value from the scale of src to the scale of dst.
#
# @rtype : int
# @type dst: list
# @type src: list
# @type val: int
#
# Examples:
# >> scaleNumber(0, (0.0, 99.0), (-1.0, 1.0))
# -1.0
# >> scaleNumber(99, (0.0, 99.0), (-1.0, 1.0))
# 1
# >> scaleNumber(1, (0.0, 2.0), (0.0, 1.0))
# 0.5
# """
# try:
# return ((val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
# except ZeroDivisionError:
# return dst[1] / 2.0
, which may contain function names, class names, or code. Output only the next line. | U = scaleNumber(ver.x, srcU, [0.0, 1.0]) |
Predict the next line for this snippet: <|code_start|>
# Based on https://gamedev.stackexchange.com/a/31312
class IcoSphereGeometry(Geometry):
def __init__(self, detailLevel=3):
Geometry.__init__(self)
self.type = 'IcoSphereGeometry'
self.parameters = {'detailLevel': detailLevel}
vectors = []
indices = []
geom = GeometryProvider(vectors, indices)
for i in range(detailLevel):
indices = geom.Subdivide(vectors, indices, True)
# normalize vectors to "inflate" the icosahedron into a sphere.
for i in range(len(vectors)):
vectors[i].normalize()
self.vertices = vectors
for i in range(0, len(indices), 3):
c, b, a = [indices[i], indices[i + 1], indices[i + 2]]
<|code_end|>
with the help of current file imports:
import math
from cycgkit.cgtypes import vec3, vec4
from .Geometry import Geometry
from .face3 import Face3
and context from other files:
# Path: e3d/model_management/pygeom/Geometry.py
# class Geometry:
# def __init__(self):
#
# self.uuid = uuid1()
#
# self.name = ''
# self.type = 'Geometry'
#
# self.vertices = []
# self.colors = [] # one-to-one vertex colors, used in Points and Line
#
# self.faces = []
#
# self.faceVertexUvs = []
#
# self.lineDistances = []
# self.hasTangents = False
# self.groups = []
#
# # def computeLineDistances(self):
# #
# # d = 0
# # vertices = self.vertices
# #
# # for ( i = 0, il = vertices.length i < il i ++ ):
# #
# # if ( i > 0 ):
# #
# # d += vertices[ i ].distanceTo( vertices[ i - 1 ] )
# #
# # }
# #
# # self.lineDistances[ i ] = d
# #
# # }
# #
# #
# #
# # def computeBoundingBox(self):
# #
# # if ( self.boundingBox == None ):
# #
# # self.boundingBox = new THREE.Box3()
# #
# # }
# #
# # self.boundingBox.setFromPoints( self.vertices )
# #
# #
# #
# # def computeBoundingSphere(self):
# #
# # if ( self.boundingSphere == None ):
# #
# # self.boundingSphere = new THREE.Sphere()
# #
# # }
# #
# # self.boundingSphere.setFromPoints( self.vertices )
# #
# #
#
# def mergeVertices(self):
# verticesMap = {} # Hashmap for looking up vertice by position coordinates (and making sure they are unique)
# unique = []
# changes = {}
#
# precisionPoints = 4 # number of decimal points, eg. 4 for epsilon of 0.0001
# precision = math.pow(10, precisionPoints)
#
# for i in range(len(self.vertices)):
# v = self.vertices[i]
# key = '{}_{}_{}'.format(round(v.x * precision), round(v.y * precision), round(v.z * precision))
#
# if verticesMap.get(key) is None:
# verticesMap[key] = i
# unique.append(self.vertices[i])
# changes[i] = len(unique) - 1
# else:
# # console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key])
# changes[i] = changes[verticesMap[key]]
#
# # if faces are completely degenerate after merging vertices, we
# # have to remove them from the geometry.
# faceIndicesToRemove = []
#
# for i in range(len(self.faces)):
#
# face = self.faces[i]
#
# face.a = changes[face.a]
# face.b = changes[face.b]
# face.c = changes[face.c]
#
# indices = [face.a, face.b, face.c]
#
# dupIndex = - 1
#
# # if any duplicate vertices are found in a Face3
# # we have to remove the face as nothing can be saved
# for n in range(3):
# if indices[n] == indices[(n + 1) % 3]:
# dupIndex = n
# faceIndicesToRemove.append(i)
# break
# for i in range(len(faceIndicesToRemove) - 1, 0, -1):
# # for ( i = faceIndicesToRemove.length - 1 i >= 0 i -- ):
# idx = faceIndicesToRemove[i]
#
# self.faces.pop(idx)
#
# # for j in range(len(self.faceVertexUvs)):
# self.faceVertexUvs.pop(idx)
#
# # Use unique set of vertices
#
# diff = len(self.vertices) - len(unique)
# self.vertices = unique
# return diff
#
# def addGroup(self, start, count):
#
# self.groups.append({'start': start, 'count': count})
#
# return self
#
# def setIndex(self, indices):
# for v in indices:
# self.faces.append(Face3(v.x, v.y, v.z))
#
# def setFaceUVS(self, uvs):
# for f in self.faces:
# self.faceVertexUvs.append([uvs[int(f.a)], uvs[int(f.b)], uvs[int(f.c)]])
#
# Path: e3d/model_management/pygeom/face3.py
# class Face3:
# def __init__(self, a, b, c, normals=None):
# if normals is None:
# normals = []
# self.a = a
# self.b = b
# self.c = c
# self.vertexNormals = normals
# self.normal = vec3()
#
# def abcVec3(self):
# return vec3(self.a, self.b, self.c)
#
# def __repr__(self):
# return '{},{},{}'.format(self.a, self.b, self.c)
, which may contain function names, class names, or code. Output only the next line. | self.faces.append(Face3(a, b, c)) |
Given the code snippet: <|code_start|>
class EventsManager(object):
def __init__(self):
self._listeners = OrderedDict()
self._keysState = SDL_GetKeyboardState(None)
self._lastX = -1
self._lastY = -1
def addListener(self, ID, listener):
"""
@type listener: e3d.events_processing.EventsListenerClass.EventsListener
@type ID: str
"""
<|code_end|>
, generate the next line using the imports in this file:
from sdl2 import SDL_GetKeyboardState, SDL_PumpEvents, SDL_GetKeyFromName, SDL_GetScancodeFromKey
from collections import OrderedDict
from ctypes import ArgumentError
from .EventsListenerClass import EventsListener
from .eventClasses import *
and context (functions, classes, or occasionally code) from other files:
# Path: e3d/events_processing/EventsListenerClass.py
# class EventsListener(object):
# def __init__(self):
# """
# Inherit from this class and implement the desired on*Event methods to respond to event
# notifications.
# @rtype : EventsListener
# """
# pass
#
# def onMouseEvent(self, event):
# pass
#
# def onKeyEvent(self, event):
# pass
#
# def onJoystickEvent(self, event):
# pass
#
# def onWindowEvent(self, event):
# pass
#
# def onCustomEvent(self, event):
# pass
. Output only the next line. | if not issubclass(type(listener), EventsListener) or not isinstance(listener, EventsListener): |
Predict the next line after this snippet: <|code_start|> if handle > -1:
lastValue = self._textureLastValues.get(handle)
if lastValue is not None and lastValue == value:
return
self._textureUnitsUsed += 1
unit = self._textureUnitsUsed
if unit != self._lastActiveUnit:
glActiveTexture(self._unitsCache[unit])
self._lastActiveUnit = unit
glBindTexture(GL_TEXTURE_2D, value)
glUniform1i(handle, unit)
self._textureLastValues[handle] = value
else:
self._engine.log('Error: Max fragment textures units reached ({0})'.format(str(self._maxTextureUnits)),
logLevelsEnum.warning)
def setStruct(self, structParamName, struct):
"""
@type structParamName: str
@type struct: ShaderStruct
"""
for it in struct.items():
name, val = it
paramName = structParamName + '.' + name
if isinstance(val, list):
handle = self._uniformsHandlesCache.get(paramName, -1)
if handle >= 0:
self.setMultipleValues(handle, val)
<|code_end|>
using the current file's imports:
import numpy as np
from glaze.GL import *
from ...base_backend import ShaderStruct
from .ShaderParametersHelper import getActiveUniforms, getActiveAttribs
from glaze import GL
and any relevant context from other files:
# Path: e3d/backends/base_backend.py
# class ShaderStruct(OrderedDict):
# def __init__(self, *args, **kwds):
# super(ShaderStruct, self).__init__(*args, **kwds)
#
# def __len__(self):
# res = super(ShaderStruct, self).__len__()
# for it in self.values():
# if isinstance(it, list):
# res += it.__len__() - 2
# return res
#
# def append(self, key, pyob):
# if key in self.keys():
# self.pop(key)
# self[key] = pyob
#
# def updateValue(self, key, value):
# self[key] = value
#
# Path: e3d/backends/ogl3/shader_management/ShaderParametersHelper.py
# def getActiveUniforms(program):
# actives = getShaderActives(program, GL_ACTIVE_UNIFORMS, GL_ACTIVE_UNIFORM_MAX_LENGTH)
# return actives
#
# def getActiveAttribs(program):
# actives = getShaderActives(program, GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH)
# return actives
. Output only the next line. | elif isinstance(val, ShaderStruct): |
Here is a snippet: <|code_start|> self._unitsCache.append(uc[i])
def __init__(self, GLSL_program, ID, shadersManager):
"""
Handy class to manipulate glsl program's uniform values.
@rtype : Shader
@type ID: str
@type shadersManager: shadersManager
@type GLSL_program: int
"""
self._maxBones = 50
self._maxTextureUnits = shadersManager._maxTextureUnits
self._program = GLSL_program
self._iID = ID
self._attributesHandlesCache = {}
self._uniformsHandlesCache = {}
self._textureLastValues = {}
self._textureUnitsUsed = -1
self._lastActiveUnit = -1
self._isSet = False
self._sman = shadersManager
self._unitsCache = []
self._reportInactive = False
self._fill_unitsCache()
self._uniformLastValueV = {}
self._uniformLastValueF = {}
self._uniformLastValueI = {}
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from glaze.GL import *
from ...base_backend import ShaderStruct
from .ShaderParametersHelper import getActiveUniforms, getActiveAttribs
from glaze import GL
and context from other files:
# Path: e3d/backends/base_backend.py
# class ShaderStruct(OrderedDict):
# def __init__(self, *args, **kwds):
# super(ShaderStruct, self).__init__(*args, **kwds)
#
# def __len__(self):
# res = super(ShaderStruct, self).__len__()
# for it in self.values():
# if isinstance(it, list):
# res += it.__len__() - 2
# return res
#
# def append(self, key, pyob):
# if key in self.keys():
# self.pop(key)
# self[key] = pyob
#
# def updateValue(self, key, value):
# self[key] = value
#
# Path: e3d/backends/ogl3/shader_management/ShaderParametersHelper.py
# def getActiveUniforms(program):
# actives = getShaderActives(program, GL_ACTIVE_UNIFORMS, GL_ACTIVE_UNIFORM_MAX_LENGTH)
# return actives
#
# def getActiveAttribs(program):
# actives = getShaderActives(program, GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH)
# return actives
, which may include functions, classes, or code. Output only the next line. | uniforms = getActiveUniforms(GLSL_program) |
Given the code snippet: <|code_start|> Handy class to manipulate glsl program's uniform values.
@rtype : Shader
@type ID: str
@type shadersManager: shadersManager
@type GLSL_program: int
"""
self._maxBones = 50
self._maxTextureUnits = shadersManager._maxTextureUnits
self._program = GLSL_program
self._iID = ID
self._attributesHandlesCache = {}
self._uniformsHandlesCache = {}
self._textureLastValues = {}
self._textureUnitsUsed = -1
self._lastActiveUnit = -1
self._isSet = False
self._sman = shadersManager
self._unitsCache = []
self._reportInactive = False
self._fill_unitsCache()
self._uniformLastValueV = {}
self._uniformLastValueF = {}
self._uniformLastValueI = {}
uniforms = getActiveUniforms(GLSL_program)
for ulocation, utype, uname in uniforms:
self._uniformsHandlesCache[uname] = ulocation
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from glaze.GL import *
from ...base_backend import ShaderStruct
from .ShaderParametersHelper import getActiveUniforms, getActiveAttribs
from glaze import GL
and context (functions, classes, or occasionally code) from other files:
# Path: e3d/backends/base_backend.py
# class ShaderStruct(OrderedDict):
# def __init__(self, *args, **kwds):
# super(ShaderStruct, self).__init__(*args, **kwds)
#
# def __len__(self):
# res = super(ShaderStruct, self).__len__()
# for it in self.values():
# if isinstance(it, list):
# res += it.__len__() - 2
# return res
#
# def append(self, key, pyob):
# if key in self.keys():
# self.pop(key)
# self[key] = pyob
#
# def updateValue(self, key, value):
# self[key] = value
#
# Path: e3d/backends/ogl3/shader_management/ShaderParametersHelper.py
# def getActiveUniforms(program):
# actives = getShaderActives(program, GL_ACTIVE_UNIFORMS, GL_ACTIVE_UNIFORM_MAX_LENGTH)
# return actives
#
# def getActiveAttribs(program):
# actives = getShaderActives(program, GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH)
# return actives
. Output only the next line. | attribs = getActiveAttribs(GLSL_program) |
Given the following code snippet before the placeholder: <|code_start|>
class Panel(BaseControl):
"""
Flat container for Gui objects.
@rtype : Panel
"""
def __init__(self, left, top, width, height, parent, pinning=PinningEnum.TopLeft, color=None, ID=None,
imgID=None, rotation=None, style=None):
<|code_end|>
, predict the next line using imports from the current file:
from .BaseControlClass import *
from .Styling import DefaultStyle
and context including class names, function names, and sometimes code from other files:
# Path: e3d/gui/Styling/StyleClass.py
# class DefaultStyle(object):
# def __init__(self, baseColor=None):
# if baseColor is None:
# baseColor = RGBA255(30, 30, 30, 255)
#
# self._baseColor = vec4(0)
# self.activeColor = RGB1(.8, .4, 0)
# self.name = 'Default'
# self.raisedGradientColor0 = WHITE
# self.raisedGradientColor1 = BLACK
# self.sunkenGradientColor0 = BLACK
# self.sunkenGradientColor1 = WHITE
# self.pressedGradientColor0 = BLACK
# self.pressedGradientColor1 = WHITE
# self.hoverGradientColor0 = WHITE
# self.hoverGradientColor1 = BLACK
# self.autoRaiseGradientColor0 = WHITE
# self.autoRaiseGradientColor1 = BLACK
# self.baseColor = baseColor
#
# def _buildGradients(self):
# baseColor = self._baseColor
# color0 = (baseColor + WHITE / 2.0) / 2.0
# color0.w = baseColor.w
# color1 = baseColor / 4.0
# color1.w = baseColor.w
# color2 = (baseColor + WHITE / 3.0) / 2.0
# color2.w = baseColor.w
# color3 = baseColor / 6.0
# color3.w = baseColor.w
# color4 = (baseColor + WHITE / 4.0) / 2.0
# color4.w = baseColor.w
# color5 = baseColor / 8.0
# color5.w = baseColor.w
# color6 = (baseColor + WHITE / 1.8) / 2.0
# color6.w = baseColor.w
# color7 = baseColor / 1.4
# color7.w = baseColor.w
#
# self.raisedGradientColor0 = color2
# self.raisedGradientColor1 = color3
# self.sunkenGradientColor0 = color3
# self.sunkenGradientColor1 = color2
# self.pressedGradientColor0 = color4
# self.pressedGradientColor1 = color5
# self.hoverGradientColor0 = color0
# self.hoverGradientColor1 = color1
# self.autoRaiseGradientColor0 = color6
# self.autoRaiseGradientColor1 = color7
#
# def __repr__(self):
# return str(self.name)
#
# def saveToFile(self, path):
# vals = {}
# with open(path, 'w') as file:
# attribs = dir(self)
# for att in attribs:
# if not att.startswith('_'):
# vals[att] = getattr(self, att)
# dump(vals, file, indent=4)
#
# @staticmethod
# def readFromFile(path):
# style = DefaultStyle()
# with open(path) as file:
# vals = load(file)
# for att in vals.keys:
# setattr(style, att, vals[att])
#
# return style
#
# @property
# def baseColor(self):
# return self._baseColor
#
# @baseColor.setter
# def baseColor(self, value):
# baseColor = vec4(value)
# self._baseColor = value
# self.backgroundColor = vec4(baseColor)
# self.fontColor = WHITE
# self.fontOutlineColor = BLUE
# self.fontSize = 10
# self.borderSize = 1
# self.borderColor = fromRGB1_A(baseColor / 4.0, 1)
# self.focusBorderColor = ORANGE
# self.hoverBorderColor = GREEN
# self.gradientType = GradientTypesEnum.noGradient
# self.hoverColor = fromRGB1_A((baseColor + (WHITE / 10.0)), baseColor.w)
# self.pressedColor = fromRGB1_A(baseColor / 1.5, baseColor.w)
# self.buttonStyleHint = StyleHintsEnum.Raised
# self.controlStyleHint = StyleHintsEnum.Raised
#
# self._buildGradients()
#
# def _copy(self):
# return copy(self)
. Output only the next line. | style = style or DefaultStyle(color) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
app = Flask(app_config.PROJECT_SLUG)
app.debug = app_config.DEBUG
@app.route('/')
def _graphics_list():
"""
Renders a list of all graphics for local testing.
"""
<|code_end|>
, predict the next line using imports from the current file:
import os
import app_config
import copytext
import graphic
import graphic_templates
import oauth
from flask import Flask, make_response, render_template
from glob import glob
from werkzeug.debug import DebuggedApplication
from render_utils import make_context
and context including class names, function names, and sometimes code from other files:
# Path: render_utils.py
# def make_context(asset_depth=0, root_path='www'):
# """
# Create a base-context for rendering views.
# Includes app_config and JS/CSS includers.
#
# `asset_depth` indicates how far into the url hierarchy
# the assets are hosted. If 0, then they are at the root.
# If 1 then at /foo/, etc.
# """
# context = flatten_app_config()
#
# context['JS'] = JavascriptIncluder(
# asset_depth=asset_depth,
# root_path=root_path
# )
# context['CSS'] = CSSIncluder(
# asset_depth=asset_depth,
# root_path=root_path
# )
#
# return context
. Output only the next line. | context = make_context() |
Given snippet: <|code_start|>## along with python-pylon. If not, see <http://www.gnu.org/licenses/>.
##
###############################################################################
#import pyximport; pyximport.install()
pylonExtension = Extension('pylon',['pylon/__init__.pyx',
'pylon/Logger.cpp',
'pylon/Factory.cpp',
'pylon/DevInfo.cpp',
'pylon/Camera.cpp',
'pylon/TransportLayer.cpp',
'pylon/GenApiWrap/INode.cpp',
'pylon/GenApiWrap/ICategory.cpp',
'pylon/GenApiWrap/IEnumeration.cpp',
'pylon/PyCallback.cpp'],
language="c++",
extra_compile_args=[#"-static",
#"-fPIC",
#"-std=c++11",
]
)
#FIXME: check how can be know if c++11 is available to be used
setup(name = 'pylon',
license = "LGPLv3+",
description = "Cython module to provide access to Pylon's SDK.",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pylon.version import version_python_pylon_string
from Cython.Distutils import build_ext
from distutils.core import setup
from distutils.extension import Extension
and context:
# Path: pylon/version.py
# def version_python_pylon_string():
# return '%d.%d.%d-%d'%(_MAJOR_VERSION,_MINOR_VERSION,
# _MAINTENANCE_VERSION,_BUILD_VERSION)
which might include code, classes, or functions. Output only the next line. | version = version_python_pylon_string(), |
Given the code snippet: <|code_start|>
class MyStaffMemberAdmin(StaffMemberAdmin):
fieldsets = (
('Personal Info', {'fields': ('bio', 'photo', 'website', 'phone',)}),
('Social Media', {'fields': ('github','twitter', 'facebook', 'google_plus')}),
('Responsibilities', {'fields': ('sites',)}),
)
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from staff.admin import StaffMemberAdmin
from .models import MyStaffMember
and context (functions, classes, or occasionally code) from other files:
# Path: staff/admin.py
# class StaffMemberAdmin(admin.StackedInline):
# """
# Admin form for a StaffMember that won't appear if the associated User
# isn't actually a staff member.
# """
# # form = StaffMemberForm
# # template = ADMIN_TEMPLATE
# fieldsets = (
# ('Personal Info', {'fields': ('title', 'bio', 'photo', 'website', 'phone',)}),
# ('Social Media', {'fields': ('twitter', 'facebook', 'google_plus')}),
# )
# model = StaffMember
# max_num = 1
#
# def get_formset(self, request, obj=None, **kwargs):
# """
# Return a form, if the obj has a staffmember object, otherwise
# return an empty form
# """
# if obj is not None and self.model.objects.filter(user=obj).count():
# return super(StaffMemberAdmin, self).get_formset(
# request,
# obj,
# **kwargs
# )
#
# defaults = {
# "exclude": None,
# "extra": 0,
# "max_num": 0,
# }
# return inlineformset_factory(self.parent_model, self.model, **defaults)
#
# Path: example/mystaff/models.py
# class MyStaffMember(BaseStaffMember):
# """docstring for MyStaffMember"""
#
# github = models.CharField(max_length=50, blank=True)
. Output only the next line. | model = MyStaffMember |
Predict the next line after this snippet: <|code_start|> """
user = models.ForeignKey(User,
limit_choices_to={'is_active': True},
unique=True, verbose_name=_('User'))
first_name = models.CharField(_('First Name'),
max_length=150,
help_text=_("""This field is linked to the User account and will
change its value."""),
blank=True,
null=True)
last_name = models.CharField(_('Last Name'),
max_length=150,
help_text=_("""This field is linked to the User account and will
change its value."""),
blank=True,
null=True)
slug = models.SlugField(unique=True)
email = models.EmailField(_('e-mail'),
blank=True,
help_text=_("""This field is linked to the User account and will
change its value."""),
null=True)
title = models.CharField(
_('Title'),
max_length=50,
blank=True,
default="")
bio = models.TextField(_('Biography'), blank=True)
is_active = models.BooleanField(_('is a current employee'), default=True)
phone = PhoneNumberField(_('Phone Number'), blank=True)
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.files.storage import get_storage_class
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django_localflavor_us.models import PhoneNumberField
from .fields import RemovableImageField
from .settings import PHOTO_STORAGE, ORDERING
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.db.models.signals import post_save
and any relevant context from other files:
# Path: staff/fields.py
# class RemovableImageField(models.ImageField, RemovableFileField):
# """
# A specific form of removeable file field, but specifically for images
# """
# attr_class = MyImageFieldFile
#
# def formfield(self, **kwargs):
# defaults = {'form_class': RemovableImageFormField}
# defaults.update(kwargs)
# return super(RemovableImageField, self).formfield(**defaults)
#
# Path: staff/settings.py
# DEFAULT_SETTINGS = {
# 'PHOTO_STORAGE': settings.DEFAULT_FILE_STORAGE,
# 'ORDERING': ('last_name', 'first_name'),
# }
# USER_SETTINGS = DEFAULT_SETTINGS.copy()
# USER_SETTINGS['ORDERING'] = settings.STAFF_ORDERING
# USER_SETTINGS['PHOTO_STORAGE'] = settings.STAFF_PHOTO_STORAGE
. Output only the next line. | photo = RemovableImageField(_('Photo'), |
Based on the snippet: <|code_start|> _('Title'),
max_length=50,
blank=True,
default="")
bio = models.TextField(_('Biography'), blank=True)
is_active = models.BooleanField(_('is a current employee'), default=True)
phone = PhoneNumberField(_('Phone Number'), blank=True)
photo = RemovableImageField(_('Photo'),
blank=True,
upload_to='img/staff/%Y',
storage=DEFAULT_STORAGE(),
height_field='photo_height',
width_field='photo_width')
photo_height = models.IntegerField(default=0, blank=True)
photo_width = models.IntegerField(default=0, blank=True)
twitter = models.CharField(_('Twitter ID'),
max_length=100,
blank=True)
facebook = models.CharField(_('Facebook Acccount'),
max_length=100,
blank=True)
google_plus = models.CharField(_('Google+ ID'),
max_length=100,
blank=True)
website = models.URLField(_('Website'),
blank=True)
objects = StaffMemberManager()
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.files.storage import get_storage_class
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django_localflavor_us.models import PhoneNumberField
from .fields import RemovableImageField
from .settings import PHOTO_STORAGE, ORDERING
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.db.models.signals import post_save
and context (classes, functions, sometimes code) from other files:
# Path: staff/fields.py
# class RemovableImageField(models.ImageField, RemovableFileField):
# """
# A specific form of removeable file field, but specifically for images
# """
# attr_class = MyImageFieldFile
#
# def formfield(self, **kwargs):
# defaults = {'form_class': RemovableImageFormField}
# defaults.update(kwargs)
# return super(RemovableImageField, self).formfield(**defaults)
#
# Path: staff/settings.py
# DEFAULT_SETTINGS = {
# 'PHOTO_STORAGE': settings.DEFAULT_FILE_STORAGE,
# 'ORDERING': ('last_name', 'first_name'),
# }
# USER_SETTINGS = DEFAULT_SETTINGS.copy()
# USER_SETTINGS['ORDERING'] = settings.STAFF_ORDERING
# USER_SETTINGS['PHOTO_STORAGE'] = settings.STAFF_PHOTO_STORAGE
. Output only the next line. | ordering = ORDERING |
Predict the next line after this snippet: <|code_start|>"""
Admin classes for the StaffMember model
"""
# from staff.forms import StaffMemberForm
# ADMIN_TEMPLATE = "admin/edit_inline/staff.html"
class StaffMemberAdmin(admin.StackedInline):
"""
Admin form for a StaffMember that won't appear if the associated User
isn't actually a staff member.
"""
# form = StaffMemberForm
# template = ADMIN_TEMPLATE
fieldsets = (
('Personal Info', {'fields': ('title', 'bio', 'photo', 'website', 'phone',)}),
('Social Media', {'fields': ('twitter', 'facebook', 'google_plus')}),
)
<|code_end|>
using the current file's imports:
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.forms.models import inlineformset_factory
from staff.models import StaffMember
and any relevant context from other files:
# Path: staff/models.py
# class StaffMember(BaseStaffMember):
# pass
. Output only the next line. | model = StaffMember |
Given snippet: <|code_start|># Changing the staff member's first name, last name or email should change the user's as well
# Changing the staff member's first name or last name should change the slug
# It would really be cool if you changed the slug, you check if redirects is
# enabled and insert a redirect from the old slug to the new slug
# Changing the user's first name, last name or email should change the staff member's as well
# Changing the user's first name or last name should change the staff member's slug
class StaffTest(TestCase):
"""Tests for the Staff model"""
def setUp(self):
self.user = User.objects.create_user("tempuser", "tempuser", "temp@user.com")
self.user.first_name = "Temporary"
self.user.last_name = "User"
self.user.save()
def assertStaffInfoEqual(self, staffmember, user):
self.assertEqual(staffmember.first_name, user.first_name)
self.assertEqual(staffmember.last_name, user.last_name)
self.assertEqual(staffmember.email, user.email)
self.assertEqual(staffmember.slug, slugify('%s %s' % (user.first_name, user.last_name)))
def testAutoCreation(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from django.contrib.auth.models import User
from staff.models import StaffMember
from django.template.defaultfilters import slugify
and context:
# Path: staff/models.py
# class StaffMember(BaseStaffMember):
# pass
which might include code, classes, or functions. Output only the next line. | self.assertEqual(StaffMember.objects.all().count(), 0) |
Based on the snippet: <|code_start|>
def index(request, template_name='staffmembers/index.html'):
"""
The list of employees or staff members
"""
return render_to_response(template_name,
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from staff.models import StaffMember
from staff.forms import ContactForm
from story.settings import PUBLISHED_STATUS
import json
and context (classes, functions, sometimes code) from other files:
# Path: staff/models.py
# class StaffMember(BaseStaffMember):
# pass
#
# Path: staff/forms.py
# class ContactForm(forms.Form):
# """
# A simple contact form to allow contacting the staff
# """
# name = forms.CharField(label=_('Your Name'))
# email = forms.EmailField(label=_('Your Email'))
# message = forms.CharField(label=_('Message'), widget=forms.Textarea)
. Output only the next line. | {'staff': StaffMember.objects.active()}, |
Predict the next line after this snippet: <|code_start|> 'last_name': '',
'email': '',
'slug': '',
'bio': '',
'phone': '',
'is_active': False}
try:
member = StaffMember.objects.get(pk=user_id)
for key in data.keys():
if hasattr(member, key):
data[key] = getattr(member, key, '')
except StaffMember.DoesNotExist:
pass
return HttpResponse(json.dumps(data),
mimetype='application/json')
def contact(request, slug, template_name='staffmembers/contact.html',
success_url='/staff/contact/done/',
email_subject_template='staffmembers/emails/subject.txt',
email_body_template='staffmembers/emails/body.txt'):
"""
Handle a contact request
"""
member = get_object_or_404(StaffMember, slug__iexact=slug, is_active=True)
if request.method == 'POST':
<|code_end|>
using the current file's imports:
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from staff.models import StaffMember
from staff.forms import ContactForm
from story.settings import PUBLISHED_STATUS
import json
and any relevant context from other files:
# Path: staff/models.py
# class StaffMember(BaseStaffMember):
# pass
#
# Path: staff/forms.py
# class ContactForm(forms.Form):
# """
# A simple contact form to allow contacting the staff
# """
# name = forms.CharField(label=_('Your Name'))
# email = forms.EmailField(label=_('Your Email'))
# message = forms.CharField(label=_('Message'), widget=forms.Textarea)
. Output only the next line. | form = ContactForm(request.POST) |
Next line prediction: <|code_start|>try:
ConnectionRefusedError
except NameError: # Python 2
ConnectionRefusedError = socket.error
sys.path.append(os.path.join(os.path.dirname(__file__), 'bad_servers'))
def check(module_name, match):
# This test module is a bit buggy.
# Sometimes we get a ConnectionRefusedError that we want to ignore.
attempts = 1
max_attempts = 3
while True:
try:
<|code_end|>
. Use current file imports:
(import os
import sys
import socket
import pytest
from msl.loadlib import ConnectionTimeoutError
from conftest import skipif_no_server32
from client import Client)
and context including class names, function names, or small code snippets from other files:
# Path: msl/loadlib/exceptions.py
# class ConnectionTimeoutError(OSError):
#
# def __init__(self, *args, **kwargs):
# """Raised when the connection to the 32-bit server cannot be established."""
# self.timeout_message = args[0] if args else 'Timeout'
# self.reason = ''
# super(ConnectionTimeoutError, self).__init__(*args, **kwargs)
#
# def __str__(self):
# return self.timeout_message + '\n' + self.reason
#
# Path: conftest.py
# def has_labview_runtime():
# def doctest_skipif(doctest_namespace):
. Output only the next line. | with pytest.raises(ConnectionTimeoutError, match=match): |
Given the code snippet: <|code_start|>try:
ConnectionRefusedError
except NameError: # Python 2
ConnectionRefusedError = socket.error
sys.path.append(os.path.join(os.path.dirname(__file__), 'bad_servers'))
def check(module_name, match):
# This test module is a bit buggy.
# Sometimes we get a ConnectionRefusedError that we want to ignore.
attempts = 1
max_attempts = 3
while True:
try:
with pytest.raises(ConnectionTimeoutError, match=match):
Client(module_name)
except ConnectionRefusedError:
if attempts == max_attempts:
raise
attempts += 1
else:
break # then this test was successful
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import socket
import pytest
from msl.loadlib import ConnectionTimeoutError
from conftest import skipif_no_server32
from client import Client
and context (functions, classes, or occasionally code) from other files:
# Path: msl/loadlib/exceptions.py
# class ConnectionTimeoutError(OSError):
#
# def __init__(self, *args, **kwargs):
# """Raised when the connection to the 32-bit server cannot be established."""
# self.timeout_message = args[0] if args else 'Timeout'
# self.reason = ''
# super(ConnectionTimeoutError, self).__init__(*args, **kwargs)
#
# def __str__(self):
# return self.timeout_message + '\n' + self.reason
#
# Path: conftest.py
# def has_labview_runtime():
# def doctest_skipif(doctest_namespace):
. Output only the next line. | @skipif_no_server32 |
Continue the code snippet: <|code_start|>
@click.command('raw', short_help='Show alert raw data')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.pass_obj
def cli(obj, ids, query, filters):
"""Show raw data for alerts."""
client = obj['client']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
import click
from tabulate import tabulate
from alertaclient.utils import build_query
and context (classes, functions, or code) from other files:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Predict the next line for this snippet: <|code_start|> more += 'customer=%r, ' % self.customer
return 'Blackout(id={!r}, priority={!r}, status={!r}, environment={!r}, {}start_time={!r}, end_time={!r}, remaining={!r})'.format(
self.id,
self.priority,
self.status,
self.environment,
more,
self.start_time,
self.end_time,
self.remaining
)
@classmethod
def parse(cls, json):
if not isinstance(json.get('service', []), list):
raise ValueError('service must be a list')
if not isinstance(json.get('tags', []), list):
raise ValueError('tags must be a list')
return Blackout(
id=json.get('id'),
environment=json.get('environment'),
service=json.get('service', list()),
resource=json.get('resource', None),
event=json.get('event', None),
group=json.get('group', None),
tags=json.get('tags', list()),
origin=json.get('origin', None),
customer=json.get('customer', None),
<|code_end|>
with the help of current file imports:
from datetime import datetime, timedelta
from alertaclient.utils import DateTime
and context from other files:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
, which may contain function names, class names, or code. Output only the next line. | start_time=DateTime.parse(json.get('startTime')), |
Next line prediction: <|code_start|>
@click.command('history', short_help='Show alert history')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.pass_obj
def cli(obj, ids, query, filters):
"""Show status and severity changes for alerts."""
client = obj['client']
if obj['output'] == 'json':
r = client.http.get('/alerts/history')
click.echo(json.dumps(r['history'], sort_keys=True, indent=4, ensure_ascii=False))
else:
timezone = obj['timezone']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
(import json
import click
from tabulate import tabulate
from alertaclient.utils import build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Using the snippet: <|code_start|>@click.option('--delete', '-D', metavar='ID', nargs=2, help='Delete note, using alert ID and note ID')
@click.pass_obj
def cli(obj, alert_ids, query, filters, text, delete):
"""
Add or delete note to alerts.
EXAMPLES
Add a note to an alert.
$ alerta note --alert-ids <alert-id> --text <note>
List notes for an alert.
$ alerta notes --alert-ids <alert-id>
Delete a note for an alert.
$ alerta note -D <alert-id> <note-id>
"""
client = obj['client']
if delete:
client.delete_alert_note(*delete)
else:
if alert_ids:
total = len(alert_ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
, determine the next line of code. You have imports:
import click
from alertaclient.utils import build_query
and context (class names, function names, or code) available:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Next line prediction: <|code_start|>
@click.command('heartbeats', short_help='List heartbeats')
@click.option('--alert', is_flag=True, help='Alert on stale or slow heartbeats')
@click.option('--severity', '-s', metavar='SEVERITY', default='major', help='Severity for heartbeat alerts')
@click.option('--timeout', metavar='SECONDS', type=int, help='Seconds before stale heartbeat alerts will be expired')
@click.option('--purge', is_flag=True, help='Delete all stale heartbeats')
@click.pass_obj
def cli(obj, alert, severity, timeout, purge):
"""List heartbeats."""
client = obj['client']
try:
default_normal_severity = obj['alarm_model']['defaults']['normal_severity']
except KeyError:
default_normal_severity = 'normal'
if severity in ['normal', 'ok', 'cleared']:
raise click.UsageError('Must be a non-normal severity. "{}" is one of {}'.format(
severity, ', '.join(['normal', 'ok', 'cleared']))
)
if severity not in obj['alarm_model']['severity'].keys():
raise click.UsageError('Must be a valid severity. "{}" is not one of {}'.format(
severity, ', '.join(obj['alarm_model']['severity'].keys()))
)
if obj['output'] == 'json':
r = client.http.get('/heartbeats')
<|code_end|>
. Use current file imports:
(import json
import click
from tabulate import tabulate
from alertaclient.models.heartbeat import Heartbeat
from alertaclient.utils import origin)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/models/heartbeat.py
# class Heartbeat:
#
# def __init__(self, origin=None, tags=None, create_time=None, timeout=None, customer=None, **kwargs):
# if any(['.' in key for key in kwargs.get('attributes', dict()).keys()])\
# or any(['$' in key for key in kwargs.get('attributes', dict()).keys()]):
# raise ValueError('Attribute keys must not contain "." or "$"')
#
# self.id = kwargs.get('id', None)
# self.origin = origin
# self.status = kwargs.get('status', None) or 'unknown'
# self.tags = tags or list()
# self.attributes = kwargs.get('attributes', None) or dict()
# self.event_type = kwargs.get('event_type', kwargs.get('type', None)) or 'Heartbeat'
# self.create_time = create_time
# self.timeout = timeout
# self.max_latency = kwargs.get('max_latency', None) or DEFAULT_MAX_LATENCY
# self.receive_time = kwargs.get('receive_time', None)
# self.customer = customer
#
# @property
# def latency(self):
# return int((self.receive_time - self.create_time).total_seconds() * 1000)
#
# @property
# def since(self):
# since = datetime.utcnow() - self.receive_time
# return since - timedelta(microseconds=since.microseconds)
#
# def __repr__(self):
# return 'Heartbeat(id={!r}, origin={!r}, create_time={!r}, timeout={!r}, customer={!r})'.format(
# self.id, self.origin, self.create_time, self.timeout, self.customer)
#
# @classmethod
# def parse(cls, json):
# if not isinstance(json.get('tags', []), list):
# raise ValueError('tags must be a list')
# if not isinstance(json.get('attributes', {}), dict):
# raise ValueError('attributes must be a JSON object')
# if not isinstance(json.get('timeout', 0), int):
# raise ValueError('timeout must be an integer')
#
# return Heartbeat(
# id=json.get('id', None),
# origin=json.get('origin', None),
# status=json.get('status', None),
# tags=json.get('tags', list()),
# attributes=json.get('attributes', dict()),
# event_type=json.get('type', None),
# create_time=DateTime.parse(json.get('createTime')),
# timeout=json.get('timeout', None),
# max_latency=json.get('maxLatency', None) or DEFAULT_MAX_LATENCY,
# receive_time=DateTime.parse(json.get('receiveTime')),
# customer=json.get('customer', None)
# )
#
# def tabular(self, timezone=None):
# return {
# 'id': self.id,
# 'origin': self.origin,
# 'customer': self.customer,
# 'tags': ','.join(self.tags),
# 'attributes': self.attributes,
# 'createTime': DateTime.localtime(self.create_time, timezone),
# 'receiveTime': DateTime.localtime(self.receive_time, timezone),
# 'since': self.since,
# 'timeout': f'{self.timeout}s',
# 'latency': f'{self.latency:.0f}ms',
# 'maxLatency': f'{self.max_latency}ms',
# 'status': self.status
# }
#
# Path: alertaclient/utils.py
# def origin():
# prog = os.path.basename(sys.argv[0])
# return f'{prog}/{platform.uname()[1]}'
. Output only the next line. | heartbeats = [Heartbeat.parse(hb) for hb in r['heartbeats']] |
Given the code snippet: <|code_start|> r = client.http.get('/heartbeats')
heartbeats = [Heartbeat.parse(hb) for hb in r['heartbeats']]
click.echo(json.dumps(r['heartbeats'], sort_keys=True, indent=4, ensure_ascii=False))
else:
timezone = obj['timezone']
headers = {
'id': 'ID', 'origin': 'ORIGIN', 'customer': 'CUSTOMER', 'tags': 'TAGS', 'attributes': 'ATTRIBUTES',
'createTime': 'CREATED', 'receiveTime': 'RECEIVED', 'since': 'SINCE', 'timeout': 'TIMEOUT',
'latency': 'LATENCY', 'maxLatency': 'MAX LATENCY', 'status': 'STATUS'
}
heartbeats = client.get_heartbeats()
click.echo(tabulate([h.tabular(timezone) for h in heartbeats], headers=headers, tablefmt=obj['output']))
not_ok = [hb for hb in heartbeats if hb.status != 'ok']
if purge:
with click.progressbar(not_ok, label=f'Purging {len(not_ok)} heartbeats') as bar:
for b in bar:
client.delete_heartbeat(b.id)
if alert:
with click.progressbar(heartbeats, label=f'Alerting {len(heartbeats)} heartbeats') as bar:
for b in bar:
want_environment = b.attributes.pop('environment', 'Production')
want_severity = b.attributes.pop('severity', severity)
want_service = b.attributes.pop('service', ['Alerta'])
want_group = b.attributes.pop('group', 'System')
if b.status == 'expired': # aka. "stale"
client.send_alert(
<|code_end|>
, generate the next line using the imports in this file:
import json
import click
from tabulate import tabulate
from alertaclient.models.heartbeat import Heartbeat
from alertaclient.utils import origin
and context (functions, classes, or occasionally code) from other files:
# Path: alertaclient/models/heartbeat.py
# class Heartbeat:
#
# def __init__(self, origin=None, tags=None, create_time=None, timeout=None, customer=None, **kwargs):
# if any(['.' in key for key in kwargs.get('attributes', dict()).keys()])\
# or any(['$' in key for key in kwargs.get('attributes', dict()).keys()]):
# raise ValueError('Attribute keys must not contain "." or "$"')
#
# self.id = kwargs.get('id', None)
# self.origin = origin
# self.status = kwargs.get('status', None) or 'unknown'
# self.tags = tags or list()
# self.attributes = kwargs.get('attributes', None) or dict()
# self.event_type = kwargs.get('event_type', kwargs.get('type', None)) or 'Heartbeat'
# self.create_time = create_time
# self.timeout = timeout
# self.max_latency = kwargs.get('max_latency', None) or DEFAULT_MAX_LATENCY
# self.receive_time = kwargs.get('receive_time', None)
# self.customer = customer
#
# @property
# def latency(self):
# return int((self.receive_time - self.create_time).total_seconds() * 1000)
#
# @property
# def since(self):
# since = datetime.utcnow() - self.receive_time
# return since - timedelta(microseconds=since.microseconds)
#
# def __repr__(self):
# return 'Heartbeat(id={!r}, origin={!r}, create_time={!r}, timeout={!r}, customer={!r})'.format(
# self.id, self.origin, self.create_time, self.timeout, self.customer)
#
# @classmethod
# def parse(cls, json):
# if not isinstance(json.get('tags', []), list):
# raise ValueError('tags must be a list')
# if not isinstance(json.get('attributes', {}), dict):
# raise ValueError('attributes must be a JSON object')
# if not isinstance(json.get('timeout', 0), int):
# raise ValueError('timeout must be an integer')
#
# return Heartbeat(
# id=json.get('id', None),
# origin=json.get('origin', None),
# status=json.get('status', None),
# tags=json.get('tags', list()),
# attributes=json.get('attributes', dict()),
# event_type=json.get('type', None),
# create_time=DateTime.parse(json.get('createTime')),
# timeout=json.get('timeout', None),
# max_latency=json.get('maxLatency', None) or DEFAULT_MAX_LATENCY,
# receive_time=DateTime.parse(json.get('receiveTime')),
# customer=json.get('customer', None)
# )
#
# def tabular(self, timezone=None):
# return {
# 'id': self.id,
# 'origin': self.origin,
# 'customer': self.customer,
# 'tags': ','.join(self.tags),
# 'attributes': self.attributes,
# 'createTime': DateTime.localtime(self.create_time, timezone),
# 'receiveTime': DateTime.localtime(self.receive_time, timezone),
# 'since': self.since,
# 'timeout': f'{self.timeout}s',
# 'latency': f'{self.latency:.0f}ms',
# 'maxLatency': f'{self.max_latency}ms',
# 'status': self.status
# }
#
# Path: alertaclient/utils.py
# def origin():
# prog = os.path.basename(sys.argv[0])
# return f'{prog}/{platform.uname()[1]}'
. Output only the next line. | resource=b.origin, |
Using the snippet: <|code_start|> else:
query = build_query(filters)
if from_date:
query.append(('from-date', from_date))
r = client.http.get('/alerts', query, page=1, page_size=1000)
if obj['output'] == 'json':
click.echo(json.dumps(r['alerts'], sort_keys=True, indent=4, ensure_ascii=False))
elif obj['output'] in ['json_lines', 'jsonl', 'ndjson']:
for alert in r['alerts']:
click.echo(json.dumps(alert, ensure_ascii=False))
else:
alerts = [Alert.parse(a) for a in r['alerts']]
last_time = r['lastTime']
auto_refresh = r['autoRefresh']
if display == 'oneline':
headers = {'id': 'ID', 'lastReceiveTime': 'LAST RECEIVED', 'severity': 'SEVERITY', 'status': 'STATUS',
'duplicateCount': 'DUPL', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE',
'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'DESCRIPTION'}
data = [{k: v for k, v in a.tabular(timezone).items() if k in headers.keys()} for a in alerts]
click.echo(tabulate(data, headers=headers, tablefmt=obj['output']))
else:
for alert in reversed(alerts):
color = COLOR_MAP.get(alert.severity, {'fg': 'white'})
click.secho('{}|{}|{}|{:5d}|{}|{:<5s}|{:<10s}|{:<18s}|{:12s}|{:16s}|{:12s}'.format(
alert.id[0:8],
<|code_end|>
, determine the next line of code. You have imports:
import json
import click
from tabulate import tabulate
from alertaclient.models.alert import Alert
from alertaclient.utils import DateTime, build_query
and context (class names, function names, or code) available:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | DateTime.localtime(alert.last_receive_time, timezone), |
Next line prediction: <|code_start|>
COLOR_MAP = {
'critical': {'fg': 'red'},
'major': {'fg': 'magenta'},
'minor': {'fg': 'yellow'},
'warning': {'fg': 'blue'},
'normal': {'fg': 'green'},
'indeterminate': {'fg': 'cyan'},
}
@click.command('query', short_help='Search for alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--oneline', 'display', flag_value='oneline', default=True, help='Show alerts using table format')
@click.option('--medium', 'display', flag_value='medium', help='Show important alert attributes')
@click.option('--full', 'display', flag_value='full', help='Show full alert details')
@click.pass_obj
def cli(obj, ids, query, filters, display, from_date=None):
"""Query for alerts based on search filter criteria."""
client = obj['client']
timezone = obj['timezone']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
(import json
import click
from tabulate import tabulate
from alertaclient.models.alert import Alert
from alertaclient.utils import DateTime, build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Next line prediction: <|code_start|>
@click.command('delete', short_help='Delete alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.pass_obj
def cli(obj, ids, query, filters):
"""Delete alerts."""
client = obj['client']
if ids:
total = len(ids)
else:
if not (query or filters):
click.confirm('Deleting all alerts. Do you want to continue?', abort=True)
if query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
(import click
from alertaclient.utils import build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Predict the next line after this snippet: <|code_start|>
if obj['output'] == 'json':
r = client.http.get('/keys')
click.echo(json.dumps(r['keys'], sort_keys=True, indent=4, ensure_ascii=False))
else:
timezone = obj['timezone']
headers = {
'id': 'ID', 'key': 'API KEY', 'user': 'USER', 'scopes': 'SCOPES', 'text': 'TEXT',
'expireTime': 'EXPIRES', 'count': 'COUNT', 'lastUsedTime': 'LAST USED', 'customer': 'CUSTOMER'
}
click.echo(tabulate([k.tabular(timezone) for k in client.get_keys()], headers=headers, tablefmt=obj['output']))
if alert:
keys = r['keys']
service = ['Alerta']
group = 'System'
environment = 'Production'
with click.progressbar(keys, label=f'Analysing {len(keys)} keys') as bar:
for b in bar:
if b['status'] == 'expired':
client.send_alert(
resource=b['id'],
event='ApiKeyExpired',
environment=environment,
severity=severity,
correlate=['ApiKeyExpired', 'ApiKeyExpiring', 'ApiKeyOK'],
service=service,
group=group,
value='Expired',
text=f"Key expired on {b['expireTime']}",
<|code_end|>
using the current file's imports:
import json
import click
from datetime import datetime, timedelta
from tabulate import tabulate
from alertaclient.utils import origin
and any relevant context from other files:
# Path: alertaclient/utils.py
# def origin():
# prog = os.path.basename(sys.argv[0])
# return f'{prog}/{platform.uname()[1]}'
. Output only the next line. | origin=origin(), |
Here is a snippet: <|code_start|>
@click.command('unshelve', short_help='Un-shelve alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'open'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
<|code_end|>
. Write the next line using the current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
, which may include functions, classes, or code. Output only the next line. | action_progressbar(client, 'unshelve', ids, label=f'Un-shelving {total} alerts', text=text) |
Using the snippet: <|code_start|>
@click.command('unshelve', short_help='Un-shelve alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'open'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
, determine the next line of code. You have imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context (class names, function names, or code) available:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Given the following code snippet before the placeholder: <|code_start|> time.sleep(2)
def update(self):
self.lines, self.cols = self.screen.getmaxyx()
self.screen.clear()
now = datetime.utcnow()
status = self.client.mgmt_status()
version = status['version']
# draw header
self._addstr(0, 0, self.client.endpoint, curses.A_BOLD)
self._addstr(0, 'C', f'alerta {version}', curses.A_BOLD)
self._addstr(0, 'R', '{}'.format(now.strftime('%H:%M:%S %d/%m/%y')), curses.A_BOLD)
# TODO - draw bars
# draw alerts
text_width = self.cols - 95 if self.cols >= 95 else 0
self._addstr(2, 1, 'Sev. Time Dupl. Customer Env. Service Resource Group Event'
+ ' Value Text' + ' ' * (text_width - 4), curses.A_UNDERLINE)
def short_sev(severity):
return self.SEVERITY_MAP.get(severity, self.SEVERITY_MAP['unknown'])[0]
def color(severity):
return self.SEVERITY_MAP.get(severity, self.SEVERITY_MAP['unknown'])[1]
r = self.client.http.get('/alerts')
alerts = [Alert.parse(a) for a in r['alerts']]
<|code_end|>
, predict the next line using imports from the current file:
import curses
import sys
import time
from curses import wrapper
from datetime import datetime
from alertaclient.models.alert import Alert
from alertaclient.utils import DateTime
and context including class names, function names, and sometimes code from other files:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
. Output only the next line. | last_time = DateTime.parse(r['lastTime']) |
Next line prediction: <|code_start|>
@click.command('action', short_help='Action alerts')
@click.option('--action', '-a', metavar='ACTION', help='Custom action (user-defined)')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with action')
@click.pass_obj
def cli(obj, action, ids, query, filters, text):
"""Take action on alert'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
label = f'Action ({action}) {total} alerts'
<|code_end|>
. Use current file imports:
(import click
from alertaclient.utils import action_progressbar, build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | action_progressbar(client, action=action, ids=ids, label=label, text=text) |
Predict the next line for this snippet: <|code_start|>
@click.command('action', short_help='Action alerts')
@click.option('--action', '-a', metavar='ACTION', help='Custom action (user-defined)')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with action')
@click.pass_obj
def cli(obj, action, ids, query, filters, text):
"""Take action on alert'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
with the help of current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
, which may contain function names, class names, or code. Output only the next line. | query = build_query(filters) |
Next line prediction: <|code_start|>
@click.command('update', short_help='Update alert attributes')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--attributes', '-A', metavar='KEY=VALUE', multiple=True, required=True, help='List of attributes eg. priority=high')
@click.pass_obj
def cli(obj, ids, query, filters, attributes):
"""Update alert attributes."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
(import click
from alertaclient.utils import build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Continue the code snippet: <|code_start|>
@click.command('shelve', short_help='Shelve alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--timeout', metavar='SECONDS', type=int, help='Seconds before alert auto-unshelved.', default=7200, show_default=True)
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, timeout, text):
"""Set alert status to 'shelved'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
<|code_end|>
. Use current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context (classes, functions, or code) from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | action_progressbar(client, action='shelve', ids=ids, |
Next line prediction: <|code_start|>
@click.command('shelve', short_help='Shelve alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--timeout', metavar='SECONDS', type=int, help='Seconds before alert auto-unshelved.', default=7200, show_default=True)
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, timeout, text):
"""Set alert status to 'shelved'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
(import click
from alertaclient.utils import action_progressbar, build_query)
and context including class names, function names, or small code snippets from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Given snippet: <|code_start|>
class Note:
def __init__(self, text, user, note_type, **kwargs):
self.id = kwargs.get('id', None)
self.text = text
self.user = user
self.note_type = note_type
self.attributes = kwargs.get('attributes', None) or dict()
self.create_time = kwargs['create_time'] if 'create_time' in kwargs else datetime.utcnow()
self.update_time = kwargs.get('update_time')
self.alert = kwargs.get('alert')
self.customer = kwargs.get('customer')
@classmethod
def parse(cls, json):
return Note(
id=json.get('id', None),
text=json.get('text', None),
user=json.get('user', None),
attributes=json.get('attributes', dict()),
note_type=json.get('type', None),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime
from alertaclient.utils import DateTime
and context:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
which might include code, classes, or functions. Output only the next line. | create_time=DateTime.parse(json['createTime']) if 'createTime' in json else None, |
Given the code snippet: <|code_start|>
@click.command('login', short_help='Login with user credentials')
@click.argument('username', required=False)
@click.pass_obj
def cli(obj, username):
"""Authenticate using Azure, Github, Gitlab, Google OAuth2, OpenID or
Basic Auth username/password instead of using an API key."""
client = obj['client']
provider = obj['provider']
client_id = obj['client_id']
try:
if provider == 'azure':
token = azure.login(client, obj['azure_tenant'], client_id)['token']
elif provider == 'github':
<|code_end|>
, generate the next line using the imports in this file:
import sys
import click
from alertaclient.auth import azure, github, gitlab, google, oidc
from alertaclient.auth.token import Jwt
from alertaclient.auth.utils import save_token
from alertaclient.exceptions import AuthError
and context (functions, classes, or occasionally code) from other files:
# Path: alertaclient/auth/github.py
# def login(client, github_url, client_id):
#
# Path: alertaclient/auth/utils.py
# def save_token(endpoint, username, token):
# with open(NETRC_FILE, 'a'): # touch file
# pass
# try:
# info = netrc(NETRC_FILE)
# except Exception as e:
# raise ConfigurationError(f'{e}')
# info.hosts[machine(endpoint)] = (username, None, token)
# with open(NETRC_FILE, 'w') as f:
# f.write(dump_netrc(info))
. Output only the next line. | token = github.login(client, obj['github_url'], client_id)['token'] |
Given snippet: <|code_start|> provider = obj['provider']
client_id = obj['client_id']
try:
if provider == 'azure':
token = azure.login(client, obj['azure_tenant'], client_id)['token']
elif provider == 'github':
token = github.login(client, obj['github_url'], client_id)['token']
elif provider == 'gitlab':
token = gitlab.login(client, obj['gitlab_url'], client_id)['token']
elif provider == 'google':
if not username:
username = click.prompt('Email')
token = google.login(client, username, client_id)['token']
elif provider == 'openid':
token = oidc.login(client, obj['oidc_auth_url'], client_id)['token']
elif provider == 'basic' or provider == 'ldap':
if not username:
username = click.prompt('Email')
password = click.prompt('Password', hide_input=True)
token = client.login(username, password)['token']
else:
click.echo(f'ERROR: unknown provider {provider}', err=True)
sys.exit(1)
except Exception as e:
raise AuthError(e)
jwt = Jwt()
preferred_username = jwt.parse(token)['preferred_username']
if preferred_username:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import click
from alertaclient.auth import azure, github, gitlab, google, oidc
from alertaclient.auth.token import Jwt
from alertaclient.auth.utils import save_token
from alertaclient.exceptions import AuthError
and context:
# Path: alertaclient/auth/github.py
# def login(client, github_url, client_id):
#
# Path: alertaclient/auth/utils.py
# def save_token(endpoint, username, token):
# with open(NETRC_FILE, 'a'): # touch file
# pass
# try:
# info = netrc(NETRC_FILE)
# except Exception as e:
# raise ConfigurationError(f'{e}')
# info.hosts[machine(endpoint)] = (username, None, token)
# with open(NETRC_FILE, 'w') as f:
# f.write(dump_netrc(info))
which might include code, classes, or functions. Output only the next line. | save_token(client.endpoint, preferred_username, token) |
Predict the next line after this snippet: <|code_start|>
@click.command('revoke', short_help='Revoke API key')
@click.option('--api-key', '-K', required=True, help='API Key or ID')
@click.pass_context
def cli(ctx, api_key):
<|code_end|>
using the current file's imports:
import click
from .cmd_key import cli as revoke
and any relevant context from other files:
# Path: alertaclient/commands/cmd_key.py
# @click.command('key', short_help='Create API key')
# @click.option('--api-key', '-K', help='User-defined API Key. [default: random string]')
# @click.option('--username', '-u', help='User (Admin only)')
# @click.option('--scope', 'scopes', multiple=True, help='List of permissions eg. admin:keys, write:alerts')
# @click.option('--duration', metavar='SECONDS', type=int, help='Duration API key is valid')
# @click.option('--text', help='Description of API key use')
# @click.option('--customer', metavar='STRING', help='Customer')
# @click.option('--delete', '-D', metavar='ID', help='Delete API key using ID or KEY')
# @click.pass_obj
# def cli(obj, api_key, username, scopes, duration, text, customer, delete):
# """Create or delete an API key."""
# client = obj['client']
# if delete:
# client.delete_key(delete)
# else:
# try:
# expires = datetime.utcnow() + timedelta(seconds=duration) if duration else None
# key = client.create_key(username, scopes, expires, text, customer, key=api_key)
# except Exception as e:
# click.echo(f'ERROR: {e}', err=True)
# sys.exit(1)
# click.echo(key.key)
. Output only the next line. | ctx.invoke(revoke, delete=api_key) |
Based on the snippet: <|code_start|>
@click.command('token', short_help='Display current auth token')
@click.option('--decode', '-D', is_flag=True, help='Decode auth token.')
@click.pass_obj
def cli(obj, decode):
"""Display the auth token for logged in user, with option to decode it."""
client = obj['client']
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from alertaclient.auth.token import Jwt
from alertaclient.auth.utils import get_token
and context (classes, functions, sometimes code) from other files:
# Path: alertaclient/auth/utils.py
# def get_token(endpoint):
# try:
# info = netrc(NETRC_FILE)
# except Exception:
# return
# auth = info.authenticators(machine(endpoint))
# if auth is not None:
# _, _, password = auth
# return password
. Output only the next line. | token = get_token(client.endpoint) |
Given snippet: <|code_start|>
@click.command('tag', short_help='Tag alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--tag', '-T', 'tags', required=True, multiple=True, help='List of tags')
@click.pass_obj
def cli(obj, ids, query, filters, tags):
"""Add tags to alerts."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from alertaclient.utils import build_query
and context:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
which might include code, classes, or functions. Output only the next line. | query = build_query(filters) |
Given snippet: <|code_start|> self.id = kwargs.get('id', None)
self.name = name
self.email = email
self.status = kwargs.get('status', None) or 'active' # 'active', 'inactive', 'unknown'
self.roles = roles
self.attributes = kwargs.get('attributes', None) or dict()
self.create_time = kwargs.get('create_time', None)
self.last_login = kwargs.get('last_login', None)
self.text = text or ''
self.update_time = kwargs.get('update_time', None)
self.email_verified = kwargs.get('email_verified', False)
@property
def domain(self):
return self.email.split('@')[1] if '@' in self.email else None
def __repr__(self):
return 'User(id={!r}, name={!r}, email={!r}, status={!r}, roles={!r}, email_verified={!r})'.format(
self.id, self.name, self.email, self.status, ','.join(self.roles), self.email_verified
)
@classmethod
def parse(cls, json):
return User(
id=json.get('id'),
name=json.get('name'),
email=json.get('email', None) or json.get('login'),
status=json.get('status'),
roles=json.get('roles', None) or ([json['role']] if 'role' in json else list()),
attributes=json.get('attributes', dict()),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from alertaclient.utils import DateTime
and context:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
which might include code, classes, or functions. Output only the next line. | create_time=DateTime.parse(json.get('createTime')), |
Continue the code snippet: <|code_start|>
@click.command('unack', short_help='Un-acknowledge alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'open'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
<|code_end|>
. Use current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context (classes, functions, or code) from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | action_progressbar(client, action='unack', ids=ids, label=f'Un-acking {total} alerts', text=text) |
Given the code snippet: <|code_start|>
@click.command('unack', short_help='Un-acknowledge alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'open'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
, generate the next line using the imports in this file:
import click
from alertaclient.utils import action_progressbar, build_query
and context (functions, classes, or occasionally code) from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Predict the next line for this snippet: <|code_start|>
@click.command('version', short_help='Display version info')
@click.pass_obj
@click.pass_context
def cli(ctx, obj):
"""Show Alerta server and client versions."""
client = obj['client']
click.echo('alerta {}'.format(client.mgmt_status()['version']))
<|code_end|>
with the help of current file imports:
import click
from requests import __version__ as requests_version
from alertaclient.version import __version__ as client_version
and context from other files:
# Path: alertaclient/version.py
, which may contain function names, class names, or code. Output only the next line. | click.echo(f'alerta client {client_version}') |
Continue the code snippet: <|code_start|>
@property
def latency(self):
return int((self.receive_time - self.create_time).total_seconds() * 1000)
@property
def since(self):
since = datetime.utcnow() - self.receive_time
return since - timedelta(microseconds=since.microseconds)
def __repr__(self):
return 'Heartbeat(id={!r}, origin={!r}, create_time={!r}, timeout={!r}, customer={!r})'.format(
self.id, self.origin, self.create_time, self.timeout, self.customer)
@classmethod
def parse(cls, json):
if not isinstance(json.get('tags', []), list):
raise ValueError('tags must be a list')
if not isinstance(json.get('attributes', {}), dict):
raise ValueError('attributes must be a JSON object')
if not isinstance(json.get('timeout', 0), int):
raise ValueError('timeout must be an integer')
return Heartbeat(
id=json.get('id', None),
origin=json.get('origin', None),
status=json.get('status', None),
tags=json.get('tags', list()),
attributes=json.get('attributes', dict()),
event_type=json.get('type', None),
<|code_end|>
. Use current file imports:
from datetime import datetime, timedelta
from alertaclient.utils import DateTime
and context (classes, functions, or code) from other files:
# Path: alertaclient/utils.py
# class DateTime:
# @staticmethod
# def parse(date_str):
# if not isinstance(date_str, str):
# return
# try:
# return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# except Exception:
# raise ValueError('dates must be ISO 8601 date format YYYY-MM-DDThh:mm:ss.sssZ')
#
# @staticmethod
# def iso8601(dt):
# return dt.replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%S') + '.%03dZ' % (dt.microsecond // 1000)
#
# @staticmethod
# def localtime(dt, timezone=None, fmt='%Y/%m/%d %H:%M:%S'):
# tz = pytz.timezone(timezone)
# try:
# return dt.replace(tzinfo=pytz.UTC).astimezone(tz).strftime(fmt)
# except AttributeError:
# return
. Output only the next line. | create_time=DateTime.parse(json.get('createTime')), |
Based on the snippet: <|code_start|>
@click.command('ack', short_help='Close alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'closed'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context (classes, functions, sometimes code) from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | action_progressbar(client, action='close', ids=ids, label=f'Closing {total} alerts', text=text) |
Continue the code snippet: <|code_start|>
@click.command('ack', short_help='Close alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'closed'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
. Use current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context (classes, functions, or code) from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Using the snippet: <|code_start|>
@click.command('logout', short_help='Clear login credentials')
@click.pass_obj
def cli(obj):
"""Clear local login credentials from netrc file."""
client = obj['client']
<|code_end|>
, determine the next line of code. You have imports:
import click
from alertaclient.auth.utils import clear_token
and context (class names, function names, or code) available:
# Path: alertaclient/auth/utils.py
# def clear_token(endpoint):
# try:
# info = netrc(NETRC_FILE)
# except Exception as e:
# raise ConfigurationError(f'{e}')
# try:
# del info.hosts[machine(endpoint)]
# with open(NETRC_FILE, 'w') as f:
# f.write(dump_netrc(info))
# except KeyError as e:
# raise ConfigurationError(f'No credentials stored for {e}')
. Output only the next line. | clear_token(client.endpoint) |
Predict the next line for this snippet: <|code_start|>
@click.command('untag', short_help='Untag alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--tag', '-T', 'tags', required=True, multiple=True, help='List of tags')
@click.pass_obj
def cli(obj, ids, query, filters, tags):
"""Remove tags from alerts."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
with the help of current file imports:
import click
from alertaclient.utils import build_query
and context from other files:
# Path: alertaclient/utils.py
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
, which may contain function names, class names, or code. Output only the next line. | query = build_query(filters) |
Predict the next line for this snippet: <|code_start|>
@click.command('ack', short_help='Acknowledge alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'ack'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
query = build_query(filters)
total, _, _ = client.get_count(query)
ids = [a.id for a in client.get_alerts(query)]
<|code_end|>
with the help of current file imports:
import click
from alertaclient.utils import action_progressbar, build_query
and context from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
, which may contain function names, class names, or code. Output only the next line. | action_progressbar(client, action='ack', ids=ids, label=f'Acking {total} alerts', text=text) |
Predict the next line after this snippet: <|code_start|>
@click.command('ack', short_help='Acknowledge alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
"""Set alert status to 'ack'."""
client = obj['client']
if ids:
total = len(ids)
else:
if query:
query = [('q', query)]
else:
<|code_end|>
using the current file's imports:
import click
from alertaclient.utils import action_progressbar, build_query
and any relevant context from other files:
# Path: alertaclient/utils.py
# def action_progressbar(client, action, ids, label, text=None, timeout=None):
# skipped = 0
#
# def show_skipped(id):
# if not id and skipped:
# return f'(skipped {skipped})'
#
# with click.progressbar(ids, label=label, show_eta=True, item_show_func=show_skipped) as bar:
# for id in bar:
# try:
# client.action(id, action=action, text=text, timeout=timeout)
# except Exception:
# skipped += 1
#
# def build_query(filters):
# return [tuple(f.split('=', 1)) for f in filters if '=' in f]
. Output only the next line. | query = build_query(filters) |
Next line prediction: <|code_start|>
class MockConnection:
def __init__(self, responses):
self._retry_count = 2
self._retry_wait = 0
self.calls = 0
self._responses = responses
@with_retry
def get(self, *args, **kwargs):
self.calls += 1
if len(self._responses) > 0:
resp = self._responses[0]
self._responses = self._responses[1:]
return resp
<|code_end|>
. Use current file imports:
(from .mock_connection import MockResponse
from qarnot._retry import with_retry)
and context including class names, function names, or small code snippets from other files:
# Path: test/mock_connection.py
# class MockResponse:
# def __init__(self, status_code, json=None):
# self.ok = status_code < 400
# self.status_code = status_code
# self._json = json
#
# def json(self):
# return self._json
#
# Path: qarnot/_retry.py
# def with_retry(http_request_func):
# def _with_retry(self, *args, **kwargs):
# retry = self._retry_count
# last_chance = False
#
# while True:
# try:
# ret = http_request_func(self, *args, **kwargs)
# except ConnectionError:
# if last_chance:
# raise
#
# if ret.ok:
# return ret
# if ret.status_code == 401:
# raise UnauthorizedException()
# # Do not retry on error except for rate limiting errors.
# if 400 <= ret.status_code <= 499 and ret.status_code != 429:
# return ret
# if last_chance:
# return ret
#
# if retry > 1:
# retry -= 1
# time.sleep(self._retry_wait * (self._retry_count - retry))
# else:
# last_chance = True
#
# return _with_retry
. Output only the next line. | return MockResponse(200) |
Given snippet: <|code_start|>
class MockConnection:
def __init__(self, responses):
self._retry_count = 2
self._retry_wait = 0
self.calls = 0
self._responses = responses
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .mock_connection import MockResponse
from qarnot._retry import with_retry
and context:
# Path: test/mock_connection.py
# class MockResponse:
# def __init__(self, status_code, json=None):
# self.ok = status_code < 400
# self.status_code = status_code
# self._json = json
#
# def json(self):
# return self._json
#
# Path: qarnot/_retry.py
# def with_retry(http_request_func):
# def _with_retry(self, *args, **kwargs):
# retry = self._retry_count
# last_chance = False
#
# while True:
# try:
# ret = http_request_func(self, *args, **kwargs)
# except ConnectionError:
# if last_chance:
# raise
#
# if ret.ok:
# return ret
# if ret.status_code == 401:
# raise UnauthorizedException()
# # Do not retry on error except for rate limiting errors.
# if 400 <= ret.status_code <= 499 and ret.status_code != 429:
# return ret
# if last_chance:
# return ret
#
# if retry > 1:
# retry -= 1
# time.sleep(self._retry_wait * (self._retry_count - retry))
# else:
# last_chance = True
#
# return _with_retry
which might include code, classes, or functions. Output only the next line. | @with_retry |
Using the snippet: <|code_start|>
def with_retry(http_request_func):
def _with_retry(self, *args, **kwargs):
retry = self._retry_count
last_chance = False
while True:
try:
ret = http_request_func(self, *args, **kwargs)
except ConnectionError:
if last_chance:
raise
if ret.ok:
return ret
if ret.status_code == 401:
<|code_end|>
, determine the next line of code. You have imports:
import time
from .exceptions import UnauthorizedException
and context (class names, function names, or code) available:
# Path: qarnot/exceptions.py
# class UnauthorizedException(QarnotException):
# """Invalid token."""
. Output only the next line. | raise UnauthorizedException() |
Given the code snippet: <|code_start|>
class TestStatusProperties:
@pytest.mark.parametrize("property_name, expected_value", [
("last_update_timestamp", default_json_status["lastUpdateTimestamp"]),
])
def test_create_status_hydrate_property_values(self, property_name, expected_value):
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import pytest
from qarnot.status import Status
from .mock_status import default_json_status
and context (functions, classes, or occasionally code) from other files:
# Path: qarnot/status.py
# class Status(object):
# """Status
# The status object of the running pools and tasks.
# To retrieve the status of a pool, use:
# * my_pool.status
#
# To retrieve the status of a task, use:
# * my_task.status
#
# .. note:: Read-only class
# """
# def __init__(self, json):
# self.download_progress = json['downloadProgress']
# """:type: :class:`float`
#
# Resources download progress to the instances."""
#
# self.execution_progress = json['executionProgress']
# """:type: :class:`float`
#
# Task execution progress."""
#
# self.upload_progress = json['uploadProgress']
# """:type: :class:`float`
#
# Task results upload progress to the API."""
#
# self.instance_count = json['instanceCount']
# """:type: :class:`int`
#
# Number of running instances."""
#
# self.download_time = json['downloadTime']
# """:type: :class:`str`
#
# Resources download time to the instances."""
#
# self.download_time_sec = json['downloadTimeSec']
# """:type: :class:`float`
#
# Resources download time to the instances in seconds."""
#
# self.environment_time = json['environmentTime']
# """:type: :class:`str`
#
# Environment time to the instances."""
#
# self.environment_time_sec = json['environmentTimeSec']
# """:type: :class:`float`
#
# Environment time to the instances in seconds."""
#
# self.execution_time = json['executionTime']
# """:type: :class:`str`
#
# Task execution time."""
#
# self.execution_time_sec = json['executionTimeSec']
# """:type: :class:`float`
#
# Task execution time in seconds."""
#
# self.upload_time = json['uploadTime']
# """:type: :class:`str`
#
# Task results upload time to the API."""
#
# self.upload_time_sec = json['uploadTimeSec']
# """:type: :class:`float`
#
# Task results upload time to the API in seconds."""
#
# self.wall_time = json["wallTime"]
# """:type: :class:`str`
#
# Wall time of the task."""
#
# self.wall_time_sec = json["wallTimeSec"]
# """:type: :class:`float`
#
# Wall time of the task in seconds."""
#
# self.succeeded_range = json['succeededRange']
# """:type: :class:`str`
#
# Successful instances range."""
#
# self.executed_range = json['executedRange']
# """:type: :class:`str`
#
# Executed instances range."""
#
# self.failed_range = json['failedRange']
# """:type: :class:`str`
#
# Failed instances range."""
#
# self.last_update_timestamp = json["lastUpdateTimestamp"]
# """:type: :class:`str`
#
# Last update time (UTC)."""
#
# self.execution_time_by_cpu_model = [ExecutionTimeByCpuModel(timeCpu) for timeCpu in json["executionTimeByCpuModel"]]
# """:type: :class:`str`
#
# Execution time by cpu."""
#
# self.execution_time_ghz_by_cpu_model = [ExecutionTimeGhzByCpuModel(timeCpu) for timeCpu in json["executionTimeGhzByCpuModel"]]
# """:type: :class:`str`
#
# Execution time ghz by cpu."""
#
# self.running_instances_info = None
# """:type: :class:`RunningInstancesInfo`
#
# Running instances information."""
#
# if 'runningInstancesInfo' in json and json['runningInstancesInfo'] is not None:
# self.running_instances_info = RunningInstancesInfo(json['runningInstancesInfo'])
#
# def __repr__(self):
# if sys.version_info > (3, 0):
# return ', '.join("{0}={1}".format(key, val) for (key, val) in self.__dict__.items())
# else:
# return ', '.join("{0}={1}".format(key, val) for (key, val) in self.__dict__.iteritems()) # pylint: disable=no-member
#
# Path: test/mock_status.py
. Output only the next line. | status = Status(default_json_status) |
Predict the next line for this snippet: <|code_start|> if pre_adjust_batch_norm and bn_name in data:
bn_data = data[bn_name]
sigma = np.sqrt(1e-5 + bn_data['1'] / bn_data['2'])
W /= sigma
init_str += ' batch-adjusted'
assigns.append(weights.assign(W))
loaded.append('{}:0 -> {}:weights{} {}'.format(key, local_key, init_str, info.get(key, '')))
if '1' in data[key]:
biases = find_weights(local_key, 'biases')
if biases is not None:
bias = data[key]['1']
init_str = ''
if pre_adjust_batch_norm and bn_name in data:
bn_data = data[bn_name]
sigma = np.sqrt(1e-5 + bn_data['1'] / bn_data['2'])
mu = bn_data['0'] / bn_data['2']
bias = (bias - mu) / sigma
init_str += ' batch-adjusted'
assigns.append(biases.assign(bias))
loaded.append('{}:1 -> {}:biases{}'.format(key, local_key, init_str))
# Check batch norm and load them (unless they have been folded into)
#if not pre_adjust_batch_norm:
session.run(assigns)
if verbose:
<|code_end|>
with the help of current file imports:
from .util import DummyDict
from .util import tprint
import deepdish as dd
import numpy as np
import tensorflow as tf
import tensorflow as tf
and context from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/util.py
# def tprint(*args, **kwargs):
# global _tlog_path
# import datetime
# GRAY = '\033[1;30m'
# RESET = '\033[0m'
# time_str = GRAY+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+RESET
# print(*((time_str,) + args), **kwargs)
#
# if _tlog_path is not None:
# with open(_tlog_path, 'a') as f:
# nocol_time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# print(*((nocol_time_str,) + args), file=f, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | tprint('Loaded model from', path) |
Next line prediction: <|code_start|> patches = []
for i, j in dd.multi_range(size, size):
#tf.slice(x, [
M = WINDOW_SIZE - patch_size + 1
assert M > 0, f'Jigsaw: Window size ({WINDOW_SIZE}) and patch size ({patch_size}) not compatible'
limit = np.array([1, M, M, 1])
offset = np.array([0, i * WINDOW_SIZE, j * WINDOW_SIZE, 0]) + tf.random_uniform(
[4], dtype=tf.int32,
maxval=M,
) % limit
patch = tf.slice(x, offset, [N, patch_size, patch_size, C])
patches.append(patch)
patches1 = tf.stack(patches, axis=1)
xyz = np.arange(batch_size)[:, np.newaxis] * size**2 + (perm - 1)
#import ipdb
#ipdb.set_trace()
perm0 = tf.reshape(xyz, [-1])
patches_flat = tf.reshape(patches1, [-1] + patches1.get_shape().as_list()[2:])
#import ipdb
##ipdb.set_trace()
patches2 = tf.gather(patches_flat, perm0)
#return tf.reshape(patches2, [-1, PATCH_SIZE, PATCH_SIZE, C])
return patches2
<|code_end|>
. Use current file imports:
(import selfsup
import tensorflow as tf
import os
import deepdish as dd
import numpy as np
import itertools
import selfsup.jigsaw
from .base import Method
from collections import OrderedDict)
and context including class names, function names, or small code snippets from other files:
# Path: selfsup/multi/methods/base.py
# class Method:
# def __init__(self, name, batch_size):
# self.name = name
# self.batch_size = batch_size
#
# def input_size(self):
# return 0
#
# def batch_loader(self):
# raise NotImplemented("Abstract base class")
#
# def build_network(network, y, phase_test):
# raise NotImplemented("Abstract base class")
#
# @property
# def basenet_settings():
# return {}
#
# def make_path(self, name, ext, iteration):
# return f'img/{self.name}_{name}_{iteration}.png'
. Output only the next line. | class Jigsaw(Method): |
Predict the next line after this snippet: <|code_start|> z = selfsup.model.alex_bn2.build_network(x, info=info,
convolutional=settings.get('convolutional', False),
final_layer=False,
well_behaved_size=False,
use_lrn=self._use_lrn,
global_step=global_step,
phase_test=phase_test)
elif self._use_batch_norm:
z = selfsup.model.alex_bn.build_network(x, info=info,
convolutional=settings.get('convolutional', False),
final_layer=False,
well_behaved_size=False,
use_lrn=self._use_lrn,
global_step=global_step,
phase_test=phase_test)
else:
z = selfsup.model.alex.build_network(x, info=info,
convolutional=settings.get('convolutional', False),
final_layer=False,
well_behaved_size=False,
use_lrn=self._use_lrn,
phase_test=phase_test)
info['activations']['x01'] = x01
info['activations']['x'] = x
info['activations']['top'] = z
info['weights']['firstconv:weights'] = info['weights']['conv1:weights']
info['weights']['firstconv:biases'] = info['weights']['conv1:biases']
return info
<|code_end|>
using the current file's imports:
from .basenet import BaseNet
from selfsup.util import DummyDict
import selfsup
import selfsup.alex_bn2
import selfsup.model.alex
import selfsup.model.alex_bn
import selfsup.model.alex_bn2
import selfsup.model.alex_transposed
and any relevant context from other files:
# Path: selfsup/multi/basenets/basenet.py
# class BaseNet:
# def __init__(self):
# pass
#
# @property
# def name(self):
# raise NotImplemented('Abstract base class')
#
# @property
# def canonical_input_size(self):
# raise NotImplemented('Abstract base class')
#
# @property
# def hypercolumn_layers(self):
# """Suggested hypercolumn layers"""
# return []
#
# @property
# def layers(self):
# return [name for name, _ in self.hypercolumn_layers]
#
# def build(self):
# raise NotImplemented('Abstract base class')
#
# def save_caffemodel(self, path, session, verbose=False):
# raise NotImplemented('Abstract base class')
#
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
. Output only the next line. | def decoder(self, z, channels=1, multiple=4, from_name=None, settings=DummyDict(), info=DummyDict()): |
Given snippet: <|code_start|> if scale_factor != 1.0:
new_size = (int(im.shape[1] * scale_factor), int(im.shape[0] * scale_factor))
return cv2.resize(im, new_size, interpolation=cv2.INTER_LINEAR)
else:
return im
for t in times:
cap.set(cv2.CAP_PROP_POS_FRAMES, min(t * n_frames, n_frames - 1 - frames))
ret, frame0 = cap.read()
im0 = resize(cv2.cvtColor(frame0, cv2.COLOR_BGR2GRAY))
mags = []
middle_frame = frame0
for f in range(frames - 1):
ret, frame1 = cap.read()
if f == frames // 2:
middle_frame = frame1
im1 = resize(cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY))
flow = cv2.calcOpticalFlowFarneback(im0, im1,
None, 0.5, 3, 15, 3, 5, 1.2, 0)
mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
mags.append(mag)
im0 = im1
mag = np.sum(mags, 0)
mag = mag.clip(min=0)
norm_mag = (mag - mag.min()) / (mag.max() - mag.min() + 1e-5)
x = middle_frame[..., ::-1].astype(np.float32) / 255
outputs.append((x, norm_mag))
return outputs
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .loader import Loader
import tensorflow as tf
import threading
import numpy as np
import time
import glob
import os
import imageio
import cv2
import deepdish as dd
and context:
# Path: selfsup/multi/loaders/loader.py
# class Loader:
# def __init__(self, batch_size=16, num_threads=5):
# self._batch_size = batch_size
# self._num_threads = num_threads
#
# def batch(self):
# raise NotImplemented('Cannot use base class')
#
# def start(self, sess):
# pass
which might include code, classes, or functions. Output only the next line. | class VideoAVIFlowSaliency(Loader): |
Given snippet: <|code_start|> flows = []
for f in range(frames - 1):
ret, frame1 = cap.read()
if f == frames // 2:
middle_frame = frame1
im1 = resize(cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY))
flow = cv2.calcOpticalFlowFarneback(im0, im1,
None,
0.5, # py_scale
8, # levels
int(40 * scale_factor), # winsize
10, # iterations
5, # poly_n
1.1, # poly_sigma
cv2.OPTFLOW_FARNEBACK_GAUSSIAN)
#mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
#mags.append(mag)
flows.append(flow)
im0 = im1
flow = (np.mean(flows, 0) / 100).clip(-1, 1)
#flow = np.mean(flows, 0)
#flow /= (flow.mean() * 5 + 1e-5)
#flow = flow.clip(-1, 1)
#flows = flows / (np.mean(flows, 0, keepdims=True) + 1e-5)
x = middle_frame[..., ::-1].astype(np.float32) / 255
outputs.append((x, flow))
return outputs
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .loader import Loader
import tensorflow as tf
import threading
import numpy as np
import time
import glob
import os
import imageio
import cv2
import deepdish as dd
and context:
# Path: selfsup/multi/loaders/loader.py
# class Loader:
# def __init__(self, batch_size=16, num_threads=5):
# self._batch_size = batch_size
# self._num_threads = num_threads
#
# def batch(self):
# raise NotImplemented('Cannot use base class')
#
# def start(self, sess):
# pass
which might include code, classes, or functions. Output only the next line. | class VideoAVIFlow(Loader): |
Given snippet: <|code_start|>
def kl_divergence(labels, logits):
#return tf.contrib.distributions.kl(p, q)
return (tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) -
tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=tf.log(labels+1e-5)))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tensorflow as tf
import selfsup
import os
import functools
import numpy as np
from .base import Method
from autocolorize.tensorflow.sparse_extractor import sparse_extractor
from autocolorize.extraction import calc_rgb_from_hue_chroma
from collections import OrderedDict
and context:
# Path: selfsup/multi/methods/base.py
# class Method:
# def __init__(self, name, batch_size):
# self.name = name
# self.batch_size = batch_size
#
# def input_size(self):
# return 0
#
# def batch_loader(self):
# raise NotImplemented("Abstract base class")
#
# def build_network(network, y, phase_test):
# raise NotImplemented("Abstract base class")
#
# @property
# def basenet_settings():
# return {}
#
# def make_path(self, name, ext, iteration):
# return f'img/{self.name}_{name}_{iteration}.png'
which might include code, classes, or functions. Output only the next line. | class ColorizeHypercolumn3(Method): |
Using the snippet: <|code_start|>from __future__ import division, print_function, absolute_import
def _random_rotate(image):
k = tf.random_uniform([], 0, 4, dtype=tf.int32)
rot = tf.image.rot90(image, k=k)
rot = tf.slice(rot, [0, 0, 0], image.get_shape().as_list())
return [rot, k]
def _batch_random_rotate(batch):
i = tf.constant(0)
batch_rotated, batch_y = tf.map_fn(_random_rotate, batch, dtype=[tf.float32, tf.int32])
return batch_rotated, batch_y
<|code_end|>
, determine the next line of code. You have imports:
import selfsup
import tensorflow as tf
import os
from .base import Method
from collections import OrderedDict
and context (class names, function names, or code) available:
# Path: selfsup/multi/methods/base.py
# class Method:
# def __init__(self, name, batch_size):
# self.name = name
# self.batch_size = batch_size
#
# def input_size(self):
# return 0
#
# def batch_loader(self):
# raise NotImplemented("Abstract base class")
#
# def build_network(network, y, phase_test):
# raise NotImplemented("Abstract base class")
#
# @property
# def basenet_settings():
# return {}
#
# def make_path(self, name, ext, iteration):
# return f'img/{self.name}_{name}_{iteration}.png'
. Output only the next line. | class Rot90(Method): |
Next line prediction: <|code_start|> frames = np.array_split(img, 34, axis=0)
grayscale_frames = [fr.mean(-1) for fr in frames]
mags = []
skip_frames = np.random.randint(34 - n_frames + 1)
middle_frame = frames[np.random.randint(skip_frames, skip_frames+n_frames)]
im0 = grayscale_frames[skip_frames]
for f in range(1+skip_frames, 1+skip_frames+n_frames-1):
im1 = grayscale_frames[f]
flow = cv2.calcOpticalFlowFarneback(im0, im1,
None, # flow
0.5, # pyr_scale
3, # levels
np.random.randint(3, 20), # winsize
3, #iterations
5, #poly_n
1.2, #poly_sigma
0 # flags
)
mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
mags.append(mag)
im0 = im1
mag = np.sum(mags, 0)
mag = mag.clip(min=0)
#norm_mag = np.tanh(mag * 10000)
norm_mag = (mag - mag.min()) / (mag.max() - mag.min() + 1e-5)
outputs = []
outputs.append((middle_frame, norm_mag))
return outputs
<|code_end|>
. Use current file imports:
(from .loader import Loader
import tensorflow as tf
import threading
import numpy as np
import time
import glob
import os
import imageio
import cv2
import deepdish as dd)
and context including class names, function names, or small code snippets from other files:
# Path: selfsup/multi/loaders/loader.py
# class Loader:
# def __init__(self, batch_size=16, num_threads=5):
# self._batch_size = batch_size
# self._num_threads = num_threads
#
# def batch(self):
# raise NotImplemented('Cannot use base class')
#
# def start(self, sess):
# pass
. Output only the next line. | class VideoJPEGRollsFlowSaliency(Loader): |
Based on the snippet: <|code_start|> W2 = W2.reshape((W2.shape[0], -1, 1, 1))
elif W2.ndim == 2 and name == 'fc8':
W2 = W2.reshape((W2.shape[0], -1, 1, 1))
W2 = W2.transpose(2, 3, 1, 0)
init_type = 'file'
if name == 'conv1' and W2.shape[2] == 3:
W2 = W2[:, :, ::-1]
init_type += ':bgr-flipped'
tr = {'fc6': (4096, 256, 6, 6)}
tfW = caffe.from_caffe(W, name=name, conv_fc_transitionals=tr, color_layer='conv1')
W = W2
bn_name = 'batch_' + name
if pre_adjust_batch_norm and bn_name in data:
bn_data = data[bn_name]
sigma = np.sqrt(1e-5 + bn_data['1'] / bn_data['2'])
W /= sigma
init_type += ':batch-adjusted'
init = tf.constant_initializer(W)
shape = W.shape
else:
init_type = 'init'
init = tf.contrib.layers.variance_scaling_initializer()
if info is not None:
info[prefix + ':' + name + '/weights'] = init_type
return init, shape
<|code_end|>
, predict the immediate next line with the help of imports:
import tensorflow as tf
import functools
import numpy as np
import sys
from selfsup.util import DummyDict
from selfsup import ops, caffe
and context (classes, functions, sometimes code) from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/ops.py
# def max_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def avg_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def dropout(x, drop_prob, phase_test=None, name=None, info=DummyDict()):
# def scale(x, name=None, value=1.0):
# def inner(x, channels, info=DummyDict(), stddev=None,
# activation=tf.nn.relu, name=None):
# def atrous_avg_pool(value, size, rate, padding, name=None, info=DummyDict()):
# def conv(x, channels, size=3, strides=1, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict(), output_shape=None):
# def upconv(x, channels, size=3, strides=1, output_shape=None, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict()):
# W = tf.get_variable('weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
#
# Path: selfsup/caffe.py
# def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def from_caffe(cfW, name=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def load_caffemodel(path, session, prefix='', ignore=set(),
# conv_fc_transitionals=None, renamed_layers=DummyDict(),
# color_layer='', verbose=False, pre_adjust_batch_norm=False):
# def find_weights(name, which='weights'):
# def save_caffemodel(path, session, layers, prefix='',
# conv_fc_transitionals=None, color_layer='', verbose=False,
# save_batch_norm=False, lax_naming=False):
# def find_weights(name, which='weights'):
# def find_batch_norm(name, which='mean'):
# W = from_caffe(data[key]['0'], name=key, info=info,
# conv_fc_transitionals=conv_fc_transitionals,
# color_layer=color_layer)
# W = W.reshape(weights.get_shape().as_list())
. Output only the next line. | def _pretrained_alex_inner_weights_initializer(name, data, info=DummyDict(), pre_adjust_batch_norm=False, prefix=''): |
Given the code snippet: <|code_start|>
def conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding="VALID", group=1):
'''From https://github.com/ethereon/caffe-tensorflow
'''
c_i = input.get_shape()[-1]
assert c_i%group==0
assert c_o%group==0
convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)
if group==1:
conv = convolve(input, kernel)
else:
input_groups = tf.split(input, group, 3)
kernel_groups = tf.split(kernel, group, 3)
output_groups = [convolve(i, k) for i,k in zip(input_groups, kernel_groups)]
conv = tf.concat(output_groups, 3)
return tf.reshape(tf.nn.bias_add(conv, biases), [-1]+conv.get_shape().as_list()[1:])
def build_network(x, info=DummyDict(), parameters={}, hole=1,
phase_test=None, convolutional=False, final_layer=True,
activation=tf.nn.relu,
pre_adjust_batch_norm=False, well_behaved_size=False,
use_lrn=True, prefix='', use_dropout=True):
# Set up AlexNet
#conv = functools.partial(alex_conv, size=3, parameters=parameters,
#info=info, pre_adjust_batch_norm=pre_adjust_batch_norm)
#pool = functools.partial(ops.max_pool, info=info)
if use_dropout:
<|code_end|>
, generate the next line using the imports in this file:
import tensorflow as tf
import functools
import numpy as np
import sys
from selfsup.util import DummyDict
from selfsup import ops, caffe
and context (functions, classes, or occasionally code) from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/ops.py
# def max_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def avg_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def dropout(x, drop_prob, phase_test=None, name=None, info=DummyDict()):
# def scale(x, name=None, value=1.0):
# def inner(x, channels, info=DummyDict(), stddev=None,
# activation=tf.nn.relu, name=None):
# def atrous_avg_pool(value, size, rate, padding, name=None, info=DummyDict()):
# def conv(x, channels, size=3, strides=1, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict(), output_shape=None):
# def upconv(x, channels, size=3, strides=1, output_shape=None, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict()):
# W = tf.get_variable('weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
#
# Path: selfsup/caffe.py
# def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def from_caffe(cfW, name=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def load_caffemodel(path, session, prefix='', ignore=set(),
# conv_fc_transitionals=None, renamed_layers=DummyDict(),
# color_layer='', verbose=False, pre_adjust_batch_norm=False):
# def find_weights(name, which='weights'):
# def save_caffemodel(path, session, layers, prefix='',
# conv_fc_transitionals=None, color_layer='', verbose=False,
# save_batch_norm=False, lax_naming=False):
# def find_weights(name, which='weights'):
# def find_batch_norm(name, which='mean'):
# W = from_caffe(data[key]['0'], name=key, info=info,
# conv_fc_transitionals=conv_fc_transitionals,
# color_layer=color_layer)
# W = W.reshape(weights.get_shape().as_list())
. Output only the next line. | dropout = functools.partial(ops.dropout, phase_test=phase_test, info=info) |
Next line prediction: <|code_start|>from __future__ import division, print_function, absolute_import
def _pretrained_alex_conv_weights_initializer(name, data, info=None, pre_adjust_batch_norm=False, prefix=''):
shape = None
if name in data and '0' in data[name]:
W = data[name]['0'].copy()
W2 = W.copy()
if W2.ndim == 2 and name == 'fc6':
#assert 0, "6x6 or 7x7? Confirm."
W2 = W2.reshape((W2.shape[0], 256, 6, 6))
elif W2.ndim == 2 and name == 'fc7':
W2 = W2.reshape((W2.shape[0], -1, 1, 1))
elif W2.ndim == 2 and name == 'fc8':
W2 = W2.reshape((W2.shape[0], -1, 1, 1))
W2 = W2.transpose(2, 3, 1, 0)
init_type = 'file'
if name == 'conv1' and W2.shape[2] == 3:
W2 = W2[:, :, ::-1]
init_type += ':bgr-flipped'
tr = {'fc6': (4096, 256, 6, 6)}
<|code_end|>
. Use current file imports:
(import tensorflow as tf
import functools
import numpy as np
import sys
from selfsup.util import DummyDict
from selfsup import ops, caffe)
and context including class names, function names, or small code snippets from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/ops.py
# def max_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def avg_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def dropout(x, drop_prob, phase_test=None, name=None, info=DummyDict()):
# def scale(x, name=None, value=1.0):
# def inner(x, channels, info=DummyDict(), stddev=None,
# activation=tf.nn.relu, name=None):
# def atrous_avg_pool(value, size, rate, padding, name=None, info=DummyDict()):
# def conv(x, channels, size=3, strides=1, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict(), output_shape=None):
# def upconv(x, channels, size=3, strides=1, output_shape=None, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict()):
# W = tf.get_variable('weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
#
# Path: selfsup/caffe.py
# def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def from_caffe(cfW, name=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
# def load_caffemodel(path, session, prefix='', ignore=set(),
# conv_fc_transitionals=None, renamed_layers=DummyDict(),
# color_layer='', verbose=False, pre_adjust_batch_norm=False):
# def find_weights(name, which='weights'):
# def save_caffemodel(path, session, layers, prefix='',
# conv_fc_transitionals=None, color_layer='', verbose=False,
# save_batch_norm=False, lax_naming=False):
# def find_weights(name, which='weights'):
# def find_batch_norm(name, which='mean'):
# W = from_caffe(data[key]['0'], name=key, info=info,
# conv_fc_transitionals=conv_fc_transitionals,
# color_layer=color_layer)
# W = W.reshape(weights.get_shape().as_list())
. Output only the next line. | tfW = caffe.from_caffe(W, name=name, conv_fc_transitionals=tr, color_layer='conv1') |
Given the code snippet: <|code_start|>from __future__ import division, print_function, absolute_import
# http://stackoverflow.com/questions/36904298/how-to-implement-multi-class-hinge-loss-in-tensorflow/36928137#36928137
def multi_class_hinge_loss(logits, labels, n_classes):
batch_size = logits.get_shape().as_list()[0]
# get the correct logit
flat_logits = tf.reshape(logits, (-1,))
correct_id = tf.range(0, batch_size) * n_classes + labels
correct_logit = tf.gather(flat_logits, correct_id)
# get the wrong maximum logit
max_label = tf.to_int32(tf.argmax(logits, 1))
top2, _ = tf.nn.top_k(logits, k=2, sorted=True)
first, second = tf.unstack(top2, axis=1)
wrong_max_logit = tf.where(tf.equal(max_label, labels), second, first)
# calculate multi-class hinge loss
return tf.maximum(0., 1.0 + wrong_max_logit - correct_logit), wrong_max_logit, correct_logit
<|code_end|>
, generate the next line using the imports in this file:
import selfsup
import tensorflow as tf
import os
import deepdish as dd
import numpy as np
from .base import Method
from collections import OrderedDict
and context (functions, classes, or occasionally code) from other files:
# Path: selfsup/multi/methods/base.py
# class Method:
# def __init__(self, name, batch_size):
# self.name = name
# self.batch_size = batch_size
#
# def input_size(self):
# return 0
#
# def batch_loader(self):
# raise NotImplemented("Abstract base class")
#
# def build_network(network, y, phase_test):
# raise NotImplemented("Abstract base class")
#
# @property
# def basenet_settings():
# return {}
#
# def make_path(self, name, ext, iteration):
# return f'img/{self.name}_{name}_{iteration}.png'
. Output only the next line. | class Supervised(Method): |
Given the following code snippet before the placeholder: <|code_start|># IN PROGRESS AND EXPERIMENTAL
from __future__ import division, print_function, absolute_import
if os.uname()[1] == 'kiriyama':
TRAIN = os.path.expandvars("$IMAGENET_10K_DIR/fullpath_imagenet_tr_nolabels.txt")
else:
TRAIN = "/share/data/vision-greg/larsson/data/fullpath_imagenet_and_places_train_shuffled.txt"
<|code_end|>
, predict the next line using imports from the current file:
import selfsup
import tensorflow as tf
import os
from .base import Method
and context including class names, function names, and sometimes code from other files:
# Path: selfsup/multi/methods/base.py
# class Method:
# def __init__(self, name, batch_size):
# self.name = name
# self.batch_size = batch_size
#
# def input_size(self):
# return 0
#
# def batch_loader(self):
# raise NotImplemented("Abstract base class")
#
# def build_network(network, y, phase_test):
# raise NotImplemented("Abstract base class")
#
# @property
# def basenet_settings():
# return {}
#
# def make_path(self, name, ext, iteration):
# return f'img/{self.name}_{name}_{iteration}.png'
. Output only the next line. | class WassersteinBiGAN(Method): |
Predict the next line after this snippet: <|code_start|>
LAYERS = ['conv0', 'conv1', 'conv2', 'conv3', 'conv4', 'conv5', 'fc6', 'fc7']
def decoder(y, from_name='fc7', to_name='conv0', info=DummyDict(), use_batch_norm=False, phase_test=None,
global_step=None):
BATCH_SIZE = y.get_shape().as_list()[0]
if use_batch_norm:
assert global_step is not None
def bn(z, name):
return batch_norm(z, global_step=global_step, phase_test=phase_test, name=name)
else:
def bn(z, name):
return z
if len(y.get_shape().as_list()) == 2:
y = tf.expand_dims(tf.expand_dims(y, 1), 1)
def check(name):
return name in LAYERS[LAYERS.index(to_name):LAYERS.index(from_name)+1]
if check('fc7'):
sh = [BATCH_SIZE, 1, 1, 4096]
<|code_end|>
using the current file's imports:
import tensorflow as tf
from selfsup.util import DummyDict
from selfsup import ops
from .alex_bn import batch_norm
and any relevant context from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/ops.py
# def max_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def avg_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def dropout(x, drop_prob, phase_test=None, name=None, info=DummyDict()):
# def scale(x, name=None, value=1.0):
# def inner(x, channels, info=DummyDict(), stddev=None,
# activation=tf.nn.relu, name=None):
# def atrous_avg_pool(value, size, rate, padding, name=None, info=DummyDict()):
# def conv(x, channels, size=3, strides=1, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict(), output_shape=None):
# def upconv(x, channels, size=3, strides=1, output_shape=None, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict()):
# W = tf.get_variable('weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
#
# Path: selfsup/model/alex_bn.py
# def batch_norm(z, global_step, phase_test, name, bn_mean=None, bn_var=None):
# mm, vv = extra.moments(z, list(range(z.get_shape().ndims-1)), keep_dims=False, name=name + '_moments')
#
# beta = 0.0
# gamma = 1.0
#
# sh = mm.get_shape().as_list()[-1:]
# if bn_mean is None and bn_var is None:
# bn_mean, bn_var = init_batch_norm_vars(name, sh)
#
# alpha0 = 0.999
# N = 1000
# alpha = tf.to_float(tf.minimum(global_step, N) / N * alpha0)
# def mean_var_train():
# apply_op_mm = tf.assign(bn_mean, bn_mean * alpha + mm * (1 - alpha))
# apply_op_vv = tf.assign(bn_var, bn_var * alpha + vv * (1 - alpha))
#
# with tf.control_dependencies([apply_op_mm, apply_op_vv]):
# return tf.identity(mm), tf.identity(vv)
# #return tf.identity(bn_mean), tf.identity(bn_var)
#
# def mean_var_test():
# return bn_mean, bn_var
#
# mean, var = tf.cond(tf.logical_not(phase_test),
# mean_var_train,
# mean_var_test)
#
# z = tf.nn.batch_normalization(z, mean, var, beta, gamma, 1e-5)
# return z
. Output only the next line. | y = ops.upconv(y, sh[-1], size=1, strides=1, info=info, activation=None, name='upfc7', output_shape=sh) |
Continue the code snippet: <|code_start|>
LAYERS = ['conv0', 'conv1', 'conv2', 'conv3', 'conv4', 'conv5', 'fc6', 'fc7']
def decoder(y, from_name='fc7', to_name='conv0', info=DummyDict(), use_batch_norm=False, phase_test=None,
global_step=None):
BATCH_SIZE = y.get_shape().as_list()[0]
if use_batch_norm:
assert global_step is not None
def bn(z, name):
<|code_end|>
. Use current file imports:
import tensorflow as tf
from selfsup.util import DummyDict
from selfsup import ops
from .alex_bn import batch_norm
and context (classes, functions, or code) from other files:
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
#
# Path: selfsup/ops.py
# def max_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def avg_pool(x, size, stride=None, name=None, info=DummyDict(), padding='SAME'):
# def dropout(x, drop_prob, phase_test=None, name=None, info=DummyDict()):
# def scale(x, name=None, value=1.0):
# def inner(x, channels, info=DummyDict(), stddev=None,
# activation=tf.nn.relu, name=None):
# def atrous_avg_pool(value, size, rate, padding, name=None, info=DummyDict()):
# def conv(x, channels, size=3, strides=1, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict(), output_shape=None):
# def upconv(x, channels, size=3, strides=1, output_shape=None, activation=tf.nn.relu, name=None, padding='SAME',
# info=DummyDict()):
# W = tf.get_variable('weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
# W = tf.get_variable(name + '/weights', shape, dtype=tf.float32,
# initializer=W_init)
#
# Path: selfsup/model/alex_bn.py
# def batch_norm(z, global_step, phase_test, name, bn_mean=None, bn_var=None):
# mm, vv = extra.moments(z, list(range(z.get_shape().ndims-1)), keep_dims=False, name=name + '_moments')
#
# beta = 0.0
# gamma = 1.0
#
# sh = mm.get_shape().as_list()[-1:]
# if bn_mean is None and bn_var is None:
# bn_mean, bn_var = init_batch_norm_vars(name, sh)
#
# alpha0 = 0.999
# N = 1000
# alpha = tf.to_float(tf.minimum(global_step, N) / N * alpha0)
# def mean_var_train():
# apply_op_mm = tf.assign(bn_mean, bn_mean * alpha + mm * (1 - alpha))
# apply_op_vv = tf.assign(bn_var, bn_var * alpha + vv * (1 - alpha))
#
# with tf.control_dependencies([apply_op_mm, apply_op_vv]):
# return tf.identity(mm), tf.identity(vv)
# #return tf.identity(bn_mean), tf.identity(bn_var)
#
# def mean_var_test():
# return bn_mean, bn_var
#
# mean, var = tf.cond(tf.logical_not(phase_test),
# mean_var_train,
# mean_var_test)
#
# z = tf.nn.batch_normalization(z, mean, var, beta, gamma, 1e-5)
# return z
. Output only the next line. | return batch_norm(z, global_step=global_step, phase_test=phase_test, name=name) |
Predict the next line after this snippet: <|code_start|> ('conv2', 2.0),
('conv2b', 2.0),
('conv3', 4.0),
('conv3b', 4.0),
('conv4', 8.0),
('conv4b', 8.0),
#('fc6', 32.0),
]
def build(self, x, phase_test, global_step, settings={}):
self._global_step = global_step
self._phase_test = phase_test
info = selfsup.info.create(scale_summary=True)
info['config']['save_pre'] = True
z = selfsup.model.cnet.build_network_small(x, info=info,# parameters=data,
convolutional=False, final_layer_channels=None,
phase_test=phase_test,
use_dropout=True,
use_batch_norm=self._use_batch_norm,
global_step=global_step,
top_channels=100 if self._thin_top else None,
)
info['activations']['x'] = x
info['activations']['top'] = z
info['weights']['firstconv:weights'] = info['weights']['conv1:weights']
info['weights']['firstconv:biases'] = info['weights']['conv1:biases']
return info
<|code_end|>
using the current file's imports:
from .basenet import BaseNet
from selfsup.util import DummyDict
import selfsup.model.cnet
import selfsup
and any relevant context from other files:
# Path: selfsup/multi/basenets/basenet.py
# class BaseNet:
# def __init__(self):
# pass
#
# @property
# def name(self):
# raise NotImplemented('Abstract base class')
#
# @property
# def canonical_input_size(self):
# raise NotImplemented('Abstract base class')
#
# @property
# def hypercolumn_layers(self):
# """Suggested hypercolumn layers"""
# return []
#
# @property
# def layers(self):
# return [name for name, _ in self.hypercolumn_layers]
#
# def build(self):
# raise NotImplemented('Abstract base class')
#
# def save_caffemodel(self, path, session, verbose=False):
# raise NotImplemented('Abstract base class')
#
# Path: selfsup/util.py
# class DummyDict(object):
# def __init__(self):
# pass
# def __getitem__(self, item):
# return DummyDict()
# def __setitem__(self, item, value):
# return DummyDict()
# def get(self, item, default=None):
# if default is None:
# return DummyDict()
# else:
# return default
. Output only the next line. | def decoder(self, z, channels=1, multiple=4, from_name=None, settings=DummyDict(), info=DummyDict()): |
Given snippet: <|code_start|>
is_winows = sys.platform.startswith('linux')
class particles_install(install):
user_options = install.user_options
def run(self):
install.run(self)
# man ... Linux only
if sys.platform.startswith('linux'):
man_dir = os.path.abspath("./man/")
prefix = re.sub( r'^/' , '' , self.prefix )
output = subprocess.Popen([os.path.join(man_dir, "install.sh")],
stdout=subprocess.PIPE,
cwd=man_dir,
env=dict({"PREFIX": os.path.join( self.root , prefix ) }, **dict(os.environ))).communicate()[0]
print( output )
setup(name = "pyparticles",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import shutil
import subprocess
import sys
import re
import sys
from distutils.core import setup
from pyparticles.utils.pypart_global import py_particle_version
from distutils.command.install import install
and context:
# Path: pyparticles/utils/pypart_global.py
# def py_particle_version( r='s' ):
# global v_major
# global v_minor
# global v_revision
#
# if r == 's' :
# return "%d.%d.%d" % ( v_major , v_minor , v_revision )
# else :
# return ( v_major , v_minor , v_revision )
which might include code, classes, or functions. Output only the next line. | version = "%s" % py_particle_version() , |
Continue the code snippet: <|code_start|>
def default_pos( pset , indx ):
t = default_pos.sim_time.time
pset.X[indx,:] = 0.01 * np.random.rand( len(indx) , pset.dim ).astype( pset.dtype )
fs = 1.0 / ( 1.0 + np.exp( -( t*4.0 - 2.0 ) ) )
alpha = 2.0 * np.pi * np.random.rand( len(indx) ).astype( pset.dtype )
vel_x = 2.0 * fs * np.cos( alpha )
vel_y = 2.0 * fs * np.sin( alpha )
pset.V[indx,0] = vel_x
pset.V[indx,1] = vel_y
pset.V[indx,2] = 10.0 * fs + 1.0 * fs * ( np.random.rand( len(indx)) )
def fountain():
"""
Fountain demo
"""
steps = 10000000
dt = 0.005
pcnt = 100000
fl = True
<|code_end|>
. Use current file imports:
import numpy as np
import pyparticles.pset.particles_set as ps
import pyparticles.pset.opencl_context as occ
import pyparticles.ode.euler_solver as els
import pyparticles.ode.leapfrog_solver as lps
import pyparticles.ode.runge_kutta_solver as rks
import pyparticles.ode.stormer_verlet_solver as svs
import pyparticles.ode.midpoint_solver as mds
import pyparticles.forces.const_force as cf
import pyparticles.forces.drag as dr
import pyparticles.forces.multiple_force as mf
import pyparticles.animation.animated_ogl as aogl
import pyparticles.pset.default_boundary as db
from pyparticles.utils.pypart_global import test_pyopencl
and context (classes, functions, or code) from other files:
# Path: pyparticles/utils/pypart_global.py
# def test_pyopencl():
# try :
# import pyopencl
# except :
# return False
# else :
# return True
. Output only the next line. | if test_pyopencl() :
|
Here is a snippet: <|code_start|> self.__tree[ix].insert_particle( pset , i )
#print ( indx )
#print("")
#print ( "ix %d" % ix )
#print ( "jj %d" % jj )
#print ( "----------" )
#if jj != ix :
# print ("Fatal!!!!")
# exit()
#
return
def search_neighbour( self , cand_queue , res_list , pset , X , r ):
"""
Search the elements included in the volume centred in *X* with the radius *r* and append the results in the list *res_list*.
*res_list* contains the indicies of the particles included in the the sphere.
"""
while len(cand_queue) :
tree = cand_queue.pop()
if distance( pset.X[tree.particle,:] , X ) <= r :
res_list.append( tree.particle )
if tree.__tree == None :
continue
for t in tree.__tree:
<|code_end|>
. Write the next line using the current file imports:
import pyparticles.pset.particles_set as ps
import multiprocessing as mpr
import numpy as np
from pyparticles.geometry.intersection import box_intersects_sphere
from pyparticles.geometry.dist import distance
from collections import deque
and context from other files:
# Path: pyparticles/geometry/intersection.py
# def box_intersects_sphere( b_min , b_max , c , r ):
# """
# return True if the box defined by the opposite vertices *n_max*, *b max* intersect the sphere centred in *c* with a radius *r*
# """
#
# r2 = r**2.0
# dmin = 0.0
#
# if c[0] < b_min[0] :
# dmin += ( c[0] - b_min[0] )**2.0
# elif c[0] > b_max[0]:
# dmin += ( c[0] - b_max[0] )**2.0
#
# if c[1] < b_min[1] :
# dmin += ( c[1] - b_min[1] )**2.0
# elif c[1] > b_max[1]:
# dmin += ( c[1] - b_max[1] )**2.0
#
# if c[2] < b_min[2] :
# dmin += ( c[2] - b_min[2] )**2.0
# elif c[2] > b_max[2]:
# dmin += ( c[2] - b_max[2] )**2.0
#
# return dmin <= r2
#
# Path: pyparticles/geometry/dist.py
# def distance( x , y ):
# """
# return the euclideian distance between *x* and *y*
# """
# return np.sqrt( np.sum( (x-y)**2.0 ) )
, which may include functions, classes, or code. Output only the next line. | if t.particle != None and box_intersects_sphere( t.min_vertex , t.max_vertex , X , r ) : |
Predict the next line after this snippet: <|code_start|> # down
indx[:] = indx * self.__down
elif pset.X[i,2] >= self.__ref_vertex[2] + self.__edge_len/2.0 and pset.X[i,2] < self.__ref_vertex[2] + self.__edge_len :
# up
indx[:] = indx * self.__up
ix = np.sum( indx )
self.__tree[ix].insert_particle( pset , i )
#print ( indx )
#print("")
#print ( "ix %d" % ix )
#print ( "jj %d" % jj )
#print ( "----------" )
#if jj != ix :
# print ("Fatal!!!!")
# exit()
#
return
def search_neighbour( self , cand_queue , res_list , pset , X , r ):
"""
Search the elements included in the volume centred in *X* with the radius *r* and append the results in the list *res_list*.
*res_list* contains the indicies of the particles included in the the sphere.
"""
while len(cand_queue) :
tree = cand_queue.pop()
<|code_end|>
using the current file's imports:
import pyparticles.pset.particles_set as ps
import multiprocessing as mpr
import numpy as np
from pyparticles.geometry.intersection import box_intersects_sphere
from pyparticles.geometry.dist import distance
from collections import deque
and any relevant context from other files:
# Path: pyparticles/geometry/intersection.py
# def box_intersects_sphere( b_min , b_max , c , r ):
# """
# return True if the box defined by the opposite vertices *n_max*, *b max* intersect the sphere centred in *c* with a radius *r*
# """
#
# r2 = r**2.0
# dmin = 0.0
#
# if c[0] < b_min[0] :
# dmin += ( c[0] - b_min[0] )**2.0
# elif c[0] > b_max[0]:
# dmin += ( c[0] - b_max[0] )**2.0
#
# if c[1] < b_min[1] :
# dmin += ( c[1] - b_min[1] )**2.0
# elif c[1] > b_max[1]:
# dmin += ( c[1] - b_max[1] )**2.0
#
# if c[2] < b_min[2] :
# dmin += ( c[2] - b_min[2] )**2.0
# elif c[2] > b_max[2]:
# dmin += ( c[2] - b_max[2] )**2.0
#
# return dmin <= r2
#
# Path: pyparticles/geometry/dist.py
# def distance( x , y ):
# """
# return the euclideian distance between *x* and *y*
# """
# return np.sqrt( np.sum( (x-y)**2.0 ) )
. Output only the next line. | if distance( pset.X[tree.particle,:] , X ) <= r : |
Next line prediction: <|code_start|>
class PwDump(object):
def __init__(self, dictionary=None):
self.dictionary = dictionary
def main(self, system, sam):
"""
:rtype : object
:param system:
:param sam:
:return:
"""
user_hash = lib.dump_file_hashes(system, sam)
elementos = user_hash.items()
final_pass = dict()
for username, mihash in elementos:
print username
print mihash
print os.getcwd()
<|code_end|>
. Use current file imports:
(import subprocess
import lib
import os
from owade.constants import PROJECT_DIR, PROJECT_NAME, HASHCAT_DIR)
and context including class names, function names, or small code snippets from other files:
# Path: owade/constants.py
# PROJECT_DIR = "/opt/"
#
# PROJECT_NAME = "OwadeReborn/"
#
# HASHCAT_DIR = PROJECT_DIR + PROJECT_NAME + "owade/fileAnalyze/hashcatLib/hashcat"
. Output only the next line. | fileRoute = HASHCAT_DIR + "/hash.txt" |
Given the following code snippet before the placeholder: <|code_start|>
## Update an instance of Model in the database, catch exception
# @param obj The instance of the Model class
def updateDb(self, obj):
try:
obj.save()
except Exception as exp:
try:
self.internLog_.addLog("Update database failed, obj: %s, exception: %s" % (str(obj), str(exp)), 2)
except Exception as exp2:
self.internLog_.addLog("Update database failed: exception: %s" % (str(exp)), 2)
return False
return True
descriptionToken = 'O_DESCRIPTION'
def recurseUpdateDbGenericDic(self, dic, partition, father):
for key in dic:
if key == self.descriptionToken:
continue
value = dic[key]
if type(value) == dict:
#New category
description = ""
if self.descriptionToken in value:
description = value[self.descriptionToken]
category = Category(name=key, description=description, partition=partition, father=father)
category.save()
self.recurseUpdateDbGenericDic(value, None, category)
else:
#New key value
<|code_end|>
, predict the next line using imports from the current file:
import re
from threading import Thread
from owade.models import Value
from owade.models import Category
from owade.launcher import Launcher
from owade.models import *
from threading import Thread
and context including class names, function names, and sometimes code from other files:
# Path: owade/models.py
# class Value(models.Model):
# #key = models.CharField(max_length=32)
# key = models.TextField()
# value = models.TextField(blank=True, null=True)
#
# category = models.ForeignKey(Category)
#
# def __unicode__(self):
# return "%s: %s" % (self.key, self.value)
#
# Path: owade/models.py
# class Category(models.Model):
# #name = models.CharField(max_length=32)
# name = models.TextField()
# description = models.TextField(blank=True)
#
# partition = models.ForeignKey(Partition, null=True)
# father = models.ForeignKey('self', null=True)
#
# def __unicode__(self):
# if self.description != "":
# return "%s (%s)" % (self.name, self.description)
# return "%s" % (self.name)
#
# Path: owade/launcher.py
# class Launcher(Thread):
# ## Constructor
# # @param internLog An instance of the Log class, replace stdout and stderr for the Launcher
# # @param terminalLog An instance of the Log class, given to subprocess to get binaries stdout and stderr
# def __init__(self, internLog, terminalLog):
# Thread.__init__(self)
# self.internLog_ = internLog
# self.terminalLog_ = terminalLog
# self.cmd_ = ""
# self.process_ = None
# self.success_ = False
#
# ## Launch the unix cmd save in self.cmd_.
# # This thread keep updating terminalLog_.
# # Call final method at the end.
# def run(self):
# try:
# self.process_ = Popen(self.cmd_, universal_newlines=True, stderr=PIPE, stdout=PIPE)
# except:
# self.internLog_.addLog("".join(self.cmd_) + " Failed to execute" , 2 )
# while self.process_.returncode is None:
# self.process_.poll()
# try:
# input,o,e = select([self.process_.stdout, self.process_.stderr], [], [], 1)
# except:
# input = []
# for s in input:
# if s == self.process_.stdout:
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# if s == self.process_.stderr:
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# line = True
# while line != '':
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# line = True
# while line != '':
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# self.final()
# self.process_ = None
#
# ## Abstract method that has to be defined. Define a behavior after the subprocess.
# # You shound set the success_ attribute to True (if deserved) inside this method, either by
# # checking the terminal log or the returnvalue of process_.
# def final(self):
# raise NotImplementedError("Subclasses should implement this!")
#
# ## Return le statut du thread (was originaly designed for more, a bit redundent now with isAlive())
# # @return False if the Thread is still alive.
# def available(self):
# if self.isAlive():
# return False
# else:
# return True
#
# ## Interupt the Launcher by killing the subprocess
# def interupt(self):
# if self.isAlive():
# if self.process_ != None:
# self.process_.kill()
# return True
# return False
#
# ## An instance of the Log class, replace stdout and stderr for a Process
# internLog_ = None
# ## An instance of the Log class, only usefull if a Launcher is used
# terminalLog_ = None
# ## The unix to be launcher as a subprocess
# cmd_ = None
# ## The subprocess (launched or not)
# process_ = None
# ## The result of the Launcher (initial = False).
# # You have to set it to True (if deserved) in the final method.
# success_ = None
. Output only the next line. | valueModel = Value(key=key, value=value, category=father) |
Using the snippet: <|code_start|> return True
if self.launcher_.is_alive():
return False
else:
return True
## Update an instance of Model in the database, catch exception
# @param obj The instance of the Model class
def updateDb(self, obj):
try:
obj.save()
except Exception as exp:
try:
self.internLog_.addLog("Update database failed, obj: %s, exception: %s" % (str(obj), str(exp)), 2)
except Exception as exp2:
self.internLog_.addLog("Update database failed: exception: %s" % (str(exp)), 2)
return False
return True
descriptionToken = 'O_DESCRIPTION'
def recurseUpdateDbGenericDic(self, dic, partition, father):
for key in dic:
if key == self.descriptionToken:
continue
value = dic[key]
if type(value) == dict:
#New category
description = ""
if self.descriptionToken in value:
description = value[self.descriptionToken]
<|code_end|>
, determine the next line of code. You have imports:
import re
from threading import Thread
from owade.models import Value
from owade.models import Category
from owade.launcher import Launcher
from owade.models import *
from threading import Thread
and context (class names, function names, or code) available:
# Path: owade/models.py
# class Value(models.Model):
# #key = models.CharField(max_length=32)
# key = models.TextField()
# value = models.TextField(blank=True, null=True)
#
# category = models.ForeignKey(Category)
#
# def __unicode__(self):
# return "%s: %s" % (self.key, self.value)
#
# Path: owade/models.py
# class Category(models.Model):
# #name = models.CharField(max_length=32)
# name = models.TextField()
# description = models.TextField(blank=True)
#
# partition = models.ForeignKey(Partition, null=True)
# father = models.ForeignKey('self', null=True)
#
# def __unicode__(self):
# if self.description != "":
# return "%s (%s)" % (self.name, self.description)
# return "%s" % (self.name)
#
# Path: owade/launcher.py
# class Launcher(Thread):
# ## Constructor
# # @param internLog An instance of the Log class, replace stdout and stderr for the Launcher
# # @param terminalLog An instance of the Log class, given to subprocess to get binaries stdout and stderr
# def __init__(self, internLog, terminalLog):
# Thread.__init__(self)
# self.internLog_ = internLog
# self.terminalLog_ = terminalLog
# self.cmd_ = ""
# self.process_ = None
# self.success_ = False
#
# ## Launch the unix cmd save in self.cmd_.
# # This thread keep updating terminalLog_.
# # Call final method at the end.
# def run(self):
# try:
# self.process_ = Popen(self.cmd_, universal_newlines=True, stderr=PIPE, stdout=PIPE)
# except:
# self.internLog_.addLog("".join(self.cmd_) + " Failed to execute" , 2 )
# while self.process_.returncode is None:
# self.process_.poll()
# try:
# input,o,e = select([self.process_.stdout, self.process_.stderr], [], [], 1)
# except:
# input = []
# for s in input:
# if s == self.process_.stdout:
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# if s == self.process_.stderr:
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# line = True
# while line != '':
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# line = True
# while line != '':
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# self.final()
# self.process_ = None
#
# ## Abstract method that has to be defined. Define a behavior after the subprocess.
# # You shound set the success_ attribute to True (if deserved) inside this method, either by
# # checking the terminal log or the returnvalue of process_.
# def final(self):
# raise NotImplementedError("Subclasses should implement this!")
#
# ## Return le statut du thread (was originaly designed for more, a bit redundent now with isAlive())
# # @return False if the Thread is still alive.
# def available(self):
# if self.isAlive():
# return False
# else:
# return True
#
# ## Interupt the Launcher by killing the subprocess
# def interupt(self):
# if self.isAlive():
# if self.process_ != None:
# self.process_.kill()
# return True
# return False
#
# ## An instance of the Log class, replace stdout and stderr for a Process
# internLog_ = None
# ## An instance of the Log class, only usefull if a Launcher is used
# terminalLog_ = None
# ## The unix to be launcher as a subprocess
# cmd_ = None
# ## The subprocess (launched or not)
# process_ = None
# ## The result of the Launcher (initial = False).
# # You have to set it to True (if deserved) in the final method.
# success_ = None
. Output only the next line. | category = Category(name=key, description=description, partition=partition, father=father) |
Given snippet: <|code_start|>## Ivan Fontarensky <ivan.fontarensky@cassidian.com> ##
## Matthieu Martin <matthieu.mar+owade@gmail.com> ##
## Jean-Michel Picod <jean-michel.picod@cassidian.com> ##
## ##
## This program is distributed under GPLv3 licence (see LICENCE.txt) ##
## ##
#############################################################################
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="ashe"
__date__ ="$Jun 3, 2011 2:53:46 PM$"
## Main class of every owade's process, inherit from thread as you don't want the ui to be frozen.
# Abstract Class (as much as Python allows such a scheme).
# Define mostly methods for the ui.
# To create a new Process, you have to define __init__ and run.
class Process(Thread):
## Constructor
# @param internLog An instance of the Log class, replace stdout and stderr for a Process
# @param terminalLog An instance of the Log class, only usefull if a Launcher is used
def __init__(self, internLog, terminalLog):
Thread.__init__(self)
self.internLog_ = internLog
self.terminalLog_ = terminalLog
self.interupt_ = False
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from threading import Thread
from owade.models import Value
from owade.models import Category
from owade.launcher import Launcher
from owade.models import *
from threading import Thread
and context:
# Path: owade/models.py
# class Value(models.Model):
# #key = models.CharField(max_length=32)
# key = models.TextField()
# value = models.TextField(blank=True, null=True)
#
# category = models.ForeignKey(Category)
#
# def __unicode__(self):
# return "%s: %s" % (self.key, self.value)
#
# Path: owade/models.py
# class Category(models.Model):
# #name = models.CharField(max_length=32)
# name = models.TextField()
# description = models.TextField(blank=True)
#
# partition = models.ForeignKey(Partition, null=True)
# father = models.ForeignKey('self', null=True)
#
# def __unicode__(self):
# if self.description != "":
# return "%s (%s)" % (self.name, self.description)
# return "%s" % (self.name)
#
# Path: owade/launcher.py
# class Launcher(Thread):
# ## Constructor
# # @param internLog An instance of the Log class, replace stdout and stderr for the Launcher
# # @param terminalLog An instance of the Log class, given to subprocess to get binaries stdout and stderr
# def __init__(self, internLog, terminalLog):
# Thread.__init__(self)
# self.internLog_ = internLog
# self.terminalLog_ = terminalLog
# self.cmd_ = ""
# self.process_ = None
# self.success_ = False
#
# ## Launch the unix cmd save in self.cmd_.
# # This thread keep updating terminalLog_.
# # Call final method at the end.
# def run(self):
# try:
# self.process_ = Popen(self.cmd_, universal_newlines=True, stderr=PIPE, stdout=PIPE)
# except:
# self.internLog_.addLog("".join(self.cmd_) + " Failed to execute" , 2 )
# while self.process_.returncode is None:
# self.process_.poll()
# try:
# input,o,e = select([self.process_.stdout, self.process_.stderr], [], [], 1)
# except:
# input = []
# for s in input:
# if s == self.process_.stdout:
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# if s == self.process_.stderr:
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# line = True
# while line != '':
# line = self.process_.stdout.readline()
# self.terminalLog_.addLog(line, 1)
# line = True
# while line != '':
# line = self.process_.stderr.readline()
# self.terminalLog_.addLog(line, 2)
# self.final()
# self.process_ = None
#
# ## Abstract method that has to be defined. Define a behavior after the subprocess.
# # You shound set the success_ attribute to True (if deserved) inside this method, either by
# # checking the terminal log or the returnvalue of process_.
# def final(self):
# raise NotImplementedError("Subclasses should implement this!")
#
# ## Return le statut du thread (was originaly designed for more, a bit redundent now with isAlive())
# # @return False if the Thread is still alive.
# def available(self):
# if self.isAlive():
# return False
# else:
# return True
#
# ## Interupt the Launcher by killing the subprocess
# def interupt(self):
# if self.isAlive():
# if self.process_ != None:
# self.process_.kill()
# return True
# return False
#
# ## An instance of the Log class, replace stdout and stderr for a Process
# internLog_ = None
# ## An instance of the Log class, only usefull if a Launcher is used
# terminalLog_ = None
# ## The unix to be launcher as a subprocess
# cmd_ = None
# ## The subprocess (launched or not)
# process_ = None
# ## The result of the Launcher (initial = False).
# # You have to set it to True (if deserved) in the final method.
# success_ = None
which might include code, classes, or functions. Output only the next line. | self.launcher_ = Launcher(internLog, terminalLog) |
Based on the snippet: <|code_start|>## Offline Windows Analyzer and Data Extractor ##
## ##
## Authors: ##
## Elie Bursztein <owade@elie.im> ##
## Ivan Fontarensky <ivan.fontarensky@cassidian.com> ##
## Matthieu Martin <matthieu.mar+owade@gmail.com> ##
## Jean-Michel Picod <jean-michel.picod@cassidian.com> ##
## ##
## This program is distributed under GPLv3 licence (see LICENCE.txt) ##
## ##
#############################################################################
__author__="ashe"
__date__ ="$Jul 26, 2011 10:56:51 AM$"
class GetSafariHistory:
#%APPDATA%\\Apple Computer\\Safari\\History.plist
def main(self, history):
placeValues = {}
formValues = {}
places = cfp.CFPropertyList(history)
places.load()
places = cfp.native_types(places.value)
i = 0
for place in places.get('WebHistoryDates', []):
i += 1
placeValues['place%d' % i] = {'url':place[''], 'title':place['title'],
'count':place['visitCount'], 'date':place['lastVisitedDate'],
<|code_end|>
, predict the immediate next line with the help of imports:
import CFPropertyList as cfp
from owade.tools.domainFormater import format
and context (classes, functions, sometimes code) from other files:
# Path: owade/tools/domainFormater.py
# def format(url):
# if not re.match(r'^http', url):
# return None
# if re.match(r'https?://[^/.]*(:[0-9]{1,5})?(/.*)?$', url):
# return None
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2}\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.com\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2,4})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*)(:[0-9]{1,5})?(/.*)?$', url)
# if match != None:
# return match.group(1) + match.group(2)
# raise Exception("One case isn't dealed with: %s" % url)
# return match.group(2)
. Output only the next line. | 'domain':format(place[''])} |
Predict the next line after this snippet: <|code_start|> enc_nt_hash = V[hash_offset+(24 if lm_exists else 8):hash_offset+(24 if lm_exists else 8)+16] if nt_exists else ""
return decrypt_hashes(rid, enc_lm_hash, enc_nt_hash, hbootkey)
def get_user_name(user_key):
samaddr = user_key.space
V = None
for v in values(user_key):
if v.Name == 'V':
V = samaddr.read(v.Data.value, v.DataLength.value)
if not V: return None
name_offset = unpack("<L", V[0x0c:0x10])[0] + 0xCC
name_length = unpack("<L", V[0x10:0x14])[0]
username = V[name_offset:name_offset+name_length].decode('utf-16-le')
return username
def dump_hashes(sysaddr, samaddr):
bootkey = get_bootkey(sysaddr)
hbootkey = get_hbootkey(samaddr,bootkey)
for user in get_user_keys(samaddr):
lmhash,nthash = get_user_hashes(user,hbootkey)
if not lmhash: lmhash = empty_lm
if not nthash: nthash = empty_nt
print "%s:%d:%s:%s:::" % (get_user_name(user), int(user.Name,16),
lmhash.encode('hex'), nthash.encode('hex'))
def dump_file_hashes(syshive_fname, samhive_fname):
<|code_end|>
using the current file's imports:
from struct import unpack,pack
from Crypto.Hash import MD5
from Crypto.Cipher import ARC4,DES
from owade.fileAnalyze.hashcatLib.framework.win32.rawreg import *
from owade.fileAnalyze.hashcatLib.framework.addrspace import HiveFileAddressSpace
and any relevant context from other files:
# Path: owade/fileAnalyze/hashcatLib/framework/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
. Output only the next line. | sysaddr = HiveFileAddressSpace(syshive_fname) |
Predict the next line after this snippet: <|code_start|>## Authors: ##
## Elie Bursztein <owade@elie.im> ##
## Ivan Fontarensky <ivan.fontarensky@cassidian.com> ##
## Matthieu Martin <matthieu.mar+owade@gmail.com> ##
## Jean-Michel Picod <jean-michel.picod@cassidian.com> ##
## ##
## This program is distributed under GPLv3 licence (see LICENCE.txt) ##
## ##
#############################################################################
# This file is part of creddump.
#
# creddump is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# creddump is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with creddump. If not, see <http://www.gnu.org/licenses/>.
"""
@author: Brendan Dolan-Gavitt
@license: GNU General Public License 2.0 or later
@contact: bdolangavitt@wesleyan.edu
"""
<|code_end|>
using the current file's imports:
from operator import itemgetter
from struct import unpack
from owade.fileAnalyze.creddump.object import *
from owade.fileAnalyze.creddump.types import regtypes as types
and any relevant context from other files:
# Path: owade/fileAnalyze/creddump/types.py
. Output only the next line. | from owade.fileAnalyze.creddump.types import regtypes as types |
Given the following code snippet before the placeholder: <|code_start|>def get_user_name(user_key):
samaddr = user_key.space
V = None
for v in values(user_key):
if v.Name == 'V':
V = samaddr.read(v.Data.value, v.DataLength.value)
if not V: return None
name_offset = unpack("<L", V[0x0c:0x10])[0] + 0xCC
name_length = unpack("<L", V[0x10:0x14])[0]
username = V[name_offset:name_offset+name_length].decode('utf-16-le')
return username
def dump_hashes(sysaddr, samaddr):
bootkey = get_bootkey(sysaddr)
hbootkey = get_hbootkey(samaddr,bootkey)
for user in get_user_keys(samaddr):
lmhash,nthash = get_user_hashes(user,hbootkey)
if not lmhash: lmhash = empty_lm
if not nthash: nthash = empty_nt
print "%s:%d:%s:%s:::" % (get_user_name(user), int(user.Name,16),
lmhash.encode('hex'), nthash.encode('hex'))
#################################################
###### BEGIN OWADE CODE ADAPTATION
#################################################
def owade_get_hashes(sysaddr, samaddr):
<|code_end|>
, predict the next line using imports from the current file:
from struct import unpack,pack
from Crypto.Hash import MD5
from Crypto.Cipher import ARC4,DES
from owade.fileAnalyze.creddump.win32.rawreg import *
from owade.fileAnalyze.creddump.addrspace import HiveFileAddressSpace
and context including class names, function names, and sometimes code from other files:
# Path: owade/fileAnalyze/creddump/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
. Output only the next line. | sysaddr = HiveFileAddressSpace(sysaddr) |
Given the following code snippet before the placeholder: <|code_start|>
def __unicode__(self):
return "%s" % (self.serial)
## The path to the image of the hard drive, could be deleted
def image_path(self):
return "%s/%s" % (IMAGE_DIR, self.serial)
## The path to the ddrescue log of the hard drive, could be deleted
def log_path(self):
return "%s/%s_log_ddrescue" % (IMAGE_DIR, self.serial)
## Represents a file in the database
class File(models.Model):
## Md5 of the file
#checksum = models.CharField(max_length=32)
checksum = models.TextField()
## Extension of the file
#extension = models.CharField(max_length=16, blank=True)
extension = models.TextField(blank=True)
## Size in bytes of the file
size = models.TextField()
def __unicode__(self):
return self.formatName()
## Format the name according to the extension
def formatName(self):
if self.extension == "":
return "%i" % (self.id)
return "%i.%s" % (self.id, self.extension)
## The path to the copy of the file on the owade server
def file_path(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from owade.constants import FILE_DIR
from owade.constants import IMAGE_DIR
and context including class names, function names, and sometimes code from other files:
# Path: owade/constants.py
# FILE_DIR = EXT_HDRIVE + "/file"
#
# Path: owade/constants.py
# IMAGE_DIR = EXT_HDRIVE + "/image"
. Output only the next line. | return "%s/%s" % (FILE_DIR, self.formatName()) |
Given the following code snippet before the placeholder: <|code_start|>
# Create your models here.
##################################################
#### File Extraction
##################################################
## Represents an hard drive in the database
class HardDrive(models.Model):
## Serial number of the hard drive
#serial = models.CharField(max_length=128, unique=True)
serial = models.TextField(unique=True)
## Size in Byte of the hard drive
size = models.TextField()
def __unicode__(self):
return "%s" % (self.serial)
## The path to the image of the hard drive, could be deleted
def image_path(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from owade.constants import FILE_DIR
from owade.constants import IMAGE_DIR
and context including class names, function names, and sometimes code from other files:
# Path: owade/constants.py
# FILE_DIR = EXT_HDRIVE + "/file"
#
# Path: owade/constants.py
# IMAGE_DIR = EXT_HDRIVE + "/image"
. Output only the next line. | return "%s/%s" % (IMAGE_DIR, self.serial) |
Next line prediction: <|code_start|>
class GetIE7Passwords:
_descr = "Decrypt Internet Explorer 7+ autocomplete passwords"
## autocomplete are stored under
## HKLM\\Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2
##
## regkeys is a dict of reg entries such as the key is the hash value and
## the value is the DPAPI blob
##
## urls is an array of URLs that will be used to decipher password entries
def main(self, regkeys, places, mkp, sid, h):
values = {}
urls = self.formatUrls(places)
i = 0
b = IE7.IE7Autocomplete()
if b.try_decrypt_with_hash(h, mkp, sid, values=regkeys, urls=urls):
for k in b.entries.keys():
if b.entries[k].entropy is None:
continue
e = b.entries[k]
u = e.entropy.decode('UTF-16LE')[:-1]
i += 1
key = 'password%d' % i
values[key] = {'login': e.login, 'password': e.password,
<|code_end|>
. Use current file imports:
(from DPAPI.Probes import IE7
from owade.tools.domainFormater import format)
and context including class names, function names, or small code snippets from other files:
# Path: owade/tools/domainFormater.py
# def format(url):
# if not re.match(r'^http', url):
# return None
# if re.match(r'https?://[^/.]*(:[0-9]{1,5})?(/.*)?$', url):
# return None
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2}\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.com\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2,4})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*)(:[0-9]{1,5})?(/.*)?$', url)
# if match != None:
# return match.group(1) + match.group(2)
# raise Exception("One case isn't dealed with: %s" % url)
# return match.group(2)
. Output only the next line. | 'origin':u, 'domain':format(u)} |
Given snippet: <|code_start|>
secrets_key = open_key(root, ["Policy", "Secrets"])
if not secrets_key:
return None
secrets = {}
for key in subkeys(secrets_key):
sec_val_key = open_key(key, ["CurrVal"])
if not sec_val_key:
continue
enc_secret_value = sec_val_key.ValueList.List[0]
if not enc_secret_value:
continue
enc_secret = secaddr.read(enc_secret_value.Data.value,
enc_secret_value.DataLength.value)
if not enc_secret:
continue
if vista:
secret = decrypt_aes(enc_secret, lsakey)
else:
secret = decrypt_secret(enc_secret[0xC:], lsakey)
secrets[key.Name] = secret
return secrets
def get_file_secrets(sysfile, secfile, vista):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from Crypto.Hash import MD5, SHA256
from Crypto.Cipher import ARC4,DES, AES
from owade.fileAnalyze.hashcatLib.framework.win32.rawreg import *
from owade.fileAnalyze.hashcatLib.framework.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.hashcatLib.framework.win32.hashdump import get_bootkey,str_to_key
and context:
# Path: owade/fileAnalyze/hashcatLib/framework/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/hashcatLib/framework/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
which might include code, classes, or functions. Output only the next line. | sysaddr = HiveFileAddressSpace(sysfile) |
Using the snippet: <|code_start|>def get_secret_by_name(secaddr, name, lsakey, vista):
root = get_root(secaddr)
if not root:
return None
enc_secret_key = open_key(root, ["Policy", "Secrets", name, "CurrVal"])
if not enc_secret_key:
return None
enc_secret_value = enc_secret_key.ValueList.List[0]
if not enc_secret_value:
return None
enc_secret = secaddr.read(enc_secret_value.Data.value,
enc_secret_value.DataLength.value)
if not enc_secret:
return None
if vista:
secret = decrypt_aes(enc_secret, lsakey)
else:
secret = decrypt_secret(enc_secret[0xC:], lsakey)
return secret
def get_secrets(sysaddr, secaddr, vista):
root = get_root(secaddr)
if not root:
return None
<|code_end|>
, determine the next line of code. You have imports:
from Crypto.Hash import MD5, SHA256
from Crypto.Cipher import ARC4,DES, AES
from owade.fileAnalyze.hashcatLib.framework.win32.rawreg import *
from owade.fileAnalyze.hashcatLib.framework.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.hashcatLib.framework.win32.hashdump import get_bootkey,str_to_key
and context (class names, function names, or code) available:
# Path: owade/fileAnalyze/hashcatLib/framework/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/hashcatLib/framework/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
. Output only the next line. | bootkey = get_bootkey(sysaddr) |
Predict the next line after this snippet: <|code_start|> obf_lsa_key = secaddr.read(enc_reg_value.Data.value,
enc_reg_value.DataLength.value)
if not obf_lsa_key:
return None
if not vista:
md5 = MD5.new()
md5.update(bootkey)
for i in range(1000):
md5.update(obf_lsa_key[60:76])
rc4key = md5.digest()
rc4 = ARC4.new(rc4key)
lsa_key = rc4.decrypt(obf_lsa_key[12:60])
lsa_key = lsa_key[0x10:0x20]
else:
lsa_key = decrypt_aes(obf_lsa_key, bootkey)
lsa_key = lsa_key[68:100]
return lsa_key
def decrypt_secret(secret, key):
"""Python implementation of SystemFunction005.
Decrypts a block of data with DES using given key.
Note that key can be longer than 7 bytes."""
decrypted_data = ''
j = 0 # key index
for i in range(0,len(secret),8):
enc_block = secret[i:i+8]
block_key = key[j:j+7]
<|code_end|>
using the current file's imports:
from Crypto.Hash import MD5, SHA256
from Crypto.Cipher import ARC4,DES, AES
from owade.fileAnalyze.hashcatLib.framework.win32.rawreg import *
from owade.fileAnalyze.hashcatLib.framework.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.hashcatLib.framework.win32.hashdump import get_bootkey,str_to_key
and any relevant context from other files:
# Path: owade/fileAnalyze/hashcatLib/framework/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/hashcatLib/framework/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
. Output only the next line. | des_key = str_to_key(block_key) |
Based on the snippet: <|code_start|> return None
bootkey = get_bootkey(sysaddr)
lsakey = get_lsa_key(secaddr, bootkey)
secrets_key = open_key(root, ["Policy", "Secrets"])
if not secrets_key:
return None
secrets = {}
for key in subkeys(secrets_key):
sec_val_key = open_key(key, ["CurrVal"])
if not sec_val_key:
continue
enc_secret_value = sec_val_key.ValueList.List[0]
if not enc_secret_value:
continue
enc_secret = secaddr.read(enc_secret_value.Data.value,
enc_secret_value.DataLength.value)
if not enc_secret:
continue
secret = decrypt_secret(enc_secret[0xC:], lsakey)
secrets[key.Name] = secret
return secrets
def get_file_secrets(sysfile, secfile):
<|code_end|>
, predict the immediate next line with the help of imports:
from Crypto.Hash import MD5
from Crypto.Cipher import ARC4,DES
from owade.fileAnalyze.creddump.win32.rawreg import *
from owade.fileAnalyze.creddump.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.creddump.win32.hashdump import get_bootkey,str_to_key
and context (classes, functions, sometimes code) from other files:
# Path: owade/fileAnalyze/creddump/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/creddump/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
. Output only the next line. | sysaddr = HiveFileAddressSpace(sysfile) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.