Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)),
byref(cversion),
byref(specversion),
byref(cuuid))
interror = int(omxerror & 0xffffffff)
<|code_end|>
using the current file's imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and any relevant context from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | err = get_string_from_il_enum(interror, "OMX_Error") |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
<|code_end|>
with the help of current file imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)() |
Using the snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s '%s'" % (element.tag, name)) |
Given the code snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)),
byref(cversion),
byref(specversion),
byref(cuuid))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
<|code_end|>
, generate the next line using the imports in this file:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (functions, classes, or occasionally code) from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_line () |
Given snippet: <|code_start|>
class tag_OMX_GetComponentVersion(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)),
byref(cversion),
byref(specversion),
byref(cuuid))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
log_line ()
msg = "Component Name : " + cast(cname, c_char_p).value
log_line (msg, 1)
log_line ()
log_line ("Component Version", 1)
for name, _ in struct_anon_1._fields_:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
which might include code, classes, or functions. Output only the next line. | log_param (name, str(getattr(cversion.s, name)), 2) |
Based on the snippet: <|code_start|> name = context.cnames[alias]
log_api ("%s '%s'" % (element.tag, name))
handle = context.handles[alias]
cname = (c_ubyte * OMX_MAX_STRINGNAME_SIZE)()
cversion = OMX_VERSIONTYPE()
specversion = OMX_VERSIONTYPE()
cuuid = OMX_UUIDTYPE()
if (handle != None):
omxerror = OMX_GetComponentVersion(handle, cast(cname, POINTER(c_char)),
byref(cversion),
byref(specversion),
byref(cuuid))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
log_line ()
msg = "Component Name : " + cast(cname, c_char_p).value
log_line (msg, 1)
log_line ()
log_line ("Component Version", 1)
for name, _ in struct_anon_1._fields_:
log_param (name, str(getattr(cversion.s, name)), 2)
log_line ()
log_line ("Spec Version", 1)
for name, _ in struct_anon_1._fields_:
log_param (name, str(getattr(specversion.s, name)), 2)
<|code_end|>
, predict the immediate next line with the help of imports:
import skema.tag
from skema.omxil12 import OMX_STRING
from skema.omxil12 import OMX_VERSIONTYPE
from skema.omxil12 import OMX_UUIDTYPE
from skema.omxil12 import struct_anon_1
from skema.omxil12 import OMX_GetComponentVersion
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_MAX_STRINGNAME_SIZE
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import byref
from ctypes import create_string_buffer
from ctypes import c_ubyte
from ctypes import c_char
from ctypes import c_char_p
from ctypes import POINTER
from ctypes import cast
and context (classes, functions, sometimes code) from other files:
# Path: skema/omxil12.py
# OMX_STRING = String # OMX_Types.h: 124
#
# Path: skema/omxil12.py
# OMX_VERSIONTYPE = union_OMX_VERSIONTYPE # OMX_Types.h: 236
#
# Path: skema/omxil12.py
# OMX_UUIDTYPE = c_ubyte * 128 # OMX_Types.h: 126
#
# Path: skema/omxil12.py
# class struct_anon_1(Structure):
# pass
#
# Path: skema/omxil12.py
# def OMX_GetComponentVersion(hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetComponentVersion) (hComponent, pComponentName, pComponentVersion, pSpecVersion, pComponentUUID))
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_MAX_STRINGNAME_SIZE = 128
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_result(element.tag, err) |
Based on the snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfilePort(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
allocatorstr = element.get('allocator')
modestr = element.get('mode')
uristr = element.get('uri')
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import pwd
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context (classes, functions, sometimes code) from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s %s:Port-%d' 'Allocator:%s' 'Mode:%s' 'Uri:%s'" \ |
Predict the next line for this snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfilePort(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
allocatorstr = element.get('allocator')
modestr = element.get('mode')
uristr = element.get('uri')
# Replace '$USER' and '$HOME' strings wih the actual representations
uristr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], uristr, 1)
uristr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], uristr, 1)
log_api ("%s %s:Port-%d' 'Allocator:%s' 'Mode:%s' 'Uri:%s'" \
% (element.tag, name, int(portstr), \
allocatorstr, modestr, uristr))
context.base_profile_mgr.manage_port(alias, portstr, allocatorstr,
modestr, uristr)
<|code_end|>
with the help of current file imports:
import os
import re
import pwd
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | log_result (element.tag, "OMX_ErrorNone") |
Based on the snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileStartBufferExchange(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
<|code_end|>
, predict the immediate next line with the help of imports:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context (classes, functions, sometimes code) from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s %s:Port-%s'" % (element.tag, name, portstr)) |
Here is a snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_BaseProfileStartBufferExchange(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
name = context.cnames[alias]
portstr = element.get('port')
log_api ("%s %s:Port-%s'" % (element.tag, name, portstr))
context.base_profile_mgr.start_exchange(alias, portstr)
<|code_end|>
. Write the next line using the current file imports:
import skema.tag
from skema.utils import log_api
from skema.utils import log_result
and context from other files:
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | log_result (element.tag, "OMX_ErrorNone") |
Next line prediction: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
PID = os.getpid()
def my_evt_hdler(a, b, c, d, e, f):
evtstr = get_string_from_il_enum(c, "OMX_Event")
config = get_config()
name = str()
name = config.cnames2[a]
if (c == OMX_EventCmdComplete):
config.cmdevents[a].set()
cmdstr = get_string_from_il_enum(d, "OMX_Command")
if (d == OMX_CommandStateSet):
statestr = get_string_from_il_enum(e, "OMX_State")
<|code_end|>
. Use current file imports:
(import os
import sys
import threading
import signal
from ctypes import *
from omxil12 import *
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_result
from skema.config import get_config)
and context including class names, function names, or small code snippets from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | log_line () |
Predict the next line for this snippet: <|code_start|># This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
PID = os.getpid()
def my_evt_hdler(a, b, c, d, e, f):
evtstr = get_string_from_il_enum(c, "OMX_Event")
config = get_config()
name = str()
name = config.cnames2[a]
if (c == OMX_EventCmdComplete):
config.cmdevents[a].set()
cmdstr = get_string_from_il_enum(d, "OMX_Command")
if (d == OMX_CommandStateSet):
statestr = get_string_from_il_enum(e, "OMX_State")
log_line ()
<|code_end|>
with the help of current file imports:
import os
import sys
import threading
import signal
from ctypes import *
from omxil12 import *
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_result
from skema.config import get_config
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
, which may contain function names, class names, or code. Output only the next line. | log_api("EventHandler '%s'" % (name)) |
Given the code snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
PID = os.getpid()
def my_evt_hdler(a, b, c, d, e, f):
evtstr = get_string_from_il_enum(c, "OMX_Event")
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import threading
import signal
from ctypes import *
from omxil12 import *
from skema.utils import log_line
from skema.utils import log_api
from skema.utils import log_result
from skema.config import get_config
and context (functions, classes, or occasionally code) from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | config = get_config() |
Predict the next line for this snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
<|code_end|>
with the help of current file imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | index = get_il_enum_from_string(indexstr) |
Given snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
which might include code, classes, or functions. Output only the next line. | err = get_string_from_il_enum(interror, "OMX_Error") |
Here is a snippet: <|code_start|># This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
<|code_end|>
. Write the next line using the current file imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context from other files:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
, which may include functions, classes, or code. Output only the next line. | param_type = OMX_PARAM_CONTENTURITYPE |
Using the snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | omxerror = OMX_GetParameter(handle, index, byref(param_struct)) |
Using the snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_api ("%s '%s' '%s'" \ |
Using the snippet: <|code_start|>
class tag_OMX_GetContentURI(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
uristr = c_char_p()
uristr = cast(param_struct.contentURI, c_char_p)
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_line () |
Using the snippet: <|code_start|> """
"""
def run(self, element, context):
indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
uristr = c_char_p()
uristr = cast(param_struct.contentURI, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "URI"):
<|code_end|>
, determine the next line of code. You have imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context (class names, function names, or code) available:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
. Output only the next line. | log_param (name, uristr.value, 1) |
Given snippet: <|code_start|> indexstr = "OMX_IndexParamContentURI"
alias = element.get('alias')
name = context.cnames[alias]
log_api ("%s '%s' '%s'" \
% (element.tag, indexstr, name))
handle = context.handles[alias]
index = get_il_enum_from_string(indexstr)
param_type = OMX_PARAM_CONTENTURITYPE
param_struct = param_type()
param_struct.nSize = sizeof(param_type)
if (handle != None):
omxerror = OMX_GetParameter(handle, index, byref(param_struct))
interror = int(omxerror & 0xffffffff)
err = get_string_from_il_enum(interror, "OMX_Error")
uristr = c_char_p()
uristr = cast(param_struct.contentURI, c_char_p)
log_line ()
log_line ("%s" % param_struct.__class__.__name__, 1)
for name, _ in param_type._fields_:
if (name == "nVersion"):
log_line ("%s -> '%08x'" \
% (name, param_struct.nVersion.nVersion), 1)
elif (name == "URI"):
log_param (name, uristr.value, 1)
else:
log_param (name, str(getattr(param_struct, name)), 1)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import skema.tag
from skema.omxil12 import get_il_enum_from_string
from skema.omxil12 import get_string_from_il_enum
from skema.omxil12 import OMX_PARAM_CONTENTURITYPE
from skema.omxil12 import OMX_GetParameter
from skema.utils import log_api
from skema.utils import log_line
from skema.utils import log_param
from skema.utils import log_result
from ctypes import c_char_p
from ctypes import sizeof
from ctypes import cast
from ctypes import byref
and context:
# Path: skema/omxil12.py
# def get_il_enum_from_string(string):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if name == string:
# return val
# raise AttributeError
#
# Path: skema/omxil12.py
# def get_string_from_il_enum(enum, hint):
# from skema import omxil12
# for name, val in omxil12.__dict__.iteritems():
# if enum == val:
# if name.startswith(hint):
# return name
# raise AttributeError
#
# Path: skema/omxil12.py
# OMX_PARAM_CONTENTURITYPE = struct_OMX_PARAM_CONTENTURITYPE # OMX_Component.h: 126
#
# Path: skema/omxil12.py
# def OMX_GetParameter(hComponent, nParamIndex, pComponentParameterStructure):
# return ((cast(hComponent, POINTER(OMX_COMPONENTTYPE)).contents.GetParameter) (hComponent, nParamIndex, pComponentParameterStructure))
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
#
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_param(param, val, tabs=0):
# l = ('\t' * tabs) + "[" + param + " -> '" + val + "']"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
which might include code, classes, or functions. Output only the next line. | log_result (element.tag, err) |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_Wait(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
delay_in_seconds = element.get('delay')
log_api ("%s '%s'" \
% (element.tag, delay_in_seconds))
time.sleep(float(delay_in_seconds))
<|code_end|>
with the help of current file imports:
import skema.tag
import time
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | log_line () |
Predict the next line for this snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_Wait(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
delay_in_seconds = element.get('delay')
log_api ("%s '%s'" \
% (element.tag, delay_in_seconds))
time.sleep(float(delay_in_seconds))
log_line ()
msg = "Waited '" + delay_in_seconds + "' seconds"
<|code_end|>
with the help of current file imports:
import skema.tag
import time
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
and context from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
, which may contain function names, class names, or code. Output only the next line. | log_result (msg, "OMX_ErrorNone") |
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_Wait(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
delay_in_seconds = element.get('delay')
<|code_end|>
, predict the next line using imports from the current file:
import skema.tag
import time
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
and context including class names, function names, and sometimes code from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
. Output only the next line. | log_api ("%s '%s'" \ |
Continue the code snippet: <|code_start|> suite.install()
except RuntimeError as strerror:
print "Suite installation error: %s" % strerror
sys.exit(1)
class cmd_run_suite(skema.command.SkemaCmd):
"""
Run suites
"""
arglist = ['*suitename']
options = [make_option('-q', '--quiet', action='store_true',
default=False, dest='quiet'),
make_option('-o', '--output', action='store',
default=None, metavar="DIR",
help="Store processed suite output to DIR")
]
def run(self):
if len(self.args) != 1:
print "please specify the name of the suite to run"
sys.exit(1)
suite = suiteloader(self.args[0])
try:
return suite.run(quiet=self.opts.quiet, output=self.opts.output)
except Exception as strerror:
print "Suite execution error: %s" % strerror
print (format_exc())
<|code_end|>
. Use current file imports:
import os
import sys
import skema.command
import skema.suite
import skema
from optparse import make_option
from traceback import format_exc
from skema.config import get_config
from skema.suiteutils import suiteloader
from skema.suiteutils import suiteloader
from skema.suiteutils import suiteloader
from skema.tagutils import tagloader
from skema.tagutils import tagloader
from skema import suites
from pkgutil import walk_packages
from skema import tags
from pkgutil import walk_packages
and context (classes, functions, or code) from other files:
# Path: skema/config.py
# def get_config():
# global _config
# if _config is not None:
# return _config
# _config = SkemaConfig()
# return _config
. Output only the next line. | config = get_config() |
Given the code snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_StartSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
cmdlinestr = element.get('cmdline')
# Replace '$USER' and '$HOME' strings wih the actual representations
cmdlinestr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], cmdlinestr, 0)
cmdlinestr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], cmdlinestr, 0)
log_api ("%s '%s' '%s'" \
% (element.tag, alias, cmdlinestr))
args = shlex.split(cmdlinestr)
process = Popen(args)
context.subprocesses[alias] = process
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import pwd
import shlex
import skema.tag
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
and context (functions, classes, or occasionally code) from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
. Output only the next line. | log_line () |
Next line prediction: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_StartSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
cmdlinestr = element.get('cmdline')
# Replace '$USER' and '$HOME' strings wih the actual representations
cmdlinestr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], cmdlinestr, 0)
cmdlinestr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], cmdlinestr, 0)
log_api ("%s '%s' '%s'" \
% (element.tag, alias, cmdlinestr))
args = shlex.split(cmdlinestr)
process = Popen(args)
context.subprocesses[alias] = process
log_line ()
msg = "Started sub-process '" + alias + "' with PID " + str(context.subprocesses[alias].pid)
<|code_end|>
. Use current file imports:
(import os
import re
import pwd
import shlex
import skema.tag
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api)
and context including class names, function names, or small code snippets from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
. Output only the next line. | log_result (msg, "OMX_ErrorNone") |
Continue the code snippet: <|code_start|># Copyright (C) 2011-2017 Aratelia Limited - Juan A. Rubio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class tag_OMX_StartSubProcess(skema.tag.SkemaTag):
"""
"""
def run(self, element, context):
alias = element.get('alias')
cmdlinestr = element.get('cmdline')
# Replace '$USER' and '$HOME' strings wih the actual representations
cmdlinestr = re.sub("\$USER", pwd.getpwuid(os.getuid())[0], cmdlinestr, 0)
cmdlinestr = re.sub("\$HOME", pwd.getpwuid(os.getuid())[5], cmdlinestr, 0)
<|code_end|>
. Use current file imports:
import os
import re
import pwd
import shlex
import skema.tag
from subprocess import Popen
from skema.utils import log_line
from skema.utils import log_result
from skema.utils import log_api
and context (classes, functions, or code) from other files:
# Path: skema/utils.py
# def log_line(line="", tabs=0):
# if (line == ""):
# lansi = "[skema] "
# l = ""
# else:
# l = ('\t' * tabs) + "[" + line + "]"
# lansi = "[skema] " + bcolors.WARNING + l + bcolors.ENDC
# logging.info(l)
# printit (lansi)
#
# Path: skema/utils.py
# def log_result(tag, err):
# log_line ()
# if (err == "OMX_ErrorNone"):
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.OKGREEN + l + bcolors.ENDC
# logging.info(l)
# else:
# l = "[" + tag + " -> '" + err + "']"
# lansi = "[skema] " + bcolors.FAIL + l + bcolors.ENDC
# logging.error(l)
#
# printit (lansi)
#
# Path: skema/utils.py
# def log_api(line):
# log_line ()
# logging.info("")
# log_line ()
# logging.info("")
# l = "[" + line +"]"
# logging.info(l)
# lansi = "[skema] " + bcolors.BOLD + l + bcolors.ENDC
# printit (lansi)
. Output only the next line. | log_api ("%s '%s' '%s'" \ |
Continue the code snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class SkemaConfig(object):
def __init__(self):
home = os.environ.get('HOME', '/')
baseconfig = os.environ.get('XDG_CONFIG_HOME',
os.path.join(home, '.config'))
basedata = os.environ.get('XDG_DATA_HOME',
os.path.join(home, '.local', 'share'))
self.configdir = os.path.join(baseconfig, 'skema')
self.suitesdir = os.path.join(basedata, 'skema', 'installed-suites')
self.tagsdir = os.path.join(basedata, 'skema', 'installed-tags')
self.resultsdir = os.path.join(basedata, 'skema', 'results')
self.fd = file(os.devnull)
self.quiet = True
self.ilevent = threading.Event()
<|code_end|>
. Use current file imports:
import os
import threading
from collections import defaultdict
from skema.omxil12 import OMX_CALLBACKTYPE
and context (classes, functions, or code) from other files:
# Path: skema/omxil12.py
# OMX_CALLBACKTYPE = struct_OMX_CALLBACKTYPE # OMX_Core.h: 290
. Output only the next line. | self.cbacks = OMX_CALLBACKTYPE() |
Based on the snippet: <|code_start|> def print_(self, printer, print_):
return ''.join(map('//{}\n'.format, self.lines))
class MethodDef(object):
def __init__(self, class_, flags, name, desc, retType, paramDecls, body):
self.flagstr = flags + ' ' if flags else ''
self.retType, self.paramDecls = retType, paramDecls
self.body = body
self.comments = Comments()
self.triple = class_.name, name, desc
self.throws = None
if name == '<clinit>':
self.isStaticInit, self.isConstructor = True, False
elif name == '<init>':
self.isStaticInit, self.isConstructor = False, True
self.clsname = ast.TypeName(objtypes.TypeTT(class_.name, 0))
else:
self.isStaticInit, self.isConstructor = False, False
def print_(self, printer, print_):
header = print_(self.comments)
argstr = ', '.join(print_(decl) for decl in self.paramDecls)
if self.isStaticInit:
header += 'static'
elif self.isConstructor:
name = print_(self.clsname).rpartition('.')[-1]
header += '{}{}({})'.format(self.flagstr, name, argstr)
else:
name = printer.methodName(*self.triple)
<|code_end|>
, predict the immediate next line with the help of imports:
from . import ast
from .stringescape import escapeString as escape
from ..ssa import objtypes
and context (classes, functions, sometimes code) from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/stringescape.py
# def escapeString(u):
# if set(u) <= ok_chars:
# return u
#
# escaped = []
# for c in u:
# if c in ok_chars:
# escaped.append(c)
# elif c in late_escape:
# escaped.append(late_escape[c])
# else:
# i = ord(c)
# if i <= 0xFFFF:
# escaped.append(r'\u{0:04x}'.format(i))
# else:
# i -= 0x10000
# high = 0xD800 + (i>>10)
# low = 0xDC00 + (i & 0x3FF)
# escaped.append(r'\u{0:04x}\u{1:04x}'.format(high,low))
# return ''.join(escaped)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
. Output only the next line. | header += '{}{} {}({})'.format(self.flagstr, print_(self.retType), escape(name), argstr) |
Based on the snippet: <|code_start|>
class Comments(object):
def __init__(self):
self.lines = []
def add(self, s):
self.lines.extend(s.strip('\n').split('\n'))
def print_(self, printer, print_):
return ''.join(map('//{}\n'.format, self.lines))
class MethodDef(object):
def __init__(self, class_, flags, name, desc, retType, paramDecls, body):
self.flagstr = flags + ' ' if flags else ''
self.retType, self.paramDecls = retType, paramDecls
self.body = body
self.comments = Comments()
self.triple = class_.name, name, desc
self.throws = None
if name == '<clinit>':
self.isStaticInit, self.isConstructor = True, False
elif name == '<init>':
self.isStaticInit, self.isConstructor = False, True
<|code_end|>
, predict the immediate next line with the help of imports:
from . import ast
from .stringescape import escapeString as escape
from ..ssa import objtypes
and context (classes, functions, sometimes code) from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/stringescape.py
# def escapeString(u):
# if set(u) <= ok_chars:
# return u
#
# escaped = []
# for c in u:
# if c in ok_chars:
# escaped.append(c)
# elif c in late_escape:
# escaped.append(late_escape[c])
# else:
# i = ord(c)
# if i <= 0xFFFF:
# escaped.append(r'\u{0:04x}'.format(i))
# else:
# i -= 0x10000
# high = 0xD800 + (i>>10)
# low = 0xDC00 + (i & 0x3FF)
# escaped.append(r'\u{0:04x}\u{1:04x}'.format(high,low))
# return ''.join(escaped)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
. Output only the next line. | self.clsname = ast.TypeName(objtypes.TypeTT(class_.name, 0)) |
Based on the snippet: <|code_start|> k = min(numzeroes, (y-x+1).bit_length()-1)
out.append((x,k))
x += 1<<k
assert(x == y+1)
return out
def propagateBitwise(arg1, arg2, op, usemin, usemax):
ranges1 = split_pow2ranges(arg1.min, arg1.max)
ranges2 = split_pow2ranges(arg2.min, arg2.max)
vals = []
for (s1,k1),(s2,k2) in itertools.product(ranges1, ranges2):
# there are three parts. The high bits fixed in both arguments,
# the middle bits fixed in one but not the other, and the
# lowest bits which can be chosen freely for both arguments
# high = op(h1,h2) and low goes from 0 to 1... but the range of
# the middle depends on the particular operation
# 0-x, x-1 and 0-1 for and, or, and xor respectively
if k1 > k2:
(s1,k1),(s2,k2) = (s2,k2),(s1,k1)
mask1 = (1<<k1) - 1
mask2 = (1<<k2) - 1 - mask1
high = op(s1, s2) & ~(mask1 | mask2)
midmin = (s1 & mask2) if usemin else 0
midmax = (s1 & mask2) if usemax else mask2
vals.append(high | midmin)
vals.append(high | midmax | mask1)
<|code_end|>
, predict the immediate next line with the help of imports:
from ..constraints import IntConstraint
import itertools, operator
and context (classes, functions, sometimes code) from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/constraints/int_c.py
# class IntConstraint(ValueType):
# __slots__ = "width min max".split()
#
# def __init__(self, width, min_, max_):
# self.width = width
# self.min = min_
# self.max = max_
# # self.isBot = (-min_ == max_+1 == (1<<width)//2)
#
# @staticmethod
# def range(width, min_, max_):
# if min_ > max_:
# return None
# return IntConstraint(width, min_, max_)
#
# @staticmethod
# def const(width, val):
# return IntConstraint(width, val, val)
#
# @staticmethod
# def bot(width):
# return IntConstraint(width, -1<<(width-1), (1<<(width-1))-1)
#
# def _key(self): return self.min, self.max
#
# def join(*cons):
# xmin = max(c.min for c in cons)
# xmax = min(c.max for c in cons)
# if xmin > xmax:
# return None
# res = IntConstraint(cons[0].width, xmin, xmax)
# return cons[0] if cons[0] == res else res
#
# def meet(*cons):
# xmin = min(c.min for c in cons)
# xmax = max(c.max for c in cons)
# return IntConstraint(cons[0].width, xmin, xmax)
. Output only the next line. | return IntConstraint.range(arg1.width, min(vals), max(vals)) |
Here is a snippet: <|code_start|>
class BaseOp(SSAFunctionBase):
def __init__(self, parent, arguments, makeException=False, makeMonad=False):
super(BaseOp, self).__init__(parent,arguments)
self.rval = None
self.outException = None
self.outMonad = None
if makeException:
<|code_end|>
. Write the next line using the current file imports:
from ..functionbase import SSAFunctionBase
from ..ssa_types import SSA_OBJECT, SSA_MONAD
and context from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/functionbase.py
# class SSAFunctionBase(object):
# def __init__(self, parent, arguments):
# self.parent = parent
# self.params = list(arguments)
# assert(None not in self.params)
#
# def replaceVars(self, rdict):
# self.params = [rdict.get(x,x) for x in self.params]
# assert(None not in self.params)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/ssa_types.py
# SSA_OBJECT = 'obj',
#
# SSA_MONAD = 'monad',
, which may include functions, classes, or code. Output only the next line. | self.outException = parent.makeVariable(SSA_OBJECT, origin=self) |
Predict the next line for this snippet: <|code_start|>
class BaseOp(SSAFunctionBase):
def __init__(self, parent, arguments, makeException=False, makeMonad=False):
super(BaseOp, self).__init__(parent,arguments)
self.rval = None
self.outException = None
self.outMonad = None
if makeException:
self.outException = parent.makeVariable(SSA_OBJECT, origin=self)
if makeMonad:
<|code_end|>
with the help of current file imports:
from ..functionbase import SSAFunctionBase
from ..ssa_types import SSA_OBJECT, SSA_MONAD
and context from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/functionbase.py
# class SSAFunctionBase(object):
# def __init__(self, parent, arguments):
# self.parent = parent
# self.params = list(arguments)
# assert(None not in self.params)
#
# def replaceVars(self, rdict):
# self.params = [rdict.get(x,x) for x in self.params]
# assert(None not in self.params)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/ssa_types.py
# SSA_OBJECT = 'obj',
#
# SSA_MONAD = 'monad',
, which may contain function names, class names, or code. Output only the next line. | self.outMonad = parent.makeVariable(SSA_MONAD, origin=self) |
Predict the next line after this snippet: <|code_start|> return yname in ('java/lang/Object','java/lang/Cloneable','java/io/Serializable')
else:
return isBaseTClass(x) and isBaseTClass(y) and env.isSubclass(xname, yname)
#Will not return interface unless all inputs are same interface or null
def commonSupertype(env, tts):
assert(hasattr(env, 'getClass')) #catch common errors where we forget the env argument
tts = set(tts)
tts.discard(NullTT)
if len(tts) == 1:
return tts.pop()
elif not tts:
return NullTT
dims = map(dim, tts)
newdim = min(dims)
if max(dims) > newdim or any(baset(tt) == 'java/lang/Object' for tt in tts):
return TypeTT('java/lang/Object', newdim)
# if any are primative arrays, result is object array of dim-1
if not all(isBaseTClass(tt) for tt in tts):
return TypeTT('java/lang/Object', newdim-1)
# find common superclass of base types
baselists = [env.getSupers(baset(tt)) for tt in tts]
common = [x for x in zip(*baselists) if len(set(x)) == 1]
return TypeTT(common[-1][0], newdim)
######################################################################################################
<|code_end|>
using the current file's imports:
from ..verifier import verifier_types as vtypes
from ..error import ClassLoaderError
and any relevant context from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# def _makeinfo(tag, dim=0, extra=None):
# def T_ADDRESS(entry):
# def T_OBJECT(name):
# def T_ARRAY(baset, newDimensions=1):
# def T_UNINIT_OBJECT(origin):
# def objOrArray(fi): #False on uninitialized
# def unSynthesizeType(t):
# def decrementDim(fi):
# def withNoDimension(fi):
# def _decToObjArray(fi):
# def _arrbase(fi):
# def mergeTypes(env, t1, t2, forAssignment=False):
# def isAssignable(env, t1, t2):
# def vt_toStr(self):
# T_INVALID = _makeinfo(None)
# T_INT = _makeinfo('.int')
# T_FLOAT = _makeinfo('.float')
# T_DOUBLE = _makeinfo('.double')
# T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things
# T_LONG = _makeinfo('.long')
# T_LONG2 = _makeinfo('.long2')
# T_NULL = _makeinfo('.obj')
# T_UNINIT_THIS = _makeinfo('.init')
# T_BYTE = _makeinfo('.byte')
# T_SHORT = _makeinfo('.short')
# T_CHAR = _makeinfo('.char')
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
# OBJECT_INFO = T_OBJECT('java/lang/Object')
# CLONE_INFO = T_OBJECT('java/lang/Cloneable')
# SERIAL_INFO = T_OBJECT('java/io/Serializable')
# THROWABLE_INFO = T_OBJECT('java/lang/Throwable')
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/error.py
# class ClassLoaderError(Exception):
# def __init__(self, typen=None, data=""):
# self.type = typen
# self.data = data
#
# message = u"\n{}: {}".format(typen, data) if typen else unicode(data)
# super(ClassLoaderError, self).__init__(message)
. Output only the next line. | _verifierConvert = {vtypes.T_INT:IntTT, vtypes.T_FLOAT:FloatTT, vtypes.T_LONG:LongTT, |
Using the snippet: <|code_start|>
class Field(object):
flagVals = {'PUBLIC':0x0001,
'PRIVATE':0x0002,
'PROTECTED':0x0004,
'STATIC':0x0008,
'FINAL':0x0010,
'VOLATILE':0x0040,
'TRANSIENT':0x0080,
'SYNTHETIC':0x1000,
'ENUM':0x4000,
}
def __init__(self, data, classFile, keepRaw):
self.class_ = classFile
cpool = self.class_.cpool
flags, name_id, desc_id, attributes_raw = data
self.name = cpool.getArgsCheck('Utf8', name_id)
self.descriptor = cpool.getArgsCheck('Utf8', desc_id)
<|code_end|>
, determine the next line of code. You have imports:
from .attributes_raw import fixAttributeNames
and context (class names, function names, or code) available:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/attributes_raw.py
# def fixAttributeNames(attributes_raw, cpool):
# return [(cpool.getArgsCheck('Utf8', name_ind), data) for name_ind, data in attributes_raw]
. Output only the next line. | self.attributes = fixAttributeNames(attributes_raw, cpool) |
Using the snippet: <|code_start|>
def getScopes(self): return self,
def print_(self, printer, print_):
assert(self.labelable or self.label is None)
contents = '\n'.join(print_(x) for x in self.statements)
indented = [' '+line for line in contents.splitlines()]
# indented[:0] = [' //{} {}'.format(self,x) for x in (self.continueKey, self.breakKey, self.jumpKey)]
lines = [self.getLabelPrefix() + '{'] + indented + ['}']
return '\n'.join(lines)
@staticmethod
def join(*scopes):
blists = [s.bases for s in scopes if s is not None] #allow None to represent the universe (top element)
if not blists:
return None
common = [x for x in zip(*blists) if len(set(x)) == 1]
return common[-1][0]
def tree(self, printer, tree): return ['blockS', self.label, map(tree, self.statements)]
#Temporary hack
class StringStatement(JavaStatement):
def __init__(self, s):
self.s = s
def print_(self, printer, print_): return self.s
def tree(self, printer, tree): return ['stringS', self.s]
#############################################################################################################################################
# Careful, order is important here!
<|code_end|>
, determine the next line of code. You have imports:
import itertools, math
from ..ssa import objtypes
from .stringescape import escapeString
and context (class names, function names, or code) available:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/stringescape.py
# def escapeString(u):
# if set(u) <= ok_chars:
# return u
#
# escaped = []
# for c in u:
# if c in ok_chars:
# escaped.append(c)
# elif c in late_escape:
# escaped.append(late_escape[c])
# else:
# i = ord(c)
# if i <= 0xFFFF:
# escaped.append(r'\u{0:04x}'.format(i))
# else:
# i -= 0x10000
# high = 0xD800 + (i>>10)
# low = 0xDC00 + (i & 0x3FF)
# escaped.append(r'\u{0:04x}\u{1:04x}'.format(high,low))
# return ''.join(escaped)
. Output only the next line. | _assignable_sprims = objtypes.ByteTT, objtypes.ShortTT, objtypes.CharTT |
Given the code snippet: <|code_start|>
def print_(self, printer, print_):
return 'new {}({})'.format(print_(self.typename), ', '.join(print_(x) for x in self.params))
def tree(self, printer, tree):
return [self.__class__.__name__, map(tree, self.params), tree(self.typename)]
def addCasts_sub(self, env):
newparams = []
for tt, expr in zip(self.tts, self.params):
if expr.dtype != tt and (ALWAYS_CAST_PARAMS or not isJavaAssignable(env, expr.dtype, tt)):
expr = makeCastExpr(tt, expr, fixEnv=env)
newparams.append(expr)
self.params = newparams
class FieldAccess(JavaExpression):
def __init__(self, primary, name, dtype, op=None, printLeft=True):
self.dtype = dtype
self.params = [primary]
self.op, self.name = op, name
self.printLeft = printLeft
# self.params, self.name = [primary], escapeString(name)
# self.fmt = ('{}.' if printLeft else '') + self.name
def print_(self, printer, print_):
if self.op is None:
name = self.name
assert(name in ('length','class'))
else:
cls, name, desc = self.op.target, self.op.name, self.op.desc
<|code_end|>
, generate the next line using the imports in this file:
import itertools, math
from ..ssa import objtypes
from .stringescape import escapeString
and context (functions, classes, or occasionally code) from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/stringescape.py
# def escapeString(u):
# if set(u) <= ok_chars:
# return u
#
# escaped = []
# for c in u:
# if c in ok_chars:
# escaped.append(c)
# elif c in late_escape:
# escaped.append(late_escape[c])
# else:
# i = ord(c)
# if i <= 0xFFFF:
# escaped.append(r'\u{0:04x}'.format(i))
# else:
# i -= 0x10000
# high = 0xD800 + (i>>10)
# low = 0xDC00 + (i & 0x3FF)
# escaped.append(r'\u{0:04x}\u{1:04x}'.format(high,low))
# return ''.join(escaped)
. Output only the next line. | name = escapeString(printer.fieldName(cls, name, desc)) |
Given snippet: <|code_start|>
# A simple throws declaration inferrer that only considers throw statements within the method
# this is mostly just useful to make sure the ExceptionHandlers test compiles
def _visit_statement(env, stmt):
if isinstance(stmt, ast.ThrowStatement):
return stmt.expr.dtype
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from . import ast
from ..ssa import objtypes
and context:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
which might include code, classes, or functions. Output only the next line. | result = objtypes.NullTT |
Here is a snippet: <|code_start|>
def parseFieldDescriptors(desc_str, unsynthesize=True):
baseTypes = {'B':T_BYTE, 'C':T_CHAR, 'D':T_DOUBLE, 'F':T_FLOAT,
'I':T_INT, 'J':T_LONG, 'S':T_SHORT, 'Z':T_BOOL}
fields = []
while desc_str:
oldlen = len(desc_str)
desc_str = desc_str.lstrip('[')
dim = oldlen - len(desc_str)
if dim > 255:
raise ValueError('Dimension {} > 255 in descriptor'.format(dim))
if not desc_str:
raise ValueError('Descriptor contains [s at end of string')
if desc_str[0] == 'L':
end = desc_str.find(';')
if end == -1:
raise ValueError('Unmatched L in descriptor')
name = desc_str[1:end]
desc_str = desc_str[end+1:]
<|code_end|>
. Write the next line using the current file imports:
from .verifier_types import T_BYTE, T_CHAR, T_DOUBLE, T_FLOAT, T_INT, T_LONG, T_SHORT, T_BOOL, T_OBJECT, T_ARRAY
from .verifier_types import unSynthesizeType, cat2tops
and context from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# T_BYTE = _makeinfo('.byte')
#
# T_CHAR = _makeinfo('.char')
#
# T_DOUBLE = _makeinfo('.double')
#
# T_FLOAT = _makeinfo('.float')
#
# T_INT = _makeinfo('.int')
#
# T_LONG = _makeinfo('.long')
#
# T_SHORT = _makeinfo('.short')
#
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
#
# def T_OBJECT(name):
# return _makeinfo('.obj', extra=name)
#
# def T_ARRAY(baset, newDimensions=1):
# assert(0 <= baset.dim <= 255-newDimensions)
# return _makeinfo(baset.tag, baset.dim+newDimensions, baset.extra)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# def _makeinfo(tag, dim=0, extra=None):
# def T_ADDRESS(entry):
# def T_OBJECT(name):
# def T_ARRAY(baset, newDimensions=1):
# def T_UNINIT_OBJECT(origin):
# def objOrArray(fi): #False on uninitialized
# def unSynthesizeType(t):
# def decrementDim(fi):
# def withNoDimension(fi):
# def _decToObjArray(fi):
# def _arrbase(fi):
# def mergeTypes(env, t1, t2, forAssignment=False):
# def isAssignable(env, t1, t2):
# def vt_toStr(self):
# T_INVALID = _makeinfo(None)
# T_INT = _makeinfo('.int')
# T_FLOAT = _makeinfo('.float')
# T_DOUBLE = _makeinfo('.double')
# T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things
# T_LONG = _makeinfo('.long')
# T_LONG2 = _makeinfo('.long2')
# T_NULL = _makeinfo('.obj')
# T_UNINIT_THIS = _makeinfo('.init')
# T_BYTE = _makeinfo('.byte')
# T_SHORT = _makeinfo('.short')
# T_CHAR = _makeinfo('.char')
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
# OBJECT_INFO = T_OBJECT('java/lang/Object')
# CLONE_INFO = T_OBJECT('java/lang/Cloneable')
# SERIAL_INFO = T_OBJECT('java/io/Serializable')
# THROWABLE_INFO = T_OBJECT('java/lang/Throwable')
, which may include functions, classes, or code. Output only the next line. | baset = T_OBJECT(name) |
Given the following code snippet before the placeholder: <|code_start|> 'I':T_INT, 'J':T_LONG, 'S':T_SHORT, 'Z':T_BOOL}
fields = []
while desc_str:
oldlen = len(desc_str)
desc_str = desc_str.lstrip('[')
dim = oldlen - len(desc_str)
if dim > 255:
raise ValueError('Dimension {} > 255 in descriptor'.format(dim))
if not desc_str:
raise ValueError('Descriptor contains [s at end of string')
if desc_str[0] == 'L':
end = desc_str.find(';')
if end == -1:
raise ValueError('Unmatched L in descriptor')
name = desc_str[1:end]
desc_str = desc_str[end+1:]
baset = T_OBJECT(name)
else:
if desc_str[0] not in baseTypes:
raise ValueError('Unrecognized code {} in descriptor'.format(desc_str[0]))
baset = baseTypes[desc_str[0]]
desc_str = desc_str[1:]
if dim:
#Hotspot considers byte[] and bool[] identical for type checking purposes
if unsynthesize and baset == T_BOOL:
baset = T_BYTE
<|code_end|>
, predict the next line using imports from the current file:
from .verifier_types import T_BYTE, T_CHAR, T_DOUBLE, T_FLOAT, T_INT, T_LONG, T_SHORT, T_BOOL, T_OBJECT, T_ARRAY
from .verifier_types import unSynthesizeType, cat2tops
and context including class names, function names, and sometimes code from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# T_BYTE = _makeinfo('.byte')
#
# T_CHAR = _makeinfo('.char')
#
# T_DOUBLE = _makeinfo('.double')
#
# T_FLOAT = _makeinfo('.float')
#
# T_INT = _makeinfo('.int')
#
# T_LONG = _makeinfo('.long')
#
# T_SHORT = _makeinfo('.short')
#
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
#
# def T_OBJECT(name):
# return _makeinfo('.obj', extra=name)
#
# def T_ARRAY(baset, newDimensions=1):
# assert(0 <= baset.dim <= 255-newDimensions)
# return _makeinfo(baset.tag, baset.dim+newDimensions, baset.extra)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# def _makeinfo(tag, dim=0, extra=None):
# def T_ADDRESS(entry):
# def T_OBJECT(name):
# def T_ARRAY(baset, newDimensions=1):
# def T_UNINIT_OBJECT(origin):
# def objOrArray(fi): #False on uninitialized
# def unSynthesizeType(t):
# def decrementDim(fi):
# def withNoDimension(fi):
# def _decToObjArray(fi):
# def _arrbase(fi):
# def mergeTypes(env, t1, t2, forAssignment=False):
# def isAssignable(env, t1, t2):
# def vt_toStr(self):
# T_INVALID = _makeinfo(None)
# T_INT = _makeinfo('.int')
# T_FLOAT = _makeinfo('.float')
# T_DOUBLE = _makeinfo('.double')
# T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things
# T_LONG = _makeinfo('.long')
# T_LONG2 = _makeinfo('.long2')
# T_NULL = _makeinfo('.obj')
# T_UNINIT_THIS = _makeinfo('.init')
# T_BYTE = _makeinfo('.byte')
# T_SHORT = _makeinfo('.short')
# T_CHAR = _makeinfo('.char')
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
# OBJECT_INFO = T_OBJECT('java/lang/Object')
# CLONE_INFO = T_OBJECT('java/lang/Cloneable')
# SERIAL_INFO = T_OBJECT('java/io/Serializable')
# THROWABLE_INFO = T_OBJECT('java/lang/Throwable')
. Output only the next line. | baset = T_ARRAY(baset, dim) |
Next line prediction: <|code_start|> oldlen = len(desc_str)
desc_str = desc_str.lstrip('[')
dim = oldlen - len(desc_str)
if dim > 255:
raise ValueError('Dimension {} > 255 in descriptor'.format(dim))
if not desc_str:
raise ValueError('Descriptor contains [s at end of string')
if desc_str[0] == 'L':
end = desc_str.find(';')
if end == -1:
raise ValueError('Unmatched L in descriptor')
name = desc_str[1:end]
desc_str = desc_str[end+1:]
baset = T_OBJECT(name)
else:
if desc_str[0] not in baseTypes:
raise ValueError('Unrecognized code {} in descriptor'.format(desc_str[0]))
baset = baseTypes[desc_str[0]]
desc_str = desc_str[1:]
if dim:
#Hotspot considers byte[] and bool[] identical for type checking purposes
if unsynthesize and baset == T_BOOL:
baset = T_BYTE
baset = T_ARRAY(baset, dim)
elif unsynthesize:
#synthetics are only meaningful as basetype of an array
#if they are by themselves, convert to int.
<|code_end|>
. Use current file imports:
(from .verifier_types import T_BYTE, T_CHAR, T_DOUBLE, T_FLOAT, T_INT, T_LONG, T_SHORT, T_BOOL, T_OBJECT, T_ARRAY
from .verifier_types import unSynthesizeType, cat2tops)
and context including class names, function names, or small code snippets from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# T_BYTE = _makeinfo('.byte')
#
# T_CHAR = _makeinfo('.char')
#
# T_DOUBLE = _makeinfo('.double')
#
# T_FLOAT = _makeinfo('.float')
#
# T_INT = _makeinfo('.int')
#
# T_LONG = _makeinfo('.long')
#
# T_SHORT = _makeinfo('.short')
#
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
#
# def T_OBJECT(name):
# return _makeinfo('.obj', extra=name)
#
# def T_ARRAY(baset, newDimensions=1):
# assert(0 <= baset.dim <= 255-newDimensions)
# return _makeinfo(baset.tag, baset.dim+newDimensions, baset.extra)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# def _makeinfo(tag, dim=0, extra=None):
# def T_ADDRESS(entry):
# def T_OBJECT(name):
# def T_ARRAY(baset, newDimensions=1):
# def T_UNINIT_OBJECT(origin):
# def objOrArray(fi): #False on uninitialized
# def unSynthesizeType(t):
# def decrementDim(fi):
# def withNoDimension(fi):
# def _decToObjArray(fi):
# def _arrbase(fi):
# def mergeTypes(env, t1, t2, forAssignment=False):
# def isAssignable(env, t1, t2):
# def vt_toStr(self):
# T_INVALID = _makeinfo(None)
# T_INT = _makeinfo('.int')
# T_FLOAT = _makeinfo('.float')
# T_DOUBLE = _makeinfo('.double')
# T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things
# T_LONG = _makeinfo('.long')
# T_LONG2 = _makeinfo('.long2')
# T_NULL = _makeinfo('.obj')
# T_UNINIT_THIS = _makeinfo('.init')
# T_BYTE = _makeinfo('.byte')
# T_SHORT = _makeinfo('.short')
# T_CHAR = _makeinfo('.char')
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
# OBJECT_INFO = T_OBJECT('java/lang/Object')
# CLONE_INFO = T_OBJECT('java/lang/Cloneable')
# SERIAL_INFO = T_OBJECT('java/io/Serializable')
# THROWABLE_INFO = T_OBJECT('java/lang/Throwable')
. Output only the next line. | baset = unSynthesizeType(baset) |
Given snippet: <|code_start|> if dim > 255:
raise ValueError('Dimension {} > 255 in descriptor'.format(dim))
if not desc_str:
raise ValueError('Descriptor contains [s at end of string')
if desc_str[0] == 'L':
end = desc_str.find(';')
if end == -1:
raise ValueError('Unmatched L in descriptor')
name = desc_str[1:end]
desc_str = desc_str[end+1:]
baset = T_OBJECT(name)
else:
if desc_str[0] not in baseTypes:
raise ValueError('Unrecognized code {} in descriptor'.format(desc_str[0]))
baset = baseTypes[desc_str[0]]
desc_str = desc_str[1:]
if dim:
#Hotspot considers byte[] and bool[] identical for type checking purposes
if unsynthesize and baset == T_BOOL:
baset = T_BYTE
baset = T_ARRAY(baset, dim)
elif unsynthesize:
#synthetics are only meaningful as basetype of an array
#if they are by themselves, convert to int.
baset = unSynthesizeType(baset)
fields.append(baset)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .verifier_types import T_BYTE, T_CHAR, T_DOUBLE, T_FLOAT, T_INT, T_LONG, T_SHORT, T_BOOL, T_OBJECT, T_ARRAY
from .verifier_types import unSynthesizeType, cat2tops
and context:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# T_BYTE = _makeinfo('.byte')
#
# T_CHAR = _makeinfo('.char')
#
# T_DOUBLE = _makeinfo('.double')
#
# T_FLOAT = _makeinfo('.float')
#
# T_INT = _makeinfo('.int')
#
# T_LONG = _makeinfo('.long')
#
# T_SHORT = _makeinfo('.short')
#
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
#
# def T_OBJECT(name):
# return _makeinfo('.obj', extra=name)
#
# def T_ARRAY(baset, newDimensions=1):
# assert(0 <= baset.dim <= 255-newDimensions)
# return _makeinfo(baset.tag, baset.dim+newDimensions, baset.extra)
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/verifier_types.py
# def _makeinfo(tag, dim=0, extra=None):
# def T_ADDRESS(entry):
# def T_OBJECT(name):
# def T_ARRAY(baset, newDimensions=1):
# def T_UNINIT_OBJECT(origin):
# def objOrArray(fi): #False on uninitialized
# def unSynthesizeType(t):
# def decrementDim(fi):
# def withNoDimension(fi):
# def _decToObjArray(fi):
# def _arrbase(fi):
# def mergeTypes(env, t1, t2, forAssignment=False):
# def isAssignable(env, t1, t2):
# def vt_toStr(self):
# T_INVALID = _makeinfo(None)
# T_INT = _makeinfo('.int')
# T_FLOAT = _makeinfo('.float')
# T_DOUBLE = _makeinfo('.double')
# T_DOUBLE2 = _makeinfo('.double2') #Hotspot only uses these in locals, but we use them on the stack too to simplify things
# T_LONG = _makeinfo('.long')
# T_LONG2 = _makeinfo('.long2')
# T_NULL = _makeinfo('.obj')
# T_UNINIT_THIS = _makeinfo('.init')
# T_BYTE = _makeinfo('.byte')
# T_SHORT = _makeinfo('.short')
# T_CHAR = _makeinfo('.char')
# T_BOOL = _makeinfo('.boolean') #Hotspot doesn't have a bool type, but we can use this elsewhere
# OBJECT_INFO = T_OBJECT('java/lang/Object')
# CLONE_INFO = T_OBJECT('java/lang/Cloneable')
# SERIAL_INFO = T_OBJECT('java/io/Serializable')
# THROWABLE_INFO = T_OBJECT('java/lang/Throwable')
which might include code, classes, or functions. Output only the next line. | if baset in cat2tops: |
Predict the next line for this snippet: <|code_start|> S = set(innodes)
for old, new in dups:
for p in old.predecessors[:]:
if p in S:
old.predecessors.remove(p)
new.predecessors.append(p)
new.replaceSuccessors(dupmap)
for c in new.successors:
c.predecessors.append(new)
return zip(*dups)[1]
def createGraphProxy(ssagraph):
assert(not ssagraph.procs) #should have already been inlined
nodes = [BlockProxy(b.key, itertools.count(), block=b) for b in ssagraph.blocks]
allnodes = nodes[:] #will also contain indirected nodes
entryNode = None
intypes = ddict(set)
for n in nodes:
invars = [phi.rval for phi in n.block.phis]
for b, t in n.block.jump.getSuccessorPairs():
intypes[b.key].add(t)
if n.bkey == ssagraph.entryKey:
assert(not entryNode and not invars) #shouldn't have more than one entryBlock and entryBlock shouldn't have phis
entryNode = n
invars = ssagraph.inputArgs #store them in the node so we don't have to keep track seperately
invars = [x for x in invars if x is not None] #will have None placeholders for Long and Double arguments
<|code_end|>
with the help of current file imports:
import collections, itertools
from ..ssa import ssa_types
and context from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/ssa_types.py
# SSA_INT = 'int', 32
# SSA_LONG = 'int', 64
# SSA_FLOAT = 'float', fu.FLOAT_SIZE
# SSA_DOUBLE = 'float', fu.DOUBLE_SIZE
# SSA_OBJECT = 'obj',
# SSA_MONAD = 'monad',
# def verifierToSSAType(vtype):
# def __init__(self, key):
# def getSuccessors(self):
# def filterVarConstraints(self, keepvars):
# def removePredPair(self, pair):
# def replacePredPair(self, oldp, newp):
# def __str__(self):
# class BasicBlock(object):
, which may contain function names, class names, or code. Output only the next line. | n.invars = [v for v in invars if v.type != ssa_types.SSA_MONAD] |
Given the following code snippet before the placeholder: <|code_start|>
def loadConstValue(cpool, index):
entry_type = cpool.pool[index][0]
args = cpool.getArgs(index)
#Note: field constant values cannot be class literals
<|code_end|>
, predict the next line using imports from the current file:
import struct
import traceback
from ..ssa import objtypes
from ..verifier.descriptors import parseFieldDescriptor
from . import ast, ast2, javamethod, throws
from .reserved import reserved_identifiers
and context including class names, function names, and sometimes code from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/descriptors.py
# def parseFieldDescriptor(desc_str, unsynthesize=True):
# rval = parseFieldDescriptors(desc_str, unsynthesize)
#
# cat = 2 if (rval and rval[0] in cat2tops) else 1
# if len(rval) != cat:
# raise ValueError('Incorrect number of fields in descriptor, expected {} but found {}'.format(cat, len(rval)))
# return rval
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/reserved.py
. Output only the next line. | tt = {'Int':objtypes.IntTT, 'Long':objtypes.LongTT, |
Given snippet: <|code_start|>
def loadConstValue(cpool, index):
entry_type = cpool.pool[index][0]
args = cpool.getArgs(index)
#Note: field constant values cannot be class literals
tt = {'Int':objtypes.IntTT, 'Long':objtypes.LongTT,
'Float':objtypes.FloatTT, 'Double':objtypes.DoubleTT,
'String':objtypes.StringTT}[entry_type]
return ast.Literal(tt, args[0])
def _getField(field):
flags = [x.lower() for x in sorted(field.flags) if x not in ('SYNTHETIC','ENUM')]
desc = field.descriptor
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import struct
import traceback
from ..ssa import objtypes
from ..verifier.descriptors import parseFieldDescriptor
from . import ast, ast2, javamethod, throws
from .reserved import reserved_identifiers
and context:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/descriptors.py
# def parseFieldDescriptor(desc_str, unsynthesize=True):
# rval = parseFieldDescriptors(desc_str, unsynthesize)
#
# cat = 2 if (rval and rval[0] in cat2tops) else 1
# if len(rval) != cat:
# raise ValueError('Incorrect number of fields in descriptor, expected {} but found {}'.format(cat, len(rval)))
# return rval
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/reserved.py
which might include code, classes, or functions. Output only the next line. | dtype = objtypes.verifierToSynthetic(parseFieldDescriptor(desc, unsynthesize=False)[0]) |
Next line prediction: <|code_start|> initexpr = None
if field.static:
cpool = field.class_.cpool
const_attrs = [data for name,data in field.attributes if name == 'ConstantValue']
if const_attrs:
assert(len(const_attrs) == 1)
data = const_attrs[0]
index = struct.unpack('>h', data)[0]
initexpr = loadConstValue(cpool, index)
return ast2.FieldDef(' '.join(flags), ast.TypeName(dtype), field.class_, field.name, desc, initexpr)
def _getMethod(method, cb, forbidden_identifiers, skip_errors):
try:
graph = cb(method) if method.code is not None else None
print 'Decompiling method', method.name.encode('utf8'), method.descriptor.encode('utf8')
code_ast = javamethod.generateAST(method, graph, forbidden_identifiers)
return code_ast
except Exception as e:
if not skip_errors:
raise
message = traceback.format_exc()
code_ast = javamethod.generateAST(method, None, forbidden_identifiers)
code_ast.comments.add(message)
print message
return code_ast
# Method argument allows decompilng only a single method, primarily useful for debugging
def generateAST(cls, cb, skip_errors, method=None, add_throws=False):
methods = cls.methods if method is None else [cls.methods[method]]
<|code_end|>
. Use current file imports:
(import struct
import traceback
from ..ssa import objtypes
from ..verifier.descriptors import parseFieldDescriptor
from . import ast, ast2, javamethod, throws
from .reserved import reserved_identifiers)
and context including class names, function names, or small code snippets from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/ssa/objtypes.py
# def TypeTT(baset, dim):
# def baset(tt): return tt[0]
# def dim(tt): return tt[1]
# def withDimInc(tt, inc): return TypeTT(baset(tt), dim(tt)+inc)
# def withNoDim(tt): return TypeTT(baset(tt), 0)
# def isBaseTClass(tt): return not baset(tt).startswith('.')
# def className(tt): return baset(tt) if not baset(tt).startswith('.') else None
# def primName(tt): return baset(tt)[1:] if baset(tt).startswith('.') else None
# def isSubtype(env, x, y):
# def commonSupertype(env, tts):
# def verifierToSynthetic_seq(vtypes):
# def verifierToSynthetic(vtype):
# def declTypeToActual(env, decltype):
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/verifier/descriptors.py
# def parseFieldDescriptor(desc_str, unsynthesize=True):
# rval = parseFieldDescriptors(desc_str, unsynthesize)
#
# cat = 2 if (rval and rval[0] in cat2tops) else 1
# if len(rval) != cat:
# raise ValueError('Incorrect number of fields in descriptor, expected {} but found {}'.format(cat, len(rval)))
# return rval
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/java/reserved.py
. Output only the next line. | fi = set(reserved_identifiers) |
Given snippet: <|code_start|> token_t = tokenize.wordget[name]
if token_t == 'OP_LBL':
assert(len(args) == 1)
args[0] = getlbl(args[0]+pos)
elif token_t in funcs:
args[0] = funcs[token_t](args[0])
parts = [name] + map(str, args)
return '\t' + ' '.join(parts)
def disMethodCode(code, add, poolm):
if code is None:
return
add('\t; method code size: {} bytes'.format(code.codelen))
add('\t.limit stack {}'.format(code.stack))
add('\t.limit locals {}'.format(code.locals))
lbls = set()
def getlbl(x):
lbls.add(x)
return 'L'+str(x)
for e in code.except_raw:
parts = poolm.classref(e.type_ind), getlbl(e.start), getlbl(e.end), getlbl(e.handler)
add('\t.catch {} from {} to {} using {}'.format(*parts))
code_attributes = getAttributesDict(code)
frames = getStackMapTable(code_attributes, poolm, getlbl)
instrs = []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import re
from . import instructions, tokenize, parse, assembler, codes
from ..binUnpacker import binUnpacker
from ..classfile import ClassFile
and context:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/binUnpacker.py
# class binUnpacker(object):
# def __init__(self, data="", fileName=""):
# if fileName:
# self.bytes = open(fileName,'rb').read()
# else:
# self.bytes = data
# self.off = 0
#
# def get(self, fmt, forceTuple=False, peek=False):
# val = struct.unpack_from(fmt, self.bytes, self.off)
#
# if not peek:
# self.off += struct.calcsize(fmt)
# if not forceTuple and len(val) == 1:
# val = val[0]
# return val
#
# def getRaw(self, num):
# val = self.bytes[self.off:self.off+num]
# self.off += num
# return val
#
# def size(self):
# return len(self.bytes) - self.off
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/classfile.py
# class ClassFile(object):
# flagVals = {'PUBLIC':0x0001,
# 'FINAL':0x0010,
# 'SUPER':0x0020,
# 'INTERFACE':0x0200,
# 'ABSTRACT':0x0400,
# 'SYNTHETIC':0x1000,
# 'ANNOTATION':0x2000,
# 'ENUM':0x4000,
#
# # These flags are only used for InnerClasses attributes
# 'PRIVATE':0x0002,
# 'PROTECTED':0x0004,
# 'STATIC':0x0008,
# }
#
# def __init__(self, bytestream):
# magic, minor, major = bytestream.get('>LHH')
# assert(magic == 0xCAFEBABE)
# self.version = major,minor
#
# const_pool_raw = get_cp_raw(bytestream)
# flags, self.this, self.super = bytestream.get('>HHH')
#
# interface_count = bytestream.get('>H')
# self.interfaces_raw = [bytestream.get('>H') for _ in range(interface_count)]
#
# self.fields_raw = get_fields_raw(bytestream)
# self.methods_raw = get_methods_raw(bytestream)
#
# ic_indices = [i for i,x in enumerate(const_pool_raw) if x == (1, ("InnerClasses",))]
# self.attributes_raw = get_attributes_raw(bytestream, ic_indices)
# assert(bytestream.size() == 0)
#
# self.flags = frozenset(name for name,mask in ClassFile.flagVals.items() if (mask & flags))
# self.cpool = constant_pool.ConstPool(const_pool_raw)
# self.name = self.cpool.getArgsCheck('Class', self.this)
# self.elementsLoaded = False
#
# self.env = self.supername = self.hierarchy = None
# self.fields = self.methods = self.attributes = None
# self.all_interfaces = None
#
# def loadSupers(self, env, name, subclasses):
# self.env = env
# assert(self.name == name)
#
# if self.super:
# self.supername = self.cpool.getArgsCheck('Class', self.super)
# superclass = self.env.getClass(self.supername, subclasses + (name,), partial=True)
# self.hierarchy = superclass.hierarchy + (self.name,)
#
# # Now get all interfaces for this class (recursively)
# interfaces = self.env.getInterfaces(self.supername)
# if 'INTERFACE' in self.flags:
# interfaces |= {self.name}
# for index in self.interfaces_raw:
# iname = self.cpool.getArgsCheck('Class', index)
# if iname not in interfaces:
# interfaces |= self.env.getInterfaces(iname)
# self.all_interfaces = interfaces
# else:
# assert(name == 'java/lang/Object')
# self.supername = None
# self.hierarchy = (self.name,)
# self.all_interfaces = frozenset()
#
# def loadElements(self, keepRaw=False):
# if self.elementsLoaded:
# return
# self.fields = [field.Field(m, self, keepRaw) for m in self.fields_raw]
# self.methods = [method.Method(m, self, keepRaw) for m in self.methods_raw]
# self.attributes = fixAttributeNames(self.attributes_raw, self.cpool)
#
# self.fields_raw = self.methods_raw = None
# if not keepRaw:
# self.attributes_raw = None
# self.elementsLoaded = True
#
# def getSuperclassHierarchy(self):
# return self.hierarchy
which might include code, classes, or functions. Output only the next line. | b = binUnpacker(code.bytecode_raw) |
Based on the snippet: <|code_start|> elif tag == 'enum':
val = poolm.utfref(bytes_.get('>H')) + ' ' + poolm.utfref(bytes_.get('>H'))
elif tag == 'array':
val = ''
add(indent + '{} {} {}'.format(prefix, tag, val))
if tag == 'array':
for _ in range(bytes_.get('>H')):
stack.append((C_EV, '', indent+'\t'))
stack.append((C_EV2, None, indent))
elif callt == C_EV2:
add(indent + '.end array')
def disElementValue(bytes_, prefix, add, poolm, indent):
_disEVorAnnotationSub(bytes_, add, poolm, False, prefix, indent)
def disAnnotation(bytes_, prefix, add, poolm, indent):
_disEVorAnnotationSub(bytes_, add, poolm, True, prefix, indent)
#Todo - make fields automatically unpack this themselves
def getConstValue(field):
if not field.static:
return None
const_attrs = [attr for attr in field.attributes if attr[0] == 'ConstantValue']
if const_attrs:
assert(len(const_attrs) == 1)
bytes_ = binUnpacker(const_attrs[0][1])
return bytes_.get('>H')
<|code_end|>
, predict the immediate next line with the help of imports:
import collections
import re
from . import instructions, tokenize, parse, assembler, codes
from ..binUnpacker import binUnpacker
from ..classfile import ClassFile
and context (classes, functions, sometimes code) from other files:
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/binUnpacker.py
# class binUnpacker(object):
# def __init__(self, data="", fileName=""):
# if fileName:
# self.bytes = open(fileName,'rb').read()
# else:
# self.bytes = data
# self.off = 0
#
# def get(self, fmt, forceTuple=False, peek=False):
# val = struct.unpack_from(fmt, self.bytes, self.off)
#
# if not peek:
# self.off += struct.calcsize(fmt)
# if not forceTuple and len(val) == 1:
# val = val[0]
# return val
#
# def getRaw(self, num):
# val = self.bytes[self.off:self.off+num]
# self.off += num
# return val
#
# def size(self):
# return len(self.bytes) - self.off
#
# Path: krakatau-lib/src/main/resources/Lib/Krakatau/classfile.py
# class ClassFile(object):
# flagVals = {'PUBLIC':0x0001,
# 'FINAL':0x0010,
# 'SUPER':0x0020,
# 'INTERFACE':0x0200,
# 'ABSTRACT':0x0400,
# 'SYNTHETIC':0x1000,
# 'ANNOTATION':0x2000,
# 'ENUM':0x4000,
#
# # These flags are only used for InnerClasses attributes
# 'PRIVATE':0x0002,
# 'PROTECTED':0x0004,
# 'STATIC':0x0008,
# }
#
# def __init__(self, bytestream):
# magic, minor, major = bytestream.get('>LHH')
# assert(magic == 0xCAFEBABE)
# self.version = major,minor
#
# const_pool_raw = get_cp_raw(bytestream)
# flags, self.this, self.super = bytestream.get('>HHH')
#
# interface_count = bytestream.get('>H')
# self.interfaces_raw = [bytestream.get('>H') for _ in range(interface_count)]
#
# self.fields_raw = get_fields_raw(bytestream)
# self.methods_raw = get_methods_raw(bytestream)
#
# ic_indices = [i for i,x in enumerate(const_pool_raw) if x == (1, ("InnerClasses",))]
# self.attributes_raw = get_attributes_raw(bytestream, ic_indices)
# assert(bytestream.size() == 0)
#
# self.flags = frozenset(name for name,mask in ClassFile.flagVals.items() if (mask & flags))
# self.cpool = constant_pool.ConstPool(const_pool_raw)
# self.name = self.cpool.getArgsCheck('Class', self.this)
# self.elementsLoaded = False
#
# self.env = self.supername = self.hierarchy = None
# self.fields = self.methods = self.attributes = None
# self.all_interfaces = None
#
# def loadSupers(self, env, name, subclasses):
# self.env = env
# assert(self.name == name)
#
# if self.super:
# self.supername = self.cpool.getArgsCheck('Class', self.super)
# superclass = self.env.getClass(self.supername, subclasses + (name,), partial=True)
# self.hierarchy = superclass.hierarchy + (self.name,)
#
# # Now get all interfaces for this class (recursively)
# interfaces = self.env.getInterfaces(self.supername)
# if 'INTERFACE' in self.flags:
# interfaces |= {self.name}
# for index in self.interfaces_raw:
# iname = self.cpool.getArgsCheck('Class', index)
# if iname not in interfaces:
# interfaces |= self.env.getInterfaces(iname)
# self.all_interfaces = interfaces
# else:
# assert(name == 'java/lang/Object')
# self.supername = None
# self.hierarchy = (self.name,)
# self.all_interfaces = frozenset()
#
# def loadElements(self, keepRaw=False):
# if self.elementsLoaded:
# return
# self.fields = [field.Field(m, self, keepRaw) for m in self.fields_raw]
# self.methods = [method.Method(m, self, keepRaw) for m in self.methods_raw]
# self.attributes = fixAttributeNames(self.attributes_raw, self.cpool)
#
# self.fields_raw = self.methods_raw = None
# if not keepRaw:
# self.attributes_raw = None
# self.elementsLoaded = True
#
# def getSuperclassHierarchy(self):
# return self.hierarchy
. Output only the next line. | _classflags = [(v,k.lower()) for k,v in ClassFile.flagVals.items()] |
Using the snippet: <|code_start|>
def compute_photon_energy(nm_axis):
"""Return the photon energy (in erg) computed for all the wavelength along
a given wavelength axis.
:param nm_axis: Wavelength axis in nm
"""
return (orb.constants.PLANCK
* orb.constants.LIGHT_VEL_KMS * 1e12
/ nm_axis)
def compute_equivalent_bandwidth(nm_axis, filter_transmission):
"""Return the equivalent bandwidth of a given filter.
:param nm_axis: Filter transmission axis in nm.
:param filter_transmission: Filter transmission curve
"""
return np.nansum(np.diff(nm_axis) * filter_transmission[:-1]
/ np.nanmax(filter_transmission))
def compute_star_central_pixel_value(seeing, plate_scale):
"""Return the relative value of the pixel containing the greatest
proportion of the flux (central pixel) of Gaussian star.
:param seeing: Star FWHM in arcsec
:param plate_scale: Size of the pixels in arcsec.
"""
N = 100
fwhm_pix = seeing / plate_scale
<|code_end|>
, determine the next line of code. You have imports:
import logging
import math
import numpy as np
import warnings
import orb.constants
import scipy.interpolate
import scipy.optimize
import orb.utils.spectrum
from orb.utils.astrometry import Gaussian
and context (class names, function names, or code) available:
# Path: orb/utils/astrometry.py
# class Gaussian(PSF):
# """Class implementing the gaussian profile
#
# .. note:: The Gaussian profile used here is:
# :math:`f(x,y) = H + A \\times \exp(\\frac{-r^2}{2 W^2})`
#
# and,
# :math:`r = (x - dx)^2 + (y - dy)^2`
#
# The total flux F under the 2D profile is:
# :math:`F = 2 \\pi A W^2`
#
# """
#
#
# input_params = list(['height', 'amplitude', 'x', 'y', 'fwhm'])
# """Keys of the input parameters"""
#
# params = dict()
# """dictionary containing the parameters of the profile"""
#
# width = None # Width = FWHM / abs(2.*sqrt(2. * log(2.)))
#
#
# def __init__(self, params):
# """Init Gaussian profile parameters
#
# :param params: Input parameters of the Gaussian profile. Input
# parameters can be given as a dictionary providing {'height',
# 'amplitude', 'x', 'y', 'fwhm'} or an array of 5
# elements stored in this order: ['height', 'amplitude', 'x',
# 'y', 'fwhm']
# """
#
# self.params = dict()
# if isinstance(params, dict):
# if (set([key for key in params.keys()])
# & set(self.input_params) == set(self.input_params)):
# self.params['height'] = float(params['height'])
# self.params['amplitude'] = float(params['amplitude'])
# self.params['x'] = float(params['x'])
# self.params['y'] = float(params['y'])
# self.params['fwhm'] = abs(float(params['fwhm']))
# else:
# raise ValueError("Input dictionary is not valid. You must provide a dictionary containing all those keys : %s"%str(self.input_params))
#
# elif (np.size(params) == np.size(self.input_params)):
# self.params['height'] = float(params[0])
# self.params['amplitude'] = float(params[1])
# self.params['x'] = float(params[2])
# self.params['y'] = float(params[3])
# self.params['fwhm'] = abs(float(params[4]))
#
# else:
# raise ValueError('Invalid input parameters')
#
#
# self.width = self.params['fwhm'] / abs(2.*math.sqrt(2. * math.log(2.)))
# self.params['flux'] = self.flux()
#
#
# # 1-D PSF function
# self.psf = lambda r: (
# self.params['height'] + self.params['amplitude']
# * np.exp(-(r)**2./(2.*self.width**2.)))
#
# # 2-D PSF function
# self.psf2d = lambda x, y: (
# self.psf(np.sqrt((x-self.params['x'])**2.
# +(y-self.params['y'])**2.)))
#
#
# def flux(self):
# """Return the total flux under the 2D profile.
#
# The total flux F under a 2D profile is :
# :math:`F = 2 \\pi A W^2`
#
# .. note:: Under a 1d profile the flux is :math:`F = \\sqrt{2\\pi}A W`
# """
# return 2. * self.params['amplitude'] * (self.width)**2 * math.pi
#
# def flux_error(self, amplitude_err, width_err):
# """Return flux error.
#
# :param amplitude_err: estimation of the amplitude error
#
# :param width_err: estimation of the width error
# """
# return self.flux() * math.sqrt(
# (amplitude_err / self.params['amplitude'])**2.
# + 2. * (width_err / self.width)**2.)
#
# def array2d(self, nx, ny):
# """Return a 2D profile given the size of the returned
# array.
#
# :param nx: Length of the returned array along x axis
# :param ny: Length of the returned array along y axis
# """
# return np.array(orb.cutils.gaussian_array2d(float(self.params['height']),
# float(self.params['amplitude']),
# float(self.params['x']),
# float(self.params['y']),
# float(self.params['fwhm']),
# int(nx), int(ny)))
. Output only the next line. | star = Gaussian([0,1,N/2,N/2,fwhm_pix]).array2d(N,N) |
Given the code snippet: <|code_start|>
def create_triggers(cls):
sa.event.listen(
cls.__table__,
'after_create',
sa.schema.DDL(
procedure_sql.format(
temporary_transaction_sql=CreateTemporaryTransactionTableSQL(),
insert_temporary_transaction_sql=(
InsertTemporaryTransactionSQL(
transaction_id_values='NEW.id'
)
),
)
)
)
sa.event.listen(
cls.__table__,
'after_create',
sa.schema.DDL(str(TransactionTriggerSQL(cls)))
)
sa.event.listen(
cls.__table__,
'after_drop',
sa.schema.DDL(
'DROP FUNCTION IF EXISTS transaction_temp_table_generator()'
)
)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from functools import partial
from collections import OrderedDict
from ordereddict import OrderedDict
from sqlalchemy.ext.compiler import compiles
from .dialects.postgresql import (
CreateTemporaryTransactionTableSQL,
InsertTemporaryTransactionSQL,
TransactionTriggerSQL
)
from .exc import ImproperlyConfigured
from .factory import ModelFactory
import six
import sqlalchemy as sa
and context (functions, classes, or occasionally code) from other files:
# Path: sqlalchemy_continuum/factory.py
# class ModelFactory(object):
# model_name = None
#
# def __call__(self, manager):
# """
# Create model class but only if it doesn't already exist
# in declarative model registry.
# """
# Base = manager.declarative_base
# try:
# registry = Base.registry._class_registry
# except AttributeError: # SQLAlchemy < 1.4
# registry = Base._decl_class_registry
# if self.model_name not in registry:
# return self.create_class(manager)
# return registry[self.model_name]
. Output only the next line. | class TransactionFactory(ModelFactory): |
Here is a snippet: <|code_start|> Activity.target == article
)
)
.. _activity stream specification:
http://www.activitystrea.ms
.. _generic relationships:
https://sqlalchemy-utils.readthedocs.io/en/latest/generic_relationship.html
"""
class ActivityBase(object):
id = sa.Column(
sa.BigInteger,
sa.schema.Sequence('activity_id_seq'),
primary_key=True,
autoincrement=True
)
verb = sa.Column(sa.Unicode(255))
@hybrid_property
def actor(self):
return self.transaction.user
<|code_end|>
. Write the next line using the current file imports:
import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.inspection import inspect
from sqlalchemy_utils import JSONType, generic_relationship
from .base import Plugin
from ..factory import ModelFactory
from ..utils import version_class, version_obj
and context from other files:
# Path: sqlalchemy_continuum/factory.py
# class ModelFactory(object):
# model_name = None
#
# def __call__(self, manager):
# """
# Create model class but only if it doesn't already exist
# in declarative model registry.
# """
# Base = manager.declarative_base
# try:
# registry = Base.registry._class_registry
# except AttributeError: # SQLAlchemy < 1.4
# registry = Base._decl_class_registry
# if self.model_name not in registry:
# return self.create_class(manager)
# return registry[self.model_name]
#
# Path: sqlalchemy_continuum/utils.py
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def version_obj(session, parent_obj):
# manager = get_versioning_manager(parent_obj)
# uow = manager.unit_of_work(session)
# for version_obj in uow.version_session:
# if (
# parent_class(version_obj.__class__) == parent_obj.__class__ and
# identity(version_obj)[:-1] == identity(parent_obj)
# ):
# return version_obj
, which may include functions, classes, or code. Output only the next line. | class ActivityFactory(ModelFactory): |
Continue the code snippet: <|code_start|> manager = self
transaction_id = sa.Column(
sa.BigInteger,
index=True,
nullable=False
)
data = sa.Column(JSONType)
object_type = sa.Column(sa.String(255))
object_id = sa.Column(sa.BigInteger)
object_tx_id = sa.Column(sa.BigInteger)
target_type = sa.Column(sa.String(255))
target_id = sa.Column(sa.BigInteger)
target_tx_id = sa.Column(sa.BigInteger)
def _calculate_tx_id(self, obj):
session = sa.orm.object_session(self)
if obj:
object_version = version_obj(session, obj)
if object_version:
return object_version.transaction_id
model = obj.__class__
<|code_end|>
. Use current file imports:
import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.inspection import inspect
from sqlalchemy_utils import JSONType, generic_relationship
from .base import Plugin
from ..factory import ModelFactory
from ..utils import version_class, version_obj
and context (classes, functions, or code) from other files:
# Path: sqlalchemy_continuum/factory.py
# class ModelFactory(object):
# model_name = None
#
# def __call__(self, manager):
# """
# Create model class but only if it doesn't already exist
# in declarative model registry.
# """
# Base = manager.declarative_base
# try:
# registry = Base.registry._class_registry
# except AttributeError: # SQLAlchemy < 1.4
# registry = Base._decl_class_registry
# if self.model_name not in registry:
# return self.create_class(manager)
# return registry[self.model_name]
#
# Path: sqlalchemy_continuum/utils.py
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def version_obj(session, parent_obj):
# manager = get_versioning_manager(parent_obj)
# uow = manager.unit_of_work(session)
# for version_obj in uow.version_session:
# if (
# parent_class(version_obj.__class__) == parent_obj.__class__ and
# identity(version_obj)[:-1] == identity(parent_obj)
# ):
# return version_obj
. Output only the next line. | version_cls = version_class(model) |
Using the snippet: <|code_start|> class Activity(
manager.declarative_base,
ActivityBase
):
__tablename__ = 'activity'
manager = self
transaction_id = sa.Column(
sa.BigInteger,
index=True,
nullable=False
)
data = sa.Column(JSONType)
object_type = sa.Column(sa.String(255))
object_id = sa.Column(sa.BigInteger)
object_tx_id = sa.Column(sa.BigInteger)
target_type = sa.Column(sa.String(255))
target_id = sa.Column(sa.BigInteger)
target_tx_id = sa.Column(sa.BigInteger)
def _calculate_tx_id(self, obj):
session = sa.orm.object_session(self)
if obj:
<|code_end|>
, determine the next line of code. You have imports:
import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.inspection import inspect
from sqlalchemy_utils import JSONType, generic_relationship
from .base import Plugin
from ..factory import ModelFactory
from ..utils import version_class, version_obj
and context (class names, function names, or code) available:
# Path: sqlalchemy_continuum/factory.py
# class ModelFactory(object):
# model_name = None
#
# def __call__(self, manager):
# """
# Create model class but only if it doesn't already exist
# in declarative model registry.
# """
# Base = manager.declarative_base
# try:
# registry = Base.registry._class_registry
# except AttributeError: # SQLAlchemy < 1.4
# registry = Base._decl_class_registry
# if self.model_name not in registry:
# return self.create_class(manager)
# return registry[self.model_name]
#
# Path: sqlalchemy_continuum/utils.py
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def version_obj(session, parent_obj):
# manager = get_versioning_manager(parent_obj)
# uow = manager.unit_of_work(session)
# for version_obj in uow.version_session:
# if (
# parent_class(version_obj.__class__) == parent_obj.__class__ and
# identity(version_obj)[:-1] == identity(parent_obj)
# ):
# return version_obj
. Output only the next line. | object_version = version_obj(session, obj) |
Predict the next line after this snippet: <|code_start|> ).group_by(
*association_cols
).having(
sa.func.max(association_table_alias.c[tx_column]) ==
self.association_version_table.c[tx_column]
).correlate(self.association_version_table)
)
return sa.exists(
sa.select(
[1]
).where(
sa.and_(
reflector(self.property.primaryjoin),
association_exists,
self.association_version_table.c.operation_type !=
Operation.DELETE,
adapt_columns(self.property.secondaryjoin),
)
).correlate(self.local_cls, self.remote_cls)
)
def build_association_version_tables(self):
"""
Builds many-to-many association version table for given property.
Association version tables are used for tracking change history of
many-to-many associations.
"""
column = list(self.property.remote_side)[0]
self.manager.association_tables.add(column.table)
<|code_end|>
using the current file's imports:
import sqlalchemy as sa
from .exc import ClassNotVersioned
from .expression_reflector import VersionExpressionReflector
from .operation import Operation
from .table_builder import TableBuilder
from .utils import adapt_columns, version_class, option
and any relevant context from other files:
# Path: sqlalchemy_continuum/table_builder.py
# class TableBuilder(object):
# """
# TableBuilder handles the building of version tables based on parent
# table's structure and versioning configuration options.
# """
# def __init__(
# self,
# versioning_manager,
# parent_table,
# model=None
# ):
# self.manager = versioning_manager
# self.parent_table = parent_table
# self.model = model
#
# def option(self, name):
# try:
# return self.manager.option(self.model, name)
# except TypeError:
# return self.manager.options[name]
#
# @property
# def table_name(self):
# """
# Returns the version table name for current parent table.
# """
# return self.option('table_name') % self.parent_table.name
#
# @property
# def columns(self):
# return list(
# column for column in
# ColumnReflector(self.manager, self.parent_table, self.model)
# )
#
# def __call__(self, extends=None):
# """
# Builds version table.
# """
# columns = self.columns if extends is None else []
# self.manager.plugins.after_build_version_table_columns(self, columns)
# return sa.schema.Table(
# extends.name if extends is not None else self.table_name,
# self.parent_table.metadata,
# *columns,
# schema=self.parent_table.schema,
# extend_existing=extends is not None
# )
#
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
. Output only the next line. | builder = TableBuilder( |
Given snippet: <|code_start|>
association_exists = sa.exists(
sa.select(
[1]
).where(
sa.and_(
association_table_alias.c[tx_column] <=
getattr(obj, tx_column),
association_table_alias.c[join_column] == getattr(obj, object_join_column),
*[association_col ==
self.association_version_table.c[association_col.name]
for association_col
in association_cols]
)
).group_by(
*association_cols
).having(
sa.func.max(association_table_alias.c[tx_column]) ==
self.association_version_table.c[tx_column]
).correlate(self.association_version_table)
)
return sa.exists(
sa.select(
[1]
).where(
sa.and_(
reflector(self.property.primaryjoin),
association_exists,
self.association_version_table.c.operation_type !=
Operation.DELETE,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sqlalchemy as sa
from .exc import ClassNotVersioned
from .expression_reflector import VersionExpressionReflector
from .operation import Operation
from .table_builder import TableBuilder
from .utils import adapt_columns, version_class, option
and context:
# Path: sqlalchemy_continuum/table_builder.py
# class TableBuilder(object):
# """
# TableBuilder handles the building of version tables based on parent
# table's structure and versioning configuration options.
# """
# def __init__(
# self,
# versioning_manager,
# parent_table,
# model=None
# ):
# self.manager = versioning_manager
# self.parent_table = parent_table
# self.model = model
#
# def option(self, name):
# try:
# return self.manager.option(self.model, name)
# except TypeError:
# return self.manager.options[name]
#
# @property
# def table_name(self):
# """
# Returns the version table name for current parent table.
# """
# return self.option('table_name') % self.parent_table.name
#
# @property
# def columns(self):
# return list(
# column for column in
# ColumnReflector(self.manager, self.parent_table, self.model)
# )
#
# def __call__(self, extends=None):
# """
# Builds version table.
# """
# columns = self.columns if extends is None else []
# self.manager.plugins.after_build_version_table_columns(self, columns)
# return sa.schema.Table(
# extends.name if extends is not None else self.table_name,
# self.parent_table.metadata,
# *columns,
# schema=self.parent_table.schema,
# extend_existing=extends is not None
# )
#
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
which might include code, classes, or functions. Output only the next line. | adapt_columns(self.property.secondaryjoin), |
Given the code snippet: <|code_start|> many-to-many associations.
"""
column = list(self.property.remote_side)[0]
self.manager.association_tables.add(column.table)
builder = TableBuilder(
self.manager,
column.table
)
metadata = column.table.metadata
if builder.parent_table.schema:
table_name = builder.parent_table.schema + '.' + builder.table_name
elif metadata.schema:
table_name = metadata.schema + '.' + builder.table_name
else:
table_name = builder.table_name
if table_name not in metadata.tables:
self.association_version_table = table = builder()
self.manager.association_version_tables.add(table)
else:
# may have already been created if we visiting the 'other' side of
# a self-referential many-to-many relationship
self.association_version_table = metadata.tables[table_name]
def __call__(self):
"""
Builds reflected relationship between version classes based on given
parent object's RelationshipProperty.
"""
<|code_end|>
, generate the next line using the imports in this file:
import sqlalchemy as sa
from .exc import ClassNotVersioned
from .expression_reflector import VersionExpressionReflector
from .operation import Operation
from .table_builder import TableBuilder
from .utils import adapt_columns, version_class, option
and context (functions, classes, or occasionally code) from other files:
# Path: sqlalchemy_continuum/table_builder.py
# class TableBuilder(object):
# """
# TableBuilder handles the building of version tables based on parent
# table's structure and versioning configuration options.
# """
# def __init__(
# self,
# versioning_manager,
# parent_table,
# model=None
# ):
# self.manager = versioning_manager
# self.parent_table = parent_table
# self.model = model
#
# def option(self, name):
# try:
# return self.manager.option(self.model, name)
# except TypeError:
# return self.manager.options[name]
#
# @property
# def table_name(self):
# """
# Returns the version table name for current parent table.
# """
# return self.option('table_name') % self.parent_table.name
#
# @property
# def columns(self):
# return list(
# column for column in
# ColumnReflector(self.manager, self.parent_table, self.model)
# )
#
# def __call__(self, extends=None):
# """
# Builds version table.
# """
# columns = self.columns if extends is None else []
# self.manager.plugins.after_build_version_table_columns(self, columns)
# return sa.schema.Table(
# extends.name if extends is not None else self.table_name,
# self.parent_table.metadata,
# *columns,
# schema=self.parent_table.schema,
# extend_existing=extends is not None
# )
#
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
. Output only the next line. | self.local_cls = version_class(self.model) |
Continue the code snippet: <|code_start|>
class RelationshipBuilder(object):
def __init__(self, versioning_manager, model, property_):
self.manager = versioning_manager
self.property = property_
self.model = model
def one_to_many_subquery(self, obj):
<|code_end|>
. Use current file imports:
import sqlalchemy as sa
from .exc import ClassNotVersioned
from .expression_reflector import VersionExpressionReflector
from .operation import Operation
from .table_builder import TableBuilder
from .utils import adapt_columns, version_class, option
and context (classes, functions, or code) from other files:
# Path: sqlalchemy_continuum/table_builder.py
# class TableBuilder(object):
# """
# TableBuilder handles the building of version tables based on parent
# table's structure and versioning configuration options.
# """
# def __init__(
# self,
# versioning_manager,
# parent_table,
# model=None
# ):
# self.manager = versioning_manager
# self.parent_table = parent_table
# self.model = model
#
# def option(self, name):
# try:
# return self.manager.option(self.model, name)
# except TypeError:
# return self.manager.options[name]
#
# @property
# def table_name(self):
# """
# Returns the version table name for current parent table.
# """
# return self.option('table_name') % self.parent_table.name
#
# @property
# def columns(self):
# return list(
# column for column in
# ColumnReflector(self.manager, self.parent_table, self.model)
# )
#
# def __call__(self, extends=None):
# """
# Builds version table.
# """
# columns = self.columns if extends is None else []
# self.manager.plugins.after_build_version_table_columns(self, columns)
# return sa.schema.Table(
# extends.name if extends is not None else self.table_name,
# self.parent_table.metadata,
# *columns,
# schema=self.parent_table.schema,
# extend_existing=extends is not None
# )
#
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
. Output only the next line. | tx_column = option(obj, 'transaction_column_name') |
Using the snippet: <|code_start|> if not hasattr(self.version_class, 'transaction'):
self.version_class.transaction = sa.orm.relationship(
tx_class,
primaryjoin=tx_class.id == transaction_column,
foreign_keys=[transaction_column],
)
def base_classes(self):
"""
Returns all base classes for history model.
"""
return (version_base(self.manager, self.model), )
def inheritance_args(self, cls, version_table, table):
"""
Return mapper inheritance args for currently built history model.
"""
args = {}
if not sa.inspect(self.model).single:
parent = find_closest_versioned_parent(
self.manager, self.model
)
if parent:
# The version classes do not contain foreign keys, hence we
# need to map inheritance condition manually for classes that
# use joined table inheritance
if parent.__table__.name != table.name:
mapper = sa.inspect(self.model)
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import column_property
from sqlalchemy_utils.functions import get_declarative_base
from .utils import adapt_columns, option
from .version import VersionClassBase
import six
import sqlalchemy as sa
and context (class names, function names, or code) available:
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
. Output only the next line. | inherit_condition = adapt_columns( |
Given the following code snippet before the placeholder: <|code_start|>
def find_closest_versioned_parent(manager, model):
"""
Finds the closest versioned parent for current parent model.
"""
for class_ in model.__bases__:
if class_ in manager.version_class_map:
return manager.version_class_map[class_]
def versioned_parents(manager, model):
"""
Finds all versioned ancestors for current parent model.
"""
for class_ in model.__mro__:
if class_ in manager.version_class_map:
yield manager.version_class_map[class_]
def get_base_class(manager, model):
"""
Returns all base classes for history model.
"""
return (
<|code_end|>
, predict the next line using imports from the current file:
from copy import copy
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import column_property
from sqlalchemy_utils.functions import get_declarative_base
from .utils import adapt_columns, option
from .version import VersionClassBase
import six
import sqlalchemy as sa
and context including class names, function names, and sometimes code from other files:
# Path: sqlalchemy_continuum/utils.py
# def adapt_columns(expr):
# return VersioningClauseAdapter().traverse(expr)
#
# def option(obj_or_class, option_name):
# """
# Return the option value of given option for given versioned object or
# class.
#
# :param obj_or_class: SQLAlchemy declarative model object or class
# :param option_name: The name of an option to return
# """
# if isinstance(obj_or_class, AliasedClass):
# obj_or_class = sa.inspect(obj_or_class).mapper.class_
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
# if not hasattr(cls, '__versioned__'):
# cls = parent_class(cls)
# return get_versioning_manager(cls).option(
# cls, option_name
# )
. Output only the next line. | option(model, 'base_classes') |
Predict the next line after this snippet: <|code_start|>
subquery = self.version_validity_subquery(
parent,
version_obj,
alias=sa.orm.aliased(class_.__table__)
)
try:
subquery = subquery.scalar_subquery()
except AttributeError: # SQLAlchemy < 1.4
subquery = subquery.as_scalar()
query = (
session.query(class_.__table__)
.filter(
sa.and_(
getattr(
class_,
tx_column_name(version_obj)
) == subquery,
*[
getattr(version_obj, pk) ==
getattr(class_.__table__.c, pk)
for pk in get_primary_keys(class_)
if pk != tx_column_name(class_)
]
)
)
)
query.update(
{
<|code_end|>
using the current file's imports:
from copy import copy
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
import sqlalchemy as sa
and any relevant context from other files:
# Path: sqlalchemy_continuum/utils.py
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def is_session_modified(session):
# """
# Return whether or not any of the versioned objects in given session have
# been either modified or deleted.
#
# :param session: SQLAlchemy session object
#
# .. seealso:: :func:`is_versioned`
# .. seealso:: :func:`versioned_objects`
# """
# return any(
# is_modified_or_deleted(obj) for obj in versioned_objects(session)
# )
#
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def versioned_column_properties(obj_or_class):
# """
# Return all versioned column properties for given versioned SQLAlchemy
# declarative model object.
#
# :param obj: SQLAlchemy declarative model object
# """
# manager = get_versioning_manager(obj_or_class)
#
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
#
# mapper = sa.inspect(cls)
# for key, column in mapper.columns.items():
# # Ignores non table columns
# if not is_table_column(column):
# continue
#
# if not manager.is_excluded_property(obj_or_class, key):
# yield getattr(mapper.attrs, key)
. Output only the next line. | end_tx_column_name(version_obj): |
Continue the code snippet: <|code_start|> def create_transaction(self, session):
"""
Create transaction object for given SQLAlchemy session.
:param session: SQLAlchemy session object
"""
args = self.transaction_args(session)
Transaction = self.manager.transaction_cls
self.current_transaction = Transaction()
for key, value in args.items():
setattr(self.current_transaction, key, value)
if not self.version_session:
self.version_session = sa.orm.session.Session(
bind=session.connection()
)
self.version_session.add(self.current_transaction)
self.version_session.flush()
self.version_session.expunge(self.current_transaction)
session.add(self.current_transaction)
return self.current_transaction
def get_or_create_version_object(self, target):
"""
Return version object for given parent object. If no version object
exists for given parent object, create one.
:param target: Parent object to create the version object for
"""
<|code_end|>
. Use current file imports:
from copy import copy
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
import sqlalchemy as sa
and context (classes, functions, or code) from other files:
# Path: sqlalchemy_continuum/utils.py
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def is_session_modified(session):
# """
# Return whether or not any of the versioned objects in given session have
# been either modified or deleted.
#
# :param session: SQLAlchemy session object
#
# .. seealso:: :func:`is_versioned`
# .. seealso:: :func:`versioned_objects`
# """
# return any(
# is_modified_or_deleted(obj) for obj in versioned_objects(session)
# )
#
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def versioned_column_properties(obj_or_class):
# """
# Return all versioned column properties for given versioned SQLAlchemy
# declarative model object.
#
# :param obj: SQLAlchemy declarative model object
# """
# manager = get_versioning_manager(obj_or_class)
#
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
#
# mapper = sa.inspect(cls)
# for key, column in mapper.columns.items():
# # Ignores non table columns
# if not is_table_column(column):
# continue
#
# if not manager.is_excluded_property(obj_or_class, key):
# yield getattr(mapper.attrs, key)
. Output only the next line. | version_cls = version_class(target.__class__) |
Continue the code snippet: <|code_start|>
class UnitOfWork(object):
def __init__(self, manager):
self.manager = manager
self.reset()
def reset(self, session=None):
"""
Reset the internal state of this UnitOfWork object. Normally this is
called after transaction has been committed or rolled back.
"""
self.version_session = None
self.current_transaction = None
self.operations = Operations()
self.pending_statements = []
self.version_objs = {}
def is_modified(self, session):
"""
Return whether or not given session has been modified. Session has been
modified if any versioned property of any version object in given
session has been modified or if any of the plugins returns that
session has been modified.
:param session: SQLAlchemy session object
"""
return (
<|code_end|>
. Use current file imports:
from copy import copy
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
import sqlalchemy as sa
and context (classes, functions, or code) from other files:
# Path: sqlalchemy_continuum/utils.py
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def is_session_modified(session):
# """
# Return whether or not any of the versioned objects in given session have
# been either modified or deleted.
#
# :param session: SQLAlchemy session object
#
# .. seealso:: :func:`is_versioned`
# .. seealso:: :func:`versioned_objects`
# """
# return any(
# is_modified_or_deleted(obj) for obj in versioned_objects(session)
# )
#
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def versioned_column_properties(obj_or_class):
# """
# Return all versioned column properties for given versioned SQLAlchemy
# declarative model object.
#
# :param obj: SQLAlchemy declarative model object
# """
# manager = get_versioning_manager(obj_or_class)
#
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
#
# mapper = sa.inspect(cls)
# for key, column in mapper.columns.items():
# # Ignores non table columns
# if not is_table_column(column):
# continue
#
# if not manager.is_excluded_property(obj_or_class, key):
# yield getattr(mapper.attrs, key)
. Output only the next line. | is_session_modified(session) or |
Given the following code snippet before the placeholder: <|code_start|> parent object and newly created version object.
This method is only used when using 'validity' versioning strategy.
:param parent: SQLAlchemy declarative parent object
:parem version_obj: SQLAlchemy declarative version object
.. seealso:: :func:`version_validity_subquery`
"""
session = sa.orm.object_session(version_obj)
for class_ in version_obj.__class__.__mro__:
if class_ in self.manager.parent_class_map:
subquery = self.version_validity_subquery(
parent,
version_obj,
alias=sa.orm.aliased(class_.__table__)
)
try:
subquery = subquery.scalar_subquery()
except AttributeError: # SQLAlchemy < 1.4
subquery = subquery.as_scalar()
query = (
session.query(class_.__table__)
.filter(
sa.and_(
getattr(
class_,
<|code_end|>
, predict the next line using imports from the current file:
from copy import copy
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
import sqlalchemy as sa
and context including class names, function names, and sometimes code from other files:
# Path: sqlalchemy_continuum/utils.py
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def is_session_modified(session):
# """
# Return whether or not any of the versioned objects in given session have
# been either modified or deleted.
#
# :param session: SQLAlchemy session object
#
# .. seealso:: :func:`is_versioned`
# .. seealso:: :func:`versioned_objects`
# """
# return any(
# is_modified_or_deleted(obj) for obj in versioned_objects(session)
# )
#
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def versioned_column_properties(obj_or_class):
# """
# Return all versioned column properties for given versioned SQLAlchemy
# declarative model object.
#
# :param obj: SQLAlchemy declarative model object
# """
# manager = get_versioning_manager(obj_or_class)
#
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
#
# mapper = sa.inspect(cls)
# for key, column in mapper.columns.items():
# # Ignores non table columns
# if not is_table_column(column):
# continue
#
# if not manager.is_excluded_property(obj_or_class, key):
# yield getattr(mapper.attrs, key)
. Output only the next line. | tx_column_name(version_obj) |
Predict the next line for this snippet: <|code_start|>
:param session: SQLAlchemy session object
"""
if not self.manager.options['versioning']:
return
if self.pending_statements:
self.create_association_versions(session)
if self.operations:
self.manager.plugins.before_create_version_objects(self, session)
self.create_version_objects(session)
self.manager.plugins.after_create_version_objects(self, session)
@property
def has_changes(self):
"""
Return whether or not this unit of work has changes.
"""
return self.operations or self.pending_statements
def assign_attributes(self, parent_obj, version_obj):
"""
Assign attributes values from parent object to version object.
:param parent_obj:
Parent object to get the attribute values from
:param version_obj:
Version object to assign the attribute values to
"""
<|code_end|>
with the help of current file imports:
from copy import copy
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
import sqlalchemy as sa
and context from other files:
# Path: sqlalchemy_continuum/utils.py
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
#
# def version_class(model):
# """
# Return the version class for given SQLAlchemy declarative model class.
#
# ::
#
# version_class(Article) # ArticleVersion class
#
#
# :param model: SQLAlchemy declarative model class
#
# .. seealso:: :func:`parent_class`
# """
# manager = get_versioning_manager(model)
# try:
# return manager.version_class_map[model]
# except KeyError:
# return model
#
# def is_session_modified(session):
# """
# Return whether or not any of the versioned objects in given session have
# been either modified or deleted.
#
# :param session: SQLAlchemy session object
#
# .. seealso:: :func:`is_versioned`
# .. seealso:: :func:`versioned_objects`
# """
# return any(
# is_modified_or_deleted(obj) for obj in versioned_objects(session)
# )
#
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def versioned_column_properties(obj_or_class):
# """
# Return all versioned column properties for given versioned SQLAlchemy
# declarative model object.
#
# :param obj: SQLAlchemy declarative model object
# """
# manager = get_versioning_manager(obj_or_class)
#
# cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
#
# mapper = sa.inspect(cls)
# for key, column in mapper.columns.items():
# # Ignores non table columns
# if not is_table_column(column):
# continue
#
# if not manager.is_excluded_property(obj_or_class, key):
# yield getattr(mapper.attrs, key)
, which may contain function names, class names, or code. Output only the next line. | for prop in versioned_column_properties(parent_obj): |
Using the snippet: <|code_start|>
def parent_identity(obj_or_class):
return tuple(
getattr(obj_or_class, column_key)
for column_key in get_primary_keys(obj_or_class).keys()
<|code_end|>
, determine the next line of code. You have imports:
import operator
import sqlalchemy as sa
from sqlalchemy_utils import get_primary_keys, identity
from .utils import tx_column_name, end_tx_column_name
and context (class names, function names, or code) available:
# Path: sqlalchemy_continuum/utils.py
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
. Output only the next line. | if column_key != tx_column_name(obj_or_class) |
Continue the code snippet: <|code_start|>class SubqueryFetcher(VersionObjectFetcher):
def previous_query(self, obj):
"""
Returns the query that fetches the previous version relative to this
version in the version history.
"""
return self._next_prev_query(obj, 'previous')
def next_query(self, obj):
"""
Returns the query that fetches the next version relative to this
version in the version history.
"""
return self._next_prev_query(obj, 'next')
class ValidityFetcher(VersionObjectFetcher):
def next_query(self, obj):
"""
Returns the query that fetches the next version relative to this
version in the version history.
"""
session = sa.orm.object_session(obj)
return (
session.query(obj.__class__)
.filter(
sa.and_(
getattr(obj.__class__, tx_column_name(obj))
==
<|code_end|>
. Use current file imports:
import operator
import sqlalchemy as sa
from sqlalchemy_utils import get_primary_keys, identity
from .utils import tx_column_name, end_tx_column_name
and context (classes, functions, or code) from other files:
# Path: sqlalchemy_continuum/utils.py
# def tx_column_name(obj):
# return option(obj, 'transaction_column_name')
#
# def end_tx_column_name(obj):
# return option(obj, 'end_transaction_column_name')
. Output only the next line. | getattr(obj, end_tx_column_name(obj)), |
Predict the next line for this snippet: <|code_start|> def __str__(self):
return self.name
@property
def events(self):
return self.event_set
def create_relation(self, obj, distinction=None, inheritable=True):
"""
Creates a CalendarRelation between self and obj.
if Inheritable is set to true this relation will cascade to all events
related to this calendar.
"""
CalendarRelation.objects.create_relation(self, obj, distinction, inheritable)
def get_recent(self, amount=5, in_datetime=datetime.datetime.now, tzinfo=pytz.utc):
"""
This shortcut function allows you to get events that have started
recently.
amount is the amount of events you want in the queryset. The default is
5.
in_datetime is the datetime you want to check against. It defaults to
datetime.datetime.now
"""
return self.events.order_by('-start').filter(start__lt=timezone.now())[:amount]
def occurrences_after(self, date=None):
<|code_end|>
with the help of current file imports:
from django.utils.six.moves.builtins import str
from django.utils.six import with_metaclass
from django.contrib.contenttypes import fields
from django.db import models
from django.db.models.base import ModelBase
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from schedule.utils import EventListManager, get_model_bases
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
import pytz
import datetime
and context from other files:
# Path: schedule/utils.py
# class EventListManager(object):
# """
# This class is responsible for doing functions on a list of events. It is
# used to when one has a list of events and wants to access the occurrences
# from these events in as a group
# """
#
# def __init__(self, events):
# self.events = events
#
# def occurrences_after(self, after=None, tzinfo=pytz.utc):
# """
# It is often useful to know what the next occurrence is given a list of
# events. This function produces a generator that yields the
# the most recent occurrence after the date ``after`` from any of the
# events in ``self.events``
# """
# from schedule.models import Occurrence
#
# if after is None:
# after = timezone.now()
# occ_replacer = OccurrenceReplacer(
# Occurrence.objects.filter(event__in=self.events))
# generators = [event._occurrences_after_generator(after) for event in self.events]
# occurrences = []
#
# for generator in generators:
# try:
# heapq.heappush(occurrences, (next(generator), generator))
# except StopIteration:
# pass
#
# while True:
# if len(occurrences) == 0:
# raise StopIteration
#
# generator = occurrences[0][1]
#
# try:
# next_occurence = heapq.heapreplace(occurrences, (next(generator), generator))[0]
# except StopIteration:
# next_occurence = heapq.heappop(occurrences)[0]
# yield occ_replacer.get_occurrence(next_occurence)
#
# def get_model_bases():
# from django.db.models import Model
# baseStrings = getattr(settings, 'SCHEDULER_BASE_CLASSES', None)
# if baseStrings is None:
# return [Model]
# else:
# return [import_string(x) for x in baseStrings]
, which may contain function names, class names, or code. Output only the next line. | return EventListManager(self.events.all()).occurrences_after(date) |
Here is a snippet: <|code_start|> "Jeremy's Calendar"
"""
try:
return self.get_calendar_for_object(obj, distinction)
except Calendar.DoesNotExist:
if name is None:
calendar = Calendar(name=str(obj))
else:
calendar = Calendar(name=name)
calendar.slug = slugify(calendar.name)
calendar.save()
calendar.create_relation(obj, distinction)
return calendar
def get_calendars_for_object(self, obj, distinction=None):
"""
This function allows you to get calendars for a specific object
If distinction is set it will filter out any relation that doesnt have
that distinction.
"""
ct = ContentType.objects.get_for_model(obj)
if distinction:
dist_q = Q(calendarrelation__distinction=distinction)
else:
dist_q = Q()
return self.filter(dist_q, calendarrelation__object_id=obj.id, calendarrelation__content_type=ct)
@python_2_unicode_compatible
<|code_end|>
. Write the next line using the current file imports:
from django.utils.six.moves.builtins import str
from django.utils.six import with_metaclass
from django.contrib.contenttypes import fields
from django.db import models
from django.db.models.base import ModelBase
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from schedule.utils import EventListManager, get_model_bases
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
import pytz
import datetime
and context from other files:
# Path: schedule/utils.py
# class EventListManager(object):
# """
# This class is responsible for doing functions on a list of events. It is
# used to when one has a list of events and wants to access the occurrences
# from these events in as a group
# """
#
# def __init__(self, events):
# self.events = events
#
# def occurrences_after(self, after=None, tzinfo=pytz.utc):
# """
# It is often useful to know what the next occurrence is given a list of
# events. This function produces a generator that yields the
# the most recent occurrence after the date ``after`` from any of the
# events in ``self.events``
# """
# from schedule.models import Occurrence
#
# if after is None:
# after = timezone.now()
# occ_replacer = OccurrenceReplacer(
# Occurrence.objects.filter(event__in=self.events))
# generators = [event._occurrences_after_generator(after) for event in self.events]
# occurrences = []
#
# for generator in generators:
# try:
# heapq.heappush(occurrences, (next(generator), generator))
# except StopIteration:
# pass
#
# while True:
# if len(occurrences) == 0:
# raise StopIteration
#
# generator = occurrences[0][1]
#
# try:
# next_occurence = heapq.heapreplace(occurrences, (next(generator), generator))[0]
# except StopIteration:
# next_occurence = heapq.heappop(occurrences)[0]
# yield occ_replacer.get_occurrence(next_occurence)
#
# def get_model_bases():
# from django.db.models import Model
# baseStrings = getattr(settings, 'SCHEDULER_BASE_CLASSES', None)
# if baseStrings is None:
# return [Model]
# else:
# return [import_string(x) for x in baseStrings]
, which may include functions, classes, or code. Output only the next line. | class Calendar(with_metaclass(ModelBase, *get_model_bases())): |
Predict the next line after this snippet: <|code_start|> # image todo
panels = [
FieldPanel('name'),
FieldPanel('capacity'),
]
def __str__(self):
return self.name
class Booking(models.Model):
"""
access from Room with .booking_set
create from Room with .booking_set.create(title='My meeting')
"""
room = models.ForeignKey(Room, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=200)
# date_time_from = models.DateTimeField()
# date_time_to = models.DateTimeField()
# description todo
# user todo
def __str__(self):
return 'name: ' + self.room.name + 'title: ' + self.title + str(self.created)
<|code_end|>
using the current file's imports:
from django.db import models
from taggit.models import TaggedItemBase
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailforms.models import AbstractEmailForm, AbstractFormField
from wagtail.wagtailsnippets.models import register_snippet
from cms.models import StandardPage
and any relevant context from other files:
# Path: cms/models.py
# class StandardPage(Page):
# body = RichTextField(blank=True)
# feed_image = models.ForeignKey(
# 'wagtailimages.Image',
# null=True,
# blank=True,
# on_delete=models.SET_NULL,
# related_name='+'
# )
#
# search_fields = Page.search_fields + (
# index.SearchField('intro'),
# index.SearchField('body'),
# )
. Output only the next line. | class RoomsWeekly(StandardPage): |
Next line prediction: <|code_start|>from __future__ import division
register = template.Library()
@register.inclusion_tag("schedule/_month_table.html", takes_context=True)
def month_table(context, calendar, month, size="regular", shift=None):
if shift:
if shift == -1:
month = month.prev()
if shift == 1:
month = next(month)
if size == "small":
context['day_names'] = weekday_abbrs
else:
<|code_end|>
. Use current file imports:
(from django.utils.six.moves.builtins import range
from django.conf import settings
from django import template
from django.core.urlresolvers import reverse
from django.utils.dateformat import format
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.utils import timezone
from schedule.conf.settings import CHECK_EVENT_PERM_FUNC, CHECK_CALENDAR_PERM_FUNC, SCHEDULER_PREVNEXT_LIMIT_SECONDS
from schedule.models import Calendar
from schedule.periods import weekday_names, weekday_abbrs
import datetime)
and context including class names, function names, or small code snippets from other files:
# Path: schedule/periods.py
# class Period(object):
# class Year(Period):
# class Month(Period):
# class Week(Period):
# class Day(Period):
# def __init__(self, events, start, end, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def _normalize_timezone_to_utc(self, point_in_time, tzinfo):
# def __eq__(self, period):
# def __ne__(self, period):
# def _get_tzinfo(self, tzinfo):
# def _get_sorted_occurrences(self):
# def cached_get_sorted_occurrences(self):
# def get_persisted_occurrences(self):
# def classify_occurrence(self, occurrence):
# def get_occurrence_partials(self):
# def get_occurrences(self):
# def has_occurrences(self):
# def get_time_slot(self, start, end):
# def create_sub_period(self, cls, start=None, tzinfo=None):
# def get_periods(self, cls, tzinfo=None):
# def start(self):
# def end(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None, tzinfo=pytz.utc):
# def get_months(self):
# def next_year(self):
# def prev_year(self):
# def _get_year_range(self, year):
# def __str__(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def get_weeks(self):
# def get_days(self):
# def get_day(self, daynumber):
# def next_month(self):
# def prev_month(self):
# def current_year(self):
# def prev_year(self):
# def next_year(self):
# def _get_month_range(self, month):
# def __str__(self):
# def name(self):
# def year(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def prev_week(self):
# def next_week(self):
# def current_month(self):
# def current_year(self):
# def get_days(self):
# def _get_week_range(self, week):
# def __str__(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def _get_day_range(self, date):
# def __str__(self):
# def prev_day(self):
# def next_day(self):
# def current_year(self):
# def current_month(self):
# def current_week(self):
. Output only the next line. | context['day_names'] = weekday_names |
Given the code snippet: <|code_start|>from __future__ import division
register = template.Library()
@register.inclusion_tag("schedule/_month_table.html", takes_context=True)
def month_table(context, calendar, month, size="regular", shift=None):
if shift:
if shift == -1:
month = month.prev()
if shift == 1:
month = next(month)
if size == "small":
<|code_end|>
, generate the next line using the imports in this file:
from django.utils.six.moves.builtins import range
from django.conf import settings
from django import template
from django.core.urlresolvers import reverse
from django.utils.dateformat import format
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.utils import timezone
from schedule.conf.settings import CHECK_EVENT_PERM_FUNC, CHECK_CALENDAR_PERM_FUNC, SCHEDULER_PREVNEXT_LIMIT_SECONDS
from schedule.models import Calendar
from schedule.periods import weekday_names, weekday_abbrs
import datetime
and context (functions, classes, or occasionally code) from other files:
# Path: schedule/periods.py
# class Period(object):
# class Year(Period):
# class Month(Period):
# class Week(Period):
# class Day(Period):
# def __init__(self, events, start, end, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def _normalize_timezone_to_utc(self, point_in_time, tzinfo):
# def __eq__(self, period):
# def __ne__(self, period):
# def _get_tzinfo(self, tzinfo):
# def _get_sorted_occurrences(self):
# def cached_get_sorted_occurrences(self):
# def get_persisted_occurrences(self):
# def classify_occurrence(self, occurrence):
# def get_occurrence_partials(self):
# def get_occurrences(self):
# def has_occurrences(self):
# def get_time_slot(self, start, end):
# def create_sub_period(self, cls, start=None, tzinfo=None):
# def get_periods(self, cls, tzinfo=None):
# def start(self):
# def end(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None, tzinfo=pytz.utc):
# def get_months(self):
# def next_year(self):
# def prev_year(self):
# def _get_year_range(self, year):
# def __str__(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def get_weeks(self):
# def get_days(self):
# def get_day(self, daynumber):
# def next_month(self):
# def prev_month(self):
# def current_year(self):
# def prev_year(self):
# def next_year(self):
# def _get_month_range(self, month):
# def __str__(self):
# def name(self):
# def year(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def prev_week(self):
# def next_week(self):
# def current_month(self):
# def current_year(self):
# def get_days(self):
# def _get_week_range(self, week):
# def __str__(self):
# def __init__(self, events, date=None, parent_persisted_occurrences=None,
# occurrence_pool=None, tzinfo=pytz.utc):
# def _get_day_range(self, date):
# def __str__(self):
# def prev_day(self):
# def next_day(self):
# def current_year(self):
# def current_month(self):
# def current_week(self):
. Output only the next line. | context['day_names'] = weekday_abbrs |
Using the snippet: <|code_start|>from __future__ import division, unicode_literals
# -*- coding: utf-8 -*-
class EventManager(models.Manager):
def get_for_object(self, content_object, distinction=None, inherit=True):
return EventRelation.objects.get_events_for_object(content_object, distinction, inherit)
@python_2_unicode_compatible
<|code_end|>
, determine the next line of code. You have imports:
from django.utils.six import with_metaclass
from django.conf import settings as django_settings
from dateutil import rrule
from django.contrib.contenttypes import fields
from django.db import models
from django.db.models.base import ModelBase
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.template.defaultfilters import date
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from schedule.conf import settings
from schedule.models.rules import Rule
from schedule.models.calendars import Calendar
from schedule.utils import OccurrenceReplacer
from schedule.utils import get_model_bases
import pytz
and context (class names, function names, or code) available:
# Path: schedule/models/calendars.py
# class Calendar(with_metaclass(ModelBase, *get_model_bases())):
# '''
# This is for grouping events so that batch relations can be made to all
# events. An example would be a project calendar.
#
# name: the name of the calendar
# events: all the events contained within the calendar.
# >>> calendar = Calendar(name = 'Test Calendar')
# >>> calendar.save()
# >>> data = {
# ... 'title': 'Recent Event',
# ... 'start': datetime.datetime(2008, 1, 5, 0, 0),
# ... 'end': datetime.datetime(2008, 1, 10, 0, 0)
# ... }
# >>> event = Event(**data)
# >>> event.save()
# >>> calendar.events.add(event)
# >>> data = {
# ... 'title': 'Upcoming Event',
# ... 'start': datetime.datetime(2008, 1, 1, 0, 0),
# ... 'end': datetime.datetime(2008, 1, 4, 0, 0)
# ... }
# >>> event = Event(**data)
# >>> event.save()
# >>> calendar.events.add(event)
# >>> data = {
# ... 'title': 'Current Event',
# ... 'start': datetime.datetime(2008, 1, 3),
# ... 'end': datetime.datetime(2008, 1, 6)
# ... }
# >>> event = Event(**data)
# >>> event.save()
# >>> calendar.events.add(event)
# '''
#
# name = models.CharField(_("name"), max_length=200)
# slug = models.SlugField(_("slug"), max_length=200)
# objects = CalendarManager()
#
# class Meta(object):
# verbose_name = _('calendar')
# verbose_name_plural = _('calendar')
# app_label = 'schedule'
#
# def __str__(self):
# return self.name
#
# @property
# def events(self):
# return self.event_set
#
# def create_relation(self, obj, distinction=None, inheritable=True):
# """
# Creates a CalendarRelation between self and obj.
#
# if Inheritable is set to true this relation will cascade to all events
# related to this calendar.
# """
# CalendarRelation.objects.create_relation(self, obj, distinction, inheritable)
#
# def get_recent(self, amount=5, in_datetime=datetime.datetime.now, tzinfo=pytz.utc):
# """
# This shortcut function allows you to get events that have started
# recently.
#
# amount is the amount of events you want in the queryset. The default is
# 5.
#
# in_datetime is the datetime you want to check against. It defaults to
# datetime.datetime.now
# """
# return self.events.order_by('-start').filter(start__lt=timezone.now())[:amount]
#
# def occurrences_after(self, date=None):
# return EventListManager(self.events.all()).occurrences_after(date)
#
# def get_absolute_url(self):
# return reverse('calendar_home', kwargs={'calendar_slug': self.slug})
#
# def add_event_url(self):
# return reverse('calendar_create_event', args=[self.slug])
#
# Path: schedule/utils.py
# class OccurrenceReplacer(object):
# """
# When getting a list of occurrences, the last thing that needs to be done
# before passing it forward is to make sure all of the occurrences that
# have been stored in the datebase replace, in the list you are returning,
# the generated ones that are equivalent. This class makes this easier.
# """
#
# def __init__(self, persisted_occurrences):
# lookup = [((occ.event, occ.original_start, occ.original_end), occ) for
# occ in persisted_occurrences]
# self.lookup = dict(lookup)
#
# def get_occurrence(self, occ):
# """
# Return a persisted occurrences matching the occ and remove it from lookup since it
# has already been matched
# """
# return self.lookup.pop(
# (occ.event, occ.original_start, occ.original_end),
# occ)
#
# def has_occurrence(self, occ):
# try:
# return (occ.event, occ.original_start, occ.original_end) in self.lookup
# except TypeError:
# if not self.lookup:
# return False
# else:
# raise TypeError('A problem with checking if a persisted occurence exists has occured!')
#
# def get_additional_occurrences(self, start, end):
# """
# Return persisted occurrences which are now in the period
# """
# return [occ for _, occ in list(self.lookup.items()) if (occ.start < end and occ.end >= start and not occ.cancelled)]
#
# Path: schedule/utils.py
# def get_model_bases():
# from django.db.models import Model
# baseStrings = getattr(settings, 'SCHEDULER_BASE_CLASSES', None)
# if baseStrings is None:
# return [Model]
# else:
# return [import_string(x) for x in baseStrings]
. Output only the next line. | class Event(with_metaclass(ModelBase, *get_model_bases())): |
Given snippet: <|code_start|> label=_("Telefon"),
widget=forms.TextInput(), required=True)
street = forms.CharField(
label=_("Straße"),
max_length=100,
)
plz_city = forms.CharField(
label=_("PLZ / Stadt"),
widget=forms.TextInput(), required=True)
code = forms.CharField(
max_length=64,
required=False,
widget=forms.HiddenInput()
)
def clean_username(self):
if not alnum_re.search(self.cleaned_data["username"]):
raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores."))
User = get_user_model()
lookup_kwargs = get_user_lookup_kwargs({
"{username}__iexact": self.cleaned_data["username"]
})
qs = User.objects.filter(**lookup_kwargs)
if not qs.exists():
return self.cleaned_data["username"]
raise forms.ValidationError(_("This username is already taken. Please choose another."))
def clean_email(self):
value = self.cleaned_data["email"]
qs = EmailAddress.objects.filter(email__iexact=value)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from collections import OrderedDict
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import auth
from django.contrib.auth import get_user_model
from account.conf import settings
from account.hooks import hookset
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
and context:
# Path: account/conf.py
# def load_path_attr(path):
# def configure_deletion_mark_callback(self, value):
# def configure_deletion_expunge_callback(self, value):
# def configure_hookset(self, value):
# class AccountAppConf(AppConf):
# OPEN_SIGNUP = True
# LOGIN_URL = "account_login"
# SIGNUP_REDIRECT_URL = "/"
# LOGIN_REDIRECT_URL = "/"
# LOGOUT_REDIRECT_URL = "/"
# PASSWORD_CHANGE_REDIRECT_URL = "account_password"
# PASSWORD_RESET_REDIRECT_URL = "account_login"
# REMEMBER_ME_EXPIRY = 60 * 60 * 24 * 365 * 10
# USER_DISPLAY = lambda user: user.username # flake8: noqa
# CREATE_ON_SAVE = True
# EMAIL_UNIQUE = True
# EMAIL_CONFIRMATION_REQUIRED = False
# EMAIL_CONFIRMATION_EMAIL = True
# EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
# EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "account_login"
# EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
# EMAIL_CONFIRMATION_URL = "account_confirm_email"
# SETTINGS_REDIRECT_URL = "account_settings"
# NOTIFY_ON_PASSWORD_CHANGE = True
# DELETION_MARK_CALLBACK = "account.callbacks.account_delete_mark"
# DELETION_EXPUNGE_CALLBACK = "account.callbacks.account_delete_expunge"
# DELETION_EXPUNGE_HOURS = 48
# HOOKSET = "account.hooks.AccountDefaultHookSet"
# TIMEZONES = TIMEZONES
# LANGUAGES = LANGUAGES
# USE_AUTH_AUTHENTICATE = False
#
# Path: account/models.py
# class EmailAddress(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# email = models.EmailField(max_length=254, unique=settings.ACCOUNT_EMAIL_UNIQUE)
# verified = models.BooleanField(_("verified"), default=False)
# primary = models.BooleanField(_("primary"), default=False)
#
# objects = EmailAddressManager()
#
# class Meta:
# verbose_name = _("email address")
# verbose_name_plural = _("email addresses")
# if not settings.ACCOUNT_EMAIL_UNIQUE:
# unique_together = [("user", "email")]
#
# def __str__(self):
# return "{0} ({1})".format(self.email, self.user)
#
# def set_as_primary(self, conditional=False):
# old_primary = EmailAddress.objects.get_primary(self.user)
# if old_primary:
# if conditional:
# return False
# old_primary.primary = False
# old_primary.save()
# self.primary = True
# self.save()
# self.user.email = self.email
# self.user.save()
# return True
#
# def send_confirmation(self, **kwargs):
# confirmation = EmailConfirmation.create(self)
# confirmation.send(**kwargs)
# return confirmation
#
# def change(self, new_email, confirm=True):
# """
# Given a new email address, change self and re-confirm.
# """
# with transaction.atomic():
# self.user.email = new_email
# self.user.save()
# self.email = new_email
# self.verified = False
# self.save()
# if confirm:
# self.send_confirmation()
#
# Path: account/utils.py
# def get_user_lookup_kwargs(kwargs):
# result = {}
# username_field = getattr(get_user_model(), "USERNAME_FIELD", "username")
# for key, value in kwargs.items():
# result[key.format(username=username_field)] = value
# return result
which might include code, classes, or functions. Output only the next line. | if not qs.exists() or not settings.ACCOUNT_EMAIL_UNIQUE: |
Based on the snippet: <|code_start|> phone = forms.CharField(
label=_("Telefon"),
widget=forms.TextInput(), required=True)
street = forms.CharField(
label=_("Straße"),
max_length=100,
)
plz_city = forms.CharField(
label=_("PLZ / Stadt"),
widget=forms.TextInput(), required=True)
code = forms.CharField(
max_length=64,
required=False,
widget=forms.HiddenInput()
)
def clean_username(self):
if not alnum_re.search(self.cleaned_data["username"]):
raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores."))
User = get_user_model()
lookup_kwargs = get_user_lookup_kwargs({
"{username}__iexact": self.cleaned_data["username"]
})
qs = User.objects.filter(**lookup_kwargs)
if not qs.exists():
return self.cleaned_data["username"]
raise forms.ValidationError(_("This username is already taken. Please choose another."))
def clean_email(self):
value = self.cleaned_data["email"]
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from collections import OrderedDict
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import auth
from django.contrib.auth import get_user_model
from account.conf import settings
from account.hooks import hookset
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
and context (classes, functions, sometimes code) from other files:
# Path: account/conf.py
# def load_path_attr(path):
# def configure_deletion_mark_callback(self, value):
# def configure_deletion_expunge_callback(self, value):
# def configure_hookset(self, value):
# class AccountAppConf(AppConf):
# OPEN_SIGNUP = True
# LOGIN_URL = "account_login"
# SIGNUP_REDIRECT_URL = "/"
# LOGIN_REDIRECT_URL = "/"
# LOGOUT_REDIRECT_URL = "/"
# PASSWORD_CHANGE_REDIRECT_URL = "account_password"
# PASSWORD_RESET_REDIRECT_URL = "account_login"
# REMEMBER_ME_EXPIRY = 60 * 60 * 24 * 365 * 10
# USER_DISPLAY = lambda user: user.username # flake8: noqa
# CREATE_ON_SAVE = True
# EMAIL_UNIQUE = True
# EMAIL_CONFIRMATION_REQUIRED = False
# EMAIL_CONFIRMATION_EMAIL = True
# EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
# EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "account_login"
# EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
# EMAIL_CONFIRMATION_URL = "account_confirm_email"
# SETTINGS_REDIRECT_URL = "account_settings"
# NOTIFY_ON_PASSWORD_CHANGE = True
# DELETION_MARK_CALLBACK = "account.callbacks.account_delete_mark"
# DELETION_EXPUNGE_CALLBACK = "account.callbacks.account_delete_expunge"
# DELETION_EXPUNGE_HOURS = 48
# HOOKSET = "account.hooks.AccountDefaultHookSet"
# TIMEZONES = TIMEZONES
# LANGUAGES = LANGUAGES
# USE_AUTH_AUTHENTICATE = False
#
# Path: account/models.py
# class EmailAddress(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# email = models.EmailField(max_length=254, unique=settings.ACCOUNT_EMAIL_UNIQUE)
# verified = models.BooleanField(_("verified"), default=False)
# primary = models.BooleanField(_("primary"), default=False)
#
# objects = EmailAddressManager()
#
# class Meta:
# verbose_name = _("email address")
# verbose_name_plural = _("email addresses")
# if not settings.ACCOUNT_EMAIL_UNIQUE:
# unique_together = [("user", "email")]
#
# def __str__(self):
# return "{0} ({1})".format(self.email, self.user)
#
# def set_as_primary(self, conditional=False):
# old_primary = EmailAddress.objects.get_primary(self.user)
# if old_primary:
# if conditional:
# return False
# old_primary.primary = False
# old_primary.save()
# self.primary = True
# self.save()
# self.user.email = self.email
# self.user.save()
# return True
#
# def send_confirmation(self, **kwargs):
# confirmation = EmailConfirmation.create(self)
# confirmation.send(**kwargs)
# return confirmation
#
# def change(self, new_email, confirm=True):
# """
# Given a new email address, change self and re-confirm.
# """
# with transaction.atomic():
# self.user.email = new_email
# self.user.save()
# self.email = new_email
# self.verified = False
# self.save()
# if confirm:
# self.send_confirmation()
#
# Path: account/utils.py
# def get_user_lookup_kwargs(kwargs):
# result = {}
# username_field = getattr(get_user_model(), "USERNAME_FIELD", "username")
# for key, value in kwargs.items():
# result[key.format(username=username_field)] = value
# return result
. Output only the next line. | qs = EmailAddress.objects.filter(email__iexact=value) |
Predict the next line after this snippet: <|code_start|> label=_("Password"),
widget=forms.PasswordInput(render_value=False)
)
password_confirm = forms.CharField(
label=_("Password (again)"),
widget=forms.PasswordInput(render_value=False)
)
email = forms.EmailField(
label=_("Email"),
widget=forms.TextInput(), required=True)
phone = forms.CharField(
label=_("Telefon"),
widget=forms.TextInput(), required=True)
street = forms.CharField(
label=_("Straße"),
max_length=100,
)
plz_city = forms.CharField(
label=_("PLZ / Stadt"),
widget=forms.TextInput(), required=True)
code = forms.CharField(
max_length=64,
required=False,
widget=forms.HiddenInput()
)
def clean_username(self):
if not alnum_re.search(self.cleaned_data["username"]):
raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores."))
User = get_user_model()
<|code_end|>
using the current file's imports:
import re
from collections import OrderedDict
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib import auth
from django.contrib.auth import get_user_model
from account.conf import settings
from account.hooks import hookset
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
and any relevant context from other files:
# Path: account/conf.py
# def load_path_attr(path):
# def configure_deletion_mark_callback(self, value):
# def configure_deletion_expunge_callback(self, value):
# def configure_hookset(self, value):
# class AccountAppConf(AppConf):
# OPEN_SIGNUP = True
# LOGIN_URL = "account_login"
# SIGNUP_REDIRECT_URL = "/"
# LOGIN_REDIRECT_URL = "/"
# LOGOUT_REDIRECT_URL = "/"
# PASSWORD_CHANGE_REDIRECT_URL = "account_password"
# PASSWORD_RESET_REDIRECT_URL = "account_login"
# REMEMBER_ME_EXPIRY = 60 * 60 * 24 * 365 * 10
# USER_DISPLAY = lambda user: user.username # flake8: noqa
# CREATE_ON_SAVE = True
# EMAIL_UNIQUE = True
# EMAIL_CONFIRMATION_REQUIRED = False
# EMAIL_CONFIRMATION_EMAIL = True
# EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
# EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "account_login"
# EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
# EMAIL_CONFIRMATION_URL = "account_confirm_email"
# SETTINGS_REDIRECT_URL = "account_settings"
# NOTIFY_ON_PASSWORD_CHANGE = True
# DELETION_MARK_CALLBACK = "account.callbacks.account_delete_mark"
# DELETION_EXPUNGE_CALLBACK = "account.callbacks.account_delete_expunge"
# DELETION_EXPUNGE_HOURS = 48
# HOOKSET = "account.hooks.AccountDefaultHookSet"
# TIMEZONES = TIMEZONES
# LANGUAGES = LANGUAGES
# USE_AUTH_AUTHENTICATE = False
#
# Path: account/models.py
# class EmailAddress(models.Model):
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# email = models.EmailField(max_length=254, unique=settings.ACCOUNT_EMAIL_UNIQUE)
# verified = models.BooleanField(_("verified"), default=False)
# primary = models.BooleanField(_("primary"), default=False)
#
# objects = EmailAddressManager()
#
# class Meta:
# verbose_name = _("email address")
# verbose_name_plural = _("email addresses")
# if not settings.ACCOUNT_EMAIL_UNIQUE:
# unique_together = [("user", "email")]
#
# def __str__(self):
# return "{0} ({1})".format(self.email, self.user)
#
# def set_as_primary(self, conditional=False):
# old_primary = EmailAddress.objects.get_primary(self.user)
# if old_primary:
# if conditional:
# return False
# old_primary.primary = False
# old_primary.save()
# self.primary = True
# self.save()
# self.user.email = self.email
# self.user.save()
# return True
#
# def send_confirmation(self, **kwargs):
# confirmation = EmailConfirmation.create(self)
# confirmation.send(**kwargs)
# return confirmation
#
# def change(self, new_email, confirm=True):
# """
# Given a new email address, change self and re-confirm.
# """
# with transaction.atomic():
# self.user.email = new_email
# self.user.save()
# self.email = new_email
# self.verified = False
# self.save()
# if confirm:
# self.send_confirmation()
#
# Path: account/utils.py
# def get_user_lookup_kwargs(kwargs):
# result = {}
# username_field = getattr(get_user_model(), "USERNAME_FIELD", "username")
# for key, value in kwargs.items():
# result[key.format(username=username_field)] = value
# return result
. Output only the next line. | lookup_kwargs = get_user_lookup_kwargs({ |
Continue the code snippet: <|code_start|> if not next_url:
# try the session if available
if hasattr(request, "session"):
session_key_value = kwargs.get("session_key_value", "redirect_to")
if session_key_value in request.session:
next_url = request.session[session_key_value]
del request.session[session_key_value]
is_safe = functools.partial(
ensure_safe_url,
allowed_protocols=kwargs.get("allowed_protocols"),
allowed_host=request.get_host()
)
if next_url and is_safe(next_url):
return next_url
else:
try:
fallback_url = urlresolvers.reverse(fallback_url)
except urlresolvers.NoReverseMatch:
if callable(fallback_url):
raise
if "/" not in fallback_url and "." not in fallback_url:
raise
# assert the fallback URL is safe to return to caller. if it is
# determined unsafe then raise an exception as the fallback value comes
# from the a source the developer choose.
is_safe(fallback_url, raise_on_fail=True)
return fallback_url
def user_display(user):
<|code_end|>
. Use current file imports:
import functools
from urllib.parse import urlparse, urlunparse
from urlparse import urlparse, urlunparse
from django.core import urlresolvers
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponseRedirect, QueryDict
from django.contrib.auth import get_user_model
from account.conf import settings
and context (classes, functions, or code) from other files:
# Path: account/conf.py
# def load_path_attr(path):
# def configure_deletion_mark_callback(self, value):
# def configure_deletion_expunge_callback(self, value):
# def configure_hookset(self, value):
# class AccountAppConf(AppConf):
# OPEN_SIGNUP = True
# LOGIN_URL = "account_login"
# SIGNUP_REDIRECT_URL = "/"
# LOGIN_REDIRECT_URL = "/"
# LOGOUT_REDIRECT_URL = "/"
# PASSWORD_CHANGE_REDIRECT_URL = "account_password"
# PASSWORD_RESET_REDIRECT_URL = "account_login"
# REMEMBER_ME_EXPIRY = 60 * 60 * 24 * 365 * 10
# USER_DISPLAY = lambda user: user.username # flake8: noqa
# CREATE_ON_SAVE = True
# EMAIL_UNIQUE = True
# EMAIL_CONFIRMATION_REQUIRED = False
# EMAIL_CONFIRMATION_EMAIL = True
# EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
# EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "account_login"
# EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
# EMAIL_CONFIRMATION_URL = "account_confirm_email"
# SETTINGS_REDIRECT_URL = "account_settings"
# NOTIFY_ON_PASSWORD_CHANGE = True
# DELETION_MARK_CALLBACK = "account.callbacks.account_delete_mark"
# DELETION_EXPUNGE_CALLBACK = "account.callbacks.account_delete_expunge"
# DELETION_EXPUNGE_HOURS = 48
# HOOKSET = "account.hooks.AccountDefaultHookSet"
# TIMEZONES = TIMEZONES
# LANGUAGES = LANGUAGES
# USE_AUTH_AUTHENTICATE = False
. Output only the next line. | return settings.ACCOUNT_USER_DISPLAY(user) |
Given snippet: <|code_start|>sys.path.append('') # need to import from base
parser = get_parser()
parser.add_argument('--upload_directory', default=False, action="store_true", help='upload all xls and fasta files in directory')
parser.add_argument('--vtype', default=None, help="type of virus, if applicable")
parser.add_argument('--subtype', default=None, help="subtype of virus")
parser.add_argument('--lineage', default=None, help="lineage of virus")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os, re, time, datetime, csv, sys, json
import numpy as np
import glob
import pandas
from rethinkdb import r
from Bio import SeqIO
from Bio import AlignIO
from unidecode import unidecode
from vdb.upload import upload
from vdb.upload import get_parser
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio import AlignIO
and context:
# Path: vdb/upload.py
# def upload(self, preview=False, **kwargs):
# '''
# format virus information, then upload to database
# '''
# self.connect(**kwargs)
# print("Uploading Viruses to VDB")
# viruses, sequences = self.parse(**kwargs)
# print('Formatting documents for upload')
# self.format_viruses(viruses, **kwargs)
# self.format_sequences(sequences, **kwargs)
# print("")
# print("Filtering out viruses")
# viruses = self.filter(viruses, 'strain', **kwargs)
# print("Filtering out sequences")
# sequences = self.filter(sequences, 'accession', **kwargs)
# print("")
# #self.match_duplicate_strains(viruses, sequences, **kwargs)
# #self.match_database_duplicate_strains(viruses, sequences, **kwargs)
# #self.match_duplicate_accessions(sequences, **kwargs)
# #self.match_database_duplicate_accessions(sequences, **kwargs)
# self.link_viruses_to_sequences(viruses, sequences)
# #self.transfer_fields(viruses, sequences, self.virus_to_sequence_transfer_fields)
# print("")
# print("Upload Step")
# if not preview:
# print("Uploading viruses to " + self.database + "." + self.viruses_table)
# self.upload_documents(self.viruses_table, viruses, index='strain', **kwargs)
# print("Uploading sequences to " + self.database + "." + self.sequences_table)
# self.upload_documents(self.sequences_table, sequences, index='accession', **kwargs)
# else:
# print("Viruses:")
# print(json.dumps(viruses[0], indent=1))
# print("Sequences:")
# print(json.dumps(sequences[0], indent=1))
# print("Remove \"--preview\" to upload documents")
# print("Printed preview of viruses to be uploaded to make sure fields make sense")
#
# Path: vdb/upload.py
# def get_parser():
# parser = argparse.ArgumentParser()
# parser.add_argument('-db', '--database', default='vdb', help="database to upload to")
# parser.add_argument('--rethink_host', default=None, help="rethink host url")
# parser.add_argument('--auth_key', default=None, help="auth_key for rethink database")
# parser.add_argument('--local', default=False, action="store_true", help ="connect to local instance of rethinkdb database")
# parser.add_argument('-v', '--virus', help="virus name")
# parser.add_argument('--fname', help="input file name")
# parser.add_argument('--ftype', default='fasta', help="input file format, default \"fasta\", other is \"genbank\", \"accession\" or \"tsv\"")
# parser.add_argument('--fasta_header_fix', default=None, help="faster header fix file. Default: None.")
# parser.add_argument('--path', default="data/", help="path to fasta file, default is \"data/\"")
# parser.add_argument('--accessions', default=None, help="comma seperated list of accessions to be uploaded")
# parser.add_argument('--email', default=None, help="email to access NCBI database via entrez to get virus information")
# parser.add_argument('--overwrite', default=False, action="store_true", help ="Overwrite fields that are not none")
# parser.add_argument('--preview', default=False, action="store_true", help ="If included, preview a virus document to be uploaded")
# parser.add_argument('--replace', default=False, action="store_true", help ="If included, delete all documents in table")
#
# parser.add_argument('--source', default=None, help="source of fasta file")
# parser.add_argument('--locus', default=None, help="gene or genomic region for sequences")
# parser.add_argument('--host', default='human', help="host virus isolated from")
# parser.add_argument('--country', default=None, help="country virus isolated from")
# parser.add_argument('--authors', default=None, help="authors of source of sequences")
# parser.add_argument('--title', default=None, help="title of sequence release")
# parser.add_argument('--url', default=None, help="url of source of sequences")
# parser.add_argument('--public', default=True, dest='public', action="store_true", help ="sequences classified as public")
# parser.add_argument('--private', default=False, dest='public', action="store_false", help ="sequences classified as private")
# return parser
which might include code, classes, or functions. Output only the next line. | class flu_upload(upload): |
Given the code snippet: <|code_start|>sys.path.append('') # need to import from base
class rethink_interact(object):
def __init__(self, **kwargs):
<|code_end|>
, generate the next line using the imports in this file:
import os, shutil, sys, datetime, re, subprocess, json
import boto3
from rethinkdb import r
from base.rethink_io import rethink_io
and context (functions, classes, or occasionally code) from other files:
# Path: base/rethink_io.py
# class rethink_io(object):
# def __init__(self, **kwargs):
# pass
#
# def assign_rethink(self, rethink_host, auth_key, local=False, **kwargs):
# '''
# Assign rethink_host, auth_key, return as tuple
# '''
# if local:
# rethink_host = 'localhost'
# elif rethink_host is not None:
# rethink_host=rethink_host
# else:
# try:
# rethink_host = os.environ['RETHINK_HOST']
# except:
# raise Exception("Missing rethink host - is $RETHINK_HOST set?")
# if local:
# auth_key = None
# elif auth_key is not None:
# auth_key = auth_key
# else:
# try:
# auth_key = os.environ['RETHINK_AUTH_KEY']
# except:
# raise Exception("Missing rethink auth_key")
# return rethink_host, auth_key
#
# def connect_rethink(self, db, rethink_host='localhost', auth_key=None, **kwargs):
# '''
# Connect to rethink database,
# '''
# if rethink_host == 'localhost':
# try:
# conn = r.connect(host=rethink_host, port=28015, db=db).repl()
# print("Connected to the \"" + db + "\" database")
# return conn
# except:
# raise Exception("Failed to connect to the database, " + db)
# else:
# try:
# conn = r.connect(host=rethink_host, port=28015, db=db, auth_key=auth_key).repl()
# print("Connected to the \"" + db + "\" database")
# return conn
# except:
# raise Exception("Failed to connect to the database, " + db)
#
# def check_table_exists(self, database, table):
# '''
# Check for existing table
# '''
# existing_tables = r.db(database).table_list().run()
# if table not in existing_tables:
# raise Exception("No table exists yet for " + table + " available are " + str(existing_tables))
#
# def get_upload_date(self):
# return str(datetime.datetime.strftime(datetime.datetime.utcnow(),'%Y-%m-%d'))
#
# def get_upload_timestamp(self):
# return str(datetime.datetime.strftime(datetime.datetime.utcnow(),'%Y-%m-%d-%H-%M'))
#
# def check_optional_attributes(self, doc, optional_fields):
# '''
# Reassign unknowns from '?' or '' to 'None'
# Create and assign 'None' to optional attributes that don't exist
# '''
# for key in doc.keys():
# if doc[key] == '?' or doc[key] == '':
# doc[key] = None
# if isinstance(doc[key], (str)):
# doc[key] = doc[key].strip()
# for atr in optional_fields:
# if atr not in doc:
# doc[atr] = None
#
# def check_required_attributes(self, doc, required_fields, index_fields, output=False):
# '''
# Checks that required upload attributes are present and not equal to None for given virus
# :return: returns true if it has all required upload attributes, else returns false and prints missing attributes
# '''
# missing_attributes = []
# for atr in required_fields:
# if atr in doc and doc[atr] is not None:
# pass
# else:
# missing_attributes.append(atr)
# if len(missing_attributes) > 0:
# if output:
# print("This document is missing a required attribute and will be removed from upload sequences")
# print([doc[index] for index in index_fields if index in doc])
# print("Missing attributes: " + str(missing_attributes))
# return False
# else:
# return True
#
# def delete_extra_fields(self, doc, fields, index_fields):
# '''
# Delete attributes not defined as a field
# '''
# for key in doc.keys():
# if key not in fields:
# print("Deleting document info " + key + ": " + doc[key] + " from " + str([doc[index] for index in index_fields if index in doc]))
# del doc[key]
. Output only the next line. | self.rethink_io = rethink_io() |
Given the following code snippet before the placeholder: <|code_start|> parser.add_argument('--present', nargs='+', type=str, default=[], help="Select specific fields to be non-null ie \'--present field1 field2\'")
parser.add_argument('--interval', nargs='+', type=str, default=[], help="Select interval of values for fields \'--interval field1:value1,value2 field2:value1,value2\'")
parser.add_argument('--years_back', type=str, help='number of past years to sample sequences from \'--years_back field:value\'')
parser.add_argument('--relaxed_interval', action="store_true", help="Relaxed comparison to date interval, 2016-XX-XX in 2016-01-01 - 2016-03-01")
def duplicate_resolver(resolve_method):
method = str(resolve_method)
accepted_methods = ('keep_duplicates', 'choose_longest', 'choose_genbank', 'split_passage')
if method not in accepted_methods:
msg = '"{}" is not a supported duplicate resolve method'.format(method)
raise argparse.ArgumentTypeError(msg)
return method
parser.add_argument('--resolve_method', type=duplicate_resolver, default="choose_longest", help="Set method of resolving duplicates for the same locus, options are \'keep_duplicates\', \'choose_longest\', \'choose_genbank\' and \'split_passage\'")
return parser
class download(object):
def __init__(self, database, virus, **kwargs):
'''
parser for virus, fasta fields, output file names, output file format path, interval
'''
self.virus = virus.lower()
self.viruses_table = virus + "_viruses"
self.sequences_table = virus + "_sequences"
self.database = database.lower()
def connect_rethink(self, **kwargs):
if self.database not in ['vdb', 'test_vdb', 'test']:
raise Exception("Can't download from this database: " + self.database)
<|code_end|>
, predict the next line using imports from the current file:
import os, json, datetime, sys, re
import numpy as np
import argparse
import time
from rethinkdb import r
from Bio import SeqIO
from base.rethink_io import rethink_io
from collections import defaultdict
and context including class names, function names, and sometimes code from other files:
# Path: base/rethink_io.py
# class rethink_io(object):
# def __init__(self, **kwargs):
# pass
#
# def assign_rethink(self, rethink_host, auth_key, local=False, **kwargs):
# '''
# Assign rethink_host, auth_key, return as tuple
# '''
# if local:
# rethink_host = 'localhost'
# elif rethink_host is not None:
# rethink_host=rethink_host
# else:
# try:
# rethink_host = os.environ['RETHINK_HOST']
# except:
# raise Exception("Missing rethink host - is $RETHINK_HOST set?")
# if local:
# auth_key = None
# elif auth_key is not None:
# auth_key = auth_key
# else:
# try:
# auth_key = os.environ['RETHINK_AUTH_KEY']
# except:
# raise Exception("Missing rethink auth_key")
# return rethink_host, auth_key
#
# def connect_rethink(self, db, rethink_host='localhost', auth_key=None, **kwargs):
# '''
# Connect to rethink database,
# '''
# if rethink_host == 'localhost':
# try:
# conn = r.connect(host=rethink_host, port=28015, db=db).repl()
# print("Connected to the \"" + db + "\" database")
# return conn
# except:
# raise Exception("Failed to connect to the database, " + db)
# else:
# try:
# conn = r.connect(host=rethink_host, port=28015, db=db, auth_key=auth_key).repl()
# print("Connected to the \"" + db + "\" database")
# return conn
# except:
# raise Exception("Failed to connect to the database, " + db)
#
# def check_table_exists(self, database, table):
# '''
# Check for existing table
# '''
# existing_tables = r.db(database).table_list().run()
# if table not in existing_tables:
# raise Exception("No table exists yet for " + table + " available are " + str(existing_tables))
#
# def get_upload_date(self):
# return str(datetime.datetime.strftime(datetime.datetime.utcnow(),'%Y-%m-%d'))
#
# def get_upload_timestamp(self):
# return str(datetime.datetime.strftime(datetime.datetime.utcnow(),'%Y-%m-%d-%H-%M'))
#
# def check_optional_attributes(self, doc, optional_fields):
# '''
# Reassign unknowns from '?' or '' to 'None'
# Create and assign 'None' to optional attributes that don't exist
# '''
# for key in doc.keys():
# if doc[key] == '?' or doc[key] == '':
# doc[key] = None
# if isinstance(doc[key], (str)):
# doc[key] = doc[key].strip()
# for atr in optional_fields:
# if atr not in doc:
# doc[atr] = None
#
# def check_required_attributes(self, doc, required_fields, index_fields, output=False):
# '''
# Checks that required upload attributes are present and not equal to None for given virus
# :return: returns true if it has all required upload attributes, else returns false and prints missing attributes
# '''
# missing_attributes = []
# for atr in required_fields:
# if atr in doc and doc[atr] is not None:
# pass
# else:
# missing_attributes.append(atr)
# if len(missing_attributes) > 0:
# if output:
# print("This document is missing a required attribute and will be removed from upload sequences")
# print([doc[index] for index in index_fields if index in doc])
# print("Missing attributes: " + str(missing_attributes))
# return False
# else:
# return True
#
# def delete_extra_fields(self, doc, fields, index_fields):
# '''
# Delete attributes not defined as a field
# '''
# for key in doc.keys():
# if key not in fields:
# print("Deleting document info " + key + ": " + doc[key] + " from " + str([doc[index] for index in index_fields if index in doc]))
# del doc[key]
. Output only the next line. | self.rethink_io = rethink_io() |
Continue the code snippet: <|code_start|># If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.1'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.todo', 'sphinx.ext.inheritance_diagram',
'sphinx.ext.extlinks']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Sider'
copyright = str(datetime.date.today().year) + u', Hong Minhee'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
<|code_end|>
. Use current file imports:
import sys, os, os.path, glob, datetime
from siderdocs import lower_sprintf_str
from sider.version import VERSION
and context (classes, functions, or code) from other files:
# Path: sider/version.py
# VERSION = '{0}.{1}.{2}'.format(*VERSION_INFO)
. Output only the next line. | version = VERSION |
Continue the code snippet: <|code_start|>
def test_chunk():
data_length = 1000
chunk_length = 7
data = list(range(data_length))
<|code_end|>
. Use current file imports:
import collections
from sider import utils
and context (classes, functions, or code) from other files:
# Path: sider/utils.py
# def chunk(iterable, n):
. Output only the next line. | chunks = utils.chunk(data, chunk_length) |
Next line prediction: <|code_start|>from __future__ import with_statement
try:
except ImportError:
def readme():
try:
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
return f.read()
except (IOError, OSError):
return ''
setup(name='Sider',
packages=['sider', 'sider.ext', "sidertests"],
py_modules=["sider__exttest"],
<|code_end|>
. Use current file imports:
(import os.path
from setuptools import setup
from distutils.core import setup
from sider.version import VERSION)
and context including class names, function names, or small code snippets from other files:
# Path: sider/version.py
# VERSION = '{0}.{1}.{2}'.format(*VERSION_INFO)
. Output only the next line. | version=VERSION, |
Here is a snippet: <|code_start|> key_type=self.key_type, value_type=self.value_type)
if value:
pipe = session.client.pipeline()
pipe.delete(key)
obj._raw_update(value, pipe)
pipe.execute()
else:
session.client.delete(key)
return obj
class List(Value):
"""The type object for :class:`sider.list.List` objects and other
:class:`collections.Sequence` objects except strings.
(Use :class:`ByteString` or :class:`UnicodeString` for strings.)
:param value_type: the type of values the list will contain.
default is :class:`String`
:type value_type: :class:`Bulk`, :class:`type`
"""
def __init__(self, value_type=None):
if value_type is None:
self.value_type = String()
else:
self.value_type = Bulk.ensure_value_type(value_type,
parameter='value_type')
def load_value(self, session, key):
<|code_end|>
. Write the next line using the current file imports:
import sys
import re
import collections
import numbers
import datetime
import uuid
from .lazyimport import list, set, sortedset
from .datetime import UTC, FixedOffset
from .hash import Hash
from .hash import Hash
and context from other files:
# Path: sider/lazyimport.py
# class DeferredModule(types.ModuleType):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, name):
# def __repr__(self):
#
# Path: sider/datetime.py
# UTC = Utc()
#
# class FixedOffset(datetime.tzinfo):
# """Fixed offset in minutes east from :const:`UTC`.
#
# .. sourcecode:: pycon
#
# >>> import datetime
# >>> day = FixedOffset(datetime.timedelta(days=1))
# >>> day
# sider.datetime.FixedOffset(1440)
# >>> day.tzname(None)
# '+24:00'
# >>> half = FixedOffset(-720)
# >>> half
# sider.datetime.FixedOffset(-720)
# >>> half.tzname(None)
# '-12:00'
# >>> half.utcoffset(None)
# datetime.timedelta(-1, 43200)
# >>> zero = FixedOffset(0)
# >>> zero.tzname(None)
# 'UTC'
# >>> zero.utcoffset(None)
# datetime.timedelta(0)
#
# :param offset: the offset integer in minutes,
# or :class:`~datetime.timedelta` (from a minute to a day)
# :type offset: :class:`numbers.Integral`, :class:`datetime.timedelta`
# :param name: an optional name. if not present, automatically generated
# :type name: :class:`basestring`
# :raises exceptions.ValueError: when ``offset``'s precision is too short
# or too long
#
# """
#
# #: (:class:`datetime.timedelta`) The maximum precision of
# #: :meth:`utcoffset()`.
# MAX_PRECISION = datetime.timedelta(days=1)
#
# #: (:class:`datetime.timedelta`) The minimum precision of
# #: :meth:`utcoffset()`.
# MIN_PRECISION = datetime.timedelta(minutes=1)
#
# def __init__(self, offset, name=None):
# if isinstance(offset, numbers.Integral):
# offset = datetime.timedelta(minutes=offset)
# elif not isinstance(offset, datetime.timedelta):
# raise TypeError('offset must be an integer or datetime.timedelta')
# if offset < self.MIN_PRECISION and total_seconds(offset) > 0:
# raise ValueError('the minimum precision of offset is minute')
# elif offset > self.MAX_PRECISION:
# raise ValueError('the maximum precision of offset is hour')
# if name is None:
# seconds = int(total_seconds(offset))
# if seconds != 0:
# name = '{0:+03d}:{1:02d}'.format(seconds // 3600,
# abs(seconds) % 3600 // 60)
# else:
# name = 'UTC'
# elif not isinstance(name, basestring):
# raise TypeError('name must be a string, not ' + repr(name))
# self.offset = offset
# self.name = name
#
# def utcoffset(self, datetime):
# return self.offset
#
# def tzname(self, datetime):
# return self.name
#
# def dst(self):
# return ZERO_DELTA
#
# def __repr__(self):
# cls = type(self)
# min = int(total_seconds(self.offset) / 60)
# return '{0}.{1}({2!r})'.format(cls.__module__, cls.__name__, min)
, which may include functions, classes, or code. Output only the next line. | return list.List(session, key, value_type=self.value_type) |
Given the code snippet: <|code_start|> pipe.execute()
return obj
def __hash__(self):
return super(List, self).__hash__() * hash(self.value_type)
def __eq__(self, operand):
if super(List, self).__eq__(operand):
return self.value_type == operand.value_type
return False
class Set(Value):
"""The type object for :class:`sider.set.Set` objects and other
:class:`collections.Set` objects.
:param value_type: the type of values the set will contain.
default is :class:`String`
:type value_type: :class:`Bulk`, :class:`type`
"""
def __init__(self, value_type=None):
if value_type is None:
self.value_type = String()
else:
self.value_type = Bulk.ensure_value_type(value_type,
parameter='value_type')
def load_value(self, session, key):
<|code_end|>
, generate the next line using the imports in this file:
import sys
import re
import collections
import numbers
import datetime
import uuid
from .lazyimport import list, set, sortedset
from .datetime import UTC, FixedOffset
from .hash import Hash
from .hash import Hash
and context (functions, classes, or occasionally code) from other files:
# Path: sider/lazyimport.py
# class DeferredModule(types.ModuleType):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, name):
# def __repr__(self):
#
# Path: sider/datetime.py
# UTC = Utc()
#
# class FixedOffset(datetime.tzinfo):
# """Fixed offset in minutes east from :const:`UTC`.
#
# .. sourcecode:: pycon
#
# >>> import datetime
# >>> day = FixedOffset(datetime.timedelta(days=1))
# >>> day
# sider.datetime.FixedOffset(1440)
# >>> day.tzname(None)
# '+24:00'
# >>> half = FixedOffset(-720)
# >>> half
# sider.datetime.FixedOffset(-720)
# >>> half.tzname(None)
# '-12:00'
# >>> half.utcoffset(None)
# datetime.timedelta(-1, 43200)
# >>> zero = FixedOffset(0)
# >>> zero.tzname(None)
# 'UTC'
# >>> zero.utcoffset(None)
# datetime.timedelta(0)
#
# :param offset: the offset integer in minutes,
# or :class:`~datetime.timedelta` (from a minute to a day)
# :type offset: :class:`numbers.Integral`, :class:`datetime.timedelta`
# :param name: an optional name. if not present, automatically generated
# :type name: :class:`basestring`
# :raises exceptions.ValueError: when ``offset``'s precision is too short
# or too long
#
# """
#
# #: (:class:`datetime.timedelta`) The maximum precision of
# #: :meth:`utcoffset()`.
# MAX_PRECISION = datetime.timedelta(days=1)
#
# #: (:class:`datetime.timedelta`) The minimum precision of
# #: :meth:`utcoffset()`.
# MIN_PRECISION = datetime.timedelta(minutes=1)
#
# def __init__(self, offset, name=None):
# if isinstance(offset, numbers.Integral):
# offset = datetime.timedelta(minutes=offset)
# elif not isinstance(offset, datetime.timedelta):
# raise TypeError('offset must be an integer or datetime.timedelta')
# if offset < self.MIN_PRECISION and total_seconds(offset) > 0:
# raise ValueError('the minimum precision of offset is minute')
# elif offset > self.MAX_PRECISION:
# raise ValueError('the maximum precision of offset is hour')
# if name is None:
# seconds = int(total_seconds(offset))
# if seconds != 0:
# name = '{0:+03d}:{1:02d}'.format(seconds // 3600,
# abs(seconds) % 3600 // 60)
# else:
# name = 'UTC'
# elif not isinstance(name, basestring):
# raise TypeError('name must be a string, not ' + repr(name))
# self.offset = offset
# self.name = name
#
# def utcoffset(self, datetime):
# return self.offset
#
# def tzname(self, datetime):
# return self.name
#
# def dst(self):
# return ZERO_DELTA
#
# def __repr__(self):
# cls = type(self)
# min = int(total_seconds(self.offset) / 60)
# return '{0}.{1}({2!r})'.format(cls.__module__, cls.__name__, min)
. Output only the next line. | return set.Set(session, key, value_type=self.value_type) |
Using the snippet: <|code_start|> def save_value(self, session, key, value):
if not isinstance(value, collections.Set):
raise TypeError('expected a set-like object, not ' +
repr(value))
obj = set.Set(session, key, value_type=self.value_type)
pipe = session.client.pipeline()
pipe.delete(key)
obj._raw_update(value, pipe)
pipe.execute()
return obj
def __hash__(self):
return super(Set, self).__hash__() * hash(self.value_type)
def __eq__(self, operand):
if super(Set, self).__eq__(operand):
return self.value_type == operand.value_type
return False
class SortedSet(Set):
"""The type object for :class:`sider.sortedset.SortedSet` objects.
:param value_type: the type of values the sorted set will contain.
default is :class:`String`
:type value_type: :class:`Bulk`, :class:`type`
"""
def load_value(self, session, key):
<|code_end|>
, determine the next line of code. You have imports:
import sys
import re
import collections
import numbers
import datetime
import uuid
from .lazyimport import list, set, sortedset
from .datetime import UTC, FixedOffset
from .hash import Hash
from .hash import Hash
and context (class names, function names, or code) available:
# Path: sider/lazyimport.py
# class DeferredModule(types.ModuleType):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, name):
# def __repr__(self):
#
# Path: sider/datetime.py
# UTC = Utc()
#
# class FixedOffset(datetime.tzinfo):
# """Fixed offset in minutes east from :const:`UTC`.
#
# .. sourcecode:: pycon
#
# >>> import datetime
# >>> day = FixedOffset(datetime.timedelta(days=1))
# >>> day
# sider.datetime.FixedOffset(1440)
# >>> day.tzname(None)
# '+24:00'
# >>> half = FixedOffset(-720)
# >>> half
# sider.datetime.FixedOffset(-720)
# >>> half.tzname(None)
# '-12:00'
# >>> half.utcoffset(None)
# datetime.timedelta(-1, 43200)
# >>> zero = FixedOffset(0)
# >>> zero.tzname(None)
# 'UTC'
# >>> zero.utcoffset(None)
# datetime.timedelta(0)
#
# :param offset: the offset integer in minutes,
# or :class:`~datetime.timedelta` (from a minute to a day)
# :type offset: :class:`numbers.Integral`, :class:`datetime.timedelta`
# :param name: an optional name. if not present, automatically generated
# :type name: :class:`basestring`
# :raises exceptions.ValueError: when ``offset``'s precision is too short
# or too long
#
# """
#
# #: (:class:`datetime.timedelta`) The maximum precision of
# #: :meth:`utcoffset()`.
# MAX_PRECISION = datetime.timedelta(days=1)
#
# #: (:class:`datetime.timedelta`) The minimum precision of
# #: :meth:`utcoffset()`.
# MIN_PRECISION = datetime.timedelta(minutes=1)
#
# def __init__(self, offset, name=None):
# if isinstance(offset, numbers.Integral):
# offset = datetime.timedelta(minutes=offset)
# elif not isinstance(offset, datetime.timedelta):
# raise TypeError('offset must be an integer or datetime.timedelta')
# if offset < self.MIN_PRECISION and total_seconds(offset) > 0:
# raise ValueError('the minimum precision of offset is minute')
# elif offset > self.MAX_PRECISION:
# raise ValueError('the maximum precision of offset is hour')
# if name is None:
# seconds = int(total_seconds(offset))
# if seconds != 0:
# name = '{0:+03d}:{1:02d}'.format(seconds // 3600,
# abs(seconds) % 3600 // 60)
# else:
# name = 'UTC'
# elif not isinstance(name, basestring):
# raise TypeError('name must be a string, not ' + repr(name))
# self.offset = offset
# self.name = name
#
# def utcoffset(self, datetime):
# return self.offset
#
# def tzname(self, datetime):
# return self.name
#
# def dst(self):
# return ZERO_DELTA
#
# def __repr__(self):
# cls = type(self)
# min = int(total_seconds(self.offset) / 60)
# return '{0}.{1}({2!r})'.format(cls.__module__, cls.__name__, min)
. Output only the next line. | return sortedset.SortedSet(session, key, value_type=self.value_type) |
Using the snippet: <|code_start|> tzinfo=sider.datetime.Utc())
>>> b = dt.parse_datetime('2012-03-28T18:21:34.638972+09:00')
>>> b # doctest: +NORMALIZE_WHITESPACE
datetime.datetime(2012, 3, 28, 18, 21, 34, 638972,
tzinfo=sider.datetime.FixedOffset(540))
>>> a == b
True
:param bulk: a :rfc:`3339` formatted string
:type bulk: :class:`basestring`
:returns: a parsing result
:rtype: :class:`datetime.datetime`
.. note::
It is for internal use and :meth:`decode()` method actually
uses this method.
"""
match = self.DATETIME_PATTERN.search(bulk)
if match:
year = int(match.group('year'))
month = int(match.group('month'))
day = int(match.group('day'))
hour = int(match.group('hour'))
minute = int(match.group('minute'))
second = int(match.group('second'))
microsecond = int(match.group('microsecond'))
if match.group('tz'):
if match.group('tz_utc'):
<|code_end|>
, determine the next line of code. You have imports:
import sys
import re
import collections
import numbers
import datetime
import uuid
from .lazyimport import list, set, sortedset
from .datetime import UTC, FixedOffset
from .hash import Hash
from .hash import Hash
and context (class names, function names, or code) available:
# Path: sider/lazyimport.py
# class DeferredModule(types.ModuleType):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, name):
# def __repr__(self):
#
# Path: sider/datetime.py
# UTC = Utc()
#
# class FixedOffset(datetime.tzinfo):
# """Fixed offset in minutes east from :const:`UTC`.
#
# .. sourcecode:: pycon
#
# >>> import datetime
# >>> day = FixedOffset(datetime.timedelta(days=1))
# >>> day
# sider.datetime.FixedOffset(1440)
# >>> day.tzname(None)
# '+24:00'
# >>> half = FixedOffset(-720)
# >>> half
# sider.datetime.FixedOffset(-720)
# >>> half.tzname(None)
# '-12:00'
# >>> half.utcoffset(None)
# datetime.timedelta(-1, 43200)
# >>> zero = FixedOffset(0)
# >>> zero.tzname(None)
# 'UTC'
# >>> zero.utcoffset(None)
# datetime.timedelta(0)
#
# :param offset: the offset integer in minutes,
# or :class:`~datetime.timedelta` (from a minute to a day)
# :type offset: :class:`numbers.Integral`, :class:`datetime.timedelta`
# :param name: an optional name. if not present, automatically generated
# :type name: :class:`basestring`
# :raises exceptions.ValueError: when ``offset``'s precision is too short
# or too long
#
# """
#
# #: (:class:`datetime.timedelta`) The maximum precision of
# #: :meth:`utcoffset()`.
# MAX_PRECISION = datetime.timedelta(days=1)
#
# #: (:class:`datetime.timedelta`) The minimum precision of
# #: :meth:`utcoffset()`.
# MIN_PRECISION = datetime.timedelta(minutes=1)
#
# def __init__(self, offset, name=None):
# if isinstance(offset, numbers.Integral):
# offset = datetime.timedelta(minutes=offset)
# elif not isinstance(offset, datetime.timedelta):
# raise TypeError('offset must be an integer or datetime.timedelta')
# if offset < self.MIN_PRECISION and total_seconds(offset) > 0:
# raise ValueError('the minimum precision of offset is minute')
# elif offset > self.MAX_PRECISION:
# raise ValueError('the maximum precision of offset is hour')
# if name is None:
# seconds = int(total_seconds(offset))
# if seconds != 0:
# name = '{0:+03d}:{1:02d}'.format(seconds // 3600,
# abs(seconds) % 3600 // 60)
# else:
# name = 'UTC'
# elif not isinstance(name, basestring):
# raise TypeError('name must be a string, not ' + repr(name))
# self.offset = offset
# self.name = name
#
# def utcoffset(self, datetime):
# return self.offset
#
# def tzname(self, datetime):
# return self.name
#
# def dst(self):
# return ZERO_DELTA
#
# def __repr__(self):
# cls = type(self)
# min = int(total_seconds(self.offset) / 60)
# return '{0}.{1}({2!r})'.format(cls.__module__, cls.__name__, min)
. Output only the next line. | tzinfo = UTC |
Predict the next line for this snippet: <|code_start|> True
:param bulk: a :rfc:`3339` formatted string
:type bulk: :class:`basestring`
:returns: a parsing result
:rtype: :class:`datetime.datetime`
.. note::
It is for internal use and :meth:`decode()` method actually
uses this method.
"""
match = self.DATETIME_PATTERN.search(bulk)
if match:
year = int(match.group('year'))
month = int(match.group('month'))
day = int(match.group('day'))
hour = int(match.group('hour'))
minute = int(match.group('minute'))
second = int(match.group('second'))
microsecond = int(match.group('microsecond'))
if match.group('tz'):
if match.group('tz_utc'):
tzinfo = UTC
else:
tzplus = match.group('tz_offset_sign') == '+'
tzhour = int(match.group('tz_offset_hour'))
tzmin = int(match.group('tz_offset_minute'))
tzoffset = datetime.timedelta(hours=tzhour, minutes=tzmin)
<|code_end|>
with the help of current file imports:
import sys
import re
import collections
import numbers
import datetime
import uuid
from .lazyimport import list, set, sortedset
from .datetime import UTC, FixedOffset
from .hash import Hash
from .hash import Hash
and context from other files:
# Path: sider/lazyimport.py
# class DeferredModule(types.ModuleType):
# def __init__(self, *args, **kwargs):
# def __getattr__(self, name):
# def __repr__(self):
#
# Path: sider/datetime.py
# UTC = Utc()
#
# class FixedOffset(datetime.tzinfo):
# """Fixed offset in minutes east from :const:`UTC`.
#
# .. sourcecode:: pycon
#
# >>> import datetime
# >>> day = FixedOffset(datetime.timedelta(days=1))
# >>> day
# sider.datetime.FixedOffset(1440)
# >>> day.tzname(None)
# '+24:00'
# >>> half = FixedOffset(-720)
# >>> half
# sider.datetime.FixedOffset(-720)
# >>> half.tzname(None)
# '-12:00'
# >>> half.utcoffset(None)
# datetime.timedelta(-1, 43200)
# >>> zero = FixedOffset(0)
# >>> zero.tzname(None)
# 'UTC'
# >>> zero.utcoffset(None)
# datetime.timedelta(0)
#
# :param offset: the offset integer in minutes,
# or :class:`~datetime.timedelta` (from a minute to a day)
# :type offset: :class:`numbers.Integral`, :class:`datetime.timedelta`
# :param name: an optional name. if not present, automatically generated
# :type name: :class:`basestring`
# :raises exceptions.ValueError: when ``offset``'s precision is too short
# or too long
#
# """
#
# #: (:class:`datetime.timedelta`) The maximum precision of
# #: :meth:`utcoffset()`.
# MAX_PRECISION = datetime.timedelta(days=1)
#
# #: (:class:`datetime.timedelta`) The minimum precision of
# #: :meth:`utcoffset()`.
# MIN_PRECISION = datetime.timedelta(minutes=1)
#
# def __init__(self, offset, name=None):
# if isinstance(offset, numbers.Integral):
# offset = datetime.timedelta(minutes=offset)
# elif not isinstance(offset, datetime.timedelta):
# raise TypeError('offset must be an integer or datetime.timedelta')
# if offset < self.MIN_PRECISION and total_seconds(offset) > 0:
# raise ValueError('the minimum precision of offset is minute')
# elif offset > self.MAX_PRECISION:
# raise ValueError('the maximum precision of offset is hour')
# if name is None:
# seconds = int(total_seconds(offset))
# if seconds != 0:
# name = '{0:+03d}:{1:02d}'.format(seconds // 3600,
# abs(seconds) % 3600 // 60)
# else:
# name = 'UTC'
# elif not isinstance(name, basestring):
# raise TypeError('name must be a string, not ' + repr(name))
# self.offset = offset
# self.name = name
#
# def utcoffset(self, datetime):
# return self.offset
#
# def tzname(self, datetime):
# return self.name
#
# def dst(self):
# return ZERO_DELTA
#
# def __repr__(self):
# cls = type(self)
# min = int(total_seconds(self.offset) / 60)
# return '{0}.{1}({2!r})'.format(cls.__module__, cls.__name__, min)
, which may contain function names, class names, or code. Output only the next line. | tzinfo = FixedOffset(tzoffset if tzplus else -tzoffset) |
Next line prediction: <|code_start|> finally:
if cc is not None:
cc.switch(*next_args)
c1 = greenlet.greenlet(test)
c2 = greenlet.greenlet(test)
c1.switch(generator(),
(c2, (generator(), (c1, ())) + args2),
*args1)
else:
def coro_test(*a, **k):
pass # skip
def test_get_ident():
result = [None, None]
local = {}
def run():
value = yield
local[get_ident()] = value
result_idx = yield
result[result_idx] = local.setdefault(get_ident())
thread_test(run, (123, 0), (456, 1))
assert result == [123, 456]
if greenlet:
result = [None, None]
coro_test(run, (123, 0), (456, 1))
assert result == [123, 456]
def test_local_dict():
<|code_end|>
. Use current file imports:
(import threading
import greenlet
from sider.threadlocal import LocalDict, get_ident)
and context including class names, function names, or small code snippets from other files:
# Path: sider/threadlocal.py
# class LocalDict(collections.MutableMapping):
# def __init__(self, mapping=[], **keywords):
# def current(self):
# def __len__(self):
# def __iter__(self):
# def __contains__(self, value):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def copy(self):
# def get(self, key, default=None):
# def has_key(self, key):
# def items(self):
# def iteritems(self):
# def iterkeys(self):
# def itervalues(self):
# def keys(self):
# def values(self):
# def clear(self):
# def pop(self, key, *args):
# def popitem(self):
# def setdefault(self, key, default=None):
# def update(self, mapping, **keywords):
. Output only the next line. | local = LocalDict() |
Given the following code snippet before the placeholder: <|code_start|>
if greenlet:
def coro_test(generator, args1=(), args2=()):
def test(g, v, *args):
cc, next_args = v
next(g)
for arg in args:
try:
g.send(arg)
except StopIteration:
break
finally:
if cc is not None:
cc.switch(*next_args)
c1 = greenlet.greenlet(test)
c2 = greenlet.greenlet(test)
c1.switch(generator(),
(c2, (generator(), (c1, ())) + args2),
*args1)
else:
def coro_test(*a, **k):
pass # skip
def test_get_ident():
result = [None, None]
local = {}
def run():
value = yield
<|code_end|>
, predict the next line using imports from the current file:
import threading
import greenlet
from sider.threadlocal import LocalDict, get_ident
and context including class names, function names, and sometimes code from other files:
# Path: sider/threadlocal.py
# class LocalDict(collections.MutableMapping):
# def __init__(self, mapping=[], **keywords):
# def current(self):
# def __len__(self):
# def __iter__(self):
# def __contains__(self, value):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def copy(self):
# def get(self, key, default=None):
# def has_key(self, key):
# def items(self):
# def iteritems(self):
# def iterkeys(self):
# def itervalues(self):
# def keys(self):
# def values(self):
# def clear(self):
# def pop(self, key, *args):
# def popitem(self):
# def setdefault(self, key, default=None):
# def update(self, mapping, **keywords):
. Output only the next line. | local[get_ident()] = value |
Given the code snippet: <|code_start|>def test_rooms_get(logged_rocket):
rooms_get = logged_rocket.rooms_get().json()
assert rooms_get.get("success")
def test_rooms_clean_history(logged_rocket):
rooms_clean_history = logged_rocket.rooms_clean_history(
room_id="GENERAL",
latest="2016-09-30T13:42:25.304Z",
oldest="2016-05-30T13:42:25.304Z",
).json()
assert rooms_clean_history.get("success")
def test_rooms_favorite(logged_rocket):
rooms_favorite = logged_rocket.rooms_favorite(
room_id="GENERAL", favorite=True
).json()
assert rooms_favorite.get("success")
rooms_favorite = logged_rocket.rooms_favorite(
room_name="general", favorite=True
).json()
assert rooms_favorite.get("success")
rooms_favorite = logged_rocket.rooms_favorite(
room_id="unexisting_channel", favorite=True
).json()
assert not rooms_favorite.get("success")
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
and context (functions, classes, or occasionally code) from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Continue the code snippet: <|code_start|>
def test_im_list_everyone(logged_rocket):
im_list_everyone = logged_rocket.im_list_everyone().json()
assert im_list_everyone.get("success")
def test_im_history(logged_rocket, recipient_user):
im_create = logged_rocket.im_create(recipient_user).json()
room_id = im_create.get("room").get("_id")
im_history = logged_rocket.im_history(room_id).json()
assert im_history.get("success")
def test_im_members(logged_rocket, recipient_user):
im_create = logged_rocket.im_create(recipient_user).json()
room_id = im_create.get("room").get("_id")
im_members = logged_rocket.im_members(room_id=room_id).json()
assert im_members.get("success")
assert im_members.get("members")[0].get("name") == "user1"
def test_im_messages(logged_rocket, recipient_user):
im_message = logged_rocket.im_messages(username=recipient_user).json()
assert im_message.get("success")
im_create = logged_rocket.im_create(recipient_user).json()
room_id = im_create.get("room").get("_id")
im_message = logged_rocket.im_messages(room_id=room_id).json()
assert im_message.get("success")
<|code_end|>
. Use current file imports:
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
and context (classes, functions, or code) from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Predict the next line for this snippet: <|code_start|> _test_group_id = (
logged_rocket.groups_create(test_group_name).json().get("group").get("_id")
)
return _test_group_id
def test_groups_list_all(logged_rocket):
groups_list = logged_rocket.groups_list_all().json()
assert groups_list.get("success")
assert "groups" in groups_list
def test_groups_list(logged_rocket):
groups_list = logged_rocket.groups_list().json()
assert groups_list.get("success")
assert "groups" in groups_list
def test_groups_info(logged_rocket, test_group_name, test_group_id):
groups_info_by_id = logged_rocket.groups_info(room_id=test_group_id).json()
assert groups_info_by_id.get("success")
assert "group" in groups_info_by_id
assert groups_info_by_id.get("group").get("_id") == test_group_id
groups_info_by_name = logged_rocket.groups_info(room_name=test_group_name).json()
assert groups_info_by_name.get("success")
assert "group" in groups_info_by_name
assert groups_info_by_name.get("group").get("_id") == test_group_id
<|code_end|>
with the help of current file imports:
import uuid
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
and context from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Continue the code snippet: <|code_start|> self.server_url + self.API_path + method,
data=reduced_args,
files=files,
headers=self.headers,
verify=self.ssl_verify,
cert=self.cert,
proxies=self.proxies,
timeout=self.timeout,
)
# Authentication
def login(self, user, password):
request_data = {"password": password}
if re.match(
r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",
user,
):
request_data["user"] = user
else:
request_data["username"] = user
login_request = requests.post(
self.server_url + self.API_path + "login",
data=request_data,
verify=self.ssl_verify,
proxies=self.proxies,
cert=self.cert,
timeout=self.timeout,
)
if login_request.status_code == 401:
<|code_end|>
. Use current file imports:
import re
import requests
from rocketchat_API.APIExceptions.RocketExceptions import (
RocketAuthenticationException,
RocketConnectionException,
)
and context (classes, functions, or code) from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketAuthenticationException(Exception):
# pass
#
# class RocketConnectionException(Exception):
# pass
. Output only the next line. | raise RocketAuthenticationException() |
Predict the next line after this snippet: <|code_start|> def login(self, user, password):
request_data = {"password": password}
if re.match(
r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",
user,
):
request_data["user"] = user
else:
request_data["username"] = user
login_request = requests.post(
self.server_url + self.API_path + "login",
data=request_data,
verify=self.ssl_verify,
proxies=self.proxies,
cert=self.cert,
timeout=self.timeout,
)
if login_request.status_code == 401:
raise RocketAuthenticationException()
if (
login_request.status_code == 200
and login_request.json().get("status") == "success"
):
self.headers["X-Auth-Token"] = (
login_request.json().get("data").get("authToken")
)
self.headers["X-User-Id"] = login_request.json().get("data").get("userId")
return login_request
<|code_end|>
using the current file's imports:
import re
import requests
from rocketchat_API.APIExceptions.RocketExceptions import (
RocketAuthenticationException,
RocketConnectionException,
)
and any relevant context from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketAuthenticationException(Exception):
# pass
#
# class RocketConnectionException(Exception):
# pass
. Output only the next line. | raise RocketConnectionException() |
Predict the next line after this snippet: <|code_start|> yield _testuser_id
logged_rocket.users_delete(_testuser_id)
def test_channels_list(logged_rocket):
channels_list = logged_rocket.channels_list().json()
assert channels_list.get("success")
assert "channels" in channels_list
def test_channels_list_joined(logged_rocket):
channels_list_joined = logged_rocket.channels_list_joined().json()
assert channels_list_joined.get("success")
assert "channels" in channels_list_joined
def test_channels_info(logged_rocket):
channels_info = logged_rocket.channels_info(room_id="GENERAL").json()
assert channels_info.get("success")
assert "channel" in channels_info
assert channels_info.get("channel").get("_id") == "GENERAL"
channel_name = channels_info.get("channel").get("name")
channels_info = logged_rocket.channels_info(channel=channel_name).json()
assert channels_info.get("success")
assert "channel" in channels_info
assert channels_info.get("channel").get("_id") == "GENERAL"
assert channels_info.get("channel").get("name") == channel_name
<|code_end|>
using the current file's imports:
import uuid
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
and any relevant context from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Continue the code snippet: <|code_start|>
class RocketChatUsers(RocketChatBase):
def me(self, **kwargs):
"""Displays information about the authenticated user."""
return self.call_api_get("me", kwargs=kwargs)
def users_info(self, user_id=None, username=None, **kwargs):
"""Gets a user’s information, limited to the caller’s permissions."""
if user_id:
return self.call_api_get("users.info", userId=user_id, kwargs=kwargs)
if username:
return self.call_api_get("users.info", username=username, kwargs=kwargs)
<|code_end|>
. Use current file imports:
import mimetypes
import os
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
from rocketchat_API.APISections.base import RocketChatBase
and context (classes, functions, or code) from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
#
# Path: rocketchat_API/APISections/base.py
# class RocketChatBase:
# API_path = "/api/v1/"
#
# def __init__(
# self,
# user=None,
# password=None,
# auth_token=None,
# user_id=None,
# server_url="http://127.0.0.1:3000",
# ssl_verify=True,
# proxies=None,
# timeout=30,
# session=None,
# client_certs=None,
# ):
# """Creates a RocketChat object and does login on the specified server"""
# self.headers = {}
# self.server_url = server_url
# self.proxies = proxies
# self.ssl_verify = ssl_verify
# self.cert = client_certs
# self.timeout = timeout
# self.req = session or requests
# if user and password:
# self.login(user, password) # skipcq: PTC-W1006
# if auth_token and user_id:
# self.headers["X-Auth-Token"] = auth_token
# self.headers["X-User-Id"] = user_id
#
# @staticmethod
# def __reduce_kwargs(kwargs):
# if "kwargs" in kwargs:
# for arg in kwargs["kwargs"].keys():
# kwargs[arg] = kwargs["kwargs"][arg]
#
# del kwargs["kwargs"]
# return kwargs
#
# def call_api_delete(self, method):
# url = self.server_url + self.API_path + method
#
# return self.req.delete(
# url,
# headers=self.headers,
# verify=self.ssl_verify,
# cert=self.cert,
# proxies=self.proxies,
# timeout=self.timeout,
# )
#
# def call_api_get(self, method, api_path=None, **kwargs):
# args = self.__reduce_kwargs(kwargs)
# if not api_path:
# api_path = self.API_path
# url = self.server_url + api_path + method
# # convert to key[]=val1&key[]=val2 for args like key=[val1, val2], else key=val
# params = "&".join(
# "&".join(i + "[]=" + j for j in args[i])
# if isinstance(args[i], list)
# else i + "=" + str(args[i])
# for i in args
# )
# return self.req.get(
# "%s?%s" % (url, params),
# headers=self.headers,
# verify=self.ssl_verify,
# cert=self.cert,
# proxies=self.proxies,
# timeout=self.timeout,
# )
#
# def call_api_post(self, method, files=None, use_json=None, **kwargs):
# reduced_args = self.__reduce_kwargs(kwargs)
# # Since pass is a reserved word in Python it has to be injected on the request dict
# # Some methods use pass (users.register) and others password (users.create)
# if "password" in reduced_args and method != "users.create":
# reduced_args["pass"] = reduced_args["password"]
# if use_json is None:
# # see https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests
# # > The json parameter is ignored if either data or files is passed.
# # If files are sent, json should not be used
# use_json = files is None
# if use_json:
# return self.req.post(
# self.server_url + self.API_path + method,
# json=reduced_args,
# files=files,
# headers=self.headers,
# verify=self.ssl_verify,
# cert=self.cert,
# proxies=self.proxies,
# timeout=self.timeout,
# )
# return self.req.post(
# self.server_url + self.API_path + method,
# data=reduced_args,
# files=files,
# headers=self.headers,
# verify=self.ssl_verify,
# cert=self.cert,
# proxies=self.proxies,
# timeout=self.timeout,
# )
#
# # Authentication
#
# def login(self, user, password):
# request_data = {"password": password}
# if re.match(
# r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",
# user,
# ):
# request_data["user"] = user
# else:
# request_data["username"] = user
# login_request = requests.post(
# self.server_url + self.API_path + "login",
# data=request_data,
# verify=self.ssl_verify,
# proxies=self.proxies,
# cert=self.cert,
# timeout=self.timeout,
# )
# if login_request.status_code == 401:
# raise RocketAuthenticationException()
#
# if (
# login_request.status_code == 200
# and login_request.json().get("status") == "success"
# ):
# self.headers["X-Auth-Token"] = (
# login_request.json().get("data").get("authToken")
# )
# self.headers["X-User-Id"] = login_request.json().get("data").get("userId")
# return login_request
#
# raise RocketConnectionException()
#
# def logout(self, **kwargs):
# """Invalidate your REST rocketchat_API authentication token."""
# return self.call_api_post("logout", kwargs=kwargs)
. Output only the next line. | raise RocketMissingParamException("userID or username required") |
Using the snippet: <|code_start|>
def test_chat_post_notext_message(logged_rocket):
chat_post_message = logged_rocket.chat_post_message(None, channel="GENERAL").json()
assert chat_post_message.get("channel") == "GENERAL"
assert chat_post_message.get("message").get("msg") == ""
assert chat_post_message.get("success")
def test_chat_post_update_delete_message(logged_rocket):
chat_post_message = logged_rocket.chat_post_message(
"hello", channel="GENERAL"
).json()
assert chat_post_message.get("channel") == "GENERAL"
assert chat_post_message.get("message").get("msg") == "hello"
assert chat_post_message.get("success")
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
and context (class names, function names, or code) available:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketMissingParamException(Exception):
# pass
. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Given the code snippet: <|code_start|>
@pytest.fixture
def delete_user2(logged_rocket):
user2_exists = logged_rocket.users_info(username="user2").json().get("success")
if user2_exists:
user_id = (
logged_rocket.users_info(username="user2").json().get("user").get("_id")
)
logged_rocket.users_delete(user_id)
def test_login(logged_rocket, user):
login = logged_rocket.login(user.name, user.password).json()
<|code_end|>
, generate the next line using the imports in this file:
import uuid
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import (
RocketAuthenticationException,
RocketMissingParamException,
)
and context (functions, classes, or occasionally code) from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketAuthenticationException(Exception):
# pass
#
# class RocketMissingParamException(Exception):
# pass
. Output only the next line. | with pytest.raises(RocketAuthenticationException): |
Here is a snippet: <|code_start|> assert login.get("status") == "success"
assert "authToken" in login.get("data")
assert "userId" in login.get("data")
def test_me(logged_rocket, user):
me = logged_rocket.me().json()
assert me.get("success")
assert me.get("username") == user.name
assert me.get("name") == user.name
def test_logout(logged_rocket, user):
logged_rocket.login(user.name, user.password).json()
logout = logged_rocket.logout().json()
assert logout.get("status") == "success"
def test_users_info(logged_rocket, user):
login = logged_rocket.login(user.name, user.password).json()
user_id = login.get("data").get("userId")
users_info_by_id = logged_rocket.users_info(user_id=user_id).json()
assert users_info_by_id.get("success")
assert users_info_by_id.get("user").get("_id") == user_id
users_info_by_name = logged_rocket.users_info(username=user.name).json()
assert users_info_by_name.get("success")
assert users_info_by_name.get("user").get("name") == user.name
<|code_end|>
. Write the next line using the current file imports:
import uuid
import pytest
from rocketchat_API.APIExceptions.RocketExceptions import (
RocketAuthenticationException,
RocketMissingParamException,
)
and context from other files:
# Path: rocketchat_API/APIExceptions/RocketExceptions.py
# class RocketAuthenticationException(Exception):
# pass
#
# class RocketMissingParamException(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(RocketMissingParamException): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.