Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|># DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipSupported(SipGenericHF):
hf_names = ('supported',)
caps = None
def __init__(self, body = None, caps = None):
SipGenericHF.__init__(self, body)
if body == None:
self.parsed = True
self.caps = caps[:]
def parse(self):
self.caps = [x.strip() for x in self.body.split(',')]
self.parsed = True
def __str__(self):
if not self.parsed:
return self.body
return reduce(lambda x,y: '%s,%s' % (x, y), self.caps)
def getCopy(self):
<|code_end|>
. Write the next line using the current file imports:
from sippy.SipGenericHF import SipGenericHF
from functools import reduce
and context from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
, which may include functions, classes, or code. Output only the next line. | if not self.parsed: |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipTo(SipFrom):
hf_names = ('to', 't')
relaxedparser = True
<|code_end|>
with the help of current file imports:
from sippy.SipFrom import SipFrom
and context from other files:
# Path: sippy/SipFrom.py
# class SipFrom(SipAddressHF):
# hf_names = ('from', 'f')
# relaxedparser = True
#
# def __init__(self, body = None, address = None):
# SipAddressHF.__init__(self, body, address)
# if body == None and address == None:
# self.address = SipAddress(name = 'Anonymous', url = SipURL(host = SipConf.my_address, port = SipConf.my_port))
#
# def getTag(self):
# return self.address.getParam('tag')
#
# def genTag(self):
# salt = str((random() * 1000000000) + time())
# self.address.setParam('tag', md5(salt.encode()).hexdigest())
#
# def setTag(self, value):
# self.address.setParam('tag', value)
#
# def delTag(self):
# self.address.delParam('tag')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'f'
# return 'From'
, which may contain function names, class names, or code. Output only the next line. | def getCanName(self, name, compact = False): |
Given the following code snippet before the placeholder: <|code_start|> nworkers = self.uopts.nworkers
for i in range(0, nworkers):
self.asenders.append(AsyncSender(self))
self.areceivers.append(AsyncReceiver(self))
def send_to(self, data, address, delayed = False):
if not isinstance(address, tuple):
raise Exception('Invalid address, not a tuple: %s' % str(address))
if not isinstance(data, bytes):
data = data.encode('utf-8')
if self.uopts.ploss_out_rate > 0.0 and not delayed:
if random() < self.uopts.ploss_out_rate:
return
if self.uopts.pdelay_out_max > 0.0 and not delayed:
pdelay = self.uopts.pdelay_out_max * random()
Timeout(self.send_to, pdelay, 1, data, address, True)
return
addr, port = address
if self.uopts.family == socket.AF_INET6:
if not addr.startswith('['):
raise Exception('Invalid IPv6 address: %s' % addr)
address = (addr[1:-1], port)
self.wi_available.acquire()
self.wi.append((data, address))
self.wi_available.notify()
self.wi_available.release()
def handle_read(self, data, address, rtime, delayed = False):
if len(data) > 0 and self.uopts.data_callback != None:
self.stats[2] += 1
<|code_end|>
, predict the next line using imports from the current file:
from errno import ECONNRESET, ENOTCONN, ESHUTDOWN, EWOULDBLOCK, ENOBUFS, EAGAIN, \
EINTR
from datetime import datetime
from time import sleep, time
from threading import Thread, Condition
from random import random
from sippy.Core.EventDispatcher import ED2
from sippy.Core.Exceptions import dump_exception
from sippy.Time.Timeout import Timeout
from sippy.Time.MonoTime import MonoTime
from sys import exit
import socket
and context including class names, function names, and sometimes code from other files:
# Path: sippy/Core/Exceptions.py
# def dump_exception(msg, f = sys.stdout, extra = None):
# exc_type, exc_value, exc_traceback = sys.exc_info()
# if isinstance(exc_value, StdException):
# cus_traceback = exc_value.traceback
# else:
# if hasattr(exc_value, 'traceback'):
# exc_traceback = exc_value.traceback
# cus_traceback = None
# f.write('%s @%s[%d] %s:\n' % (datetime.now(), sys.argv[0], os.getpid(), msg))
# f.write(SEPT)
# if cus_traceback != None:
# f.write('Traceback (most recent call last):\n')
# print_list(cus_traceback, file = f)
# f.write(format_exception_only(exc_type, exc_value)[0])
# else:
# print_exception(exc_type, exc_value, exc_traceback, file = f)
# f.write(SEPT)
# if extra != None:
# f.write(extra)
# f.write(SEPT)
# f.flush()
. Output only the next line. | if self.uopts.ploss_in_rate > 0.0 and not delayed: |
Given the code snippet: <|code_start|> rsth = None
state_lock = Lock()
state = RTPGenInit
userv = None
target = None
pl_queue = None
plq_lock = Lock()
def __init__(self):
Thread.__init__(self)
self.setDaemon(True)
self.pl_queue = []
def start(self, userv, target):
self.state_lock.acquire()
self.target = target
self.userv = userv
if self.state == RTPGenSuspend:
self.state = RTPGenRun
self.state_lock.release()
return
self.state_lock.release()
pfreq = 1.0 / self.ptime
self.elp = ElPeriodic(pfreq)
self.rsth = RtpSynth(8000, 30)
Thread.start(self)
def enqueue(self, pload):
self.plq_lock.acquire()
self.pl_queue.append(pload)
<|code_end|>
, generate the next line using the imports in this file:
from threading import Thread, Lock
from math import floor
from elperiodic.ElPeriodic import ElPeriodic
from rtpsynth.RtpSynth import RtpSynth
from sippy.Core.EventDispatcher import ED2
from sippy.Time.clock_dtime import clock_getdtime, CLOCK_MONOTONIC
from time import sleep
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/Time/clock_dtime.py
# def clock_getdtime(type):
# ts = clock_getitime(type)
# return float(ts[0]) + float(ts[1] * 1e-09)
#
# CLOCK_MONOTONIC = 4 # see <linux/time.h> / <include/time.h>
. Output only the next line. | self.plq_lock.release() |
Based on the snippet: <|code_start|> else:
etext = 'suspend() is called in the wrong state: %s' % self.state
self.state_lock.release()
raise Exception(etext)
self.state_lock.release()
class FakeUserv(object):
nsent = 0
def send_to(self, *args):
self.nsent += 1
pass
if __name__ == '__main__':
r = RTPGen()
s = FakeUserv()
t = ('127.0.0.1', 12345)
r.start(s, t)
sleep(2)
r.suspend()
sleep(1)
r.start(s, t)
sleep(2)
r.stop()
try:
r.suspend()
except:
pass
else:
raise Exception('suspend() test failed')
<|code_end|>
, predict the immediate next line with the help of imports:
from threading import Thread, Lock
from math import floor
from elperiodic.ElPeriodic import ElPeriodic
from rtpsynth.RtpSynth import RtpSynth
from sippy.Core.EventDispatcher import ED2
from sippy.Time.clock_dtime import clock_getdtime, CLOCK_MONOTONIC
from time import sleep
and context (classes, functions, sometimes code) from other files:
# Path: sippy/Time/clock_dtime.py
# def clock_getdtime(type):
# ts = clock_getitime(type)
# return float(ts[0]) + float(ts[1] * 1e-09)
#
# CLOCK_MONOTONIC = 4 # see <linux/time.h> / <include/time.h>
. Output only the next line. | nsent_base = 135 |
Based on the snippet: <|code_start|># Copyright (c) 2006-2016 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipDiversion(SipAddressHF):
hf_names = ('diversion',)
def getCanName(self, name, compact = False):
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.SipAddressHF import SipAddressHF
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SipAddressHF.py
# class SipAddressHF(SipGenericHF):
# address = None
# relaxedparser = False
#
# def __init__(self, body = None, address = None):
# SipGenericHF.__init__(self, body)
# if body != None:
# csvs = []
# pidx = 0
# while 1:
# idx = body.find(',', pidx)
# if idx == -1:
# break;
# onum = body[:idx].count('<')
# cnum = body[:idx].count('>')
# qnum = body[:idx].count('"')
# if (onum == 0 and cnum == 0 and qnum == 0) or (onum > 0 and \
# onum == cnum and (qnum % 2 == 0)):
# csvs.append(body[:idx])
# body = body[idx + 1:]
# pidx = 0
# else:
# pidx = idx + 1
# if (len(csvs) > 0):
# csvs.append(body)
# raise ESipHeaderCSV(None, csvs)
# else:
# self.parsed = True
# self.address = address
#
# def parse(self):
# self.address = SipAddress(self.body, relaxedparser = self.relaxedparser)
# self.parsed = True
#
# def __str__(self):
# return self.localStr()
#
# def localStr(self, local_addr = None, local_port = None):
# if not self.parsed:
# return self.body
# return self.address.localStr(local_addr, local_port)
#
# def getCopy(self):
# if not self.parsed:
# oret = self.__class__(self.body)
# else:
# oret = self.__class__(address = self.address.getCopy())
# oret.relaxedparser = self.relaxedparser
# return oret
#
# def setBody(self, body):
# self.address = body
#
# def getUri(self):
# return self.address
#
# def getUrl(self):
# return self.address.url
. Output only the next line. | return 'Diversion' |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipPAssertedIdentity(SipFrom):
hf_names = ('p-asserted-identity',)
def getCanName(self, name, compact = False):
<|code_end|>
with the help of current file imports:
from sippy.SipFrom import SipFrom
and context from other files:
# Path: sippy/SipFrom.py
# class SipFrom(SipAddressHF):
# hf_names = ('from', 'f')
# relaxedparser = True
#
# def __init__(self, body = None, address = None):
# SipAddressHF.__init__(self, body, address)
# if body == None and address == None:
# self.address = SipAddress(name = 'Anonymous', url = SipURL(host = SipConf.my_address, port = SipConf.my_port))
#
# def getTag(self):
# return self.address.getParam('tag')
#
# def genTag(self):
# salt = str((random() * 1000000000) + time())
# self.address.setParam('tag', md5(salt.encode()).hexdigest())
#
# def setTag(self, value):
# self.address.setParam('tag', value)
#
# def delTag(self):
# self.address.delParam('tag')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'f'
# return 'From'
, which may contain function names, class names, or code. Output only the next line. | return 'P-Asserted-Identity' |
Using the snippet: <|code_start|> self.startline = startline
def getSL(self):
return self.startline
def getHFs(self, name):
return [x for x in self.headers if x.name == name]
def countHFs(self, name):
return len([x for x in self.headers if x.name == name])
def delHFs(self, name):
self.headers = [x for x in self.headers if x.name != name]
def getHF(self, name):
return [x for x in self.headers if x.name == name][0]
def getHFBodys(self, name):
return [x.getBody() for x in self.headers if x.name == name]
def getHFBody(self, name, idx = 0):
return [x for x in self.headers if x.name == name][idx].getBody()
def getHFBCopys(self, name):
return [x.getBCopy() for x in self.headers if x.name == name]
def getHFBCopy(self, name, idx = 0):
return [x for x in self.headers if x.name == name][idx].getBCopy()
def replaceHeader(self, oheader, nheader):
<|code_end|>
, determine the next line of code. You have imports:
from sippy.SipHeader import SipHeader
from sippy.SipContentLength import SipContentLength
from sippy.SipContentType import SipContentType
from sippy.MsgBody import MsgBody
from sippy.ESipHeaderCSV import ESipHeaderCSV
from sippy.ESipHeaderIgnore import ESipHeaderIgnore
from sippy.ESipParseException import ESipParseException
and context (class names, function names, or code) available:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipContentLength.py
# class SipContentLength(SipNumericHF):
# hf_names = ('content-length', 'l')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'l'
# return 'Content-Length'
#
# Path: sippy/SipContentType.py
# class SipContentType(SipGenericHF):
# hf_names = ('content-type', 'c')
#
# def __init__(self, body):
# SipGenericHF.__init__(self, body)
# self.parsed = True
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'c'
# return 'Content-Type'
#
# Path: sippy/MsgBody.py
# class MsgBody(object):
# content = None
# mtype = None
# needs_update = True
# parsed = False
#
# def __init__(self, content = None, mtype = 'application/sdp', cself = None):
# if content != None:
# self.mtype = mtype
# self.content = content
# else:
# if type(cself.content) in str_types:
# self.content = cself.content
# else:
# self.content = cself.content.getCopy()
# self.mtype = cself.mtype
# self.parsed = True
#
# def parse(self):
# if not self.parsed:
# if self.mtype in b_types:
# self.content = b_types[self.mtype](self.content)
# self.parsed = True
#
# def __str__(self):
# return str(self.content)
#
# def localStr(self, local_addr = None, local_port = None):
# if type(self.content) in str_types:
# return self.content
# return self.content.localStr(local_addr, local_port)
#
# def getType(self):
# return self.mtype
#
# def getCopy(self):
# if not self.parsed:
# return MsgBody(self.content)
# return MsgBody(cself = self)
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
#
# Path: sippy/ESipHeaderIgnore.py
# class ESipHeaderIgnore(Exception):
# def __init__(self):
# Exception.__init__(self)
#
# Path: sippy/ESipParseException.py
# class ESipParseException(Exception):
# sip_response = None
# arg = None
#
# def __init__(self, arg, sip_response = None):
# self.arg = arg
# self.sip_response = sip_response
#
# def __str__(self):
# return str(self.arg)
. Output only the next line. | self.headers[self.headers.index(oheader)] = nheader |
Using the snippet: <|code_start|> self.source = address
def getTId(self, wCSM = False, wBRN = False, wTTG = False):
headers_dict = dict([(x.name, x) for x in self.headers if x.name in ('cseq', 'call-id', 'from')])
cseq, method = headers_dict['cseq'].getBody().getCSeq()
rval = [str(headers_dict['call-id'].getBody()), headers_dict['from'].getBody().getTag(), cseq]
if wCSM:
rval.append(method)
if wBRN:
rval.append(self.getHFBody('via').getBranch())
if wTTG:
rval.append(self.getHFBody('to').getTag())
return tuple(rval)
def getTIds(self):
headers_dict = dict([(x.name, x) for x in self.headers if x.name in ('cseq', 'call-id', 'from')])
call_id = str(headers_dict['call-id'].getBody())
ftag = headers_dict['from'].getBody().getTag()
cseq, method = headers_dict['cseq'].getBody().getCSeq()
return tuple([(call_id, ftag, cseq, method, via.getBranch()) for via in self.getHFBodys('via')])
def getCopy(self):
cself = self.__class__()
for header in self.headers:
cself.appendHeader(header.getCopy())
if self.body != None:
cself.body = self.body.getCopy()
cself.startline = self.startline
cself.target = self.target
cself.source = self.source
<|code_end|>
, determine the next line of code. You have imports:
from sippy.SipHeader import SipHeader
from sippy.SipContentLength import SipContentLength
from sippy.SipContentType import SipContentType
from sippy.MsgBody import MsgBody
from sippy.ESipHeaderCSV import ESipHeaderCSV
from sippy.ESipHeaderIgnore import ESipHeaderIgnore
from sippy.ESipParseException import ESipParseException
and context (class names, function names, or code) available:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipContentLength.py
# class SipContentLength(SipNumericHF):
# hf_names = ('content-length', 'l')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'l'
# return 'Content-Length'
#
# Path: sippy/SipContentType.py
# class SipContentType(SipGenericHF):
# hf_names = ('content-type', 'c')
#
# def __init__(self, body):
# SipGenericHF.__init__(self, body)
# self.parsed = True
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'c'
# return 'Content-Type'
#
# Path: sippy/MsgBody.py
# class MsgBody(object):
# content = None
# mtype = None
# needs_update = True
# parsed = False
#
# def __init__(self, content = None, mtype = 'application/sdp', cself = None):
# if content != None:
# self.mtype = mtype
# self.content = content
# else:
# if type(cself.content) in str_types:
# self.content = cself.content
# else:
# self.content = cself.content.getCopy()
# self.mtype = cself.mtype
# self.parsed = True
#
# def parse(self):
# if not self.parsed:
# if self.mtype in b_types:
# self.content = b_types[self.mtype](self.content)
# self.parsed = True
#
# def __str__(self):
# return str(self.content)
#
# def localStr(self, local_addr = None, local_port = None):
# if type(self.content) in str_types:
# return self.content
# return self.content.localStr(local_addr, local_port)
#
# def getType(self):
# return self.mtype
#
# def getCopy(self):
# if not self.parsed:
# return MsgBody(self.content)
# return MsgBody(cself = self)
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
#
# Path: sippy/ESipHeaderIgnore.py
# class ESipHeaderIgnore(Exception):
# def __init__(self):
# Exception.__init__(self)
#
# Path: sippy/ESipParseException.py
# class ESipParseException(Exception):
# sip_response = None
# arg = None
#
# def __init__(self, arg, sip_response = None):
# self.arg = arg
# self.sip_response = sip_response
#
# def __str__(self):
# return str(self.arg)
. Output only the next line. | cself.nated = self.nated |
Next line prediction: <|code_start|>
def localStr(self, local_addr = None, local_port = None, compact = False):
s = self.getSL() + '\r\n'
for header in self.headers:
s += header.localStr(local_addr, local_port, compact) + '\r\n'
if self.body != None:
mbody = self.body.localStr(local_addr, local_port)
if compact:
s += 'c: %s\r\n' % self.body.mtype
s += 'l: %d\r\n\r\n' % len(mbody)
else:
s += 'Content-Type: %s\r\n' % self.body.mtype
s += 'Content-Length: %d\r\n\r\n' % len(mbody)
s += mbody
else:
if compact:
s += 'l: 0\r\n\r\n'
else:
s += 'Content-Length: 0\r\n\r\n'
return s
def setSL(self, startline):
self.startline = startline
def getSL(self):
return self.startline
def getHFs(self, name):
return [x for x in self.headers if x.name == name]
<|code_end|>
. Use current file imports:
(from sippy.SipHeader import SipHeader
from sippy.SipContentLength import SipContentLength
from sippy.SipContentType import SipContentType
from sippy.MsgBody import MsgBody
from sippy.ESipHeaderCSV import ESipHeaderCSV
from sippy.ESipHeaderIgnore import ESipHeaderIgnore
from sippy.ESipParseException import ESipParseException)
and context including class names, function names, or small code snippets from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipContentLength.py
# class SipContentLength(SipNumericHF):
# hf_names = ('content-length', 'l')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'l'
# return 'Content-Length'
#
# Path: sippy/SipContentType.py
# class SipContentType(SipGenericHF):
# hf_names = ('content-type', 'c')
#
# def __init__(self, body):
# SipGenericHF.__init__(self, body)
# self.parsed = True
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'c'
# return 'Content-Type'
#
# Path: sippy/MsgBody.py
# class MsgBody(object):
# content = None
# mtype = None
# needs_update = True
# parsed = False
#
# def __init__(self, content = None, mtype = 'application/sdp', cself = None):
# if content != None:
# self.mtype = mtype
# self.content = content
# else:
# if type(cself.content) in str_types:
# self.content = cself.content
# else:
# self.content = cself.content.getCopy()
# self.mtype = cself.mtype
# self.parsed = True
#
# def parse(self):
# if not self.parsed:
# if self.mtype in b_types:
# self.content = b_types[self.mtype](self.content)
# self.parsed = True
#
# def __str__(self):
# return str(self.content)
#
# def localStr(self, local_addr = None, local_port = None):
# if type(self.content) in str_types:
# return self.content
# return self.content.localStr(local_addr, local_port)
#
# def getType(self):
# return self.mtype
#
# def getCopy(self):
# if not self.parsed:
# return MsgBody(self.content)
# return MsgBody(cself = self)
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
#
# Path: sippy/ESipHeaderIgnore.py
# class ESipHeaderIgnore(Exception):
# def __init__(self):
# Exception.__init__(self)
#
# Path: sippy/ESipParseException.py
# class ESipParseException(Exception):
# sip_response = None
# arg = None
#
# def __init__(self, arg, sip_response = None):
# self.arg = arg
# self.sip_response = sip_response
#
# def __str__(self):
# return str(self.arg)
. Output only the next line. | def countHFs(self, name): |
Predict the next line after this snippet: <|code_start|> else:
self.headers.append(header)
header_names.append(header.name)
except ESipHeaderCSV as einst:
for body in einst.bodys:
header = SipHeader(name = einst.name, bodys = body)
if header.name == 'content-type':
self.__content_type = header
elif header.name == 'content-length':
self.__content_length = header
else:
self.headers.append(header)
header_names.append(header.name)
except ESipHeaderIgnore:
continue
if 'via' not in header_names:
raise Exception('Via HF is missed')
if 'to' not in header_names:
raise Exception('To HF is missed')
if 'from' not in header_names:
raise Exception('From HF is missed')
if 'cseq' not in header_names:
raise Exception('CSeq HF is missed')
def init_body(self):
if self.__content_length != None:
blen = self.__content_length.getBody().number
if self.__mbody == None:
mblen = 0
else:
<|code_end|>
using the current file's imports:
from sippy.SipHeader import SipHeader
from sippy.SipContentLength import SipContentLength
from sippy.SipContentType import SipContentType
from sippy.MsgBody import MsgBody
from sippy.ESipHeaderCSV import ESipHeaderCSV
from sippy.ESipHeaderIgnore import ESipHeaderIgnore
from sippy.ESipParseException import ESipParseException
and any relevant context from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipContentLength.py
# class SipContentLength(SipNumericHF):
# hf_names = ('content-length', 'l')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'l'
# return 'Content-Length'
#
# Path: sippy/SipContentType.py
# class SipContentType(SipGenericHF):
# hf_names = ('content-type', 'c')
#
# def __init__(self, body):
# SipGenericHF.__init__(self, body)
# self.parsed = True
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'c'
# return 'Content-Type'
#
# Path: sippy/MsgBody.py
# class MsgBody(object):
# content = None
# mtype = None
# needs_update = True
# parsed = False
#
# def __init__(self, content = None, mtype = 'application/sdp', cself = None):
# if content != None:
# self.mtype = mtype
# self.content = content
# else:
# if type(cself.content) in str_types:
# self.content = cself.content
# else:
# self.content = cself.content.getCopy()
# self.mtype = cself.mtype
# self.parsed = True
#
# def parse(self):
# if not self.parsed:
# if self.mtype in b_types:
# self.content = b_types[self.mtype](self.content)
# self.parsed = True
#
# def __str__(self):
# return str(self.content)
#
# def localStr(self, local_addr = None, local_port = None):
# if type(self.content) in str_types:
# return self.content
# return self.content.localStr(local_addr, local_port)
#
# def getType(self):
# return self.mtype
#
# def getCopy(self):
# if not self.parsed:
# return MsgBody(self.content)
# return MsgBody(cself = self)
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
#
# Path: sippy/ESipHeaderIgnore.py
# class ESipHeaderIgnore(Exception):
# def __init__(self):
# Exception.__init__(self)
#
# Path: sippy/ESipParseException.py
# class ESipParseException(Exception):
# sip_response = None
# arg = None
#
# def __init__(self, arg, sip_response = None):
# self.arg = arg
# self.sip_response = sip_response
#
# def __str__(self):
# return str(self.arg)
. Output only the next line. | mblen = len(self.__mbody) |
Given the code snippet: <|code_start|> raise ESipParseException('Truncated SIP body, %d bytes expected, %d received' % (blen, mblen))
elif blen < mblen:
self.__mbody = self.__mbody[:blen]
mblen = blen
if self.__mbody != None:
if self.__content_type != None:
self.body = MsgBody(self.__mbody, str(self.__content_type.getBody()).lower())
else:
self.body = MsgBody(self.__mbody)
def __str__(self):
s = self.getSL() + '\r\n'
for header in self.headers:
s += str(header) + '\r\n'
if self.body != None:
mbody = str(self.body)
s += 'Content-Type: %s\r\n' % self.body.mtype
s += 'Content-Length: %d\r\n\r\n' % len(mbody)
s += mbody
else:
s += 'Content-Length: 0\r\n\r\n'
return s
def localStr(self, local_addr = None, local_port = None, compact = False):
s = self.getSL() + '\r\n'
for header in self.headers:
s += header.localStr(local_addr, local_port, compact) + '\r\n'
if self.body != None:
mbody = self.body.localStr(local_addr, local_port)
if compact:
<|code_end|>
, generate the next line using the imports in this file:
from sippy.SipHeader import SipHeader
from sippy.SipContentLength import SipContentLength
from sippy.SipContentType import SipContentType
from sippy.MsgBody import MsgBody
from sippy.ESipHeaderCSV import ESipHeaderCSV
from sippy.ESipHeaderIgnore import ESipHeaderIgnore
from sippy.ESipParseException import ESipParseException
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipContentLength.py
# class SipContentLength(SipNumericHF):
# hf_names = ('content-length', 'l')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'l'
# return 'Content-Length'
#
# Path: sippy/SipContentType.py
# class SipContentType(SipGenericHF):
# hf_names = ('content-type', 'c')
#
# def __init__(self, body):
# SipGenericHF.__init__(self, body)
# self.parsed = True
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'c'
# return 'Content-Type'
#
# Path: sippy/MsgBody.py
# class MsgBody(object):
# content = None
# mtype = None
# needs_update = True
# parsed = False
#
# def __init__(self, content = None, mtype = 'application/sdp', cself = None):
# if content != None:
# self.mtype = mtype
# self.content = content
# else:
# if type(cself.content) in str_types:
# self.content = cself.content
# else:
# self.content = cself.content.getCopy()
# self.mtype = cself.mtype
# self.parsed = True
#
# def parse(self):
# if not self.parsed:
# if self.mtype in b_types:
# self.content = b_types[self.mtype](self.content)
# self.parsed = True
#
# def __str__(self):
# return str(self.content)
#
# def localStr(self, local_addr = None, local_port = None):
# if type(self.content) in str_types:
# return self.content
# return self.content.localStr(local_addr, local_port)
#
# def getType(self):
# return self.mtype
#
# def getCopy(self):
# if not self.parsed:
# return MsgBody(self.content)
# return MsgBody(cself = self)
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
#
# Path: sippy/ESipHeaderIgnore.py
# class ESipHeaderIgnore(Exception):
# def __init__(self):
# Exception.__init__(self)
#
# Path: sippy/ESipParseException.py
# class ESipParseException(Exception):
# sip_response = None
# arg = None
#
# def __init__(self, arg, sip_response = None):
# self.arg = arg
# self.sip_response = sip_response
#
# def __str__(self):
# return str(self.arg)
. Output only the next line. | s += 'c: %s\r\n' % self.body.mtype |
Given the following code snippet before the placeholder: <|code_start|>#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipRoute(SipFrom):
hf_names = ('route',)
relaxedparser = False
def getCanName(self, name, compact = False):
if name == 'record-route':
return 'Record-Route'
<|code_end|>
, predict the next line using imports from the current file:
from sippy.SipFrom import SipFrom
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipFrom.py
# class SipFrom(SipAddressHF):
# hf_names = ('from', 'f')
# relaxedparser = True
#
# def __init__(self, body = None, address = None):
# SipAddressHF.__init__(self, body, address)
# if body == None and address == None:
# self.address = SipAddress(name = 'Anonymous', url = SipURL(host = SipConf.my_address, port = SipConf.my_port))
#
# def getTag(self):
# return self.address.getParam('tag')
#
# def genTag(self):
# salt = str((random() * 1000000000) + time())
# self.address.setParam('tag', md5(salt.encode()).hexdigest())
#
# def setTag(self, value):
# self.address.setParam('tag', value)
#
# def delTag(self):
# self.address.delParam('tag')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'f'
# return 'From'
. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|>#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipMaxForwards(SipNumericHF):
hf_names = ('max-forwards',)
def __init__(self, body = None, number = 70):
SipNumericHF.__init__(self, body, number)
def getCanName(self, name, compact = False):
<|code_end|>
using the current file's imports:
from sippy.SipNumericHF import SipNumericHF
and any relevant context from other files:
# Path: sippy/SipNumericHF.py
# class SipNumericHF(SipGenericHF):
# number = None
#
# def __init__(self, body = None, number = 0):
# SipGenericHF.__init__(self, body)
# if body == None:
# self.parsed = True
# self.number = number
#
# def parse(self):
# self.number = int(self.body)
# self.parsed = True
#
# def __str__(self):
# if not self.parsed:
# return self.body
# return str(self.number)
#
# def getCopy(self):
# if not self.parsed:
# return self.__class__(body = self.body)
# return self.__class__(number = self.number)
#
# def getNum(self):
# return self.number
#
# def incNum(self):
# self.number += 1
# return self.number
. Output only the next line. | return 'Max-Forwards' |
Given the following code snippet before the placeholder: <|code_start|># SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CALL_ID_CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.!%*_+`\'~()<>:\\"/[]?{}'
_clen = len(CALL_ID_CHARSET)
DEFAULT_TEST_LEN = (32, 16)
def gen_test_cid(lens = DEFAULT_TEST_LEN):
r = ''
for j in (0, 1):
for i in range(0, lens[j]):
r += CALL_ID_CHARSET[int(floor(random() * _clen))]
if j == 0:
r += '@'
return r
class SipCallId(SipGenericHF):
hf_names = ('call-id', 'i')
body = None
def __init__(self, body = None):
SipGenericHF.__init__(self, body)
self.parsed = True
if body == None:
salt = str((random() * 1000000000) + time())
self.body = md5(salt.encode()).hexdigest() + '@' + str(SipConf.my_address)
def __add__(self, other):
return SipCallId(self.body + str(other))
<|code_end|>
, predict the next line using imports from the current file:
from random import random
from hashlib import md5
from time import time
from math import floor
from sippy.SipConf import SipConf
from sippy.SipGenericHF import SipGenericHF
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | def genCallId(self): |
Given the code snippet: <|code_start|> else:
self.hostport = route[0]
if not self.hostport.startswith('['):
hostport = self.hostport.split(':', 1)
af = 0
self.hostonly = hostport[0]
else:
hostport = self.hostport[1:].split(']', 1)
if len(hostport) > 1:
if len(hostport[1]) == 0:
del hostport[1]
else:
hostport[1] = hostport[1][1:]
af = AF_INET6
self.hostonly = '[%s]' % hostport[0]
if len(hostport) == 1:
port = SipConf.default_port
else:
port = int(hostport[1])
self.ainfo = getaddrinfo(hostport[0], port, af, SOCK_STREAM)
self.params = {}
extra_headers = []
for a, v in [x.split('=', 1) for x in route[1:]]:
if a == 'credit-time':
self.credit_time = int(v)
if self.credit_time < 0:
self.credit_time = None
self.crt_set = True
elif a == 'expires':
self.expires = int(v)
<|code_end|>
, generate the next line using the imports in this file:
from sippy.SipHeader import SipHeader
from sippy.SipConf import SipConf
from urllib import unquote
from urllib.parse import unquote
from socket import getaddrinfo, SOCK_STREAM, AF_INET, AF_INET6
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
. Output only the next line. | if self.expires < 0: |
Given snippet: <|code_start|> try:
event.reason = req.getHFBody('reason')
except:
pass
self.ua.equeue.append(event)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = req.rtime
return (UaStateDisconnected, self.ua.disc_cbs, req.rtime, self.ua.origin)
#print 'wrong request %s in the state Updating' % req.getMethod()
return None
def recvResponse(self, resp, tr):
body = resp.getBody()
code, reason = resp.getSCode()
scode = (code, reason, body)
if code < 200:
self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin))
return None
if code >= 200 and code < 300:
event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
if body != None:
if self.ua.on_remote_sdp_change != None:
cb_func = lambda x: self.ua.delayed_remote_sdp_update(event, x)
try:
self.ua.on_remote_sdp_change(body, cb_func, en_excpt = True)
except Exception as e:
event = CCEventFail((502, 'Bad Gateway'), rtime = event.rtime)
event.setWarning('Malformed SDP Body received from ' \
'downstream: "%s"' % str(e))
return self.updateFailed(event)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
which might include code, classes, or functions. Output only the next line. | return (UaStateConnected,) |
Continue the code snippet: <|code_start|> return None
elif req.getMethod() == 'BYE':
self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr)
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', server = self.ua.local_ua))
#print 'BYE received in the Updating state, going to the Disconnected state'
event = CCEventDisconnect(rtime = req.rtime, origin = self.ua.origin)
try:
event.reason = req.getHFBody('reason')
except:
pass
self.ua.equeue.append(event)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = req.rtime
return (UaStateDisconnected, self.ua.disc_cbs, req.rtime, self.ua.origin)
#print 'wrong request %s in the state Updating' % req.getMethod()
return None
def recvResponse(self, resp, tr):
body = resp.getBody()
code, reason = resp.getSCode()
scode = (code, reason, body)
if code < 200:
self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin))
return None
if code >= 200 and code < 300:
event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
if body != None:
if self.ua.on_remote_sdp_change != None:
cb_func = lambda x: self.ua.delayed_remote_sdp_update(event, x)
try:
<|code_end|>
. Use current file imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context (classes, functions, or code) from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
. Output only the next line. | self.ua.on_remote_sdp_change(body, cb_func, en_excpt = True) |
Based on the snippet: <|code_start|> self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', server = self.ua.local_ua))
#print 'BYE received in the Updating state, going to the Disconnected state'
event = CCEventDisconnect(rtime = req.rtime, origin = self.ua.origin)
try:
event.reason = req.getHFBody('reason')
except:
pass
self.ua.equeue.append(event)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = req.rtime
return (UaStateDisconnected, self.ua.disc_cbs, req.rtime, self.ua.origin)
#print 'wrong request %s in the state Updating' % req.getMethod()
return None
def recvResponse(self, resp, tr):
body = resp.getBody()
code, reason = resp.getSCode()
scode = (code, reason, body)
if code < 200:
self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin))
return None
if code >= 200 and code < 300:
event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
if body != None:
if self.ua.on_remote_sdp_change != None:
cb_func = lambda x: self.ua.delayed_remote_sdp_update(event, x)
try:
self.ua.on_remote_sdp_change(body, cb_func, en_excpt = True)
except Exception as e:
event = CCEventFail((502, 'Bad Gateway'), rtime = event.rtime)
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context (classes, functions, sometimes code) from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
. Output only the next line. | event.setWarning('Malformed SDP Body received from ' \ |
Here is a snippet: <|code_start|> redirects = tuple(x.getUri().getCopy() for x in resp.getHFBodys('contact'))
scode = (code, reason, body, redirects)
event = CCEventRedirect(scode, rtime = resp.rtime, origin = self.ua.origin)
else:
event = CCEventFail(scode, rtime = resp.rtime, origin = self.ua.origin)
try:
event.reason = resp.getHFBody('reason')
except:
pass
if code in (408, 481):
# If the response for a request within a dialog is a 481
# (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the
# UAC SHOULD terminate the dialog. A UAC SHOULD also terminate a
# dialog if no response at all is received for the request (the
# client transaction would inform the TU about the timeout.)
return self.updateFailed(event)
self.ua.equeue.append(event)
return (UaStateConnected,)
def updateFailed(self, event):
self.ua.equeue.append(event)
req = self.ua.genRequest('BYE', reason = event.reason)
self.ua.lCSeq += 1
self.ua.global_config['_sip_tm'].newTransaction(req, \
laddress = self.ua.source_address, compact = self.ua.compact_sip)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = event.rtime
self.ua.equeue.append(CCEventDisconnect(rtime = event.rtime, \
<|code_end|>
. Write the next line using the current file imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
, which may include functions, classes, or code. Output only the next line. | origin = self.ua.origin)) |
Continue the code snippet: <|code_start|> except:
pass
if code in (408, 481):
# If the response for a request within a dialog is a 481
# (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the
# UAC SHOULD terminate the dialog. A UAC SHOULD also terminate a
# dialog if no response at all is received for the request (the
# client transaction would inform the TU about the timeout.)
return self.updateFailed(event)
self.ua.equeue.append(event)
return (UaStateConnected,)
def updateFailed(self, event):
self.ua.equeue.append(event)
req = self.ua.genRequest('BYE', reason = event.reason)
self.ua.lCSeq += 1
self.ua.global_config['_sip_tm'].newTransaction(req, \
laddress = self.ua.source_address, compact = self.ua.compact_sip)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = event.rtime
self.ua.equeue.append(CCEventDisconnect(rtime = event.rtime, \
origin = self.ua.origin))
return (UaStateDisconnected, self.ua.disc_cbs, event.rtime, \
event.origin)
def recvEvent(self, event):
if isinstance(event, CCEventDisconnect) or isinstance(event, CCEventFail) or isinstance(event, CCEventRedirect):
self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr)
<|code_end|>
. Use current file imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context (classes, functions, or code) from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
. Output only the next line. | req = self.ua.genRequest('BYE', reason = event.reason) |
Predict the next line for this snippet: <|code_start|>
def recvRequest(self, req):
if req.getMethod() == 'INVITE':
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(491, 'Request Pending', server = self.ua.local_ua))
return None
elif req.getMethod() == 'BYE':
self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr)
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', server = self.ua.local_ua))
#print 'BYE received in the Updating state, going to the Disconnected state'
event = CCEventDisconnect(rtime = req.rtime, origin = self.ua.origin)
try:
event.reason = req.getHFBody('reason')
except:
pass
self.ua.equeue.append(event)
self.ua.cancelCreditTimer()
self.ua.disconnect_ts = req.rtime
return (UaStateDisconnected, self.ua.disc_cbs, req.rtime, self.ua.origin)
#print 'wrong request %s in the state Updating' % req.getMethod()
return None
def recvResponse(self, resp, tr):
body = resp.getBody()
code, reason = resp.getSCode()
scode = (code, reason, body)
if code < 200:
self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin))
return None
if code >= 200 and code < 300:
event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
<|code_end|>
with the help of current file imports:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect
from sippy.UaStateConnected import UaStateConnected
from sippy.UaStateDisconnected import UaStateDisconnected
and context from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
#
# Path: sippy/CCEvents.py
# class CCEventDisconnect(CCEventGeneric):
# name = 'CCEventDisconnect'
# pass
#
# class CCEventRing(CCEventGeneric):
# name = 'CCEventRing'
# pass
#
# class CCEventConnect(CCEventGeneric):
# name = 'CCEventConnect'
# pass
#
# class CCEventFail(CCEventGeneric):
# name = 'CCEventFail'
# challenges = None
# warning = None
#
# def getCopy(self):
# cself = CCEventGeneric.getCopy(self)
# if self.challenges != None:
# cself.challenges = [x.getCopy() for x in self.challenges]
# return cself
#
# def setWarning(self, eistr):
# self.warning = SipHeader(body = SipWarning(text = eistr))
#
# class CCEventRedirect(CCEventGeneric):
# name = 'CCEventRedirect'
# pass
, which may contain function names, class names, or code. Output only the next line. | if body != None: |
Given the following code snippet before the placeholder: <|code_start|># 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipRecordRoute(SipFrom):
hf_names = ('record-route',)
relaxedparser = False
def getCanName(self, name, compact = False):
if name == 'record-route':
return 'Record-Route'
else:
return 'Route'
def getAddr(self):
<|code_end|>
, predict the next line using imports from the current file:
from sippy.SipFrom import SipFrom
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipFrom.py
# class SipFrom(SipAddressHF):
# hf_names = ('from', 'f')
# relaxedparser = True
#
# def __init__(self, body = None, address = None):
# SipAddressHF.__init__(self, body, address)
# if body == None and address == None:
# self.address = SipAddress(name = 'Anonymous', url = SipURL(host = SipConf.my_address, port = SipConf.my_port))
#
# def getTag(self):
# return self.address.getParam('tag')
#
# def genTag(self):
# salt = str((random() * 1000000000) + time())
# self.address.setParam('tag', md5(salt.encode()).hexdigest())
#
# def setTag(self, value):
# self.address.setParam('tag', value)
#
# def delTag(self):
# self.address.delParam('tag')
#
# def getCanName(self, name, compact = False):
# if compact:
# return 'f'
# return 'From'
. Output only the next line. | return self.address.url.getAddr() |
Based on the snippet: <|code_start|># ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
f_types = {'m':SdpMedia, 'i':SdpGeneric, 'c':SdpConnecton, 'b':SdpGeneric, \
'k':SdpGeneric}
class SdpMediaDescription(object):
m_header = None
i_header = None
c_header = None
b_header = None
k_header = None
a_headers = None
all_headers = ('m', 'i', 'c', 'b', 'k')
needs_update = True
def __init__(self, cself = None):
if cself != None:
for header_name in [x + '_header' for x in self.all_headers]:
try:
setattr(self, header_name, getattr(cself, header_name).getCopy())
except AttributeError:
pass
self.a_headers = [x for x in cself.a_headers]
return
self.a_headers = []
def __str__(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.SdpConnecton import SdpConnecton
from sippy.SdpMedia import SdpMedia
from sippy.SdpGeneric import SdpGeneric
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SdpConnecton.py
# class SdpConnecton(object):
# ntype = None
# atype = None
# addr = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# self.ntype, self.atype, self.addr = body.split()[:3]
# else:
# self.ntype = cself.ntype
# self.atype = cself.atype
# self.addr = cself.addr
#
# def __str__(self):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def localStr(self, local_addr = None, local_port = None):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def getCopy(self):
# return SdpConnecton(cself = self)
#
# Path: sippy/SdpMedia.py
# class SdpMedia(object):
# type = None
# stype = None
# port = None
# transport = None
# formats = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# params = body.split()
# self.stype = params[0]
# if self.stype.lower() == 'audio':
# self.type = MTAudio
# else:
# self.type = MTOther
# self.port = int(params[1])
# self.transport = params[2]
# if self.type == MTAudio:
# self.formats = [int(x) for x in params[3:]]
# else:
# self.formats = params[3:]
# else:
# self.type = cself.type
# self.stype = cself.stype
# self.port = cself.port
# self.transport = cself.transport
# self.formats = cself.formats[:]
#
# def __str__(self):
# rval = '%s %d %s' % (self.stype, self.port, self.transport)
# if self.type == MTAudio:
# for format in self.formats:
# rval += ' %d' % format
# else:
# for format in self.formats:
# rval += ' %s' % format
# return rval
#
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return SdpMedia(cself = self)
#
# Path: sippy/SdpGeneric.py
# class SdpGeneric(str):
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return self
. Output only the next line. | s = '' |
Based on the snippet: <|code_start|> 'k':SdpGeneric}
class SdpMediaDescription(object):
m_header = None
i_header = None
c_header = None
b_header = None
k_header = None
a_headers = None
all_headers = ('m', 'i', 'c', 'b', 'k')
needs_update = True
def __init__(self, cself = None):
if cself != None:
for header_name in [x + '_header' for x in self.all_headers]:
try:
setattr(self, header_name, getattr(cself, header_name).getCopy())
except AttributeError:
pass
self.a_headers = [x for x in cself.a_headers]
return
self.a_headers = []
def __str__(self):
s = ''
for name in self.all_headers:
header = getattr(self, name + '_header')
if header != None:
s += '%s=%s\r\n' % (name, str(header))
for header in self.a_headers:
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.SdpConnecton import SdpConnecton
from sippy.SdpMedia import SdpMedia
from sippy.SdpGeneric import SdpGeneric
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SdpConnecton.py
# class SdpConnecton(object):
# ntype = None
# atype = None
# addr = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# self.ntype, self.atype, self.addr = body.split()[:3]
# else:
# self.ntype = cself.ntype
# self.atype = cself.atype
# self.addr = cself.addr
#
# def __str__(self):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def localStr(self, local_addr = None, local_port = None):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def getCopy(self):
# return SdpConnecton(cself = self)
#
# Path: sippy/SdpMedia.py
# class SdpMedia(object):
# type = None
# stype = None
# port = None
# transport = None
# formats = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# params = body.split()
# self.stype = params[0]
# if self.stype.lower() == 'audio':
# self.type = MTAudio
# else:
# self.type = MTOther
# self.port = int(params[1])
# self.transport = params[2]
# if self.type == MTAudio:
# self.formats = [int(x) for x in params[3:]]
# else:
# self.formats = params[3:]
# else:
# self.type = cself.type
# self.stype = cself.stype
# self.port = cself.port
# self.transport = cself.transport
# self.formats = cself.formats[:]
#
# def __str__(self):
# rval = '%s %d %s' % (self.stype, self.port, self.transport)
# if self.type == MTAudio:
# for format in self.formats:
# rval += ' %d' % format
# else:
# for format in self.formats:
# rval += ' %s' % format
# return rval
#
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return SdpMedia(cself = self)
#
# Path: sippy/SdpGeneric.py
# class SdpGeneric(str):
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return self
. Output only the next line. | s += 'a=%s\r\n' % str(header) |
Given snippet: <|code_start|> s += 'a=%s\r\n' % str(header)
return s
def __iadd__(self, other):
self.addHeader(*other.strip().split('=', 1))
return self
def getCopy(self):
return SdpMediaDescription(cself = self)
def addHeader(self, name, header):
if name == 'a':
self.a_headers.append(header)
else:
setattr(self, name + '_header', f_types[name](header))
def optimize_a(self):
new_a_headers = []
for ah in self.a_headers:
pt = None
try:
if ah.startswith('rtpmap:'):
pt = int(ah[7:].split(' ')[0])
elif ah.startswith('fmtp:'):
pt = int(ah[5:].split(' ')[0])
except:
pass
if pt != None and not pt in self.m_header.formats:
continue
new_a_headers.append(ah)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sippy.SdpConnecton import SdpConnecton
from sippy.SdpMedia import SdpMedia
from sippy.SdpGeneric import SdpGeneric
and context:
# Path: sippy/SdpConnecton.py
# class SdpConnecton(object):
# ntype = None
# atype = None
# addr = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# self.ntype, self.atype, self.addr = body.split()[:3]
# else:
# self.ntype = cself.ntype
# self.atype = cself.atype
# self.addr = cself.addr
#
# def __str__(self):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def localStr(self, local_addr = None, local_port = None):
# return '%s %s %s' % (self.ntype, self.atype, self.addr)
#
# def getCopy(self):
# return SdpConnecton(cself = self)
#
# Path: sippy/SdpMedia.py
# class SdpMedia(object):
# type = None
# stype = None
# port = None
# transport = None
# formats = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# params = body.split()
# self.stype = params[0]
# if self.stype.lower() == 'audio':
# self.type = MTAudio
# else:
# self.type = MTOther
# self.port = int(params[1])
# self.transport = params[2]
# if self.type == MTAudio:
# self.formats = [int(x) for x in params[3:]]
# else:
# self.formats = params[3:]
# else:
# self.type = cself.type
# self.stype = cself.stype
# self.port = cself.port
# self.transport = cself.transport
# self.formats = cself.formats[:]
#
# def __str__(self):
# rval = '%s %d %s' % (self.stype, self.port, self.transport)
# if self.type == MTAudio:
# for format in self.formats:
# rval += ' %d' % format
# else:
# for format in self.formats:
# rval += ' %s' % format
# return rval
#
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return SdpMedia(cself = self)
#
# Path: sippy/SdpGeneric.py
# class SdpGeneric(str):
# def localStr(self, local_addr = None, local_port = None):
# return str(self)
#
# def getCopy(self):
# return self
which might include code, classes, or functions. Output only the next line. | self.a_headers = new_a_headers |
Using the snippet: <|code_start|># 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipCSeq(SipGenericHF):
hf_names = ('cseq',)
cseq = None
method = None
def __init__(self, body = None, cseq = None, method = None):
SipGenericHF.__init__(self, body)
if body == None:
self.parsed = True
self.method = method
if cseq != None:
<|code_end|>
, determine the next line of code. You have imports:
from sippy.SipGenericHF import SipGenericHF
and context (class names, function names, or code) available:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | self.cseq = cseq |
Here is a snippet: <|code_start|>
def _prepare_attributes(self, type, attributes):
data = [type]
for a, v in attributes:
if a in self._avpair_names:
v = '%s=%s' % (str(a), str(v))
a = 'Cisco-AVPair'
elif a in self._cisco_vsa_names:
v = '%s=%s' % (str(a), str(v))
data.append('%s="%s"' % (str(a), str(v)))
return data
def do_auth(self, attributes, result_callback, *callback_parameters):
return External_command.process_command(self, self._prepare_attributes('AUTH', attributes), result_callback, *callback_parameters)
def do_acct(self, attributes, result_callback = None, *callback_parameters):
External_command.process_command(self, self._prepare_attributes('ACCT', attributes), result_callback, *callback_parameters)
def process_result(self, result_callback, result, *callback_parameters):
if result_callback == None:
return
nav = []
for av in result[:-1]:
a, v = [x.strip() for x in av.split(' = ', 1)]
v = v.strip('\'')
if (a == 'Cisco-AVPair' or a in self._cisco_vsa_names):
t = v.split('=', 1)
if len(t) > 1:
a, v = t
elif v.startswith(a + '='):
<|code_end|>
. Write the next line using the current file imports:
from sippy.External_command import External_command
and context from other files:
# Path: sippy/External_command.py
# class External_command(object):
# work_available = None
# work = None
#
# def __init__(self, command, max_workers = _MAX_WORKERS):
# self.work_available = Condition()
# self.work = []
# for i in range(0, max_workers):
# _Worker(command, self)
#
# def process_command(self, data, result_callback, *callback_parameters):
# wi = Work_item(tuple(data), result_callback, callback_parameters)
# self.work_available.acquire()
# self.work.append(wi)
# self.work_available.notify()
# self.work_available.release()
# return wi
#
# def shutdown(self):
# self.work_available.acquire()
# self.work.append(None)
# self.work_available.notify()
# self.work_available.release()
#
# def process_result(self, result_callback, result, *callback_parameters):
# try:
# result_callback(result, *callback_parameters)
# except Exception as ex:
# if isinstance(ex, SystemExit):
# raise
# dump_exception('External_command: unhandled exception in external command results callback')
, which may include functions, classes, or code. Output only the next line. | v = v[len(a) + 1:] |
Predict the next line after this snippet: <|code_start|> return
self.__play(None, rtpps, prompt_name, times, result_callback, index)
def _stop_play(self, rtpps, result_callback = None, index = 0):
if not self.session_exists:
ED2.callFromThread(rtpps.command_result, None, result_callback)
return
from_tag, to_tag = self.gettags(rtpps)
command = 'S %s %s %s' % ('%s-%d' % (rtpps.call_id, index), from_tag, to_tag)
rtpps.rtp_proxy_client.send_command(command, rtpps.command_result, result_callback)
def _on_sdp_change(self, rtpps, sdp_body, result_callback, en_excpt):
sects = []
try:
sdp_body.parse()
except Exception as exception:
dump_exception('can\'t parse SDP body', extra = sdp_body.content)
if en_excpt:
raise exception
else:
return
for i in range(0, len(sdp_body.content.sections)):
sect = sdp_body.content.sections[i]
if sect.m_header.transport.lower() not in ('udp', 'udptl', 'rtp/avp', \
'rtp/savp', 'udp/bfcp'):
continue
sects.append(sect)
if len(sects) == 0:
sdp_body.needs_update = False
result_callback(sdp_body)
<|code_end|>
using the current file's imports:
from sippy.SdpOrigin import SdpOrigin
from hashlib import md5
from random import random
from time import time
from _thread import get_ident
from thread import get_ident
from sippy.Core.Exceptions import dump_exception
from sippy.Core.EventDispatcher import ED2
from sippy.Time.Timeout import Timeout
from sippy.Rtp_proxy_client import Rtp_proxy_client
import sys
and any relevant context from other files:
# Path: sippy/SdpOrigin.py
# class SdpOrigin(object):
# _session_id = int(random() * time() * 1000.0)
# username = None
# session_id = None
# version = None
# network_type = None
# address_type = None
# address = None
# session_id = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# self.username, self.session_id, self.version, self.network_type, self.address_type, self.address = body.split()
# elif cself == None:
# self.username = '-'
# self.session_id = SdpOrigin._session_id
# SdpOrigin._session_id += 1
# self.version = self.session_id
# self.network_type = 'IN'
# self.address_type = 'IP4'
# self.address = SipConf.my_address
# else:
# self.username = cself.username
# self.session_id = cself.session_id
# self.version = cself.version
# self.network_type = cself.network_type
# self.address_type = cself.address_type
# self.address = cself.address
#
# def __str__(self):
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, self.address_type, self.address)
#
# def localStr(self, local_addr = None, local_port = None):
# if local_addr != None and 'my' in dir(self.address):
# if local_addr.startswith('['):
# address_type = 'IP6'
# local_addr = local_addr[1:-1]
# else:
# address_type = 'IP4'
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, address_type, local_addr)
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, self.address_type, self.address)
#
# def getCopy(self):
# return self.__class__(cself = self)
#
# Path: sippy/Core/Exceptions.py
# def dump_exception(msg, f = sys.stdout, extra = None):
# exc_type, exc_value, exc_traceback = sys.exc_info()
# if isinstance(exc_value, StdException):
# cus_traceback = exc_value.traceback
# else:
# if hasattr(exc_value, 'traceback'):
# exc_traceback = exc_value.traceback
# cus_traceback = None
# f.write('%s @%s[%d] %s:\n' % (datetime.now(), sys.argv[0], os.getpid(), msg))
# f.write(SEPT)
# if cus_traceback != None:
# f.write('Traceback (most recent call last):\n')
# print_list(cus_traceback, file = f)
# f.write(format_exception_only(exc_type, exc_value)[0])
# else:
# print_exception(exc_type, exc_value, exc_traceback, file = f)
# f.write(SEPT)
# if extra != None:
# f.write(extra)
# f.write(SEPT)
# f.flush()
. Output only the next line. | return |
Next line prediction: <|code_start|> def gettags(self, rtpps):
if self not in (rtpps.caller, rtpps.callee):
raise Exception("Corrupt Rtp_proxy_session")
if self == rtpps.caller:
return (rtpps.from_tag, rtpps.to_tag)
else:
return (rtpps.to_tag, rtpps.from_tag)
def getother(self, rtpps):
if self not in (rtpps.caller, rtpps.callee):
raise Exception("Corrupt Rtp_proxy_session")
if self == rtpps.caller:
return rtpps.callee
else:
return rtpps.caller
def update_result(self, result, args):
#print '%s.update_result(%s)' % (id(self), result)
rtpps, result_callback, cpo = args
self.session_exists = True
if result == None:
result_callback(None, rtpps, *cpo.callback_parameters)
return
t1 = result.split()
if t1[0][0] == 'E':
result_callback(None, rtpps, *cpo.callback_parameters)
return
rtpproxy_port = int(t1[0])
if rtpproxy_port == 0:
result_callback(None, rtpps, *cpo.callback_parameters)
<|code_end|>
. Use current file imports:
(from sippy.SdpOrigin import SdpOrigin
from hashlib import md5
from random import random
from time import time
from _thread import get_ident
from thread import get_ident
from sippy.Core.Exceptions import dump_exception
from sippy.Core.EventDispatcher import ED2
from sippy.Time.Timeout import Timeout
from sippy.Rtp_proxy_client import Rtp_proxy_client
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: sippy/SdpOrigin.py
# class SdpOrigin(object):
# _session_id = int(random() * time() * 1000.0)
# username = None
# session_id = None
# version = None
# network_type = None
# address_type = None
# address = None
# session_id = None
#
# def __init__(self, body = None, cself = None):
# if body != None:
# self.username, self.session_id, self.version, self.network_type, self.address_type, self.address = body.split()
# elif cself == None:
# self.username = '-'
# self.session_id = SdpOrigin._session_id
# SdpOrigin._session_id += 1
# self.version = self.session_id
# self.network_type = 'IN'
# self.address_type = 'IP4'
# self.address = SipConf.my_address
# else:
# self.username = cself.username
# self.session_id = cself.session_id
# self.version = cself.version
# self.network_type = cself.network_type
# self.address_type = cself.address_type
# self.address = cself.address
#
# def __str__(self):
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, self.address_type, self.address)
#
# def localStr(self, local_addr = None, local_port = None):
# if local_addr != None and 'my' in dir(self.address):
# if local_addr.startswith('['):
# address_type = 'IP6'
# local_addr = local_addr[1:-1]
# else:
# address_type = 'IP4'
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, address_type, local_addr)
# return '%s %s %s %s %s %s' % (self.username, self.session_id, self.version, self.network_type, self.address_type, self.address)
#
# def getCopy(self):
# return self.__class__(cself = self)
#
# Path: sippy/Core/Exceptions.py
# def dump_exception(msg, f = sys.stdout, extra = None):
# exc_type, exc_value, exc_traceback = sys.exc_info()
# if isinstance(exc_value, StdException):
# cus_traceback = exc_value.traceback
# else:
# if hasattr(exc_value, 'traceback'):
# exc_traceback = exc_value.traceback
# cus_traceback = None
# f.write('%s @%s[%d] %s:\n' % (datetime.now(), sys.argv[0], os.getpid(), msg))
# f.write(SEPT)
# if cus_traceback != None:
# f.write('Traceback (most recent call last):\n')
# print_list(cus_traceback, file = f)
# f.write(format_exception_only(exc_type, exc_value)[0])
# else:
# print_exception(exc_type, exc_value, exc_traceback, file = f)
# f.write(SEPT)
# if extra != None:
# f.write(extra)
# f.write(SEPT)
# f.flush()
. Output only the next line. | return |
Given the code snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipServer(SipGenericHF):
hf_names = ('server',)
name = None
def __init__(self, body = None, name = None):
SipGenericHF.__init__(self, body)
self.parsed = True
if body != None:
self.name = body
elif name != None:
self.name = name
else:
self.name = SipConf.my_uaname
def __str__(self):
return self.name
def getCopy(self):
<|code_end|>
, generate the next line using the imports in this file:
from sippy.SipGenericHF import SipGenericHF
from sippy.SipConf import SipConf
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | return self.__class__(name = self.name) |
Given snippet: <|code_start|>
class RadiusAuthorisation(Radius_client):
def do_auth(self, username, caller, callee, sip_cid, remote_ip, res_cb, \
realm = None, nonce = None, uri = None, response = None, extra_attributes = None):
sip_cid = str(sip_cid)
attributes = None
if None not in (realm, nonce, uri, response):
attributes = [('User-Name', username), ('Digest-Realm', realm), \
('Digest-Nonce', nonce), ('Digest-Method', 'INVITE'), ('Digest-URI', uri), \
('Digest-Algorithm', 'MD5'), ('Digest-User-Name', username), ('Digest-Response', response)]
else:
attributes = [('User-Name', remote_ip), ('Password', 'cisco')]
if caller == None:
caller = ''
attributes.extend((('Calling-Station-Id', caller), ('Called-Station-Id', callee), \
('call-id', sip_cid), ('h323-remote-address', remote_ip), ('h323-session-protocol', 'sipv2')))
if extra_attributes != None:
for a, v in extra_attributes:
attributes.append((a, v))
message = 'sending AAA request:\n'
message += reduce(lambda x, y: x + y, ['%-32s = \'%s\'\n' % (x[0], str(x[1])) for x in attributes])
self.global_config['_sip_logger'].write(message, call_id = sip_cid)
Radius_client.do_auth(self, attributes, self._process_result, res_cb, sip_cid, time())
def _process_result(self, results, res_cb, sip_cid, btime):
delay = time() - btime
rcode = results[1]
if rcode in (0, 1):
if rcode == 0:
message = 'AAA request accepted (delay is %.3f), processing response:\n' % delay
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sippy.Radius_client import Radius_client
from time import time
from functools import reduce
and context:
# Path: sippy/Radius_client.py
# class Radius_client(External_command):
# global_config = None
# _avpair_names = ('call-id', 'h323-session-protocol', 'h323-ivr-out', 'h323-incoming-conf-id', \
# 'release-source', 'alert-timepoint', 'provisional-timepoint')
# _cisco_vsa_names = ('h323-remote-address', 'h323-conf-id', 'h323-setup-time', 'h323-call-origin', \
# 'h323-call-type', 'h323-connect-time', 'h323-disconnect-time', 'h323-disconnect-cause', \
# 'h323-voice-quality', 'h323-credit-time', 'h323-return-code', 'h323-redirect-number', \
# 'h323-preferred-lang', 'h323-billing-model', 'h323-currency')
#
# def __init__(self, global_config = {}):
# self.global_config = global_config
# command = global_config.getdefault('radiusclient', '/usr/local/sbin/radiusclient')
# config = global_config.getdefault('radiusclient.conf', None)
# max_workers = global_config.getdefault('max_radiusclients', 20)
# if config != None:
# External_command.__init__(self, (command, '-f', config, '-s'), max_workers = max_workers)
# else:
# External_command.__init__(self, (command, '-s'), max_workers = max_workers)
#
# def _prepare_attributes(self, type, attributes):
# data = [type]
# for a, v in attributes:
# if a in self._avpair_names:
# v = '%s=%s' % (str(a), str(v))
# a = 'Cisco-AVPair'
# elif a in self._cisco_vsa_names:
# v = '%s=%s' % (str(a), str(v))
# data.append('%s="%s"' % (str(a), str(v)))
# return data
#
# def do_auth(self, attributes, result_callback, *callback_parameters):
# return External_command.process_command(self, self._prepare_attributes('AUTH', attributes), result_callback, *callback_parameters)
#
# def do_acct(self, attributes, result_callback = None, *callback_parameters):
# External_command.process_command(self, self._prepare_attributes('ACCT', attributes), result_callback, *callback_parameters)
#
# def process_result(self, result_callback, result, *callback_parameters):
# if result_callback == None:
# return
# nav = []
# for av in result[:-1]:
# a, v = [x.strip() for x in av.split(' = ', 1)]
# v = v.strip('\'')
# if (a == 'Cisco-AVPair' or a in self._cisco_vsa_names):
# t = v.split('=', 1)
# if len(t) > 1:
# a, v = t
# elif v.startswith(a + '='):
# v = v[len(a) + 1:]
# nav.append((a, v))
# External_command.process_result(self, result_callback, (tuple(nav), int(result[-1])), *callback_parameters)
which might include code, classes, or functions. Output only the next line. | else: |
Based on the snippet: <|code_start|> 'SHA-256':(sha256, DGST_SHA256), 'SHA-256-sess':(sha256, DGST_SHA256SESS), \
'SHA-512-256':(sha512_256, DGST_SHA512), 'SHA-512-256-sess':(sha512_256, DGST_SHA512SESS)}
class SipAuthorization(SipGenericHF):
hf_names = ('authorization',)
username = None
uri = None
realm = None
nonce = None
response = None
qop = None
cnonce = None
nc = None
algorithm = None
otherparams = None
ho = HashOracle()
def __init__(self, body = None, username = None, uri = None, realm = None, nonce = None, response = None, \
cself = None):
SipGenericHF.__init__(self, body)
if body != None:
return
self.parsed = True
if cself != None:
self.username = cself.username
self.uri = cself.uri
self.realm = cself.realm
self.nonce = cself.nonce
self.response = cself.response
self.qop = cself.qop
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | self.cnonce = cself.cnonce |
Continue the code snippet: <|code_start|>class SipAuthorization(SipGenericHF):
hf_names = ('authorization',)
username = None
uri = None
realm = None
nonce = None
response = None
qop = None
cnonce = None
nc = None
algorithm = None
otherparams = None
ho = HashOracle()
def __init__(self, body = None, username = None, uri = None, realm = None, nonce = None, response = None, \
cself = None):
SipGenericHF.__init__(self, body)
if body != None:
return
self.parsed = True
if cself != None:
self.username = cself.username
self.uri = cself.uri
self.realm = cself.realm
self.nonce = cself.nonce
self.response = cself.response
self.qop = cself.qop
self.cnonce = cself.cnonce
self.nc = cself.nc
self.algorithm = cself.algorithm
<|code_end|>
. Use current file imports:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context (classes, functions, or code) from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | self.otherparams = cself.otherparams[:] |
Here is a snippet: <|code_start|> return 'Authorization'
def IsDigestAlgSupported(algorithm):
return (algorithm in _HASH_FUNC)
def NameList2AlgMask(nlist):
return tuple([_HASH_FUNC[x][1] for x in nlist])
def DigestCalcHA1(pszAlg, pszUserName, pszRealm, pszPassword, pszNonce, pszCNonce):
delim = ':'.encode()
hashfunc = _HASH_FUNC[pszAlg][0]
m = hashfunc()
m.update(pszUserName.encode())
m.update(delim)
m.update(pszRealm.encode())
m.update(delim)
m.update(pszPassword.encode())
HA1 = m.hexdigest().encode()
if pszAlg and pszAlg.endswith('-sess'):
m = hashfunc()
m.update(HA1)
m.update(delim)
m.update(pszNonce.encode())
m.update(delim)
m.update(pszCNonce.encode())
HA1 = m.hexdigest().encode()
return HA1
def DigestCalcResponse(pszAlg, HA1, pszNonce, pszNonceCount, pszCNonce, pszQop, pszMethod, pszDigestUri, pszHEntity):
delim = ':'.encode()
<|code_end|>
. Write the next line using the current file imports:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
, which may include functions, classes, or code. Output only the next line. | hashfunc = _HASH_FUNC[pszAlg][0] |
Given the following code snippet before the placeholder: <|code_start|> if not self.parsed:
self.parse()
HA1 = DigestCalcHA1(self.algorithm, self.username, self.realm, password, self.nonce, self.cnonce)
return self.verifyHA1(HA1, method, body)
def verifyHA1(self, HA1, method, body):
if not self.parsed:
self.parse()
if self.algorithm not in _HASH_FUNC:
return False
if self.qop != None and self.qop not in ('auth', 'auth-int'):
return False
algmask = _HASH_FUNC[self.algorithm][1]
if not self.ho.validate_challenge(self.nonce, (algmask,)):
return False
response = DigestCalcResponse(self.algorithm, HA1, self.nonce, self.nc, \
self.cnonce, self.qop, method, self.uri, body)
return response == self.response
def getCanName(self, name, compact = False):
return 'Authorization'
def IsDigestAlgSupported(algorithm):
return (algorithm in _HASH_FUNC)
def NameList2AlgMask(nlist):
return tuple([_HASH_FUNC[x][1] for x in nlist])
def DigestCalcHA1(pszAlg, pszUserName, pszRealm, pszPassword, pszNonce, pszCNonce):
delim = ':'.encode()
<|code_end|>
, predict the next line using imports from the current file:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | hashfunc = _HASH_FUNC[pszAlg][0] |
Predict the next line after this snippet: <|code_start|> def genAuthResponse(self, password, method, body):
HA1 = DigestCalcHA1(self.algorithm, self.username, self.realm, password, \
self.nonce, self.cnonce)
self.response = DigestCalcResponse(self.algorithm, HA1, self.nonce, \
self.nc, self.cnonce, self.qop, method, self.uri, body)
def __str__(self):
if not self.parsed:
return self.body
rval = 'Digest username="%s",realm="%s",nonce="%s",uri="%s",response="%s"' % \
(self.username, self.realm, self.nonce, self.uri, self.response)
if self.algorithm != None:
rval += ',algorithm=%s' % (self.algorithm,)
if self.qop != None:
rval += ',qop=%s,nc=%s,cnonce="%s"' % (self.qop, self.nc, self.cnonce)
for param in self.otherparams:
rval += ',%s=%s' % param
return rval
def getCopy(self):
if not self.parsed:
return self.__class__(self.body)
return self.__class__(cself = self)
def verify(self, password, method, body = None):
if not self.parsed:
self.parse()
HA1 = DigestCalcHA1(self.algorithm, self.username, self.realm, password, self.nonce, self.cnonce)
return self.verifyHA1(HA1, method, body)
<|code_end|>
using the current file's imports:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and any relevant context from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | def verifyHA1(self, HA1, method, body): |
Predict the next line for this snippet: <|code_start|> m.update(pszRealm.encode())
m.update(delim)
m.update(pszPassword.encode())
HA1 = m.hexdigest().encode()
if pszAlg and pszAlg.endswith('-sess'):
m = hashfunc()
m.update(HA1)
m.update(delim)
m.update(pszNonce.encode())
m.update(delim)
m.update(pszCNonce.encode())
HA1 = m.hexdigest().encode()
return HA1
def DigestCalcResponse(pszAlg, HA1, pszNonce, pszNonceCount, pszCNonce, pszQop, pszMethod, pszDigestUri, pszHEntity):
delim = ':'.encode()
hashfunc = _HASH_FUNC[pszAlg][0]
m = hashfunc()
m.update(pszMethod.encode())
m.update(delim)
m.update(pszDigestUri.encode())
if pszQop == "auth-int":
m.update(delim)
if pszHEntity is None:
pszHEntity = ''
m1 = hashfunc()
m1.update(pszHEntity.encode())
HA_pszHEntity = m1.hexdigest()
m.update(HA_pszHEntity.encode())
HA2 = m.hexdigest()
<|code_end|>
with the help of current file imports:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
, which may contain function names, class names, or code. Output only the next line. | m = hashfunc() |
Given the following code snippet before the placeholder: <|code_start|> HA1 = DigestCalcHA1(self.algorithm, self.username, self.realm, password, \
self.nonce, self.cnonce)
self.response = DigestCalcResponse(self.algorithm, HA1, self.nonce, \
self.nc, self.cnonce, self.qop, method, self.uri, body)
def __str__(self):
if not self.parsed:
return self.body
rval = 'Digest username="%s",realm="%s",nonce="%s",uri="%s",response="%s"' % \
(self.username, self.realm, self.nonce, self.uri, self.response)
if self.algorithm != None:
rval += ',algorithm=%s' % (self.algorithm,)
if self.qop != None:
rval += ',qop=%s,nc=%s,cnonce="%s"' % (self.qop, self.nc, self.cnonce)
for param in self.otherparams:
rval += ',%s=%s' % param
return rval
def getCopy(self):
if not self.parsed:
return self.__class__(self.body)
return self.__class__(cself = self)
def verify(self, password, method, body = None):
if not self.parsed:
self.parse()
HA1 = DigestCalcHA1(self.algorithm, self.username, self.realm, password, self.nonce, self.cnonce)
return self.verifyHA1(HA1, method, body)
def verifyHA1(self, HA1, method, body):
<|code_end|>
, predict the next line using imports from the current file:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | if not self.parsed: |
Given the following code snippet before the placeholder: <|code_start|> if cself != None:
self.username = cself.username
self.uri = cself.uri
self.realm = cself.realm
self.nonce = cself.nonce
self.response = cself.response
self.qop = cself.qop
self.cnonce = cself.cnonce
self.nc = cself.nc
self.algorithm = cself.algorithm
self.otherparams = cself.otherparams[:]
return
self.username = username
self.uri = uri
self.realm = realm
self.nonce = nonce
self.response = response
self.otherparams = []
def parse(self):
self.otherparams = []
for name, value in [x.strip(', ').split('=', 1) for x in self.body.split(' ', 1)[1].split(',')]:
ci_name = name.lower()
if ci_name == 'username':
self.username = value.strip('"')
elif ci_name == 'uri':
self.uri = value.strip('"')
elif ci_name == 'realm':
self.realm = value.strip('"')
elif ci_name == 'nonce':
<|code_end|>
, predict the next line using imports from the current file:
from sippy.SipGenericHF import SipGenericHF
from sippy.Security.SipNonce import HashOracle, DGST_MD5, DGST_MD5SESS, \
DGST_SHA256, DGST_SHA256SESS, DGST_SHA512, DGST_SHA512SESS
from hashlib import md5, sha256
from time import time
from Crypto.Hash import SHA512
and context including class names, function names, and sometimes code from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/Security/SipNonce.py
# class HashOracle(object):
# try: key
# except: key = Random.new().read(AES.block_size * 2)
# ac = None
# vtime = 32 * 10**9
#
# def __init__(self):
# self.ac = AESCipher(self.key)
#
# def emit_challenge(self, cmask):
# ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
# for ms in cmask:
# ts128 |= ms
# cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
# #return cryptic
# return cryptic.decode()
#
# def validate_challenge(self, cryptic, cmask):
# new_ts = clock_getntime(CLOCK_MONOTONIC)
# decryptic = from_bytes_be(self.ac.decrypt(cryptic.encode()))
# for ms in cmask:
# if (ms & decryptic) == 0:
# return False
# orig_ts = decryptic >> len(DGST_PRIOS)
# tsdiff = new_ts - orig_ts
# if tsdiff < 0 or tsdiff > self.vtime:
# return False
# return True
#
# DGST_MD5 = (1 << 0)
#
# DGST_MD5SESS = (1 << 1)
#
# DGST_SHA256 = (1 << 2)
#
# DGST_SHA256SESS = (1 << 3)
#
# DGST_SHA512 = (1 << 4)
#
# DGST_SHA512SESS = (1 << 5)
. Output only the next line. | self.nonce = value.strip('"') |
Using the snippet: <|code_start|> hf_names = ('replaces',)
call_id = None
from_tag = None
to_tag = None
early_only = False
params = None
def __init__(self, body = None, call_id = None, from_tag = None, to_tag = None, \
early_only = False, params = None):
SipGenericHF.__init__(self, body)
if body != None:
return
self.parsed = True
self.params = []
self.call_id = call_id
self.from_tag = from_tag
self.to_tag = to_tag
self.early_only = early_only
if params != None:
self.params = params[:]
def parse(self):
self.params = []
params = self.body.split(';')
self.call_id = params.pop(0)
for param in params:
if param.startswith('from-tag='):
self.from_tag = param[len('from-tag='):]
elif param.startswith('to-tag='):
self.to_tag = param[len('to-tag='):]
<|code_end|>
, determine the next line of code. You have imports:
from sippy.SipGenericHF import SipGenericHF
and context (class names, function names, or code) available:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | elif param == 'early-only': |
Based on the snippet: <|code_start|> return cself
# Speacial method allowing tweaking internal parameters of the UAC
# after everything has been setup but before INVITE goes out.
def onUacSetupComplete(self, uac):
pass
class CCEventRing(CCEventGeneric):
name = 'CCEventRing'
pass
class CCEventPreConnect(CCEventGeneric):
name = 'CCEventPreConnect'
pass
class CCEventConnect(CCEventGeneric):
name = 'CCEventConnect'
pass
class CCEventUpdate(CCEventGeneric):
name = 'CCEventUpdate'
max_forwards = None
def getCopy(self):
cself = CCEventGeneric.getCopy(self)
cself.max_forwards = self.max_forwards
return cself
class CCEventInfo(CCEventGeneric):
name = 'CCEventInfo'
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.Time.MonoTime import MonoTime
from sippy.SipHeader import SipHeader
from sippy.SipWarning import SipWarning
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipWarning.py
# class SipWarning(SipGenericHF):
# hf_names = ('warning',)
# code = 399
# agent = socket.gethostname()
# text = None
#
# def __init__(self, body = None, cself = None, code = None, text = None):
# SipGenericHF.__init__(self, body)
# if body != None:
# return
# self.parsed = True
# if cself != None:
# self.code, self.agent, self.text = \
# cself.code, cself.agent, cself.text
# else:
# self.agent = socket.gethostname()
# if code != None:
# self.code = code
# self.text = text.replace('"', "'")
#
# def parse(self):
# code, self.agent, text = self.body.split(None, 2)
# self.text = text.strip('"')
# self.code = int(code)
# self.parsed = True
#
# def __str__(self):
# if not self.parsed:
# return self.body
# return '%d %s "%s"' % (self.code, self.agent, self.text)
#
# def getCopy(self):
# return self.__class__(cself = self)
. Output only the next line. | pass |
Given the code snippet: <|code_start|> cself = CCEventGeneric.getCopy(self)
cself.max_forwards = self.max_forwards
return cself
# Speacial method allowing tweaking internal parameters of the UAC
# after everything has been setup but before INVITE goes out.
def onUacSetupComplete(self, uac):
pass
class CCEventRing(CCEventGeneric):
name = 'CCEventRing'
pass
class CCEventPreConnect(CCEventGeneric):
name = 'CCEventPreConnect'
pass
class CCEventConnect(CCEventGeneric):
name = 'CCEventConnect'
pass
class CCEventUpdate(CCEventGeneric):
name = 'CCEventUpdate'
max_forwards = None
def getCopy(self):
cself = CCEventGeneric.getCopy(self)
cself.max_forwards = self.max_forwards
return cself
<|code_end|>
, generate the next line using the imports in this file:
from sippy.Time.MonoTime import MonoTime
from sippy.SipHeader import SipHeader
from sippy.SipWarning import SipWarning
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/SipHeader.py
# class SipHeader(object):
# name = None
# body = None
#
# def __init__(self, s = None, name = None, body = None, bodys = None, fixname = False):
# if s != None:
# name, bodys = [x.strip() for x in s.split(':', 1)]
# if name != None:
# self.name = name.lower()
# if body == None:
# try:
# try:
# body = hf_types[self.name](bodys)
# except KeyError:
# body = SipGenericHF(bodys, name)
# except ESipHeaderCSV as einst:
# einst.name = self.name
# raise einst
# self.body = body
# # If no name is provided use canonic name from the body-specific
# # class.
# if self.name == None or fixname:
# self.name = body.hf_names[0]
#
# def __str__(self):
# return str(self.body.getCanName(self.name)) + ': ' + str(self.body)
#
# def localStr(self, local_addr = None, local_port = None, compact = False):
# return str(self.body.getCanName(self.name, compact)) + ': ' + \
# self.body.localStr(local_addr, local_port)
#
# def getBody(self):
# if not self.body.parsed:
# self.body.parse()
# return self.body
#
# def getBCopy(self):
# return self.body.getCopy()
#
# def getCopy(self):
# cself = self.__class__(name = self.name, body = self.body.getCopy())
# return cself
#
# Path: sippy/SipWarning.py
# class SipWarning(SipGenericHF):
# hf_names = ('warning',)
# code = 399
# agent = socket.gethostname()
# text = None
#
# def __init__(self, body = None, cself = None, code = None, text = None):
# SipGenericHF.__init__(self, body)
# if body != None:
# return
# self.parsed = True
# if cself != None:
# self.code, self.agent, self.text = \
# cself.code, cself.agent, cself.text
# else:
# self.agent = socket.gethostname()
# if code != None:
# self.code = code
# self.text = text.replace('"', "'")
#
# def parse(self):
# code, self.agent, text = self.body.split(None, 2)
# self.text = text.strip('"')
# self.code = int(code)
# self.parsed = True
#
# def __str__(self):
# if not self.parsed:
# return self.body
# return '%d %s "%s"' % (self.code, self.agent, self.text)
#
# def getCopy(self):
# return self.__class__(cself = self)
. Output only the next line. | class CCEventInfo(CCEventGeneric): |
Based on the snippet: <|code_start|> master = None
def __init__(self, command, master):
Thread.__init__(self)
self.command = command
self.master = master
self.setDaemon(True)
self.start()
def run(self):
need_close_fds = True
if platform == 'win32':
need_close_fds = False
pipe = Popen(self.command, shell = False, stdin = PIPE, \
stdout = PIPE, stderr = PIPE, close_fds = need_close_fds)
while True:
self.master.work_available.acquire()
while len(self.master.work) == 0:
self.master.work_available.wait()
wi = self.master.work.pop(0)
if wi == None:
# Shutdown request, relay it further
self.master.work.append(None)
self.master.work_available.notify()
self.master.work_available.release()
if wi == None:
break
if wi.is_cancelled():
wi.data = None
wi.result_callback = None
<|code_end|>
, predict the immediate next line with the help of imports:
from threading import Condition
from subprocess import Popen, PIPE
from sys import platform
from threading import Thread, Lock
from errno import EINTR
from sippy.Core.Exceptions import dump_exception
from sippy.Core.EventDispatcher import ED2
from sys import exit
from time import sleep
and context (classes, functions, sometimes code) from other files:
# Path: sippy/Core/Exceptions.py
# def dump_exception(msg, f = sys.stdout, extra = None):
# exc_type, exc_value, exc_traceback = sys.exc_info()
# if isinstance(exc_value, StdException):
# cus_traceback = exc_value.traceback
# else:
# if hasattr(exc_value, 'traceback'):
# exc_traceback = exc_value.traceback
# cus_traceback = None
# f.write('%s @%s[%d] %s:\n' % (datetime.now(), sys.argv[0], os.getpid(), msg))
# f.write(SEPT)
# if cus_traceback != None:
# f.write('Traceback (most recent call last):\n')
# print_list(cus_traceback, file = f)
# f.write(format_exception_only(exc_type, exc_value)[0])
# else:
# print_exception(exc_type, exc_value, exc_traceback, file = f)
# f.write(SEPT)
# if extra != None:
# f.write(extra)
# f.write(SEPT)
# f.flush()
. Output only the next line. | wi.callback_parameters = None |
Next line prediction: <|code_start|># Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipWarning(SipGenericHF):
hf_names = ('warning',)
code = 399
<|code_end|>
. Use current file imports:
(from sippy.SipGenericHF import SipGenericHF
import socket)
and context including class names, function names, or small code snippets from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | agent = socket.gethostname() |
Based on the snippet: <|code_start|># ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class UaStateDisconnected(UaStateGeneric):
sname = 'Disconnected'
def __init__(self, ua):
UaStateGeneric.__init__(self, ua)
ua.on_local_sdp_change = None
ua.on_remote_sdp_change = None
Timeout(self.goDead, ua.godead_timeout)
def recvRequest(self, req):
if req.getMethod() == 'BYE':
#print 'BYE received in the Disconnected state'
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', server = self.ua.local_ua))
else:
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(500, 'Disconnected', server = self.ua.local_ua))
return None
def goDead(self):
#print 'Time in Disconnected state expired, going to the Dead state'
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.Time.Timeout import Timeout
from sippy.UaStateGeneric import UaStateGeneric
from sippy.UaStateDead import UaStateDead
and context (classes, functions, sometimes code) from other files:
# Path: sippy/UaStateGeneric.py
# class UaStateGeneric(object):
# sname = 'Generic'
# ua = None
# connected = False
# dead = False
#
# def __init__(self, ua):
# self.ua = ua
#
# def recvRequest(self, req):
# return None
#
# def recvResponse(self, resp, tr):
# return None
#
# def recvEvent(self, event):
# return None
#
# def cancel(self, rtime, req):
# return None
#
# def onStateChange(self, newstate):
# pass
#
# def __str__(self):
# return self.sname
. Output only the next line. | self.ua.changeState((UaStateDead,)) |
Here is a snippet: <|code_start|> return
self.parsed = True
if ciscoGUID != None:
self.ciscoGUID = ciscoGUID
else:
salt = str((random() * 1000000000) + time())
s = md5(salt.encode()).hexdigest()
self.ciscoGUID = (int(s[0:8], 16), int(s[8:16], 16), int(s[16:24], 16), int(s[24:32], 16))
def parse(self):
self.ciscoGUID = tuple([int(x) for x in self.body.split('-', 3)])
self.parsed = True
def __str__(self):
if not self.parsed:
return self.body
return '%d-%d-%d-%d' % self.ciscoGUID
def getCiscoGUID(self):
return self.ciscoGUID
def hexForm(self):
return '%.8X %.8X %.8X %.8X' % self.ciscoGUID
def getCanName(self, name, compact = False):
if name.lower() == 'h323-conf-id':
return 'h323-conf-id'
else:
return 'cisco-GUID'
<|code_end|>
. Write the next line using the current file imports:
from random import random
from hashlib import md5
from time import time
from sippy.SipGenericHF import SipGenericHF
and context from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
, which may include functions, classes, or code. Output only the next line. | def getCopy(self): |
Next line prediction: <|code_start|># (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipNumericHF(SipGenericHF):
number = None
def __init__(self, body = None, number = 0):
SipGenericHF.__init__(self, body)
if body == None:
self.parsed = True
self.number = number
def parse(self):
self.number = int(self.body)
self.parsed = True
def __str__(self):
if not self.parsed:
return self.body
return str(self.number)
def getCopy(self):
if not self.parsed:
return self.__class__(body = self.body)
return self.__class__(number = self.number)
def getNum(self):
return self.number
<|code_end|>
. Use current file imports:
(from sippy.SipGenericHF import SipGenericHF)
and context including class names, function names, or small code snippets from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
. Output only the next line. | def incNum(self): |
Based on the snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SipRAck(SipCSeq):
hf_names = ('rack',)
rseq = None
def __init__(self, body = None, rseq = None, cseq = None, method = None):
if body == None:
self.rseq = rseq
SipCSeq.__init__(self, cseq = cseq, method = method)
return
SipCSeq.__init__(self, body)
def parse(self):
rseq, cseq, self.method = self.body.split(None, 2)
self.rseq = int(rseq)
self.cseq = int(cseq)
self.parsed = True
def getCopy(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from sippy.SipCSeq import SipCSeq
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SipCSeq.py
# class SipCSeq(SipGenericHF):
# hf_names = ('cseq',)
# cseq = None
# method = None
#
# def __init__(self, body = None, cseq = None, method = None):
# SipGenericHF.__init__(self, body)
# if body == None:
# self.parsed = True
# self.method = method
# if cseq != None:
# self.cseq = cseq
# else:
# self.cseq = 1
#
# def parse(self):
# cseq, self.method = self.body.split()
# self.cseq = int(cseq)
# self.parsed = True
#
# def __str__(self):
# if not self.parsed:
# return self.body
# return str(self.cseq) + ' ' + self.method
#
# def getCSeq(self):
# return (self.cseq, self.method)
#
# def getCSeqNum(self):
# return self.cseq
#
# def getCSeqMethod(self):
# return self.method
#
# def getCopy(self):
# if not self.parsed:
# return SipCSeq(self.body)
# return SipCSeq(cseq = self.cseq, method = self.method)
#
# def getCanName(self, name, compact = False):
# return 'CSeq'
#
# def incCSeqNum(self):
# self.cseq += 1
# return self.cseq
. Output only the next line. | if not self.parsed: |
Based on the snippet: <|code_start|> if not self.parsed:
return self.body
if local_addr != None and 'my' in dir(self.hostname):
s = self.sipver + ' ' + local_addr
else:
s = self.sipver + ' ' + str(self.hostname)
if self.port != None:
if local_port != None and 'my' in dir(self.port):
s += ':' + str(local_port)
else:
s += ':' + str(self.port)
for key, val in self.params.items():
s += ';' + key
if val != None:
s += '=' + val
return s
def getCopy(self):
if not self.parsed:
return SipVia(self.body)
return SipVia(sipver = self.sipver, hostname = self.hostname, port = self.port, params = self.params.copy())
def genBranch(self):
salt = str((random() * 1000000000) + time())
self.params['branch'] = 'z9hG4bK' + md5(salt.encode()).hexdigest()
def getBranch(self):
return self.params.get('branch', None)
def setParam(self, name, value = None):
<|code_end|>
, predict the immediate next line with the help of imports:
from random import random
from hashlib import md5
from time import time
from sippy.SipGenericHF import SipGenericHF
from sippy.SipConf import SipConf
from sippy.ESipHeaderCSV import ESipHeaderCSV
and context (classes, functions, sometimes code) from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
. Output only the next line. | self.params[name] = value |
Given the code snippet: <|code_start|> def localStr(self, local_addr = None, local_port = None):
if not self.parsed:
return self.body
if local_addr != None and 'my' in dir(self.hostname):
s = self.sipver + ' ' + local_addr
else:
s = self.sipver + ' ' + str(self.hostname)
if self.port != None:
if local_port != None and 'my' in dir(self.port):
s += ':' + str(local_port)
else:
s += ':' + str(self.port)
for key, val in self.params.items():
s += ';' + key
if val != None:
s += '=' + val
return s
def getCopy(self):
if not self.parsed:
return SipVia(self.body)
return SipVia(sipver = self.sipver, hostname = self.hostname, port = self.port, params = self.params.copy())
def genBranch(self):
salt = str((random() * 1000000000) + time())
self.params['branch'] = 'z9hG4bK' + md5(salt.encode()).hexdigest()
def getBranch(self):
return self.params.get('branch', None)
<|code_end|>
, generate the next line using the imports in this file:
from random import random
from hashlib import md5
from time import time
from sippy.SipGenericHF import SipGenericHF
from sippy.SipConf import SipConf
from sippy.ESipHeaderCSV import ESipHeaderCSV
and context (functions, classes, or occasionally code) from other files:
# Path: sippy/SipGenericHF.py
# class SipGenericHF(object):
# hf_names = None # Set this in each subclass!!
# body = None
# parsed = False
#
# def __init__(self, body, name = None):
# self.body = body
# if name != None:
# self.hf_names = (name.lower(),)
#
# def parse(self):
# pass
#
# def localStr(self, local_addr = None, local_port = None):
# return self.__str__()
#
# def __str__(self):
# return self.body
#
# def getCopy(self):
# return self.__class__(self.body)
#
# def getCanName(self, name, compact = False):
# return name.capitalize()
#
# Path: sippy/ESipHeaderCSV.py
# class ESipHeaderCSV(Exception):
# def __init__(self, name, bodys):
# Exception.__init__(self)
# self.name = name
# self.bodys = bodys
. Output only the next line. | def setParam(self, name, value = None): |
Here is a snippet: <|code_start|>
default_logger = getLogger()
default_logger.setLevel(DEBUG if IS_DEVELOPMENT else WARNING)
log_console = StreamHandler()
log_format = '%(name)-12s %(levelname)-7s %(message)s'
log_console.setFormatter(Formatter(log_format))
<|code_end|>
. Write the next line using the current file imports:
from logging import getLogger, Formatter, DEBUG, WARNING, StreamHandler
from pysecure.config import IS_DEVELOPMENT
and context from other files:
# Path: pysecure/config.py
# IS_DEVELOPMENT = bool(int(environ.get('DEBUG', '0')))
, which may include functions, classes, or code. Output only the next line. | default_logger.addHandler(log_console) |
Predict the next line after this snippet: <|code_start|>
class ForwardReverseTest(TestCase):
def __ssh_cb(self, ssh):
def build_body(status_code, status_string, content):
replacements = { 'scode': status_code,
'sstring': status_string,
'length': len(content),
'content': content }
<|code_end|>
using the current file's imports:
from unittest import TestCase
from pysecure import log_config
from pysecure.test.test_base import connect_ssh_test
and any relevant context from other files:
# Path: pysecure/log_config.py
#
# Path: pysecure/test/test_base.py
# def connect_ssh_test(ssh_cb):
# print("Connecting SSH with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_ssh_with_cb(ssh_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | return """HTTP/1.1 %(scode)d %(sstring)s |
Next line prediction: <|code_start|>
class BinaryReadTest(TestCase):
def __sftp_cb(self, ssh, sftp):
# print("Opening file.")
with SftpFile(sftp, 'test_libgksu2.so.0', 'r') as sf:
buffer_ = sf.read()
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from pysecure.adapters.sftpa import SftpFile
from pysecure.test.test_base import connect_sftp_test)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/adapters/sftpa.py
# class SftpFile(object):
# def __init__(self, sftp_session, filepath, access_type_om='r',
# create_mode=DEFAULT_CREATE_MODE):
#
# at_im = self.__at_om_to_im(access_type_om)
#
# self.__sftp_session_int = getattr(sftp_session,
# 'session_id',
# sftp_session)
#
# self.__filepath = filepath
# self.__access_type = at_im
# self.__create_mode = create_mode
#
# def __repr__(self):
# return ('<SFTP_FILE [%s] \"%s\">' %
# (self.__access_type[0], self.__filepath))
#
# def __at_om_to_im(self, om):
# """Convert an "outer" access mode to an "inner" access mode.
# Returns a tuple of:
#
# (<system access mode>, <is append>, <is universal newlines>).
# """
#
# original_om = om
#
# if om[0] == 'U':
# om = om[1:]
# is_um = True
# else:
# is_um = False
#
# if om == 'r':
# return (original_om, O_RDONLY, False, is_um)
# elif om == 'w':
# return (original_om, O_WRONLY | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a':
# return (original_om, O_WRONLY | O_CREAT, False, is_um)
# elif om == 'r+':
# return (original_om, O_RDWR | O_CREAT, False, is_um)
# elif om == 'w+':
# return (original_om, O_RDWR | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a+':
# return (original_om, O_RDWR | O_CREAT, True, is_um)
# else:
# raise Exception("Outer access mode [%s] is invalid." %
# (original_om))
#
# def __enter__(self):
# return self.open()
#
# def open(self):
# """This is the only way to open a file resource."""
#
# self.__sf = _sftp_open(self.__sftp_session_int,
# self.__filepath,
# self.access_type_int,
# self.__create_mode)
#
# if self.access_type_is_append is True:
# self.seek(self.filesize)
#
# return SftpFileObject(self)
#
# def __exit__(self, e_type, e_value, e_tb):
# self.close()
#
# def close(self):
# _sftp_close(self.__sf)
#
# def write(self, buffer_):
# return _sftp_write(self.__sf, buffer_)
#
# def seek(self, position):
# return _sftp_seek(self.__sf, position)
#
# def read(self, size):
# """Read a length of bytes. Return empty on EOF."""
#
# return _sftp_read(self.__sf, size)
#
# def fstat(self):
# return _sftp_fstat(self.__sf)
#
# def rewind(self):
# return _sftp_rewind(self.__sf)
#
# @property
# def sf(self):
# return self.__sf
#
# @property
# def position(self):
# return _sftp_tell(self.__sf)
#
# @property
# def filesize(self):
# return self.fstat().size
#
# @property
# def filepath(self):
# return self.__filepath
#
# @property
# def access_type_str(self):
# return self.__access_type[0]
#
# @property
# def access_type_int(self):
# return self.__access_type[1]
#
# @property
# def access_type_is_append(self):
# return self.__access_type[2]
#
# @property
# def access_type_has_universal_nl(self):
# return self.__access_type[3]
#
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | with open('/tmp/sftp_dump', 'wb') as f: |
Here is a snippet: <|code_start|>
class BinaryReadTest(TestCase):
def __sftp_cb(self, ssh, sftp):
# print("Opening file.")
with SftpFile(sftp, 'test_libgksu2.so.0', 'r') as sf:
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from pysecure.adapters.sftpa import SftpFile
from pysecure.test.test_base import connect_sftp_test
and context from other files:
# Path: pysecure/adapters/sftpa.py
# class SftpFile(object):
# def __init__(self, sftp_session, filepath, access_type_om='r',
# create_mode=DEFAULT_CREATE_MODE):
#
# at_im = self.__at_om_to_im(access_type_om)
#
# self.__sftp_session_int = getattr(sftp_session,
# 'session_id',
# sftp_session)
#
# self.__filepath = filepath
# self.__access_type = at_im
# self.__create_mode = create_mode
#
# def __repr__(self):
# return ('<SFTP_FILE [%s] \"%s\">' %
# (self.__access_type[0], self.__filepath))
#
# def __at_om_to_im(self, om):
# """Convert an "outer" access mode to an "inner" access mode.
# Returns a tuple of:
#
# (<system access mode>, <is append>, <is universal newlines>).
# """
#
# original_om = om
#
# if om[0] == 'U':
# om = om[1:]
# is_um = True
# else:
# is_um = False
#
# if om == 'r':
# return (original_om, O_RDONLY, False, is_um)
# elif om == 'w':
# return (original_om, O_WRONLY | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a':
# return (original_om, O_WRONLY | O_CREAT, False, is_um)
# elif om == 'r+':
# return (original_om, O_RDWR | O_CREAT, False, is_um)
# elif om == 'w+':
# return (original_om, O_RDWR | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a+':
# return (original_om, O_RDWR | O_CREAT, True, is_um)
# else:
# raise Exception("Outer access mode [%s] is invalid." %
# (original_om))
#
# def __enter__(self):
# return self.open()
#
# def open(self):
# """This is the only way to open a file resource."""
#
# self.__sf = _sftp_open(self.__sftp_session_int,
# self.__filepath,
# self.access_type_int,
# self.__create_mode)
#
# if self.access_type_is_append is True:
# self.seek(self.filesize)
#
# return SftpFileObject(self)
#
# def __exit__(self, e_type, e_value, e_tb):
# self.close()
#
# def close(self):
# _sftp_close(self.__sf)
#
# def write(self, buffer_):
# return _sftp_write(self.__sf, buffer_)
#
# def seek(self, position):
# return _sftp_seek(self.__sf, position)
#
# def read(self, size):
# """Read a length of bytes. Return empty on EOF."""
#
# return _sftp_read(self.__sf, size)
#
# def fstat(self):
# return _sftp_fstat(self.__sf)
#
# def rewind(self):
# return _sftp_rewind(self.__sf)
#
# @property
# def sf(self):
# return self.__sf
#
# @property
# def position(self):
# return _sftp_tell(self.__sf)
#
# @property
# def filesize(self):
# return self.fstat().size
#
# @property
# def filepath(self):
# return self.__filepath
#
# @property
# def access_type_str(self):
# return self.__access_type[0]
#
# @property
# def access_type_int(self):
# return self.__access_type[1]
#
# @property
# def access_type_is_append(self):
# return self.__access_type[2]
#
# @property
# def access_type_has_universal_nl(self):
# return self.__access_type[3]
#
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
, which may include functions, classes, or code. Output only the next line. | buffer_ = sf.read() |
Given the following code snippet before the placeholder: <|code_start|>
class SftpLsTest(TestCase):
def __sftp_cb(self, ssh, sftp):
# print("Name Size Perms Owner\tGroup\n")
for attributes in sftp.listdir('.'):
print("%-40s %10d %.8o %s(%d)\t%s(%d)" %
(attributes.name[0:40], attributes.size,
attributes.permissions, attributes.owner,
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from pysecure.test.test_base import connect_sftp_test
and context including class names, function names, and sometimes code from other files:
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | attributes.uid, attributes.group, attributes.gid)) |
Based on the snippet: <|code_start|>c_sftp_statvfs_free = libssh.sftp_statvfs_free
c_sftp_statvfs_free.argtypes = [c_void_p]
c_sftp_statvfs_free.restype = None
# libssh2_sftp_symlink(sftp, orig, linkpath)
# int sftp_symlink (sftp_session sftp, const char *target, const char *dest)
c_sftp_symlink = libssh.sftp_symlink
c_sftp_symlink.argtypes = [c_sftp_session, c_char_p, c_char_p]
c_sftp_symlink.restype = c_int
# size_t libssh2_sftp_tell(LIBSSH2_SFTP_HANDLE *handle);
# unsigned long sftp_tell (sftp_file file)
c_sftp_tell = libssh.sftp_tell
c_sftp_tell.argtypes = [c_sftp_file]
c_sftp_tell.restype = c_ulong
# libssh2_uint64_t libssh2_sftp_tell64(LIBSSH2_SFTP_HANDLE *handle);
# uint64_t sftp_tell64 (sftp_file file)
c_sftp_tell64 = libssh.sftp_tell64
c_sftp_tell64.argtypes = [c_sftp_file]
c_sftp_tell64.restype = c_uint64
# int libssh2_sftp_unlink(LIBSSH2_SFTP *sftp, const char *filename);
# int sftp_unlink (sftp_session sftp, const char *file)
c_sftp_unlink = libssh.sftp_unlink
c_sftp_unlink.argtypes = [c_sftp_session, c_char_p]
<|code_end|>
, predict the immediate next line with the help of imports:
from ctypes import *
from pysecure.library import libssh
from pysecure.types import *
and context (classes, functions, sometimes code) from other files:
# Path: pysecure/library.py
# _LIBSSH_FILEPATH = os.environ.get('PS_LIBRARY_FILEPATH', '')
# _LIBSSH_FILEPATH = find_library('libssh')
# _LIBSSH_FILEPATH = 'libssh.so'
. Output only the next line. | c_sftp_unlink.restype = c_int |
Predict the next line for this snippet: <|code_start|>
class ForwardLocalTest(TestCase):
def __ssh_cb(self, ssh):
host_remote = 'localhost'
port_remote = 80
host_source = 'localhost'
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from pysecure.adapters.channela import SshChannel
from pysecure.test.test_base import connect_ssh_test
and context from other files:
# Path: pysecure/adapters/channela.py
# class SshChannel(object):
# def __init__(self, ssh_session, ssh_channel=None):
# self.__ssh_session_int = getattr(ssh_session,
# 'session_id',
# ssh_session)
#
# self.__ssh_channel_int = getattr(ssh_channel,
# 'session_id',
# ssh_channel)
#
# def __enter__(self):
# if self.__ssh_channel_int is None:
# self.__ssh_channel_int = _ssh_channel_new(self.__ssh_session_int)
#
# return self
#
# def __exit__(self, e_type, e_value, e_tb):
# # The documentation says that a "free" implies a "close", and that a
# # "close" implies a "send eof". From a cursory glance, this seems
# # accurate.
# _ssh_channel_free(self.__ssh_channel_int)
# self.__ssh_channel_int = None
#
# def __del__(self):
# # The documentation says that a "free" implies a "close", and that a
# # "close" implies a "send eof". From a cursory glance, this seems
# # accurate.
# if self.__ssh_channel_int is not None:
# _ssh_channel_free(self.__ssh_channel_int)
#
# def open_forward(self, host_remote, port_remote, host_source, port_local):
# _ssh_channel_open_forward(self.__ssh_channel_int,
# host_remote,
# port_remote,
# host_source,
# port_local)
#
# def write(self, data):
# _ssh_channel_write(self.__ssh_channel_int, data)
#
# def read(self, count, is_stderr=False):
# return _ssh_channel_read(self.__ssh_channel_int, count, is_stderr)
#
# def read_nonblocking(self, count, is_stderr=False):
# return _ssh_channel_read_nonblocking(self.__ssh_channel_int,
# count,
# is_stderr)
#
# def send_eof(self):
# _ssh_channel_send_eof(self.__ssh_channel_int)
#
# def is_open(self):
# return _ssh_channel_is_open(self.__ssh_channel_int)
#
# def open_session(self):
# _ssh_channel_open_session(self.__ssh_channel_int)
#
# def request_exec(self, cmd):
# """Execute a command. Note that this can only be done once, and may be
# the only operation performed with the current channel.
# """
#
# return _ssh_channel_request_exec(self.__ssh_channel_int, cmd)
#
# def request_shell(self):
# """Activate shell services on the channel (for PTY emulation)."""
#
# _ssh_channel_request_shell(self.__ssh_channel_int)
#
# def request_pty(self):
# _ssh_channel_request_pty(self.__ssh_channel_int)
#
# def change_pty_size(self, col, row):
# _ssh_channel_change_pty_size(self.__ssh_channel_int, col, row)
#
# def is_eof(self):
# return _ssh_channel_is_eof(self.__ssh_channel_int)
#
# def request_env(self, name, value):
# return _ssh_channel_request_env(self.__ssh_channel_int, name, value)
#
# def accept_x11(self, timeout_ms):
# ssh_x11_channel_int = _ssh_channel_accept_x11(self.__ssh_channel_int,
# timeout_ms)
#
# return SshChannel(self.__ssh_session_int, ssh_x11_channel_int)
#
# def request_x11(screen_number=0, single_connection=False, protocol=None,
# cookie=None):
# return _ssh_channel_request_x11(self.__ssh_channel_int, screen_number,
# single_connection, protocol, cookie)
#
# Path: pysecure/test/test_base.py
# def connect_ssh_test(ssh_cb):
# print("Connecting SSH with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_ssh_with_cb(ssh_cb, user, host, auth_cb, verbosity=verbosity)
, which may contain function names, class names, or code. Output only the next line. | port_local = 1111 |
Next line prediction: <|code_start|>
class ForwardLocalTest(TestCase):
def __ssh_cb(self, ssh):
host_remote = 'localhost'
port_remote = 80
host_source = 'localhost'
port_local = 1111
data = b"GET / HTTP/1.1\nHost: localhost\n\n"
with SshChannel(ssh) as sc:
sc.open_forward(host_remote,
port_remote,
host_source,
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from pysecure.adapters.channela import SshChannel
from pysecure.test.test_base import connect_ssh_test)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/adapters/channela.py
# class SshChannel(object):
# def __init__(self, ssh_session, ssh_channel=None):
# self.__ssh_session_int = getattr(ssh_session,
# 'session_id',
# ssh_session)
#
# self.__ssh_channel_int = getattr(ssh_channel,
# 'session_id',
# ssh_channel)
#
# def __enter__(self):
# if self.__ssh_channel_int is None:
# self.__ssh_channel_int = _ssh_channel_new(self.__ssh_session_int)
#
# return self
#
# def __exit__(self, e_type, e_value, e_tb):
# # The documentation says that a "free" implies a "close", and that a
# # "close" implies a "send eof". From a cursory glance, this seems
# # accurate.
# _ssh_channel_free(self.__ssh_channel_int)
# self.__ssh_channel_int = None
#
# def __del__(self):
# # The documentation says that a "free" implies a "close", and that a
# # "close" implies a "send eof". From a cursory glance, this seems
# # accurate.
# if self.__ssh_channel_int is not None:
# _ssh_channel_free(self.__ssh_channel_int)
#
# def open_forward(self, host_remote, port_remote, host_source, port_local):
# _ssh_channel_open_forward(self.__ssh_channel_int,
# host_remote,
# port_remote,
# host_source,
# port_local)
#
# def write(self, data):
# _ssh_channel_write(self.__ssh_channel_int, data)
#
# def read(self, count, is_stderr=False):
# return _ssh_channel_read(self.__ssh_channel_int, count, is_stderr)
#
# def read_nonblocking(self, count, is_stderr=False):
# return _ssh_channel_read_nonblocking(self.__ssh_channel_int,
# count,
# is_stderr)
#
# def send_eof(self):
# _ssh_channel_send_eof(self.__ssh_channel_int)
#
# def is_open(self):
# return _ssh_channel_is_open(self.__ssh_channel_int)
#
# def open_session(self):
# _ssh_channel_open_session(self.__ssh_channel_int)
#
# def request_exec(self, cmd):
# """Execute a command. Note that this can only be done once, and may be
# the only operation performed with the current channel.
# """
#
# return _ssh_channel_request_exec(self.__ssh_channel_int, cmd)
#
# def request_shell(self):
# """Activate shell services on the channel (for PTY emulation)."""
#
# _ssh_channel_request_shell(self.__ssh_channel_int)
#
# def request_pty(self):
# _ssh_channel_request_pty(self.__ssh_channel_int)
#
# def change_pty_size(self, col, row):
# _ssh_channel_change_pty_size(self.__ssh_channel_int, col, row)
#
# def is_eof(self):
# return _ssh_channel_is_eof(self.__ssh_channel_int)
#
# def request_env(self, name, value):
# return _ssh_channel_request_env(self.__ssh_channel_int, name, value)
#
# def accept_x11(self, timeout_ms):
# ssh_x11_channel_int = _ssh_channel_accept_x11(self.__ssh_channel_int,
# timeout_ms)
#
# return SshChannel(self.__ssh_session_int, ssh_x11_channel_int)
#
# def request_x11(screen_number=0, single_connection=False, protocol=None,
# cookie=None):
# return _ssh_channel_request_x11(self.__ssh_channel_int, screen_number,
# single_connection, protocol, cookie)
#
# Path: pysecure/test/test_base.py
# def connect_ssh_test(ssh_cb):
# print("Connecting SSH with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_ssh_with_cb(ssh_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | port_local) |
Given the code snippet: <|code_start|>
class SftpMirror(object):
def __init__(self, sftp, allow_creates=True, allow_deletes=True,
create_cb=None, delete_cb=None):
self.__sftp_session = sftp
self.__allow_creates = allow_creates
self.__allow_deletes = allow_deletes
<|code_end|>
, generate the next line using the imports in this file:
import logging
from datetime import datetime
from os import mkdir, unlink, symlink
from collections import deque
from shutil import rmtree
from time import mktime
from pysecure.config import MAX_MIRROR_LISTING_CHUNK_SIZE
from pysecure.utility import local_recurse, stringify
from pysecure.exceptions import SftpAlreadyExistsError
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/config.py
# MAX_MIRROR_LISTING_CHUNK_SIZE = 5
#
# Path: pysecure/utility.py
# def local_recurse(path, dir_cb, listing_cb, max_listing_size=0,
# max_depth=None):
#
# def get_flags_from_attr(attr):
# return (stat_is_regular(attr),
# stat_is_symlink(attr),
# stat_is_special(attr))
#
# q = deque([(path, 0)])
# while q:
# (path, current_depth) = q.popleft()
#
# entries = listdir(path)
# collected = []
#
# def push_entry(entry):
# collected.append(entry)
# if max_listing_size > 0 and \
# max_listing_size <= len(collected):
# listing_cb(path, collected)
# del collected[:]
#
# def push_entry_with_filepath(file_path, name, is_link):
# attr = lstat(file_path) if is_link else stat(file_path)
# entry = (name,
# int(attr.st_mtime),
# attr.st_size,
# get_flags_from_attr(attr))
#
# push_entry(entry)
#
# for name in entries:
# file_path = ('%s/%s' % (path, name))
# # print("ENTRY: %s" % (file_path))
#
# if islink(file_path):
# if listing_cb is not None:
# push_entry_with_filepath(file_path, name, True)
# elif isdir(file_path):
# if name == '.' or name == '..':
# continue
#
# if dir_cb is not None:
# dir_cb(path, file_path, name)
#
# new_depth = current_depth + 1
#
# if max_depth is not None and max_depth >= new_depth:
# q.append((file_path, new_depth))
# elif isfile(file_path):
# if listing_cb is not None:
# push_entry_with_filepath(file_path, name, False)
#
# if listing_cb is not None and max_listing_size == 0 or \
# len(collected) > 0:
# listing_cb(path, collected)
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/exceptions.py
# class SftpAlreadyExistsError(SftpError):
# pass
. Output only the next line. | self.__create_cb = create_cb |
Given the code snippet: <|code_start|>
class SftpMirror(object):
def __init__(self, sftp, allow_creates=True, allow_deletes=True,
create_cb=None, delete_cb=None):
self.__sftp_session = sftp
self.__allow_creates = allow_creates
self.__allow_deletes = allow_deletes
<|code_end|>
, generate the next line using the imports in this file:
import logging
from datetime import datetime
from os import mkdir, unlink, symlink
from collections import deque
from shutil import rmtree
from time import mktime
from pysecure.config import MAX_MIRROR_LISTING_CHUNK_SIZE
from pysecure.utility import local_recurse, stringify
from pysecure.exceptions import SftpAlreadyExistsError
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/config.py
# MAX_MIRROR_LISTING_CHUNK_SIZE = 5
#
# Path: pysecure/utility.py
# def local_recurse(path, dir_cb, listing_cb, max_listing_size=0,
# max_depth=None):
#
# def get_flags_from_attr(attr):
# return (stat_is_regular(attr),
# stat_is_symlink(attr),
# stat_is_special(attr))
#
# q = deque([(path, 0)])
# while q:
# (path, current_depth) = q.popleft()
#
# entries = listdir(path)
# collected = []
#
# def push_entry(entry):
# collected.append(entry)
# if max_listing_size > 0 and \
# max_listing_size <= len(collected):
# listing_cb(path, collected)
# del collected[:]
#
# def push_entry_with_filepath(file_path, name, is_link):
# attr = lstat(file_path) if is_link else stat(file_path)
# entry = (name,
# int(attr.st_mtime),
# attr.st_size,
# get_flags_from_attr(attr))
#
# push_entry(entry)
#
# for name in entries:
# file_path = ('%s/%s' % (path, name))
# # print("ENTRY: %s" % (file_path))
#
# if islink(file_path):
# if listing_cb is not None:
# push_entry_with_filepath(file_path, name, True)
# elif isdir(file_path):
# if name == '.' or name == '..':
# continue
#
# if dir_cb is not None:
# dir_cb(path, file_path, name)
#
# new_depth = current_depth + 1
#
# if max_depth is not None and max_depth >= new_depth:
# q.append((file_path, new_depth))
# elif isfile(file_path):
# if listing_cb is not None:
# push_entry_with_filepath(file_path, name, False)
#
# if listing_cb is not None and max_listing_size == 0 or \
# len(collected) > 0:
# listing_cb(path, collected)
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/exceptions.py
# class SftpAlreadyExistsError(SftpError):
# pass
. Output only the next line. | self.__create_cb = create_cb |
Based on the snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.insert(0, '..')
def _configure_logging():
_FMT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
_FORMATTER = logging.Formatter(_FMT)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setFormatter(_FORMATTER)
logger.addHandler(ch)
_configure_logging()
user = 'dustin'
host = 'localhost'
key_filepath = '/Users/dustin/.ssh/id_dsa'
auth_cb = get_key_auth_cb(key_filepath)
# Or, for SFTP-enabled SSH functionality.
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import logging
from pysecure.adapters.sftpa import SftpFile
from pysecure.easy import connect_sftp_with_cb, get_key_auth_cb
and context (classes, functions, sometimes code) from other files:
# Path: pysecure/adapters/sftpa.py
# class SftpFile(object):
# def __init__(self, sftp_session, filepath, access_type_om='r',
# create_mode=DEFAULT_CREATE_MODE):
#
# at_im = self.__at_om_to_im(access_type_om)
#
# self.__sftp_session_int = getattr(sftp_session,
# 'session_id',
# sftp_session)
#
# self.__filepath = filepath
# self.__access_type = at_im
# self.__create_mode = create_mode
#
# def __repr__(self):
# return ('<SFTP_FILE [%s] \"%s\">' %
# (self.__access_type[0], self.__filepath))
#
# def __at_om_to_im(self, om):
# """Convert an "outer" access mode to an "inner" access mode.
# Returns a tuple of:
#
# (<system access mode>, <is append>, <is universal newlines>).
# """
#
# original_om = om
#
# if om[0] == 'U':
# om = om[1:]
# is_um = True
# else:
# is_um = False
#
# if om == 'r':
# return (original_om, O_RDONLY, False, is_um)
# elif om == 'w':
# return (original_om, O_WRONLY | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a':
# return (original_om, O_WRONLY | O_CREAT, False, is_um)
# elif om == 'r+':
# return (original_om, O_RDWR | O_CREAT, False, is_um)
# elif om == 'w+':
# return (original_om, O_RDWR | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a+':
# return (original_om, O_RDWR | O_CREAT, True, is_um)
# else:
# raise Exception("Outer access mode [%s] is invalid." %
# (original_om))
#
# def __enter__(self):
# return self.open()
#
# def open(self):
# """This is the only way to open a file resource."""
#
# self.__sf = _sftp_open(self.__sftp_session_int,
# self.__filepath,
# self.access_type_int,
# self.__create_mode)
#
# if self.access_type_is_append is True:
# self.seek(self.filesize)
#
# return SftpFileObject(self)
#
# def __exit__(self, e_type, e_value, e_tb):
# self.close()
#
# def close(self):
# _sftp_close(self.__sf)
#
# def write(self, buffer_):
# return _sftp_write(self.__sf, buffer_)
#
# def seek(self, position):
# return _sftp_seek(self.__sf, position)
#
# def read(self, size):
# """Read a length of bytes. Return empty on EOF."""
#
# return _sftp_read(self.__sf, size)
#
# def fstat(self):
# return _sftp_fstat(self.__sf)
#
# def rewind(self):
# return _sftp_rewind(self.__sf)
#
# @property
# def sf(self):
# return self.__sf
#
# @property
# def position(self):
# return _sftp_tell(self.__sf)
#
# @property
# def filesize(self):
# return self.fstat().size
#
# @property
# def filepath(self):
# return self.__filepath
#
# @property
# def access_type_str(self):
# return self.__access_type[0]
#
# @property
# def access_type_int(self):
# return self.__access_type[1]
#
# @property
# def access_type_is_append(self):
# return self.__access_type[2]
#
# @property
# def access_type_has_universal_nl(self):
# return self.__access_type[3]
#
# Path: pysecure/easy.py
# def connect_sftp_with_cb(sftp_cb, *args, **kwargs):
# """A "managed" SFTP session. When the SSH session and an additional SFTP
# session are ready, invoke the sftp_cb callback.
# """
#
# with _connect_sftp(*args, **kwargs) as (ssh, sftp):
# sftp_cb(ssh, sftp)
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
. Output only the next line. | def sftp_cb(ssh, sftp): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.insert(0, '..')
def _configure_logging():
_FMT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
_FORMATTER = logging.Formatter(_FMT)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setFormatter(_FORMATTER)
<|code_end|>
using the current file's imports:
import sys
import logging
from pysecure.adapters.sftpa import SftpFile
from pysecure.easy import connect_sftp_with_cb, get_key_auth_cb
and any relevant context from other files:
# Path: pysecure/adapters/sftpa.py
# class SftpFile(object):
# def __init__(self, sftp_session, filepath, access_type_om='r',
# create_mode=DEFAULT_CREATE_MODE):
#
# at_im = self.__at_om_to_im(access_type_om)
#
# self.__sftp_session_int = getattr(sftp_session,
# 'session_id',
# sftp_session)
#
# self.__filepath = filepath
# self.__access_type = at_im
# self.__create_mode = create_mode
#
# def __repr__(self):
# return ('<SFTP_FILE [%s] \"%s\">' %
# (self.__access_type[0], self.__filepath))
#
# def __at_om_to_im(self, om):
# """Convert an "outer" access mode to an "inner" access mode.
# Returns a tuple of:
#
# (<system access mode>, <is append>, <is universal newlines>).
# """
#
# original_om = om
#
# if om[0] == 'U':
# om = om[1:]
# is_um = True
# else:
# is_um = False
#
# if om == 'r':
# return (original_om, O_RDONLY, False, is_um)
# elif om == 'w':
# return (original_om, O_WRONLY | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a':
# return (original_om, O_WRONLY | O_CREAT, False, is_um)
# elif om == 'r+':
# return (original_om, O_RDWR | O_CREAT, False, is_um)
# elif om == 'w+':
# return (original_om, O_RDWR | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a+':
# return (original_om, O_RDWR | O_CREAT, True, is_um)
# else:
# raise Exception("Outer access mode [%s] is invalid." %
# (original_om))
#
# def __enter__(self):
# return self.open()
#
# def open(self):
# """This is the only way to open a file resource."""
#
# self.__sf = _sftp_open(self.__sftp_session_int,
# self.__filepath,
# self.access_type_int,
# self.__create_mode)
#
# if self.access_type_is_append is True:
# self.seek(self.filesize)
#
# return SftpFileObject(self)
#
# def __exit__(self, e_type, e_value, e_tb):
# self.close()
#
# def close(self):
# _sftp_close(self.__sf)
#
# def write(self, buffer_):
# return _sftp_write(self.__sf, buffer_)
#
# def seek(self, position):
# return _sftp_seek(self.__sf, position)
#
# def read(self, size):
# """Read a length of bytes. Return empty on EOF."""
#
# return _sftp_read(self.__sf, size)
#
# def fstat(self):
# return _sftp_fstat(self.__sf)
#
# def rewind(self):
# return _sftp_rewind(self.__sf)
#
# @property
# def sf(self):
# return self.__sf
#
# @property
# def position(self):
# return _sftp_tell(self.__sf)
#
# @property
# def filesize(self):
# return self.fstat().size
#
# @property
# def filepath(self):
# return self.__filepath
#
# @property
# def access_type_str(self):
# return self.__access_type[0]
#
# @property
# def access_type_int(self):
# return self.__access_type[1]
#
# @property
# def access_type_is_append(self):
# return self.__access_type[2]
#
# @property
# def access_type_has_universal_nl(self):
# return self.__access_type[3]
#
# Path: pysecure/easy.py
# def connect_sftp_with_cb(sftp_cb, *args, **kwargs):
# """A "managed" SFTP session. When the SSH session and an additional SFTP
# session are ready, invoke the sftp_cb callback.
# """
#
# with _connect_sftp(*args, **kwargs) as (ssh, sftp):
# sftp_cb(ssh, sftp)
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
. Output only the next line. | logger.addHandler(ch) |
Next line prediction: <|code_start|>
def connect_sftp_test(sftp_cb):
print("Connecting SFTP with key: %s" % (key_filepath))
auth_cb = get_key_auth_cb(key_filepath)
connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
<|code_end|>
. Use current file imports:
(from pysecure import log_config
from pysecure.easy import connect_ssh_with_cb, connect_sftp_with_cb, \
get_key_auth_cb, get_password_auth_cb
from pysecure.test.test_config import user, host, key_filepath, verbosity)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/log_config.py
#
# Path: pysecure/easy.py
# def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True,
# verbosity=0):
# """A "managed" SSH session. When the session is ready, we'll invoke the
# "ssh_cb" callback.
# """
#
# with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
# ssh_cb(ssh)
#
# def connect_sftp_with_cb(sftp_cb, *args, **kwargs):
# """A "managed" SFTP session. When the SSH session and an additional SFTP
# session are ready, invoke the sftp_cb callback.
# """
#
# with _connect_sftp(*args, **kwargs) as (ssh, sftp):
# sftp_cb(ssh, sftp)
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# def get_password_auth_cb(password):
# """This is just a convenience function for password-based login."""
#
# def auth_cb(ssh):
# ssh.userauth_password(password)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
. Output only the next line. | def connect_ssh_test(ssh_cb): |
Next line prediction: <|code_start|>
def connect_sftp_test(sftp_cb):
print("Connecting SFTP with key: %s" % (key_filepath))
auth_cb = get_key_auth_cb(key_filepath)
connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
<|code_end|>
. Use current file imports:
(from pysecure import log_config
from pysecure.easy import connect_ssh_with_cb, connect_sftp_with_cb, \
get_key_auth_cb, get_password_auth_cb
from pysecure.test.test_config import user, host, key_filepath, verbosity)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/log_config.py
#
# Path: pysecure/easy.py
# def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True,
# verbosity=0):
# """A "managed" SSH session. When the session is ready, we'll invoke the
# "ssh_cb" callback.
# """
#
# with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
# ssh_cb(ssh)
#
# def connect_sftp_with_cb(sftp_cb, *args, **kwargs):
# """A "managed" SFTP session. When the SSH session and an additional SFTP
# session are ready, invoke the sftp_cb callback.
# """
#
# with _connect_sftp(*args, **kwargs) as (ssh, sftp):
# sftp_cb(ssh, sftp)
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# def get_password_auth_cb(password):
# """This is just a convenience function for password-based login."""
#
# def auth_cb(ssh):
# ssh.userauth_password(password)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
. Output only the next line. | def connect_ssh_test(ssh_cb): |
Using the snippet: <|code_start|>
def connect_sftp_test(sftp_cb):
print("Connecting SFTP with key: %s" % (key_filepath))
auth_cb = get_key_auth_cb(key_filepath)
connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
<|code_end|>
, determine the next line of code. You have imports:
from pysecure import log_config
from pysecure.easy import connect_ssh_with_cb, connect_sftp_with_cb, \
get_key_auth_cb, get_password_auth_cb
from pysecure.test.test_config import user, host, key_filepath, verbosity
and context (class names, function names, or code) available:
# Path: pysecure/log_config.py
#
# Path: pysecure/easy.py
# def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True,
# verbosity=0):
# """A "managed" SSH session. When the session is ready, we'll invoke the
# "ssh_cb" callback.
# """
#
# with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
# ssh_cb(ssh)
#
# def connect_sftp_with_cb(sftp_cb, *args, **kwargs):
# """A "managed" SFTP session. When the SSH session and an additional SFTP
# session are ready, invoke the sftp_cb callback.
# """
#
# with _connect_sftp(*args, **kwargs) as (ssh, sftp):
# sftp_cb(ssh, sftp)
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# def get_password_auth_cb(password):
# """This is just a convenience function for password-based login."""
#
# def auth_cb(ssh):
# ssh.userauth_password(password)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
. Output only the next line. | def connect_ssh_test(ssh_cb): |
Continue the code snippet: <|code_start|>
class DirManipTest(TestCase):
def __sftp_cb(self, ssh, sftp):
# print("Creating directory.")
sftp.mkdir("xyz")
# print("Removing directory.")
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pysecure.test.test_base import connect_sftp_test
and context (classes, functions, or code) from other files:
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | sftp.rmdir("xyz") |
Given the code snippet: <|code_start|>
def dumphex(data):
data_len = len(data)
row_size = 16
i = 0
while i < data_len:
stdout.write('%05X:' % (i))
# Display bytes as hex.
j = 0
while j < row_size:
<|code_end|>
, generate the next line using the imports in this file:
from sys import stdout
from collections import deque
from os import listdir, stat, lstat
from os.path import basename, isfile, isdir, islink
from stat import S_ISCHR, S_ISBLK, S_ISREG, S_ISLNK
from os import SEEK_SET, SEEK_CUR, SEEK_END
from pysecure.exceptions import SshNonblockingTryAgainException
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/exceptions.py
# class SshNonblockingTryAgainException(SshException):
# pass
. Output only the next line. | index = i + j |
Continue the code snippet: <|code_start|>
class TextIterateTest(TestCase):
def __sftp_cb(self, ssh, sftp):
with SftpFile(sftp, 'test_doc_rfc1958.txt') as sf:
i = 0
for data in sf:
# stdout.write("> " + data)
if i >= 30:
<|code_end|>
. Use current file imports:
from unittest import TestCase
from sys import stdout
from pysecure.adapters.sftpa import SftpFile
from pysecure.test.test_base import connect_sftp_test
and context (classes, functions, or code) from other files:
# Path: pysecure/adapters/sftpa.py
# class SftpFile(object):
# def __init__(self, sftp_session, filepath, access_type_om='r',
# create_mode=DEFAULT_CREATE_MODE):
#
# at_im = self.__at_om_to_im(access_type_om)
#
# self.__sftp_session_int = getattr(sftp_session,
# 'session_id',
# sftp_session)
#
# self.__filepath = filepath
# self.__access_type = at_im
# self.__create_mode = create_mode
#
# def __repr__(self):
# return ('<SFTP_FILE [%s] \"%s\">' %
# (self.__access_type[0], self.__filepath))
#
# def __at_om_to_im(self, om):
# """Convert an "outer" access mode to an "inner" access mode.
# Returns a tuple of:
#
# (<system access mode>, <is append>, <is universal newlines>).
# """
#
# original_om = om
#
# if om[0] == 'U':
# om = om[1:]
# is_um = True
# else:
# is_um = False
#
# if om == 'r':
# return (original_om, O_RDONLY, False, is_um)
# elif om == 'w':
# return (original_om, O_WRONLY | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a':
# return (original_om, O_WRONLY | O_CREAT, False, is_um)
# elif om == 'r+':
# return (original_om, O_RDWR | O_CREAT, False, is_um)
# elif om == 'w+':
# return (original_om, O_RDWR | O_CREAT | O_TRUNC, False, is_um)
# elif om == 'a+':
# return (original_om, O_RDWR | O_CREAT, True, is_um)
# else:
# raise Exception("Outer access mode [%s] is invalid." %
# (original_om))
#
# def __enter__(self):
# return self.open()
#
# def open(self):
# """This is the only way to open a file resource."""
#
# self.__sf = _sftp_open(self.__sftp_session_int,
# self.__filepath,
# self.access_type_int,
# self.__create_mode)
#
# if self.access_type_is_append is True:
# self.seek(self.filesize)
#
# return SftpFileObject(self)
#
# def __exit__(self, e_type, e_value, e_tb):
# self.close()
#
# def close(self):
# _sftp_close(self.__sf)
#
# def write(self, buffer_):
# return _sftp_write(self.__sf, buffer_)
#
# def seek(self, position):
# return _sftp_seek(self.__sf, position)
#
# def read(self, size):
# """Read a length of bytes. Return empty on EOF."""
#
# return _sftp_read(self.__sf, size)
#
# def fstat(self):
# return _sftp_fstat(self.__sf)
#
# def rewind(self):
# return _sftp_rewind(self.__sf)
#
# @property
# def sf(self):
# return self.__sf
#
# @property
# def position(self):
# return _sftp_tell(self.__sf)
#
# @property
# def filesize(self):
# return self.fstat().size
#
# @property
# def filepath(self):
# return self.__filepath
#
# @property
# def access_type_str(self):
# return self.__access_type[0]
#
# @property
# def access_type_int(self):
# return self.__access_type[1]
#
# @property
# def access_type_is_append(self):
# return self.__access_type[2]
#
# @property
# def access_type_has_universal_nl(self):
# return self.__access_type[3]
#
# Path: pysecure/test/test_base.py
# def connect_sftp_test(sftp_cb):
# print("Connecting SFTP with key: %s" % (key_filepath))
# auth_cb = get_key_auth_cb(key_filepath)
# connect_sftp_with_cb(sftp_cb, user, host, auth_cb, verbosity=verbosity)
. Output only the next line. | break |
Here is a snippet: <|code_start|>
# Auxiliary calls.
c_strerror = libssh.strerror
c_free = libssh.free
# Function calls.
# LIBSSH_API ssh_session ssh_new(void);
c_ssh_new = libssh.ssh_new
c_ssh_new.argtypes = []
c_ssh_new.restype = c_ssh_session
# LIBSSH_API int ssh_options_set(ssh_session session, enum ssh_options_e type, const void *value);
c_ssh_options_set = libssh.ssh_options_set
c_ssh_options_set.argtypes = [c_ssh_session, c_int, c_void_p]
c_ssh_options_set.restype = c_int
# LIBSSH_API void ssh_free(ssh_session session);
c_ssh_free = libssh.ssh_free
c_ssh_free.argtypes = [c_ssh_session]
c_ssh_free.restype = None
# LIBSSH_API int ssh_connect(ssh_session session);
c_ssh_connect = libssh.ssh_connect
c_ssh_connect.argtypes = [c_ssh_session]
c_ssh_connect.restype = c_int
# LIBSSH_API void ssh_disconnect(ssh_session session);
c_ssh_disconnect = libssh.ssh_disconnect
<|code_end|>
. Write the next line using the current file imports:
from ctypes import *
from pysecure.library import libssh
from pysecure.types import *
and context from other files:
# Path: pysecure/library.py
# _LIBSSH_FILEPATH = os.environ.get('PS_LIBRARY_FILEPATH', '')
# _LIBSSH_FILEPATH = find_library('libssh')
# _LIBSSH_FILEPATH = 'libssh.so'
, which may include functions, classes, or code. Output only the next line. | c_ssh_disconnect.argtypes = [c_ssh_session] |
Continue the code snippet: <|code_start|>
class SftpNoCbTest(TestCase):
def __init__(self, *args, **kwargs):
super(SftpNoCbTest, self).__init__(*args, **kwargs)
self.__log = logging.getLogger('SftpNoCb')
def setUp(self):
auth_cb = get_key_auth_cb(key_filepath)
self.__easy = EasySsh(user, host, auth_cb)
self.__easy.open_ssh()
self.__easy.open_sftp()
def tearDown(self):
self.__easy.close_sftp()
<|code_end|>
. Use current file imports:
import logging
import pysecure.log_config
from unittest import TestCase
from pysecure.easy import EasySsh, get_key_auth_cb
from pysecure.test.test_config import user, host, key_filepath
and context (classes, functions, or code) from other files:
# Path: pysecure/easy.py
# class EasySsh(object):
# """This class allows a connection to be opened and closed at two separate
# points (as opposed to the callback methods, above).
# """
#
# def __init__(self, user, host, auth_cb, allow_new=True, **session_args):
# self.__user = user
# self.__host = host
# self.__auth_cb = auth_cb
# self.__allow_new = allow_new
# self.__session_args = session_args
#
# self.__log = logging.getLogger('EasySsh')
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# def __del__(self):
# if self.__ssh_opened is True:
# self.close_ssh()
#
# def open_ssh(self):
# self.__log.debug("Opening SSH.")
#
# if self.__ssh_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# # TODO: This might be required to only be run once, globally.
# self.__system = SshSystem()
# self.__system.open()
#
# self.__ssh_session = SshSession(user=self.__user, host=self.__host,
# **self.__session_args)
# self.__ssh_session.open()
#
# self.__connect = SshConnect(self.__ssh_session)
# self.__connect.open()
#
# self.__ssh_session.is_server_known(allow_new=self.__allow_new)
# self.__auth_cb(self.__ssh_session)
#
# self.__ssh_opened = True
#
# def close_ssh(self):
# self.__log.debug("Closing SSH.")
#
# if self.__ssh_opened is False:
# raise Exception("Can not close SSH session that is not currently "
# "opened.")
#
# if self.__sftp_opened is True:
# self.close_sftp()
#
# self.__connect.close()
# self.__ssh_session.close()
# self.__system.close()
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# def open_sftp(self):
# self.__log.debug("Opening SFTP.")
#
# if self.__sftp_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# self.__sftp_session = SftpSession(self.__ssh_session)
# self.__sftp_session.open()
#
# self.__sftp_opened = True
#
# def close_sftp(self):
# self.__log.debug("Closing SFTP.")
#
# if self.__sftp_opened is False:
# raise Exception("Can not close SFTP session that is not currently "
# "opened.")
#
# self.__sftp_session.close()
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# @property
# def ssh(self):
# if self.__ssh_opened is False:
# raise Exception("Can not return an SSH session. A session is not "
# "open.")
#
# return self.__ssh_session
#
# @property
# def sftp(self):
# if self.__sftp_opened is False:
# raise Exception("Can not return an SFTP session. A session is not "
# "open.")
#
# return self.__sftp_session
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
. Output only the next line. | self.__easy.close_ssh() |
Given snippet: <|code_start|>
class SftpNoCbTest(TestCase):
def __init__(self, *args, **kwargs):
super(SftpNoCbTest, self).__init__(*args, **kwargs)
self.__log = logging.getLogger('SftpNoCb')
def setUp(self):
auth_cb = get_key_auth_cb(key_filepath)
self.__easy = EasySsh(user, host, auth_cb)
self.__easy.open_ssh()
self.__easy.open_sftp()
def tearDown(self):
self.__easy.close_sftp()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import pysecure.log_config
from unittest import TestCase
from pysecure.easy import EasySsh, get_key_auth_cb
from pysecure.test.test_config import user, host, key_filepath
and context:
# Path: pysecure/easy.py
# class EasySsh(object):
# """This class allows a connection to be opened and closed at two separate
# points (as opposed to the callback methods, above).
# """
#
# def __init__(self, user, host, auth_cb, allow_new=True, **session_args):
# self.__user = user
# self.__host = host
# self.__auth_cb = auth_cb
# self.__allow_new = allow_new
# self.__session_args = session_args
#
# self.__log = logging.getLogger('EasySsh')
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# def __del__(self):
# if self.__ssh_opened is True:
# self.close_ssh()
#
# def open_ssh(self):
# self.__log.debug("Opening SSH.")
#
# if self.__ssh_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# # TODO: This might be required to only be run once, globally.
# self.__system = SshSystem()
# self.__system.open()
#
# self.__ssh_session = SshSession(user=self.__user, host=self.__host,
# **self.__session_args)
# self.__ssh_session.open()
#
# self.__connect = SshConnect(self.__ssh_session)
# self.__connect.open()
#
# self.__ssh_session.is_server_known(allow_new=self.__allow_new)
# self.__auth_cb(self.__ssh_session)
#
# self.__ssh_opened = True
#
# def close_ssh(self):
# self.__log.debug("Closing SSH.")
#
# if self.__ssh_opened is False:
# raise Exception("Can not close SSH session that is not currently "
# "opened.")
#
# if self.__sftp_opened is True:
# self.close_sftp()
#
# self.__connect.close()
# self.__ssh_session.close()
# self.__system.close()
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# def open_sftp(self):
# self.__log.debug("Opening SFTP.")
#
# if self.__sftp_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# self.__sftp_session = SftpSession(self.__ssh_session)
# self.__sftp_session.open()
#
# self.__sftp_opened = True
#
# def close_sftp(self):
# self.__log.debug("Closing SFTP.")
#
# if self.__sftp_opened is False:
# raise Exception("Can not close SFTP session that is not currently "
# "opened.")
#
# self.__sftp_session.close()
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# @property
# def ssh(self):
# if self.__ssh_opened is False:
# raise Exception("Can not return an SSH session. A session is not "
# "open.")
#
# return self.__ssh_session
#
# @property
# def sftp(self):
# if self.__sftp_opened is False:
# raise Exception("Can not return an SFTP session. A session is not "
# "open.")
#
# return self.__sftp_session
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
which might include code, classes, or functions. Output only the next line. | self.__easy.close_ssh() |
Continue the code snippet: <|code_start|>
class SftpNoCbTest(TestCase):
def __init__(self, *args, **kwargs):
super(SftpNoCbTest, self).__init__(*args, **kwargs)
self.__log = logging.getLogger('SftpNoCb')
def setUp(self):
auth_cb = get_key_auth_cb(key_filepath)
self.__easy = EasySsh(user, host, auth_cb)
self.__easy.open_ssh()
self.__easy.open_sftp()
def tearDown(self):
<|code_end|>
. Use current file imports:
import logging
import pysecure.log_config
from unittest import TestCase
from pysecure.easy import EasySsh, get_key_auth_cb
from pysecure.test.test_config import user, host, key_filepath
and context (classes, functions, or code) from other files:
# Path: pysecure/easy.py
# class EasySsh(object):
# """This class allows a connection to be opened and closed at two separate
# points (as opposed to the callback methods, above).
# """
#
# def __init__(self, user, host, auth_cb, allow_new=True, **session_args):
# self.__user = user
# self.__host = host
# self.__auth_cb = auth_cb
# self.__allow_new = allow_new
# self.__session_args = session_args
#
# self.__log = logging.getLogger('EasySsh')
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# def __del__(self):
# if self.__ssh_opened is True:
# self.close_ssh()
#
# def open_ssh(self):
# self.__log.debug("Opening SSH.")
#
# if self.__ssh_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# # TODO: This might be required to only be run once, globally.
# self.__system = SshSystem()
# self.__system.open()
#
# self.__ssh_session = SshSession(user=self.__user, host=self.__host,
# **self.__session_args)
# self.__ssh_session.open()
#
# self.__connect = SshConnect(self.__ssh_session)
# self.__connect.open()
#
# self.__ssh_session.is_server_known(allow_new=self.__allow_new)
# self.__auth_cb(self.__ssh_session)
#
# self.__ssh_opened = True
#
# def close_ssh(self):
# self.__log.debug("Closing SSH.")
#
# if self.__ssh_opened is False:
# raise Exception("Can not close SSH session that is not currently "
# "opened.")
#
# if self.__sftp_opened is True:
# self.close_sftp()
#
# self.__connect.close()
# self.__ssh_session.close()
# self.__system.close()
#
# self.__ssh_session = None
# self.__ssh_opened = False
#
# def open_sftp(self):
# self.__log.debug("Opening SFTP.")
#
# if self.__sftp_opened is True:
# raise Exception("Can not open SFTP session that is already open.")
#
# self.__sftp_session = SftpSession(self.__ssh_session)
# self.__sftp_session.open()
#
# self.__sftp_opened = True
#
# def close_sftp(self):
# self.__log.debug("Closing SFTP.")
#
# if self.__sftp_opened is False:
# raise Exception("Can not close SFTP session that is not currently "
# "opened.")
#
# self.__sftp_session.close()
#
# self.__sftp_session = None
# self.__sftp_opened = False
#
# @property
# def ssh(self):
# if self.__ssh_opened is False:
# raise Exception("Can not return an SSH session. A session is not "
# "open.")
#
# return self.__ssh_session
#
# @property
# def sftp(self):
# if self.__sftp_opened is False:
# raise Exception("Can not return an SFTP session. A session is not "
# "open.")
#
# return self.__sftp_session
#
# def get_key_auth_cb(key_filepath):
# """This is just a convenience function for key-based login."""
#
# def auth_cb(ssh):
# key = ssh_pki_import_privkey_file(key_filepath)
# ssh.userauth_publickey(key)
#
# return auth_cb
#
# Path: pysecure/test/test_config.py
. Output only the next line. | self.__easy.close_sftp() |
Given the code snippet: <|code_start|> raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
<|code_end|>
, generate the next line using the imports in this file:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Continue the code snippet: <|code_start|>
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
<|code_end|>
. Use current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (classes, functions, or code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | data_len = len(data) |
Here is a snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
<|code_end|>
. Write the next line using the current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may include functions, classes, or code. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Next line prediction: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | c_int(port_remote), |
Next line prediction: <|code_start|> logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | def _ssh_channel_write(ssh_channel_int, data): |
Here is a snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
<|code_end|>
. Write the next line using the current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may include functions, classes, or code. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Based on the snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (classes, functions, sometimes code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Predict the next line for this snippet: <|code_start|>def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Channel write failed: %s" % (error))
<|code_end|>
with the help of current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may contain function names, class names, or code. Output only the next line. | elif sent_bytes != data_len: |
Given the code snippet: <|code_start|>
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Channel write failed: %s" % (error))
elif sent_bytes != data_len:
raise SshError("Channel write of (%d) bytes failed for length (%d) of "
"written data." % (data_len, sent_bytes))
<|code_end|>
, generate the next line using the imports in this file:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | def _ssh_channel_read(ssh_channel_int, count, is_stderr): |
Given the following code snippet before the placeholder: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
<|code_end|>
, predict the next line using imports from the current file:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context including class names, function names, and sometimes code from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Predict the next line for this snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
<|code_end|>
with the help of current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may contain function names, class names, or code. Output only the next line. | c_int(port_local)) |
Here is a snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
<|code_end|>
. Write the next line using the current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may include functions, classes, or code. Output only the next line. | def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote, |
Using the snippet: <|code_start|> raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
<|code_end|>
, determine the next line of code. You have imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (class names, function names, or code) available:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Given snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
which might include code, classes, or functions. Output only the next line. | def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote, |
Here is a snippet: <|code_start|>
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Channel write failed: %s" % (error))
elif sent_bytes != data_len:
raise SshError("Channel write of (%d) bytes failed for length (%d) of "
<|code_end|>
. Write the next line using the current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may include functions, classes, or code. Output only the next line. | "written data." % (data_len, sent_bytes)) |
Given snippet: <|code_start|> raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
which might include code, classes, or functions. Output only the next line. | ssh_session_int = _ssh_channel_get_session(ssh_channel_int) |
Next line prediction: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | logging.debug("Requesting forward on channel.") |
Given snippet: <|code_start|>def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Channel write failed: %s" % (error))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
which might include code, classes, or functions. Output only the next line. | elif sent_bytes != data_len: |
Next line prediction: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | if result is None: |
Given snippet: <|code_start|>
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
which might include code, classes, or functions. Output only the next line. | data_len = len(data) |
Given the following code snippet before the placeholder: <|code_start|>def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
c_uint32(data_len))
if sent_bytes == SSH_ERROR:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Channel write failed: %s" % (error))
<|code_end|>
, predict the next line using imports from the current file:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context including class names, function names, and sometimes code from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | elif sent_bytes != data_len: |
Continue the code snippet: <|code_start|> ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
host_source, port_local):
logging.debug("Requesting forward on channel.")
result = c_ssh_channel_open_forward(ssh_channel_int,
c_char_p(bytify(host_remote)),
c_int(port_remote),
c_char_p(bytify(host_source)),
c_int(port_local))
if result == SSH_AGAIN:
raise SshNonblockingTryAgainException()
elif result != SSH_OK:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Forward failed: %s" % (error))
def _ssh_channel_write(ssh_channel_int, data):
data_len = len(data)
sent_bytes = c_ssh_channel_write(ssh_channel_int,
cast(c_char_p(data), c_void_p),
<|code_end|>
. Use current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (classes, functions, or code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | c_uint32(data_len)) |
Given the code snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
<|code_end|>
, generate the next line using the imports in this file:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context (functions, classes, or occasionally code) from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | return result |
Next line prediction: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
return result
def _ssh_channel_open_forward(ssh_channel_int, host_remote, port_remote,
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | host_source, port_local): |
Next line prediction: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
<|code_end|>
. Use current file imports:
(import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code)
and context including class names, function names, or small code snippets from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
. Output only the next line. | return result |
Predict the next line for this snippet: <|code_start|>
def _ssh_channel_new(ssh_session_int):
logging.debug("Opening channel on session.")
result = c_ssh_channel_new(ssh_session_int)
if result is None:
ssh_session_int = _ssh_channel_get_session(ssh_channel_int)
error = ssh_get_error(ssh_session_int)
raise SshError("Could not open channel: %s" % (error))
<|code_end|>
with the help of current file imports:
import logging
from ctypes import c_char_p, c_void_p, cast, c_uint32, c_int, \
create_string_buffer
from time import time
from pysecure.config import NONBLOCK_READ_TIMEOUT_MS, \
DEFAULT_SHELL_READ_BLOCK_SIZE
from pysecure.constants.ssh import SSH_OK, SSH_ERROR, SSH_AGAIN
from pysecure.exceptions import SshError, SshNonblockingTryAgainException, \
SshNoDataReceivedException, SshTimeoutException
from pysecure.utility import sync, bytify, stringify
from pysecure.calls.channeli import c_ssh_channel_new, \
c_ssh_channel_open_forward, \
c_ssh_channel_write, c_ssh_channel_free, \
c_ssh_channel_read, \
c_ssh_channel_send_eof, \
c_ssh_channel_is_open, \
c_ssh_channel_open_session, \
c_ssh_channel_request_exec, \
c_ssh_channel_request_shell, \
c_ssh_channel_request_pty, \
c_ssh_channel_change_pty_size, \
c_ssh_channel_is_eof, \
c_ssh_channel_read_nonblocking, \
c_ssh_channel_request_env, \
c_ssh_channel_get_session, \
c_ssh_channel_accept_x11, \
c_ssh_channel_request_x11
from pysecure.error import ssh_get_error, ssh_get_error_code
and context from other files:
# Path: pysecure/config.py
# NONBLOCK_READ_TIMEOUT_MS = 1500
#
# DEFAULT_SHELL_READ_BLOCK_SIZE = 1024
#
# Path: pysecure/constants/ssh.py
# SSH_OK = 0
#
# SSH_ERROR = -1
#
# SSH_AGAIN = -2
#
# Path: pysecure/exceptions.py
# class SshError(SshException):
# pass
#
# class SshNonblockingTryAgainException(SshException):
# pass
#
# class SshNoDataReceivedException(SshException):
# pass
#
# class SshTimeoutException(SshException):
# pass
#
# Path: pysecure/utility.py
# def sync(cb):
# """A function that will repeatedly invoke a callback until it doesn't
# return a try-again error.
# """
#
# while 1:
# try:
# cb()
# except SshNonblockingTryAgainException:
# pass
# else:
# break
#
# def bytify(s):
# if issubclass(s.__class__, str):
# return s.encode('ascii')
# else:
# return s
#
# def stringify(s):
# if issubclass(s.__class__, (bytes, bytearray)):
# return s.decode('ascii')
# else:
# return s
#
# Path: pysecure/calls/channeli.py
#
# Path: pysecure/error.py
# def ssh_get_error(ssh_session_int):
# return c_ssh_get_error(ssh_session_int)
#
# def ssh_get_error_code(ssh_session_int):
# return c_ssh_get_error_code(ssh_session_int)
, which may contain function names, class names, or code. Output only the next line. | return result |
Using the snippet: <|code_start|>c_ssh_channel_change_pty_size.restype = c_int
# int ssh_channel_is_eof(ssh_channel channel)
c_ssh_channel_is_eof = libssh.ssh_channel_is_eof
c_ssh_channel_is_eof.argtypes = [c_ssh_channel]
c_ssh_channel_is_eof.restype = c_int
# int ssh_channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count, int is_stderr)
c_ssh_channel_read_nonblocking = libssh.ssh_channel_read_nonblocking
c_ssh_channel_read_nonblocking.argtypes = [c_ssh_channel, c_void_p, c_uint32, c_int]
c_ssh_channel_read_nonblocking.restype = c_int
# int ssh_channel_request_env(ssh_channel channel, const char *name, const char *value)
c_ssh_channel_request_env = libssh.ssh_channel_request_env
c_ssh_channel_request_env.argtypes = [c_ssh_channel, c_char_p, c_char_p]
c_ssh_channel_request_env.restype = c_int
# ssh_session ssh_channel_get_session(ssh_channel channel)
c_ssh_channel_get_session = libssh.ssh_channel_get_session
c_ssh_channel_get_session.argtypes = [c_ssh_channel]
c_ssh_channel_get_session.restype = c_ssh_session
# ssh_channel ssh_channel_accept_x11(ssh_channel channel, int timeout_ms)
c_ssh_channel_accept_x11 = libssh.ssh_channel_accept_x11
c_ssh_channel_accept_x11.argtypes = [c_ssh_channel, c_int]
c_ssh_channel_accept_x11.restype = c_ssh_channel
# int ssh_channel_request_x11(ssh_channel channel, int single_connection, const char *protocol, const char *cookie, int screen_number)
c_ssh_channel_request_x11 = libssh.ssh_channel_request_x11
c_ssh_channel_request_x11.argtypes = [c_ssh_channel, c_int, c_char_p, c_char_p, c_int]
<|code_end|>
, determine the next line of code. You have imports:
from ctypes import *
from pysecure.library import libssh
from pysecure.types import *
and context (class names, function names, or code) available:
# Path: pysecure/library.py
# _LIBSSH_FILEPATH = os.environ.get('PS_LIBRARY_FILEPATH', '')
# _LIBSSH_FILEPATH = find_library('libssh')
# _LIBSSH_FILEPATH = 'libssh.so'
. Output only the next line. | c_ssh_channel_request_x11.restype = c_int |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.