示例#1
0
    def removeFollower(self, username, follower):
        """removeFollower username follower"""

        following_fn = "following:" + follower

        with Transaction() as fs:
            yield fs.begin()

            content = (yield fs.read(following_fn))
            if content is None:
                yield Op.FollowerChangeResult.FAILURE

            content = Utility.byteArrayToString(content)
            out = StringBuffer()
            absent = True

            for line in lines(content):
                followed_user, timestamp = line.split("\t")
                if followed_user == username:
                    absent = False
                else:
                    out.append(line + "\n")

            fs.overwrite(following_fn, Utility.stringToByteArray(out.toString()))
            if not (yield fs.commit()):
                yield Op.FollowerChangeResult.FAILURE
            elif absent:
                yield Op.FollowerChangeResult.DOES_NOT_EXIST
            else:
                yield Op.FollowerChangeResult.SUCCESS
示例#2
0
 def __init__(self, program):
     self.saveBoolean = (1 == 1)
     self.CurrentBuffer = StringBuffer()
     self.CurrentBuffer.append("<file_created time=\"")
     self.CurrentBuffer.append(
         (Date(System.currentTimeMillis())).toString())
     self.CurrentBuffer.append("\">\n")
示例#3
0
文件: zlib.py 项目: choudarykvsp/kali
def _get_deflate_data(deflater):
    buf = jarray.zeros(1024, 'b')
    sb = StringBuffer()
    while not deflater.finished():
        l = deflater.deflate(buf)
        if l == 0:
            break
        sb.append(String(buf, 0, 0, l))
    return sb.toString()
示例#4
0
文件: zlib.py 项目: babble/babble
def _get_deflate_data(deflater):
    buf = jarray.zeros(1024, 'b')
    sb = StringBuffer()
    while not deflater.finished():
        l = deflater.deflate(buf)
        if l == 0:
            break
        sb.append(String(buf, 0, 0, l))
    return sb.toString()
示例#5
0
文件: zlib.py 项目: babble/babble
def _get_inflate_data(inflater, max_length=0):
    buf = jarray.zeros(1024, 'b')
    sb = StringBuffer()
    total = 0
    while not inflater.finished():
        if max_length:
            l = inflater.inflate(buf, 0, min(1024, max_length - total))
        else:
            l = inflater.inflate(buf)
        if l == 0:
            break

        total += l
        sb.append(String(buf, 0, 0, l))
        if max_length and total == max_length:
            break
    return sb.toString()
示例#6
0
文件: zlib.py 项目: choudarykvsp/kali
def _get_inflate_data(inflater, max_length=0):
    buf = jarray.zeros(1024, 'b')
    sb = StringBuffer()
    total = 0
    while not inflater.finished():
        if max_length:
            l = inflater.inflate(buf, 0, min(1024, max_length - total))
        else:
            l = inflater.inflate(buf)
        if l == 0:
            break

        total += l
        sb.append(String(buf, 0, 0, l))
        if max_length and total == max_length:
            break
    return sb.toString()
    def openLogFile(self, fileName):
	self.CurrentBuffer= StringBuffer();
	try:
	    file=open(fileName+"log", "rt");
	    self.CurrentBuffer.append(file.read());
            if self.CurrentBuffer.length()>16:
                self.CurrentBuffer=StringBuffer(self.CurrentBuffer.substring(0,
                                                     self.CurrentBuffer.length()-16));
	    self.CurrentBuffer.append("<file_opened time=\"");
            self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
            self.CurrentBuffer.append("\">");
	    self.CurrentBuffer.append(fileName);
	    self.CurrentBuffer.append("</file_opened>");
	    self.CurrentBuffer.append("\n");
	except:
            self.resetBuffer();
	    self.CurrentBuffer.append("<Could not find "+fileName+ "log,");
	    self.CurrentBuffer.append(" creating a new logfile>\n");
示例#8
0
def evaluate_dataset(classifier,data):
    evaluation = Evaluation(data)
    output = PlainText()
    output.setHeader(data)
    eval_buffer = StringBuffer() # buffer to use
    output.setBuffer(eval_buffer)
    options = [output]
    evaluation.evaluateModel(classifier,data,options)
    return evaluation
示例#9
0
		class HistoryTaskRunnable (Runnable):
			def __init__(self, textArea, br):
				self.textArea = textArea
				self.br = br
				self.sbf = StringBuffer()
			#@Override
			def run(self):
				while True:
					line = self.br.readLine()
					if line != None:
						self.sbf.append(line + "\n")
						# self.textArea.appendText(line + "\n") - Very slow
					else:
						break
				#Add Text to TextArea
				self.textArea.setText(self.sbf.toString())
				self.textArea.appendText("") #Used to trigger event handler
				#Close Buffered Reader
				br.close()
示例#10
0
 def __init__(self):
     sessionDuration = grinder.properties.getInt("player.sessionDurationInSeconds", 0)
     self.password = grinder.properties.getProperty("player.password")
     players_url = grinder.properties.getProperty("player.source-url")
     passwordHash = URLEncoder.encode(grinder.properties.getProperty("player.passwordHash"), "UTF-8")
     workers = grinder.properties.getInt("grinder.processes", 0)
     threads = grinder.properties.getInt("grinder.threads", 0)
     workerIndex = grinder.processNumber - grinder.firstProcessNumber
     threadsPerAgent = workers * threads
     agentIndex = grinder.agentNumber
     start = agentIndex * threadsPerAgent + workerIndex * threads
     if isLogEnabled:
         log("Worker will handle %s players starting from %d" % (threads, start))
     playerRange = (start, threads)
     self.workerPlayers = []
     params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % (
         passwordHash,
         str(sessionDuration / 5),
         str(playerRange[0]),
         str(threads),
     )
     urlStr = players_url + "?" + params
     try:
         data = StringBuffer()
         url = URL(urlStr)
         conn = url.openConnection()
         rd = BufferedReader(InputStreamReader(conn.getInputStream()))
         line = rd.readLine()
         while line is not None:
             data.append(line)
             line = rd.readLine()
         rd.close()
         if isLogEnabled:
             log(data.toString())
         message = JSONValue.parse(str(String(data.toString(), "UTF-8")))
         for entry in message:
             self.workerPlayers.append((entry.get(0), entry.get(1)))
     except Exception:
         raise Exception("Couldn't fetch players from %s: %s" % (urlStr, traceback.format_exc()))
     if isLogEnabled:
         log(str(self.workerPlayers))
示例#11
0
 def openLogFile(self, fileName):
     self.CurrentBuffer = StringBuffer()
     try:
         file = open(fileName + "log", "rt")
         self.CurrentBuffer.append(file.read())
         if self.CurrentBuffer.length() > 16:
             self.CurrentBuffer = StringBuffer(
                 self.CurrentBuffer.substring(
                     0,
                     self.CurrentBuffer.length() - 16))
         self.CurrentBuffer.append("<file_opened time=\"")
         self.CurrentBuffer.append(
             (Date(System.currentTimeMillis())).toString())
         self.CurrentBuffer.append("\">")
         self.CurrentBuffer.append(fileName)
         self.CurrentBuffer.append("</file_opened>")
         self.CurrentBuffer.append("\n")
     except:
         self.resetBuffer()
         self.CurrentBuffer.append("<Could not find " + fileName + "log,")
         self.CurrentBuffer.append(" creating a new logfile>\n")
示例#12
0
    def _get_response_msg(self, url_conn):
        """Функция, возвращающая тело ответа"""
        get_input_stream = url_conn.responseCode < HttpURLConnection.HTTP_BAD_REQUEST
        if get_input_stream:
            in_stream = url_conn.getInputStream()
        else:
            in_stream = url_conn.getErrorStream()

        response = ""

        if in_stream:
            in_stream = BufferedReader(InputStreamReader(in_stream, 'utf-8'))

            response = StringBuffer()
            while True:
                inputLine = in_stream.readLine()
                if not inputLine:
                    break
                response.append(inputLine)

            in_stream.close()

        return unicode(response)
示例#13
0
文件: yazino.py 项目: pticun/bet21
 def __init__(self):
     sessionDuration = grinder.properties.getInt(
         "player.sessionDurationInSeconds", 0)
     self.password = grinder.properties.getProperty("player.password")
     players_url = grinder.properties.getProperty("player.source-url")
     passwordHash = URLEncoder.encode(
         grinder.properties.getProperty("player.passwordHash"), "UTF-8")
     workers = grinder.properties.getInt("grinder.processes", 0)
     threads = grinder.properties.getInt("grinder.threads", 0)
     workerIndex = grinder.processNumber - grinder.firstProcessNumber
     threadsPerAgent = workers * threads
     agentIndex = grinder.agentNumber
     start = agentIndex * threadsPerAgent + workerIndex * threads
     if isLogEnabled:
         log("Worker will handle %s players starting from %d" %
             (threads, start))
     playerRange = (start, threads)
     self.workerPlayers = []
     params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % (
         passwordHash, str(sessionDuration / 5), str(
             playerRange[0]), str(threads))
     urlStr = players_url + "?" + params
     try:
         data = StringBuffer()
         url = URL(urlStr)
         conn = url.openConnection()
         rd = BufferedReader(InputStreamReader(conn.getInputStream()))
         line = rd.readLine()
         while line is not None:
             data.append(line)
             line = rd.readLine()
         rd.close()
         if isLogEnabled:
             log(data.toString())
         message = JSONValue.parse(str(String(data.toString(), "UTF-8")))
         for entry in message:
             self.workerPlayers.append((entry.get(0), entry.get(1)))
     except Exception:
         raise Exception("Couldn't fetch players from %s: %s" %
                         (urlStr, traceback.format_exc()))
     if isLogEnabled:
         log(str(self.workerPlayers))
示例#14
0
import sys
from java.lang import StringBuffer, System


sb = StringBuffer(100)    # Preallocate StringBuffer size for performance.

sb.append('The platform is: ')
sb.append(sys.platform)  # Python property
sb.append(' time for an omelette.')

sb.append('\n')     # Newline
sb.append('Home directory: ')
sb.append( System.getProperty('user.home') )

sb.append('\n')     # Newline
sb.append('Some numbers: ')
sb.append(44.1)
sb.append(', ')
sb.append(42)
sb.append(' ')

# Try appending a tuple.
tup=( 'Red', 'Green', 'Blue', 255, 204, 127 )
sb.append(tup)

print(sb.toString())


# Treat java.util.Properties as Python dictionary.
props = System.getProperties()
示例#15
0
def space(number):
    from java.lang import StringBuffer
    buf = StringBuffer(number)
    for i in range(number):
        buf.append(' ')
    return buf.toString()
示例#16
0
def monthlyTable(file, search, twstring):
    # Create Data Reference from Inputs
    g = opendss(file)
    from java.lang import System
    lineSeparator = System.getProperty(
        'line.separator')  # '\r\n' # '\n' on unix
    desiredSpaceCount = 6
    g.filterBy(search)
    # Set time window and create a new ref with this window
    tw = timeWindow(twstring)
    ref = DataReference.create(g[0], tw)

    pref = PeriodAverageProxy(
        ref,
        DSSUtil.getTimeFactory().createTimeInterval('1month'))
    dsi = pref.getData().getIterator()
    tm = DSSUtil.getTimeFactory().getTimeInstance()
    tmf = DSSUtil.getTimeFactory().getTimeFormatInstance().create("MMM yyyy")
    tmf1 = DSSUtil.getTimeFactory().getTimeFormatInstance().create("MMM")
    tmf2 = DSSUtil.getTimeFactory().getTimeFormatInstance().create("yyyy")
    from java.lang import Float, Math
    from java.util import Date
    sys.add_package('java.text')
    from java.text import NumberFormat
    nf = NumberFormat.getInstance()
    nf.setGroupingUsed(0)
    nf.setMinimumFractionDigits(1)
    nf.setMinimumIntegerDigits(1)
    nf.setMaximumFractionDigits(1)
    fp = FieldPosition(nf.INTEGER_FIELD)
    lines = []
    lines.append('STUDY: ' + ref.getPathname().getPart(Pathname.F_PART) +
                 space(10) + 'FILE: ' + file + space(10) + Date().toString())
    lines.append('')
    lines.append('Searched: ' + search)
    lines.append('Units: ' + ref.getData().getAttributes().getYUnits())
    lines.append('Project:  ' + ref.getPathname().toString())
    lines.append('')
    desiredSpace = space(desiredSpaceCount + nf.getMinimumIntegerDigits() +
                         nf.getMinimumFractionDigits() - 3)
    startSpace = desiredSpace + space(4)
    lines.append('YEAR' + desiredSpace + 'OCT' + desiredSpace + 'NOV' +
                 desiredSpace + 'DEC' + desiredSpace + 'JAN' + desiredSpace +
                 'FEB' + desiredSpace + 'MAR' + desiredSpace + 'APR' +
                 desiredSpace + 'MAY' + desiredSpace + 'JUN' + desiredSpace +
                 'JUL' + desiredSpace + 'AUG' + desiredSpace + 'SEP' +
                 space(desiredSpaceCount - 3) + 'TOTAL')
    cl = ''
    gotOct = 0
    yrsum = 0.0
    allyrtot = 0.0
    yravg = 0.0
    totavg = 0.0
    totmin = Float.MAX_VALUE
    totmax = Float.MIN_VALUE
    nsum = 0
    nyears = 0
    while not dsi.atEnd():
        e = dsi.getElement()
        date = tm.create(Math.round(e.getX())).toString()
        mon = date[2:5]
        if mon == 'OCT':
            if nsum > 0:
                yravg = yrsum
                allyrtot = allyrtot + yrsum
                nyears = nyears + 1
                totmin = Math.min(totmin, yrsum)
                totmax = Math.max(totmax, yrsum)
            if cl != '':
                strbuf = StringBuffer(10)
                nf.format(yravg, strbuf, fp)
                cl = cl + space(desiredSpaceCount -
                                fp.getEndIndex()) + strbuf.toString()
                lines.append(cl)
            #
            yrsum = 0.0
            nsum = 0
            # water year
            cl = repr(int(tm.create(Math.round(e.getX())).format(tmf2)) + 1)
            gotOct = 1
        #
        if gotOct:
            if (e.getY() == -901):
                strbuf = StringBuffer(10)
                nf.format(yravg, strbuf, fp)
                cl = cl + space(desiredSpaceCount) + \
                     space(nf.getMinimumIntegerDigits() + nf.getMinimumIntegerDigits())
            else:
                strbuf = StringBuffer(10)
                nf.format(e.getY(), strbuf, fp)
                cl = cl + space(desiredSpaceCount -
                                fp.getEndIndex()) + strbuf.toString()
                yrsum = yrsum + e.getY()
                nsum = nsum + 1
            # print tm.create(Math.round(e.getX())).format(tmf), e.getY()
        #
        dsi.advance()
    #
    # Get average, min, max for each month
    totavg = allyrtot / nyears
    minV = Float.MAX_VALUE
    maxV = Float.MIN_VALUE
    monavg = {
        'OCT': 0.0,
        'NOV': 0.0,
        'DEC': 0.0,
        'JAN': 0.0,
        'FEB': 0.0,
        'MAR': 0.0,
        'APR': 0.0,
        'MAY': 0.0,
        'JUN': 0.0,
        'JUL': 0.0,
        'AUG': 0.0,
        'SEP': 0.0
    }
    monmin = {
        'OCT': minV,
        'NOV': minV,
        'DEC': minV,
        'JAN': minV,
        'FEB': minV,
        'MAR': minV,
        'APR': minV,
        'MAY': minV,
        'JUN': minV,
        'JUL': minV,
        'AUG': minV,
        'SEP': minV
    }
    monmax = {
        'OCT': maxV,
        'NOV': maxV,
        'DEC': maxV,
        'JAN': maxV,
        'FEB': maxV,
        'MAR': maxV,
        'APR': maxV,
        'MAY': maxV,
        'JUN': maxV,
        'JUL': maxV,
        'AUG': maxV,
        'SEP': maxV
    }
    numavg = {
        'OCT': 0,
        'NOV': 0,
        'DEC': 0,
        'JAN': 0,
        'FEB': 0,
        'MAR': 0,
        'APR': 0,
        'MAY': 0,
        'JUN': 0,
        'JUL': 0,
        'AUG': 0,
        'SEP': 0
    }
    gotOct = 0
    dsi.resetIterator()
    while not dsi.atEnd():
        e = dsi.getElement()
        date = tm.create(Math.round(e.getX())).toString()
        mon = date[2:5]
        if mon == 'OCT':
            gotOct = 1
        if gotOct:
            if (e.getY() == -901):
                pass
            else:
                monmin[mon] = Math.min(monmin[mon], e.getY())
                monmax[mon] = Math.max(monmax[mon], e.getY())
                monavg[mon] = monavg[mon] + e.getY()
                numavg[mon] = numavg[mon] + 1
            #
        #
        dsi.advance()
    #
    lines.append(' ')
    cl = 'AVG:'
    for val in monavg.keys():
        monavg[val] = monavg[val] / numavg[val]
        strbuf = StringBuffer(10)
        nf.format(monavg[val], strbuf, fp)
        cl = cl + space(desiredSpaceCount -
                        fp.getEndIndex()) + strbuf.toString()
    #
    strbuf = StringBuffer(10)
    nf.format(totavg, strbuf, fp)
    cl = cl + space(desiredSpaceCount - fp.getEndIndex()) + strbuf.toString()
    lines.append(cl)
    #
    cl = 'MIN:'
    for val in monmin.keys():
        strbuf = StringBuffer(10)
        nf.format(monmin[val], strbuf, fp)
        cl = cl + space(desiredSpaceCount -
                        fp.getEndIndex()) + strbuf.toString()
    #
    strbuf = StringBuffer(10)
    nf.format(totmin, strbuf, fp)
    cl = cl + space(desiredSpaceCount - fp.getEndIndex()) + strbuf.toString()
    lines.append(cl)
    #
    cl = 'MAX:'
    for val in monmax.keys():
        strbuf = StringBuffer(10)
        nf.format(monmax[val], strbuf, fp)
        cl = cl + space(desiredSpaceCount -
                        fp.getEndIndex()) + strbuf.toString()
    #
    strbuf = StringBuffer(10)
    nf.format(totmax, strbuf, fp)
    cl = cl + space(desiredSpaceCount - fp.getEndIndex()) + strbuf.toString()
    lines.append(cl)
    #
    #
    # f=open(search + '.txt','w')
    # for line in lines :
    #     f.write(line + lineSeparator)
    #     print line
    #
    # f.close()
    return lines
示例#17
0
 def resetBuffer(self):
     self.CurrentBuffer=StringBuffer();
     self.CurrentBuffer.append("<file_created time=\"");
     self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
     self.CurrentBuffer.append("\">\n");
示例#18
0
			def __init__(self, textArea, br):
				self.textArea = textArea
				self.br = br
				self.sbf = StringBuffer()
示例#19
0
class JESLogBuffer:

################################################################################
# Function name: __init__
# Return:
#     An instance of the JESLogBuffer class.
# Description:
#     Creates a new instance of the JESLogBuffer.
################################################################################
    def __init__(self, program):
        self.saveBoolean = (1 == 1);
	self.CurrentBuffer=StringBuffer();
        self.CurrentBuffer.append("<file_created time=\"");
        self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">\n");
        
################################################################################
# Function name: resetBuffer
# Parameters:
#           None.
# Description:
#     This function clears the log buffer.
################################################################################
    def resetBuffer(self):
        self.CurrentBuffer=StringBuffer();
        self.CurrentBuffer.append("<file_created time=\"");
        self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">\n");

################################################################################
# Function name: addCommand
# Parameters:
#           newString: the command that is to be added into the log
# Description:
#     This function adds a command into the log file
################################################################################
    def addCommand(self, newString):
        self.CurrentBuffer.append("<command_run time=\"");
        self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">");
        self.CurrentBuffer.append(newString);
	self.CurrentBuffer.setCharAt(self.CurrentBuffer.length()-1, '>');
        self.CurrentBuffer.append("</command_run>\n");

################################################################################
# Function name: addMenuOption
# Parameters:
#           newString: the name of the menu option to be added to the log
# Description:
#     This function adds a menu option into the log
################################################################################
    def addMenuOption(self, newString):
        self.CurrentBuffer.append("<menu_button time=\"");
        self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">");
        self.CurrentBuffer.append(newString);
        self.CurrentBuffer.append("</menu_button>\n");

################################################################################
# Function name: openLogFile
# Parameters:
#           fileName: the file name to open
# Description:
#     This function clears the log buffer and replaces it with the logfile that
# is in the filename specified.
################################################################################

    def openLogFile(self, fileName):
	self.CurrentBuffer= StringBuffer();
	try:
	    file=open(fileName+"log", "rt");
	    self.CurrentBuffer.append(file.read());
            if self.CurrentBuffer.length()>16:
                self.CurrentBuffer=StringBuffer(self.CurrentBuffer.substring(0,
                                                     self.CurrentBuffer.length()-16));
	    self.CurrentBuffer.append("<file_opened time=\"");
            self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
            self.CurrentBuffer.append("\">");
	    self.CurrentBuffer.append(fileName);
	    self.CurrentBuffer.append("</file_opened>");
	    self.CurrentBuffer.append("\n");
	except:
            self.resetBuffer();
	    self.CurrentBuffer.append("<Could not find "+fileName+ "log,");
	    self.CurrentBuffer.append(" creating a new logfile>\n");

################################################################################
# Function name: saveLogFile
# Parameters:
#           fileName: the filename to save to
# Description:
#     This function dumps the log buffer into the specified file
################################################################################

    def saveLogFile(self, fileName):
        if self.saveBoolean==(1==0):
            return;
	logfile=open(fileName+"log", "wt");
	self.CurrentBuffer.append("<file_saved time=\"");
    	self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">");
	self.CurrentBuffer.append(fileName);
	self.CurrentBuffer.append("</file_saved>");
	self.CurrentBuffer.append("\n");
        self.CurrentBuffer.append("</file_created>\n");
	logfile.write(self.CurrentBuffer.toString());
	logfile.close();

################################################################################
# Function name: dumpLogToTerm
# Parameters:
#           None.
# Description:
#     This funcion dumps the log buffer to the terminal. Intended for debugging
# use primarily.
################################################################################

    def dumpLogToTerm(self):
        System.out.println(self.CurrentBuffer.toString());
示例#20
0
    def __init__(self, program):
        self.saveBoolean = (1 == 1);
	self.CurrentBuffer=StringBuffer();
        self.CurrentBuffer.append("<file_created time=\"");
        self.CurrentBuffer.append((Date(System.currentTimeMillis())).toString());
        self.CurrentBuffer.append("\">\n");
示例#21
0
文件: weka.py 项目: chustar/limitless
import weka.classifiers.functions.MultilayerPerceptron as MultilayerPerceptron
import weka.core.SerializationHelper as SerializationHelper

# check commandline parameters
if (not (len(sys.argv) == 3)):
    print "Usage: weka.py <ARFF-file>"
    sys.exit()

file = FileReader(sys.argv[1])
file2 = FileReader(sys.argv[2])
data = Instances(file)
test = Instances(file2)
data.setClassIndex(data.numAttributes() - 1)
test.setClassIndex(test.numAttributes() - 1)
evaluation = Evaluation(data)
buffer = StringBuffer()
attRange = Range()  # no additional attributes output
outputDistribution = Boolean(False)  # we don't want distribution
nn = MultilayerPerceptron()
nn.buildClassifier(data)  # only a trained classifier can be evaluated

#print evaluation.evaluateModel(nn, ['-t', sys.argv[1], '-T', sys.argv[2]])#;, [buffer, attRange, outputDistribution])
res = evaluation.evaluateModel(nn, test,
                               [buffer, attRange, outputDistribution])
f = open('predictions/' + data.relationName(), 'w')
for d in res:
    f.write(str(d) + '\n')
f.close()

SerializationHelper.write("models/" + data.relationName() + ".model", nn)
示例#22
0
import sys
import java
import java.lang.System as System
import java.util.Date as Date
import java.lang.StringBuffer as StringBuffer
import org.python.core


# workaround to support java 1.5 jython bug
if sys.registry.getProperty('java.version') >= '1.5.0':
    for n,f in java.lang.AbstractStringBuilder.__dict__.items():
        x = org.python.core.PyReflectedFunction(n)
        for a in f.argslist:
            if a is None: continue
            m = StringBuffer.getMethod(n,a.args)
            x.addMethod(m)
        StringBuffer.__dict__[n] = x


class JESLogBuffer:

################################################################################
# Function name: __init__
# Return:
#     An instance of the JESLogBuffer class.
# Description:
#     Creates a new instance of the JESLogBuffer.
################################################################################
    def __init__(self, program):
        self.saveBoolean = (1 == 1);
示例#23
0
algo = algo_dict['LibSVM']
tag = SelectedTag("1",algo.TAGS_KERNELTYPE)  # 0 = linear, 1 = polynomial, 2 = radial basis function, 3 = sigmoid
algo.setKernelType(tag)

# train classifiers
print "Training classifiers..."
for key in algo_keys :
   algo = algo_dict[key]
   algo.buildClassifier(data)

# evaluate classifiers and print a result summary including confusion matrix
my_evaluations = []
for key in algo_keys :
   evaluation = Evaluation(data)
   algo = algo_dict[key]
   buffer = StringBuffer()             # buffer for the predictions
   attRange = Range()                  # no additional attributes output
   outputDistribution = Boolean(False) # we don't want distribution
   evaluation.evaluateModel(algo, data, [buffer, attRange, outputDistribution])
   my_evaluations.append(evaluation)
   print "------------------------------------"
   print algo.__class__.__name__
   print evaluation.toSummaryString()
   confusion_matrix = evaluation.confusionMatrix()  # confusion matrix
   print "Confusion Matrix:"
   for l in confusion_matrix:
       print '** ', ','.join('%2d'%int(x) for x in l)

# example to collect an individual statistic for all evaluated classifiers
print "------------------------------------"
print "Example to collect an individual statistic for all evaluated classifiers"
示例#24
0
 def toString(self):
     s = StringBuffer()
     s.append("name=" + self.name + "\t")
     s.append("value=" + str(self.value) + "\t")
     s.append("type=" + self.type + "\t")
     s.append("units=" + self.units + "\t")
     s.append("spoof=" + self.spoof + "\t")
     for name, value in self.correlatedData.iteritems():
          s.append(name + "=" + value + "\t")
     return s.toString()
示例#25
0
def listADDEImages(localEntry=None,
                   server=None,
                   dataset=None,
                   descriptor=None,
                   accounting=DEFAULT_ACCOUNTING,
                   location=None,
                   coordinateSystem=CoordinateSystems.LATLON,
                   place=None,
                   mag=None,
                   position=None,
                   unit=None,
                   day=None,
                   time=None,
                   debug=False,
                   band=None,
                   size=None,
                   showUrls=True):
    """Creates a list of ADDE images.
    
    Args:
        localEntry: Local ADDE dataset.
        server: ADDE server.
        dataset: ADDE dataset group name.
        descriptor: ADDE dataset descriptor.
        day: Day range. ('begin date', 'end date')
        time: ('begin time', 'end time')
        position: Position number. Values may be integers or the string "ALL". (default=0)
        band: McIDAS band number; only images that have matching band number will be returned.
        accounting: ('user', 'project number') User and project number required by servers using McIDAS accounting. default = ('idv','0')
        
    Returns:
        ADDE image matching the given criteria, if any.
    """
    if localEntry:
        server = localEntry.getAddress()
        dataset = localEntry.getGroup()
        descriptor = localEntry.getDescriptor().upper()
    elif (server is None) or (dataset is None) or (descriptor is None):
        raise TypeError(
            "must provide localEntry or server, dataset, and descriptor values."
        )

    if server == "localhost" or server == "127.0.0.1":
        port = EntryStore.getLocalPort()
    else:
        port = "112"

    # server = '%s:%s' % (server, port)

    user = accounting[0]
    proj = accounting[1]
    debug = str(debug).lower()

    if mag:
        mag = '&MAG=%s %s' % (mag[0], mag[1])
    else:
        mag = ''

    if unit:
        origUnit = unit
        unit = '&UNIT=%s' % (unit)
    else:
        # origUnit = None
        unit = ''

    if place is Places.CENTER:
        place = '&PLACE=CENTER'
    elif place is Places.ULEFT:
        place = '&PLACE=ULEFT'
    else:
        # raise ValueError()
        place = ''

    if coordinateSystem is CoordinateSystems.LATLON:
        coordSys = 'LATLON'
    elif coordinateSystem is CoordinateSystems.AREA or coordinateSystem is CoordinateSystems.IMAGE:
        coordSys = 'LINELE'
    else:
        raise ValueError()

    if location:
        location = '&%s=%s %s' % (coordSys, location[0], location[1])
    else:
        location = ''

    if size:
        if size == 'ALL':
            size = '&SIZE=99999 99999'
        else:
            size = '&SIZE=%s %s' % (size[0], size[1])
    else:
        size = ''

    if time:
        time = '&TIME=%s %s I' % (time[0], time[1])
    else:
        time = ''

    if band:
        band = '&BAND=%s' % (str(band))
    else:
        band = '&BAND=ALL'

    if position is not None:
        if isinstance(position, int):
            position = '&POS=%s' % (position)
        elif isinstance(position, tuple):
            if len(position) != 2:
                raise ValueError(
                    'position range may only contain values for the beginning and end of a range.'
                )
            position = '&POS=%s %s' % (str(position[0]), str(position[1]))
        else:
            position = '&POS=%s' % (str(position).upper())
    else:
        position = '&POS=0'

    tz = TimeZone.getTimeZone('Z')

    dateFormat = SimpleDateFormat()
    dateFormat.setTimeZone(tz)
    dateFormat.applyPattern('yyyyDDD')

    timeFormat = SimpleDateFormat()
    timeFormat.setTimeZone(tz)
    timeFormat.applyPattern('HH:mm:ss')

    addeUrlFormat = "adde://%(server)s/imagedirectory?&PORT=%(port)s&COMPRESS=gzip&USER=%(user)s&PROJ=%(proj)s&VERSION=1&DEBUG=%(debug)s&TRACE=0&GROUP=%(dataset)s&DESCRIPTOR=%(descriptor)s%(band)s%(location)s%(place)s%(size)s%(unit)s%(mag)s%(day)s%(time)s%(position)s"

    urls = []
    areaDirectories = []

    dates = _normalizeDates(day)
    for date in dates:
        formatValues = {
            'server': server,
            'port': port,
            'user': user,
            'proj': proj,
            'debug': debug,
            'dataset': dataset,
            'descriptor': descriptor,
            'band': band,
            'location': location,
            'place': place,
            'size': size,
            'unit': unit,
            'mag': mag,
            'day': date,
            'time': time,
            'position': position,
        }
        url = addeUrlFormat % formatValues
        if showUrls:
            print url
        adl = AreaDirectoryList(url)
        results = adl.getSortedDirs()
        for imageTimes in results:
            for areaDirectory in imageTimes:
                urls.append(url)
                areaDirectories.append(areaDirectory)

    temp = _AreaDirectoryList()
    for i, d in enumerate(areaDirectories):
        nominalTime = d.getNominalTime()
        tempDay = str(
            dateFormat.format(nominalTime, StringBuffer(), FieldPosition(0)))
        tempTime = str(
            timeFormat.format(nominalTime, StringBuffer(), FieldPosition(0)))

        bandList = list(d.getBands())
        # tempUnitList = list(d.getCalInfo()[0])
        # unitList = tempUnitList[::2]
        # unitDescList = tempUnitList[1::2]
        # calInfo = dict(zip(unitList, unitDescList))
        if unit:
            unitList = [origUnit]
        else:
            unitList = map(str, list(d.getCalInfo()[0])[::2])

        for band in bandList:
            for calUnit in unitList:
                dt = {
                    'server':
                    server,
                    'dataset':
                    dataset,
                    'descriptor':
                    descriptor,
                    'bandNumber':
                    band,
                    'bandList':
                    bandList,
                    'debug':
                    debug,
                    'accounting':
                    accounting,
                    'day':
                    tempDay,
                    'time':
                    tempTime,
                    'imageSize': (d.getLines(), d.getElements()),
                    'centerLocation':
                    (d.getCenterLatitude(), d.getCenterLongitude()),
                    'resolution': (d.getCenterLatitudeResolution(),
                                   d.getCenterLongitudeResolution()),
                    'unitList':
                    unitList,
                    'unitType':
                    calUnit,
                    'bands':
                    bandList,
                    'band-count':
                    d.getNumberOfBands(),
                    'calinfo':
                    map(str, list(d.getCalInfo()[0])),
                    'calibration-scale-factor':
                    d.getCalibrationScaleFactor(),
                    'calibration-type':
                    str(d.getCalibrationType()),
                    'calibration-unit-name':
                    d.getCalibrationUnitName(),
                    'center-latitude':
                    d.getCenterLatitude(),
                    'center-latitude-resolution':
                    d.getCenterLatitudeResolution(),
                    'center-longitude':
                    d.getCenterLongitude(),
                    'center-longitude-resolution':
                    d.getCenterLongitudeResolution(),
                    'directory-block':
                    list(d.getDirectoryBlock()),
                    'elements':
                    d.getElements(),
                    'lines':
                    d.getLines(),
                    'memo-field':
                    str(d.getMemoField()),
                    'nominal-time':
                    DateTime(d.getNominalTime()),
                    'sensor-id':
                    d.getSensorID(),
                    'sensor-type':
                    str(d.getSensorType()),
                    'source-type':
                    str(d.getSourceType()),
                    'start-time':
                    DateTime(d.getStartTime()),
                    'url':
                    urls[i],
                }
            temp.append(dt)
    return temp
示例#26
0
class JESLogBuffer:

    ################################################################################
    # Function name: __init__
    # Return:
    #     An instance of the JESLogBuffer class.
    # Description:
    #     Creates a new instance of the JESLogBuffer.
    ################################################################################
    def __init__(self, program):
        self.saveBoolean = (1 == 1)
        self.CurrentBuffer = StringBuffer()
        self.CurrentBuffer.append("<file_created time=\"")
        self.CurrentBuffer.append(
            (Date(System.currentTimeMillis())).toString())
        self.CurrentBuffer.append("\">\n")

################################################################################
# Function name: resetBuffer
# Parameters:
#           None.
# Description:
#     This function clears the log buffer.
################################################################################

    def resetBuffer(self):
        self.CurrentBuffer = StringBuffer()
        self.CurrentBuffer.append("<file_created time=\"")
        self.CurrentBuffer.append(
            (Date(System.currentTimeMillis())).toString())
        self.CurrentBuffer.append("\">\n")

################################################################################
# Function name: addCommand
# Parameters:
#           newString: the command that is to be added into the log
# Description:
#     This function adds a command into the log file
################################################################################

    def addCommand(self, newString):
        self.CurrentBuffer.append("<command_run time=\"")
        self.CurrentBuffer.append(
            (Date(System.currentTimeMillis())).toString())
        self.CurrentBuffer.append("\">")
        self.CurrentBuffer.append(newString)
        self.CurrentBuffer.setCharAt(self.CurrentBuffer.length() - 1, '>')
        self.CurrentBuffer.append("</command_run>\n")

################################################################################
# Function name: addMenuOption
# Parameters:
#           newString: the name of the menu option to be added to the log
# Description:
#     This function adds a menu option into the log
################################################################################

    def addMenuOption(self, newString):
        self.CurrentBuffer.append("<menu_button time=\"")
        self.CurrentBuffer.append(
            (Date(System.currentTimeMillis())).toString())
        self.CurrentBuffer.append("\">")
        self.CurrentBuffer.append(newString)
        self.CurrentBuffer.append("</menu_button>\n")

################################################################################
# Function name: openLogFile
# Parameters:
#           fileName: the file name to open
# Description:
#     This function clears the log buffer and replaces it with the logfile that
# is in the filename specified.
################################################################################

    def openLogFile(self, fileName):
        self.CurrentBuffer = StringBuffer()
        try:
            file = open(fileName + "log", "rt")
            self.CurrentBuffer.append(file.read())
            if self.CurrentBuffer.length() > 16:
                self.CurrentBuffer = StringBuffer(
                    self.CurrentBuffer.substring(
                        0,
                        self.CurrentBuffer.length() - 16))
            self.CurrentBuffer.append("<file_opened time=\"")
            self.CurrentBuffer.append(
                (Date(System.currentTimeMillis())).toString())
            self.CurrentBuffer.append("\">")
            self.CurrentBuffer.append(fileName)
            self.CurrentBuffer.append("</file_opened>")
            self.CurrentBuffer.append("\n")
        except:
            self.resetBuffer()
            self.CurrentBuffer.append("<Could not find " + fileName + "log,")
            self.CurrentBuffer.append(" creating a new logfile>\n")

################################################################################
# Function name: saveLogFile
# Parameters:
#           fileName: the filename to save to
# Description:
#     This function dumps the log buffer into the specified file
################################################################################

    def saveLogFile(self, fileName):
        if self.saveBoolean == (1 == 0):
            return
        logfile = open(fileName + "log", "wt")
        self.CurrentBuffer.append("<file_saved time=\"")
        self.CurrentBuffer.append(
            (Date(System.currentTimeMillis())).toString())
        self.CurrentBuffer.append("\">")
        self.CurrentBuffer.append(fileName)
        self.CurrentBuffer.append("</file_saved>")
        self.CurrentBuffer.append("\n")
        self.CurrentBuffer.append("</file_created>\n")
        logfile.write(self.CurrentBuffer.toString())
        logfile.close()

################################################################################
# Function name: dumpLogToTerm
# Parameters:
#           None.
# Description:
#     This funcion dumps the log buffer to the terminal. Intended for debugging
# use primarily.
################################################################################

    def dumpLogToTerm(self):
        System.out.println(self.CurrentBuffer.toString())
示例#27
0
#Copyright (C) 2004 Aron Giles, Ryan Connelly, Adam Poncz, Patrick Carnahan

import sys
import java
import java.lang.System as System
import java.util.Date as Date
import java.lang.StringBuffer as StringBuffer
import org.python.core

# workaround to support java 1.5 jython bug
if sys.registry.getProperty('java.version') >= '1.5.0':
    for n, f in java.lang.AbstractStringBuilder.__dict__.items():
        x = org.python.core.PyReflectedFunction(n)
        for a in f.argslist:
            if a is None: continue
            m = StringBuffer.getMethod(n, a.args)
            x.addMethod(m)
        StringBuffer.__dict__[n] = x


class JESLogBuffer:

    ################################################################################
    # Function name: __init__
    # Return:
    #     An instance of the JESLogBuffer class.
    # Description:
    #     Creates a new instance of the JESLogBuffer.
    ################################################################################
    def __init__(self, program):
        self.saveBoolean = (1 == 1)
示例#28
0
 def resetBuffer(self):
     self.CurrentBuffer = StringBuffer()
     self.CurrentBuffer.append("<file_created time=\"")
     self.CurrentBuffer.append(
         (Date(System.currentTimeMillis())).toString())
     self.CurrentBuffer.append("\">\n")
示例#29
0
#!/usr/bin/env python
# vim: set fileencoding=utf-8

from java.awt import Color
from java.lang import StringBuffer
from java.awt import Button


print("\nString buffer")

s = StringBuffer()
print(s)
print(s.length())

s.append("hello world!")
print(s)
print(s.length())

s.setLength(10)
print(s)
print(s.length())

# nebude fungovat
s.length = 5
print(s)
print(s.length())
示例#30
0
    print "Usage: UsingJ48Ext.py <ARFF-file>"
    sys.exit()

# load data file
print "Loading data..."
file = FileReader(sys.argv[1])
data = Instances(file)

# set the class Index - the index of the dependent variable
data.setClassIndex(data.numAttributes() - 1)

# create the model
evaluation = Evaluation(data)
output = PlainText()  # plain text output for predictions
output.setHeader(data)
buffer = StringBuffer()  # buffer to use
output.setBuffer(buffer)
attRange = Range()  # no additional attributes output
outputDistribution = Boolean(False)  # we don't want distribution
j48 = J48()
j48.buildClassifier(data)  # only a trained classifier can be evaluated
evaluation.evaluateModel(j48, data, [output, attRange, outputDistribution])

# print out the built model
print "--> Generated model:\n"
print j48

print "--> Evaluation:\n"
print evaluation.toSummaryString()

print "--> Predictions:\n"
示例#31
0
import sys
from java.lang import StringBuffer, System


sb = StringBuffer(100)    # Preallocate StringBuffer size for performance.

sb.append('The platform is: ')
sb.append(sys.platform)  # Python property
sb.append(' time for an omelette.')

sb.append('\n')     # Newline
sb.append('Home directory: ')
sb.append( System.getProperty('user.home') )

sb.append('\n')     # Newline
sb.append('Some numbers: ')
sb.append(44.1)
sb.append(', ')
sb.append(42)
sb.append(' ')

# Try appending a tuple.
tup=( 'Red', 'Green', 'Blue', 255, 204, 127 )
sb.append(tup)

print(sb.toString())


# Treat java.util.Properties as Python dictionary.
props = System.getProperties()