text:
<?php

require_once 'OffAmazonPayments/Model.php';

/**
 * OffAmazonPaymentsNotifications_Model_OrderReferenceStatus
 *
 * Properties:
 *

 *
 *
State: string

 *
LastUpdateTimestamp: string

 *
ReasonCode: string

 *
ReasonDescription: string

 *
 *

 */
class OffAmazonPaymentsNotifications_Model_OrderReferenceStatus extends OffAmazonPayments_Model
{

    /**
     * Construct new OffAmazonPaymentsNotifications_Model_OrderReferenceStatus
     *
     * @param mixed $data DOMElement or Associative Array to construct from.
     *
     * Valid properties:
     *

     *
     *
State: string

     *
LastUpdateTimestamp: string

     *
ReasonCode: string

     *
ReasonDescription: string

     *
     *

     */
    public function __construct($data = null)
    {
        $this->fields = array (
        'State' => array('FieldValue' => null, 'FieldType' => 'string'),
        'LastUpdateTimestamp' => array('FieldValue' => null, 'FieldType' => 'string'),
        'ReasonCode' => array('FieldValue' => null, 'FieldType' => 'string'),
        'ReasonDescription' => array('FieldValue' => null, 'FieldType' => 'string'),
        );
        parent::__construct($data);
    }

        /**
     * Gets the value of the State property.
     *
     * @return string State
     */
    public function getState()
    {
        return $this->fields['State']['FieldValue'];
    }

    /**
     * Sets the value of the State property.
     *
     * @param string State
     * @return this instance
     */
    public function setState($value)
    {
        $this->fields['State']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the State and returns this instance
     *
     * @param string $value State
     * @return OffAmazonPaymentsNotifications_Model_OrderReferenceStatus instance
     */
    public function withState($value)
    {
        $this->setState($value);
        return $this;
    }

    /**
     * Checks if State is set
     *
     * @return bool true if State  is set
     */
    public function isSetState()
    {
        return !is_null($this->fields['State']['FieldValue']);
    }

    /**
     * Gets the value of the LastUpdateTimestamp property.
     *
     * @return string LastUpdateTimestamp
     */
    public function getLastUpdateTimestamp()
    {
        return $this->fields['LastUpdateTimestamp']['FieldValue'];
    }

    /**
     * Sets the value of the LastUpdateTimestamp property.
     *
     * @param string LastUpdateTimestamp
     * @return this instance
     */
    public function setLastUpdateTimestamp($value)
    {
        $this->fields['LastUpdateTimestamp']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the LastUpdateTimestamp and returns this instance
     *
     * @param string $value LastUpdateTimestamp
     * @return OffAmazonPaymentsNotifications_Model_OrderReferenceStatus instance
     */
    public function withLastUpdateTimestamp($value)
    {
        $this->setLastUpdateTimestamp($value);
        return $this;
    }

    /**
     * Checks if LastUpdateTimestamp is set
     *
     * @return bool true if LastUpdateTimestamp  is set
     */
    public function isSetLastUpdateTimestamp()
    {
        return !is_null($this->fields['LastUpdateTimestamp']['FieldValue']);
    }

    /**
     * Gets the value of the ReasonCode property.
     *
     * @return string ReasonCode
     */
    public function getReasonCode()
    {
        return $this->fields['ReasonCode']['FieldValue'];
    }

    /**
     * Sets the value of the ReasonCode property.
     *
     * @param string ReasonCode
     * @return this instance
     */
    public function setReasonCode($value)
    {
        $this->fields['ReasonCode']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the ReasonCode and returns this instance
     *
     * @param string $value ReasonCode
     * @return OffAmazonPaymentsNotifications_Model_OrderReferenceStatus instance
     */
    public function withReasonCode($value)
    {
        $this->setReasonCode($value);
        return $this;
    }

    /**
     * Checks if ReasonCode is set
     *
     * @return bool true if ReasonCode  is set
     */
    public function isSetReasonCode()
    {
        return !is_null($this->fields['ReasonCode']['FieldValue']);
    }

    /**
     * Gets the value of the ReasonDescription property.
     *
     * @return string ReasonDescription
     */
    public function getReasonDescription()
    {
        return $this->fields['ReasonDescription']['FieldValue'];
    }

    /**
     * Sets the value of the ReasonDescription property.
     *
     * @param string ReasonDescription
     * @return this instance
     */
    public function setReasonDescription($value)
    {
        $this->fields['ReasonDescription']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the ReasonDescription and returns this instance
     *
     * @param string $value ReasonDescription
     * @return OffAmazonPaymentsNotifications_Model_OrderReferenceStatus instance
     */
    public function withReasonDescription($value)
    {
        $this->setReasonDescription($value);
        return $this;
    }

    /**
     * Checks if ReasonDescription is set
     *
     * @return bool true if ReasonDescription  is set
     */
    public function isSetReasonDescription()
    {
        return !is_null($this->fields['ReasonDescription']['FieldValue']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from twisted.python import log

from buildbot.status import testresult
from buildbot.status.results import SUCCESS, FAILURE, WARNINGS, SKIPPED
from buildbot.process.buildstep import LogLineObserver, OutputProgressObserver
from buildbot.process.buildstep import RemoteShellCommand
from buildbot.steps.shell import ShellCommand

try:
    import cStringIO
    StringIO = cStringIO
except ImportError:
    import StringIO
import re

# BuildSteps that are specific to the Twisted source tree

class HLint(ShellCommand):
    """I run a 'lint' checker over a set of .xhtml files. Any deviations
    from recommended style is flagged and put in the output log.

    This step looks at .changes in the parent Build to extract a list of
    Lore XHTML files to check."""

    name = "hlint"
    description = ["running", "hlint"]
    descriptionDone = ["hlint"]
    warnOnWarnings = True
    warnOnFailure = True
    # TODO: track time, but not output
    warnings = 0

    def __init__(self, python=None, **kwargs):
        ShellCommand.__init__(self, **kwargs)
        self.addFactoryArguments(python=python)
        self.python = python

    def start(self):
        # create the command
        htmlFiles = {}
        for f in self.build.allFiles():
            if f.endswith(".xhtml") and not f.startswith("sandbox/"):
                htmlFiles[f] = 1
        # remove duplicates
        hlintTargets = htmlFiles.keys()
        hlintTargets.sort()
        if not hlintTargets:
            return SKIPPED
        self.hlintFiles = hlintTargets
        c = []
        if self.python:
            c.append(self.python)
        c += ["bin/lore", "-p", "--output", "lint"] + self.hlintFiles
        self.setCommand(c)

        # add an extra log file to show the .html files we're checking
        self.addCompleteLog("files", "\n".join(self.hlintFiles)+"\n")

        ShellCommand.start(self)

    def commandComplete(self, cmd):
        # TODO: remove the 'files' file (a list of .xhtml files that were
        # submitted to hlint) because it is available in the logfile and
        # mostly exists to give the user an idea of how long the step will
        # take anyway).
        lines = cmd.logs['stdio'].getText().split("\n")
        warningLines = filter(lambda line:':' in line, lines)
        if warningLines:
            self.addCompleteLog("warnings", "".join(warningLines))
        warnings = len(warningLines)
        self.warnings = warnings

    def evaluateCommand(self, cmd):
        # warnings are in stdout, rc is always 0, unless the tools break
        if cmd.rc != 0:
            return FAILURE
        if self.warnings:
            return WARNINGS
        return SUCCESS

    def getText2(self, cmd, results):
        if cmd.rc != 0:
            return ["hlint"]
        return ["%d hlin%s" % (self.warnings,
                               self.warnings == 1 and 't' or 'ts')]

def countFailedTests(output):
    # start scanning 10kb from the end, because there might be a few kb of
    # import exception tracebacks between the total/time line and the errors
    # line
    chunk = output[-10000:]
    lines = chunk.split("\n")
    lines.pop() # blank line at end
    # lines[-3] is "Ran NN tests in 0.242s"
    # lines[-2] is blank
    # lines[-1] is 'OK' or 'FAILED (failures=1, errors=12)'
    #  or 'FAILED (failures=1)'
    #  or "PASSED (skips=N, successes=N)"  (for Twisted-2.0)
    # there might be other lines dumped here. Scan all the lines.
    res = {'total': None,
           'failures': 0,
           'errors': 0,
           'skips': 0,
           'expectedFailures': 0,
           'unexpectedSuccesses': 0,
           }
    for l in lines:
        out = re.search(r'Ran (\d+) tests', l)
        if out:
            res['total'] = int(out.group(1))
        if (l.startswith("OK") or
            l.startswith("FAILED ") or
            l.startswith("PASSED")):
            # the extra space on FAILED_ is to distinguish the overall
            # status from an individual test which failed. The lack of a
            # space on the OK is because it may be printed without any
            # additional text (if there are no skips,etc)
            out = re.search(r'failures=(\d+)', l)
            if out: res['failures'] = int(out.group(1))
            out = re.search(r'errors=(\d+)', l)
            if out: res['errors'] = int(out.group(1))
            out = re.search(r'skips=(\d+)', l)
            if out: res['skips'] = int(out.group(1))
            out = re.search(r'expectedFailures=(\d+)', l)
            if out: res['expectedFailures'] = int(out.group(1))
            out = re.search(r'unexpectedSuccesses=(\d+)', l)
            if out: res['unexpectedSuccesses'] = int(out.group(1))
            # successes= is a Twisted-2.0 addition, and is not currently used
            out = re.search(r'successes=(\d+)', l)
            if out: res['successes'] = int(out.group(1))

    return res

class TrialTestCaseCounter(LogLineObserver):
    _line_re = re.compile(r'^(?:Doctest: )?([\w\.]+) \.\.\. \[([^\]]+)\]$')
    numTests = 0
    finished = False

    def outLineReceived(self, line):
        # different versions of Twisted emit different per-test lines with
        # the bwverbose reporter.
        #  2.0.0: testSlave (buildbot.test.test_runner.Create) ... [OK]
        #  2.1.0: buildbot.test.test_runner.Create.testSlave ... [OK]
        #  2.4.0: buildbot.test.test_runner.Create.testSlave ... [OK]
        # Let's just handle the most recent version, since it's the easiest.
        # Note that doctests create lines line this:
        #  Doctest: viff.field.GF ... [OK]

        if self.finished:
            return
        if line.startswith("=" * 40):
            self.finished = True
            return

        m = self._line_re.search(line.strip())
        if m:
            testname, result = m.groups()
            self.numTests += 1
            self.step.setProgress('tests', self.numTests)

UNSPECIFIED=() # since None is a valid choice

class Trial(ShellCommand):
    """
    There are some class attributes which may be usefully overridden
    by subclasses. 'trialMode' and 'trialArgs' can influence the trial
    command line.
    """

    name = "trial"
    progressMetrics = ('output', 'tests', 'test.log')
    # note: the slash only works on unix buildslaves, of course, but we have
    # no way to know what the buildslave uses as a separator.
    # TODO: figure out something clever.
    logfiles = {"test.log": "_trial_temp/test.log"}
    # we use test.log to track Progress at the end of __init__()

    flunkOnFailure = True
    python = None
    trial = "trial"
    trialMode = ["--reporter=bwverbose"] # requires Twisted-2.1.0 or newer
    # for Twisted-2.0.0 or 1.3.0, use ["-o"] instead
    trialArgs = []
    testpath = UNSPECIFIED # required (but can be None)
    testChanges = False # TODO: needs better name
    recurse = False
    reactor = None
    randomly = False
    tests = None # required

    def __init__(self, reactor=UNSPECIFIED, python=None, trial=None,
                 testpath=UNSPECIFIED,
                 tests=None, testChanges=None,
                 recurse=None, randomly=None,
                 trialMode=None, trialArgs=None,
                 **kwargs):
        """
        @type  testpath: string
        @param testpath: use in PYTHONPATH when running the tests. If
                         None, do not set PYTHONPATH. Setting this to '.' will
                         cause the source files to be used in-place.

        @type  python: string (without spaces) or list
        @param python: which python executable to use. Will form the start of
                       the argv array that will launch trial. If you use this,
                       you should set 'trial' to an explicit path (like
                       /usr/bin/trial or ./bin/trial). Defaults to None, which
                       leaves it out entirely (running 'trial args' instead of
                       'python ./bin/trial args'). Likely values are 'python',
                       ['python2.2'], ['python', '-Wall'], etc.

        @type  trial: string
        @param trial: which 'trial' executable to run.
                      Defaults to 'trial', which will cause $PATH to be
                      searched and probably find /usr/bin/trial . If you set
                      'python', this should be set to an explicit path (because
                      'python2.3 trial' will not work).

        @type trialMode: list of strings
        @param trialMode: a list of arguments to pass to trial, specifically
                          to set the reporting mode. This defaults to ['-to']
                          which means 'verbose colorless output' to the trial
                          that comes with Twisted-2.0.x and at least -2.1.0 .
                          Newer versions of Twisted may come with a trial
                          that prefers ['--reporter=bwverbose'].

        @type trialArgs: list of strings
        @param trialArgs: a list of arguments to pass to trial, available to
                          turn on any extra flags you like. Defaults to [].

        @type  tests: list of strings
        @param tests: a list of test modules to run, like
                      ['twisted.test.test_defer', 'twisted.test.test_process'].
                      If this is a string, it will be converted into a one-item
                      list.

        @type  testChanges: boolean
        @param testChanges: if True, ignore the 'tests' parameter and instead
                            ask the Build for all the files that make up the
                            Changes going into this build. Pass these filenames
                            to trial and ask it to look for test-case-name
                            tags, running just the tests necessary to cover the
                            changes.

        @type  recurse: boolean
        @param recurse: If True, pass the --recurse option to trial, allowing
                        test cases to be found in deeper subdirectories of the
                        modules listed in 'tests'. This does not appear to be
                        necessary when using testChanges.

        @type  reactor: string
        @param reactor: which reactor to use, like 'gtk' or 'java'. If not
                        provided, the Twisted's usual platform-dependent
                        default is used.

        @type  randomly: boolean
        @param randomly: if True, add the --random=0 argument, which instructs
                         trial to run the unit tests in a random order each
                         time. This occasionally catches problems that might be
                         masked when one module always runs before another
                         (like failing to make registerAdapter calls before
                         lookups are done).

        @type  kwargs: dict
        @param kwargs: parameters. The following parameters are inherited from
                       L{ShellCommand} and may be useful to set: workdir,
                       haltOnFailure, flunkOnWarnings, flunkOnFailure,
                       warnOnWarnings, warnOnFailure, want_stdout, want_stderr,
                       timeout.
        """
        ShellCommand.__init__(self, **kwargs)
        self.addFactoryArguments(reactor=reactor,
                                 python=python,
                                 trial=trial,
                                 testpath=testpath,
                                 tests=tests,
                                 testChanges=testChanges,
                                 recurse=recurse,
                                 randomly=randomly,
                                 trialMode=trialMode,
                                 trialArgs=trialArgs,
                                 )

        if python:
            self.python = python
        if self.python is not None:
            if type(self.python) is str:
                self.python = [self.python]
            for s in self.python:
                if " " in s:
                    # this is not strictly an error, but I suspect more
                    # people will accidentally try to use python="python2.3
                    # -Wall" than will use embedded spaces in a python flag
                    log.msg("python= component '%s' has spaces")
                    log.msg("To add -Wall, use python=['python', '-Wall']")
                    why = "python= value has spaces, probably an error"
                    raise ValueError(why)

        if trial:
            self.trial = trial
        if " " in self.trial:
            raise ValueError("trial= value has spaces")
        if trialMode is not None:
            self.trialMode = trialMode
        if trialArgs is not None:
            self.trialArgs = trialArgs

        if testpath is not UNSPECIFIED:
            self.testpath = testpath
        if self.testpath is UNSPECIFIED:
            raise ValueError("You must specify testpath= (it can be None)")
        assert isinstance(self.testpath, str) or self.testpath is None

        if reactor is not UNSPECIFIED:
            self.reactor = reactor

        if tests is not None:
            self.tests = tests
        if type(self.tests) is str:
            self.tests = [self.tests]
        if testChanges is not None:
            self.testChanges = testChanges
            #self.recurse = True  # not sure this is necessary

        if not self.testChanges and self.tests is None:
            raise ValueError("Must either set testChanges= or provide tests=")

        if recurse is not None:
            self.recurse = recurse
        if randomly is not None:
            self.randomly = randomly

        # build up most of the command, then stash it until start()
        command = []
        if self.python:
            command.extend(self.python)
        command.append(self.trial)
        command.extend(self.trialMode)
        if self.recurse:
            command.append("--recurse")
        if self.reactor:
            command.append("--reactor=%s" % reactor)
        if self.randomly:
            command.append("--random=0")
        command.extend(self.trialArgs)
        self.command = command

        if self.reactor:
            self.description = ["testing", "(%s)" % self.reactor]
            self.descriptionDone = ["tests"]
            # commandComplete adds (reactorname) to self.text
        else:
            self.description = ["testing"]
            self.descriptionDone = ["tests"]

        # this counter will feed Progress along the 'test cases' metric
        self.addLogObserver('stdio', TrialTestCaseCounter())
        # this one just measures bytes of output in _trial_temp/test.log
        self.addLogObserver('test.log', OutputProgressObserver('test.log'))

    def setupEnvironment(self, cmd):
        ShellCommand.setupEnvironment(self, cmd)
        if self.testpath != None:
            e = cmd.args['env']
            if e is None:
                cmd.args['env'] = {'PYTHONPATH': self.testpath}
            else:
                # TODO: somehow, each build causes another copy of
                # self.testpath to get prepended
                if e.get('PYTHONPATH', "") == "":
                    e['PYTHONPATH'] = self.testpath
                else:
                    e['PYTHONPATH'] = self.testpath + ":" + e['PYTHONPATH']
        try:
            p = cmd.args['env']['PYTHONPATH']
            if type(p) is not str:
                log.msg("hey, not a string:", p)
                assert False
        except (KeyError, TypeError):
            # KeyError if args doesn't have ['env']
            # KeyError if args['env'] doesn't have ['PYTHONPATH']
            # TypeError if args is None
            pass

    def start(self):
        # now that self.build.allFiles() is nailed down, finish building the
        # command
        if self.testChanges:
            for f in self.build.allFiles():
                if f.endswith(".py"):
                    self.command.append("--testmodule=%s" % f)
        else:
            self.command.extend(self.tests)
        log.msg("Trial.start: command is", self.command)

        # if our slave is too old to understand logfiles=, fetch them
        # manually. This is a fallback for the Twisted buildbot and some old
        # buildslaves.
        self._needToPullTestDotLog = False
        if self.slaveVersionIsOlderThan("shell", "2.1"):
            log.msg("Trial: buildslave %s is too old to accept logfiles=" %
                    self.getSlaveName())
            log.msg(" falling back to 'cat _trial_temp/test.log' instead")
            self.logfiles = {}
            self._needToPullTestDotLog = True

        ShellCommand.start(self)

    def commandComplete(self, cmd):
        if not self._needToPullTestDotLog:
            return self._gotTestDotLog(cmd)

        # if the buildslave was too old, pull test.log now
        catcmd = ["cat", "_trial_temp/test.log"]
        c2 = RemoteShellCommand(command=catcmd, workdir=self.workdir)
        loog = self.addLog("test.log")
        c2.useLog(loog, True, logfileName="stdio")
        self.cmd = c2 # to allow interrupts
        d = c2.run(self, self.remote)
        d.addCallback(lambda res: self._gotTestDotLog(cmd))
        return d

    def rtext(self, fmt='%s'):
        if self.reactor:
            rtext = fmt % self.reactor
            return rtext.replace("reactor", "")
        return ""

    def _gotTestDotLog(self, cmd):
        # figure out all status, then let the various hook functions return
        # different pieces of it

        # 'cmd' is the original trial command, so cmd.logs['stdio'] is the
        # trial output. We don't have access to test.log from here.
        output = cmd.logs['stdio'].getText()
        counts = countFailedTests(output)

        total = counts['total']
        failures, errors = counts['failures'], counts['errors']
        parsed = (total != None)
        text = []
        text2 = ""

        if cmd.rc == 0:
            if parsed:
                results = SUCCESS
                if total:
                    text += ["%d %s" % \
                             (total,
                              total == 1 and "test" or "tests"),
                             "passed"]
                else:
                    text += ["no tests", "run"]
            else:
                results = FAILURE
                text += ["testlog", "unparseable"]
                text2 = "tests"
        else:
            # something failed
            results = FAILURE
            if parsed:
                text.append("tests")
                if failures:
                    text.append("%d %s" % \
                                (failures,
                                 failures == 1 and "failure" or "failures"))
                if errors:
                    text.append("%d %s" % \
                                (errors,
                                 errors == 1 and "error" or "errors"))
                count = failures + errors
                text2 = "%d tes%s" % (count, (count == 1 and 't' or 'ts'))
            else:
                text += ["tests", "failed"]
                text2 = "tests"

        if counts['skips']:
            text.append("%d %s" %  \
                        (counts['skips'],
                         counts['skips'] == 1 and "skip" or "skips"))
        if counts['expectedFailures']:
            text.append("%d %s" %  \
                        (counts['expectedFailures'],
                         counts['expectedFailures'] == 1 and "todo"
                         or "todos"))
            if 0: # TODO
                results = WARNINGS
                if not text2:
                    text2 = "todo"

        if 0:
            # ignore unexpectedSuccesses for now, but it should really mark
            # the build WARNING
            if counts['unexpectedSuccesses']:
                text.append("%d surprises" % counts['unexpectedSuccesses'])
                results = WARNINGS
                if not text2:
                    text2 = "tests"

        if self.reactor:
            text.append(self.rtext('(%s)'))
            if text2:
                text2 = "%s %s" % (text2, self.rtext('(%s)'))

        self.results = results
        self.text = text
        self.text2 = [text2]

    def addTestResult(self, testname, results, text, tlog):
        if self.reactor is not None:
            testname = (self.reactor,) + testname
        tr = testresult.TestResult(testname, results, text, logs={'log': tlog})
        #self.step_status.build.addTestResult(tr)
        self.build.build_status.addTestResult(tr)

    def createSummary(self, loog):
        output = loog.getText()
        problems = ""
        sio = StringIO.StringIO(output)
        warnings = {}
        while 1:
            line = sio.readline()
            if line == "":
                break
            if line.find(" exceptions.DeprecationWarning: ") != -1:
                # no source
                warning = line # TODO: consider stripping basedir prefix here
                warnings[warning] = warnings.get(warning, 0) + 1
            elif (line.find(" DeprecationWarning: ") != -1 or
                line.find(" UserWarning: ") != -1):
                # next line is the source
                warning = line + sio.readline()
                warnings[warning] = warnings.get(warning, 0) + 1
            elif line.find("Warning: ") != -1:
                warning = line
                warnings[warning] = warnings.get(warning, 0) + 1

            if line.find("=" * 60) == 0 or line.find("-" * 60) == 0:
                problems += line
                problems += sio.read()
                break

        if problems:
            self.addCompleteLog("problems", problems)
            # now parse the problems for per-test results
            pio = StringIO.StringIO(problems)
            pio.readline() # eat the first separator line
            testname = None
            done = False
            while not done:
                while 1:
                    line = pio.readline()
                    if line == "":
                        done = True
                        break
                    if line.find("=" * 60) == 0:
                        break
                    if line.find("-" * 60) == 0:
                        # the last case has --- as a separator before the
                        # summary counts are printed
                        done = True
                        break
                    if testname is None:
                        # the first line after the === is like:
# EXPECTED FAILURE: testLackOfTB (twisted.test.test_failure.FailureTestCase)
# SKIPPED: testRETR (twisted.test.test_ftp.TestFTPServer)
# FAILURE: testBatchFile (twisted.conch.test.test_sftp.TestOurServerBatchFile)
                        r = re.search(r'^([^:]+): (\w+) \(([\w\.]+)\)', line)
                        if not r:
                            # TODO: cleanup, if there are no problems,
                            # we hit here
                            continue
                        result, name, case = r.groups()
                        testname = tuple(case.split(".") + [name])
                        results = {'SKIPPED': SKIPPED,
                                   'EXPECTED FAILURE': SUCCESS,
                                   'UNEXPECTED SUCCESS': WARNINGS,
                                   'FAILURE': FAILURE,
                                   'ERROR': FAILURE,
                                   'SUCCESS': SUCCESS, # not reported
                                   }.get(result, WARNINGS)
                        text = result.lower().split()
                        loog = line
                        # the next line is all dashes
                        loog += pio.readline()
                    else:
                        # the rest goes into the log
                        loog += line
                if testname:
                    self.addTestResult(testname, results, text, loog)
                    testname = None

        if warnings:
            lines = warnings.keys()
            lines.sort()
            self.addCompleteLog("warnings", "".join(lines))

    def evaluateCommand(self, cmd):
        return self.results

    def getText(self, cmd, results):
        return self.text
    def getText2(self, cmd, results):
        return self.text2

class RemovePYCs(ShellCommand):
    name = "remove-.pyc"
    command = ['find', '.', '-name', '*.pyc', '-exec', 'rm', '{}', ';']
    description = ["removing", ".pyc", "files"]
    descriptionDone = ["remove", ".pycs"]


text:
package transport.javascript

import transport._
import scala.concurrent._
import scala.util._
import scala.scalajs.js
import org.scalajs.dom._
import jsapi._

/** WebSocket JavaScript client using the native browser implementation.
 *
 *  Usage example:
 *  {{{
 *  new WebSocketClient().connect(url).foreach { connection =>
 *    connection.handlerPromise.success { string => println("Recived: " + string) }
 *    connection.write("Hello WebSocket!")
 *  }
 *  }}}
 */
class WebSocketClient(implicit ec: ExecutionContext) extends WebSocketTransport {
  def listen(): Future[Promise[ConnectionListener]] =
    Future.failed(new UnsupportedOperationException(
      "Browsers can only initiate WebSockets connections."))

  def connect(remote: WebSocketUrl): Future[ConnectionHandle] = {
    val connectionPromise = Promise[ConnectionHandle]()

    new ConnectionHandle {
      val webSocket = new WebSocket(remote.url)
      val closePromise = Promise[Unit]()
      val promise = QueueablePromise[MessageListener]()

      webSocket.onopen = { event: Event =>
        connectionPromise.success(this)
      }
      webSocket.onmessage = { event: MessageEvent =>
        promise.queue(_(event.data.toString))
      }
      webSocket.onclose = { event: CloseEvent =>
        closePromise.trySuccess(())
      }
      webSocket.onerror = { event: ErrorEvent =>
        val message = try { event.message.toString } catch { case e: ClassCastException => "" }
        closePromise.tryFailure(WebSocketException(message))
      }

      def handlerPromise: Promise[MessageListener] = promise
      def closedFuture: Future[Unit] = closePromise.future
      def write(outboundPayload: String): Unit = webSocket.send(outboundPayload)
      def close(): Unit = webSocket.close()
    }

    connectionPromise.future
  }

  def shutdown(): Future[Unit] = Future.successful(Unit)
}


text:
from stompy.stomp import Stomp
from Queue import Empty
from uuid import uuid4

class TransactionError(Exception):
    """Transaction related error."""

class Client(object):
    """Simple STOMP client.

    :keyword host: Hostname of the server to connect to (default:
        ``localhost``)
    :keyword port: Port of the server to connect to (default: ``61613``)

    Example

        >>> from stompy.simple import Client
        >>> stomp = Client()
        >>> stomp.connect()
        >>> stomp.put("The quick brown fox...", destination="/queue/test")
        >>> stomp.subscribe("/queue/test")
        >>> message = stomp.get_nowait()
        >>> message.body
        'The quick brown fox...'
        >>> stomp.ack(message)
        >>> stomp.unsubscribe("/queue/test")
        >>> stomp.disconnect()

    """
    Empty = Empty

    def __init__(self, host="localhost", port=61613):
        self.stomp = Stomp(host, port)
        self._current_transaction = None

    def get(self, block=True, callback=None):
        """Get message.

        :keyword block: Block if necessary until an item is available.
            If this is ``False``, return an item if one is immediately
            available, else raise the :exc:`Empty` exception.

        :keyword callback: Optional function to execute when message recieved.

        :raises Empty: If ``block`` is off and no message was receied.

        """
        frame = self.stomp.receive_frame(nonblocking=not block, callback=callback)
        if frame is None and not block:
            raise self.Empty()
        return frame

    def get_nowait(self):
        """Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the :exc:`Empty` exception.

        See :meth:`get`.

        """
        return self.get(block=False)

    def put(self, item, destination, persistent=True, conf=None,receipt=True):
        """Put an item into the queue.

        :param item: Body of the message.
        :param destination: Destination queue.
        :keyword persistent: Is message persistent? (store on disk).
        :keyword conf: Extra headers to send to the broker.

        :returns: The resulting :class:`stompy.frame.Frame` instance.

        """
        persistent = "true" if persistent else "false"
        conf = self._make_conf(conf, body=item, destination=destination,
                               persistent=persistent)

        return self.stomp.send(conf,receipt)

    def connect(self, username=None, password=None, clientid=None):
        """Connect to the broker.

        :keyword username: Username for connection
        :keyword password: Password for connection
        :keyword clientid: Client identification for persistent connections

        :raises :exc:`stompy.stomp.ConnectionError`:
            if the connection was unsuccessful.
        :raises :exc:`stompy.stomp.ConnectionTimeoutError`:
            if the connection timed out.

        """
        self.stomp.connect(username=username, password=password, clientid=clientid)

    def disconnect(self):
        """Disconnect from the broker."""
        self.stomp.disconnect()

    def subscribe(self, destination, ack="auto", conf=None):
        """Subscribe to topic/queue.

        :param destination: The destination queue/topic to subscribe to.
        :keyword ack: How to handle acknowledgment, either
            ``auto`` - ack is handled by the server automatically, or
            ``client`` - ack is handled by the client itself by calling
            :meth:`ack`.
        :keyword conf: Additional headers to send with the subscribe request.

        """
        conf = self._make_conf(conf, destination=destination, ack=ack)
        return self.stomp.subscribe(conf)

    def unsubscribe(self, destination, conf=None):
        """Unsubscribe from topic/queue previously subscribed to.

        :param destination: The destination queue/topic to unsubscribe from.
        :keyword conf: Additional headers to send with the unsubscribe
            request.

        """
        conf = self._make_conf(conf, destination=destination)
        return self.stomp.unsubscribe(conf)

    def begin(self, transaction):
        """Begin transaction.

        Every :meth:`ack` and :meth:`send` will be affected by this
        transaction and won't be real until a :meth:`commit` is issued.
        To roll-back any changes since the transaction started use
        :meth:`abort`.

        """
        if self._current_transaction:
            raise TransactionError(
                "Already in transaction. Please commit or abort first!")
        self._current_transaction = str(uuid4())
        return self.stomp.begin({"transaction": self._current_transaction})

    def commit(self, transaction):
        """Commit current transaction."""
        if not self._current_transaction:
            raise TransactionError("Not in transaction")
        self.stomp.commit({"transaction": self._current_transaction})
        self._current_transaction = None

    def abort(self):
        """Roll-back current transaction."""
        if not self._current_transaction:
            raise TransactionError("Not in transaction")
        self.stomp.abort({"transaction": self._current_transaction})
        self._current_transaction = None

    def ack(self, frame):
        """Acknowledge message.

        :param frame: The message to acknowledge.

        """
        return self.stomp.ack(frame)

    def _make_conf(self, conf, **kwargs):
        kwargs.update(dict(conf or {}))
        if self._current_transaction:
            conf["transaction"] = self._current_transaction
        return kwargs


text:
function currentUser(request)
  return currentUserFromHeaders(request.headers)
end

-- determine the current user from the session information
-- stored in webservice or websocket request headers.
-- returns user table or nil if no user is contained
-- in headers
function currentUserFromHeaders(headers)
  if type(headers.cookie) ~= "string" then
    return nil
  end
  local _, _, sid = string.find(headers.cookie, "sid=([^;]+)")
  if type(sid) ~= "string" then
    return nil
  end
  local user = User.getCurrentUser({token = sid})
  if user ~= nil and user.id ~= nil then
    user.token = sid
    return user
  end
  return nil
end

function table.contains(table, element)
  for _, value in pairs(table) do
    if value == element then
      return true
    end
  end
  return false
end

-- default a particular key in a table to value
-- if that index already exists, otherwise does nothing.
function default(t, key, defaultValue)
  if not table.contains(t, key) then
    t[key] = defaultValue
  end
end

function kv_read(sn)
  return kv_read_opt(sn, true)
end
-- read the latest values for a lightbulb device
-- from the key value cache and from One Platform
--
-- if first variable arg is true, device will be read for
-- any nil values so their latest state is available
-- to the UI.
function kv_read_opt(sn, readDevice)
  local resp = Keystore.get({key = "identifier_" .. sn})
  local device = nil
  if type(resp) == "table" and type(resp.value) == "string" then
    -- device has written. Get the latest written values
    -- and look up everything else.
    device = from_json(resp.value)

    if device ~= nil then
      -- backward compatibility with old example versions
      if not table.contains(device, 'rid') then
        device.rid = lookup_rid(device.pid, sn)
      end

      if readDevice then
        -- if any resource values haven't been written in
        -- fetch the last value via the Device service
        if device.temperature == nil or device.humidity == nil or device.state == nil or
           device.temperature == 'undefined' or device.humidity == 'undefined' or device.state == 'undefined' then
          temperature, humidity, state = device_read(device.pid, device.rid)
          device.temperature = temperature
          device.humidity = humidity
          device.state = state
          --default(device, 'temperature', temperature)
          --default(device, 'humidity', humidity)
          --default(device, 'state', state)
        end
      end
    end
  end

  return device
end

-- store device settings to the key value store
function kv_write(sn, values)
  Keystore.set({key = "identifier_" .. sn, value = to_json(values)})
end

-- return the device's temperature, humidity, state
function device_read(pid, rid)
  calls = {}
  for k, alias in pairs({'temperature', 'humidity', 'state'}) do
    table.insert(calls, {id=alias, procedure="read", arguments={{alias=alias}, {limit=1}}})
  end
  local rpcret = Device.rpcCall({
    pid = pid,
    auth = {client_id = rid},
    calls = calls})

  -- find and extract the read value from RPC response rpcret
  function get_read_result(alias)
    for k, r in pairs(rpcret) do
      if r.id == alias then
        if table.getn(r.result) > 0 then
          -- get the value part of the data point
          return r.result[1][2]
        else
          return nil
        end
      end
    end
  end
  temperature = get_read_result('temperature')
  humidity = get_read_result('humidity')
  state = get_read_result('state')
  return temperature, humidity, state
end

-- return rid for device, or nil if there is an error
function lookup_rid(pid, sn)
  if pid == nil then
    -- device needs to send data first
    return nil
  end
  local ret = Device.rpcCall({pid = pid, calls = {{
    id = "1",
    procedure = "lookup",
    arguments = {"alias", tostring(sn)}
  }}})
  if type(ret) ~= "table" then
    return "error in lookup rpc call"
  end
  if ret[1].status ~= "ok" then
    -- "error in lookup: "..ret[1].result
    return nil
  end
  return ret[1].result
end

function deviceRpcCall(sn, procedure, args)
  local device = kv_read(sn)
  if device.pid == nil then
    return "device needs to send data first"
  end
  local ret = Device.rpcCall({pid = device.pid, auth = {client_id = device.rid}, calls = {{
    id = "1",
    procedure = procedure,
    arguments = args
  }}})
  return ret[1]
end

function write(sn, alias, value)
  return deviceRpcCall(sn, "write", {
    {alias = alias},
    value
  })
end

http_error_codes = {
  [400] = {
    code = 400,
    message = "Bad Request",
    headers = {}
  },
  [403] = {
    code = 403,
    message = "Permission Denied",
    headers = {}
  },
  [404] = {
    code = 404,
    message = "Not Found",
    headers = {}
  }
}

function http_error(code, response)
  if http_error_codes[code] ~= nil then
    for key, value in pairs(http_error_codes[code]) do
      response[key] = value
    end
  else
    response.code = code
    response.message = "No prepared message for this code"
  end
end

function trigger(alert, timerid)
  Timer.sendAfter({
    message = alert.message,
    duration = alert.timer * 60 * 1000,
    timer_id = timerid
  })
  alert.timer_running = true
  alert.timer_id = timerid
end

function cancel_trigger(alert)
  Timer.cancel({timer_id = alert.timer_id})
  alert.timer_running = false
end


text:
class AddHasProfilePicToProfile < ActiveRecord::Migration[5.1]
  def up
    add_column :profiles, :has_profile_pic, :boolean, default: false
    Profile.all.each{ |p|
      if p.image.present?
        unless p.image[:original].original_filename == 'default.png'
          p.has_profile_pic = true
          p.save
        end
      end
    }
  end
  def down
    remove_column :profiles, :has_profile_pic
  end
end


text:
<?php

namespace Airavata\Facades;

use Illuminate\Support\Facades\Facade;

class IamAdminServices extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'iam_admin_services'; }

}


text:
:: Got this file by email from Twangboy
copy patch_for_nsis__version_3000_req.txt    ..\salt\pkg\windows\req.txt


text:
package com.mooveit.fakeit.models;

import android.databinding.BaseObservable;
import android.databinding.ObservableField;

public class RickAndMortyData extends BaseObservable {

    public final ObservableField<String> rickAndMortyCharacter = new ObservableField<>();
    public final ObservableField<String> rickAndMortyLocation = new ObservableField<>();
    public final ObservableField<String> rickAndMortyQuote = new ObservableField<>();
}


text:
  @foreach ($block->items as $i)

id}}" data-model="GalleryItem">
      url.'?w=1400&nu')}}" @if ($i->credit or $i->description()) data-sub-html=".caption" @endif>
        url.'?w=200&h=200&nu')}}">
        @if ($i->credit or $i->description())

            {!! $i->description() !!}
            @if ($i->credit and $i->description())
 @endif
            @if ($i->credit) ©{{$i->credit}} @endif

        @endif

   {{--

        @if ($i->credit) ©{{$i->credit}} @endif

--}}

  @endforeach

@if (!Auth::guest() && Auth::user()->isAdmin())

    <button class="btn btn-default btn-red" data-toggle="redmodal" data-url='add?model=GalleryItem&data={"gallery_id":{{$block->id}}}' title="Add picture">
       Add picture
    </button>
    Drag and drop to order pictures.

@endif

@push('head')
  <link type="text/css" rel="stylesheet" href="{{url('bower_components/lightgallery/dist/css/lightgallery.min.css')}}" />
@endpush

@push('scripts')

@endpush


text:
package com.ajjpj.adiagram_.ui

import com.ajjpj.adiagram_.ui.fw.{JavaFxHelper, Digest}
import javafx.scene.canvas.Canvas
import com.ajjpj.adiagram_.render.base.PartialImageWithShadow
import com.ajjpj.adiagram_.geometry.APoint
import com.ajjpj.adiagram_.ui.mouse.MouseTracker
import com.ajjpj.adiagram_.model.diagram.{ShapeSpecReRenderSnapshot, AShapeSpec, ADiagram}
import com.ajjpj.adiagram_.model.SelectedStyles
import com.ajjpj.adiagram_.model.style.AStyleRepository
import java.io.File
import javafx.stage.Stage
import com.ajjpj.adiagram_.ui.presentation.{ShapePresentationHelper, CanvasWithDerivedZOrder, DiagramRootContainer}

/**
 * @author arno
 */
class ADiagramController (val root: DiagramRootContainer, val diagram: ADiagram, val styleRepository: AStyleRepository, val selectedStyles: SelectedStyles, var file: Option[File])(implicit val digest: Digest) {
  var zoom = Zoom.Identity

  def isDirty = digest.undoRedo.hasUndo
  def isPristine = file.isEmpty && ! isDirty

  def windowTitle = "A-Diagram - " + (file match {
    case Some(f) => f.getName
    case None => "<New Diagram>"
  }) + (if (isDirty) "*" else "")

  def window = root.getScene.getWindow.asInstanceOf[Stage]

  val selections = new SelectionTracker(diagram, root, this)
  val mouseTracker = new MouseTracker(this)

  private var detailsByElement = Map[AShapeSpec, RenderDetails]()

  digest.registerPostprocessor(updatePresentation)

  private def updatePresentation() {
    def unregisterElement(spec: AShapeSpec) {
      root.getChildren.removeAll(detailsByElement(spec).shapeCanvas, detailsByElement(spec).shadowCanvas)
      detailsByElement -= spec
    }

    def registerElement(spec: AShapeSpec) {
      val details = RenderDetails(-1, new CanvasWithDerivedZOrder(spec), new Canvas(), APoint.ZERO, APoint.ZERO, null)
      root.getChildren.addAll(details.shapeCanvas, details.shadowCanvas)
      detailsByElement += (spec -> details)
    }

    def render(spec: AShapeSpec) = {
      val zoomSnapshot = zoom

      def render: PartialImageWithShadow = spec.shape.render(zoomSnapshot)

      val snapshotCurrentlyRendered = SnapshotWithZoom(zoomSnapshot, spec.snapshot)
      if(detailsByElement(spec).snapshot != snapshotCurrentlyRendered) {
        val counterSnapshot = spec.changeCounter

        JavaFxHelper.inBackgroundNoDigest(render, (pi: PartialImageWithShadow) => {
          detailsByElement.get(spec) match {
            //TODO change '<=' to '<' : Problem is repaint of bound lines
            case Some(details) if details.changeCounter <= counterSnapshot =>
              ShapePresentationHelper.drawShapeOnCanvas(pi, spec.pos, details.shapeCanvas, details.shadowCanvas, zoom)
              detailsByElement += (spec -> details.copy(
                snapshot = snapshotCurrentlyRendered,
                changeCounter = counterSnapshot,
                shapeOffset = pi.shape.renderOffset,
                shadowOffset = pi.shadow.map(_.renderOffset).getOrElse(APoint.ZERO)
              ))
            case None =>
          }
        }) // no changes are performed in this UI callback --> no need for events to be triggered
      }
    }

    def refreshPos(spec: AShapeSpec) = {
      val details = detailsByElement(spec)
      ShapePresentationHelper.refreshPos(details.shapeCanvas, details.shadowCanvas, spec.pos, details.shapeOffset, details.shadowOffset, zoom)
    }

    // deal with added and removed elements
    detailsByElement.keys.filterNot(diagram.elements.       contains).foreach(unregisterElement)
    diagram.elements.     filterNot(detailsByElement.keySet.contains).foreach(registerElement)

    // update changed elements
    //TODO work with snapshots, re-render only changed elements
    diagram.elements.foreach (render)
    diagram.elements.foreach (refreshPos)
  }

  private case class SnapshotWithZoom (zoom: Zoom, snapshot: ShapeSpecReRenderSnapshot)

  private case class RenderDetails(changeCounter: Int, shapeCanvas: Canvas, shadowCanvas: Canvas, shapeOffset: APoint, shadowOffset: APoint, snapshot: SnapshotWithZoom)
}


text:
<?php

namespace Phalcon\Db {

    /**
     * Phalcon\Db\Exception
     *
     * Exceptions thrown in Phalcon\Db will use this class
     *
     */
    class Exception extends \Phalcon\Exception
    {
    }
}


text:
<?php

class Etailer_Backorders_Model_Observer_Adminhtml
{

    public function addColumnsToGrid($observer)
    {
        $block = $observer->getBlock();

        if ($block instanceof Mage_Adminhtml_Block_Catalog_Product_Grid
            || $block instanceof Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config_Grid
            || ($block instanceof Mage_Adminhtml_Block_Widget_Grid && $block->getNameInLayout() === 'category.product.grid')
        ) {
            $block->addColumnAfter('min_qty',
                array(
                    'header'=> Mage::helper('catalog')->__('Backorderable'),
                    'type'  => 'number',
                    'index' => 'min_qty',
                    'width' => '50px'
            ), 'qty');
        }
    }

    public function joinFieldsToCollection($observer)
    {
        $collection = $observer->getCollection();
        $collection->joinField('min_qty',
                'cataloginventory/stock_item',
                'min_qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left');
    }

}


text:
var assert = chai.assert

afterEach(function () {
    // destroy and remove all spinners
    $("input[type='number']").inputSpinner("destroy")
    $("input").remove()
})

describe('bootstrap-input-spinner', function () {
    it('Should display the spinner', function () {
        addInput()
        $("input[type='number']").inputSpinner()
    })
    // TODO more testing
})

function addInput() {
    var testContainer = document.getElementById("testContainer")
    var input = document.createElement("input")
    input.type = "number"
    testContainer.append(input)
}


text:
package com.morgoo.droidplugin.hook.proxy;

import android.content.Context;
import android.util.AndroidRuntimeException;

import com.morgoo.droidplugin.hook.BaseHookHandle;
import com.morgoo.droidplugin.hook.handle.IActivityManagerHookHandle;
import com.morgoo.droidplugin.reflect.FieldUtils;
import com.morgoo.droidplugin.reflect.Utils;
import com.morgoo.helper.Log;
import com.morgoo.helper.MyProxy;
import com.morgoo.helper.compat.ActivityManagerNativeCompat;
import com.morgoo.helper.compat.IActivityManagerCompat;
import com.morgoo.helper.compat.SingletonCompat;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * Hook some function on IActivityManager
 * <p/>
 * Code by Andy Zhang (zhangyong232@gmail.com) on 15/2/7.
 */
public class IActivityManagerHook extends ProxyHook {

    private static final String TAG = IActivityManagerHook.class.getSimpleName();

    public IActivityManagerHook(Context hostContext) {
        super(hostContext);
    }

    @Override
    public BaseHookHandle createHookHandle() {
        return new IActivityManagerHookHandle(mHostContext);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return super.invoke(proxy, method, args);
        } catch (SecurityException e) {
            String msg = String.format("msg[%s],args[%s]", e.getMessage(), Arrays.toString(args));
            SecurityException e1 = new SecurityException(msg);
            e1.initCause(e);
            throw e1;
        }
    }

    @Override
    public void onInstall(ClassLoader classLoader) throws Throwable {
        Class cls = ActivityManagerNativeCompat.Class();
        Object obj = FieldUtils.readStaticField(cls, "gDefault");
        if (obj == null) {
            ActivityManagerNativeCompat.getDefault();
            obj = FieldUtils.readStaticField(cls, "gDefault");
        }

        if (IActivityManagerCompat.isIActivityManager(obj)) {
            setOldObj(obj);
            Class<?> objClass = mOldObj.getClass();
            List<Class<?>> interfaces = Utils.getAllInterfaces(objClass);
            Class[] ifs = interfaces != null && interfaces.size() > 0 ? interfaces.toArray(new Class[interfaces.size()]) : new Class[0];
            Object proxiedActivityManager = MyProxy.newProxyInstance(objClass.getClassLoader(), ifs, this);
            FieldUtils.writeStaticField(cls, "gDefault", proxiedActivityManager);
            Log.i(TAG, "Install ActivityManager Hook 1 old=%s,new=%s", mOldObj, proxiedActivityManager);
        } else if (SingletonCompat.isSingleton(obj)) {
            Object obj1 = FieldUtils.readField(obj, "mInstance");
            if (obj1 == null) {
                SingletonCompat.get(obj);
                obj1 = FieldUtils.readField(obj, "mInstance");
            }
            setOldObj(obj1);
            List<Class<?>> interfaces = Utils.getAllInterfaces(mOldObj.getClass());
            Class[] ifs = interfaces != null && interfaces.size() > 0 ? interfaces.toArray(new Class[interfaces.size()]) : new Class[0];
            final Object object = MyProxy.newProxyInstance(mOldObj.getClass().getClassLoader(), ifs, IActivityManagerHook.this);
            Object iam1 = ActivityManagerNativeCompat.getDefault();

            //这里先写一次,防止后面找不到Singleton类导致的挂钩子失败的问题。
            FieldUtils.writeField(obj, "mInstance", object);

            //这里使用方式1,如果成功的话,会导致上面的写操作被覆盖。
            FieldUtils.writeStaticField(cls, "gDefault", new android.util.Singleton<Object>() {
                @Override
                protected Object create() {
                    Log.e(TAG, "Install ActivityManager 3 Hook  old=%s,new=%s", mOldObj, object);
                    return object;
                }
            });

            Log.i(TAG, "Install ActivityManager Hook 2 old=%s,new=%s", mOldObj.toString(), object);
            Object iam2 = ActivityManagerNativeCompat.getDefault();
            // 方式2
            if (iam1 == iam2) {
                //这段代码是废的,没啥用,写这里只是不想改而已。
                FieldUtils.writeField(obj, "mInstance", object);
            }
        } else {
            throw new AndroidRuntimeException("Can not install IActivityManagerNative hook");
        }
    }
}


text:
package api_server

import (
	"fmt"

	workflowapi "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
	"github.com/go-openapi/strfmt"
	runparams "github.com/kubeflow/pipelines/backend/api/go_http_client/run_client/run_service"
	runmodel "github.com/kubeflow/pipelines/backend/api/go_http_client/run_model"
)

const (
	RunForDefaultTest     = "RUN_DEFAULT"
	RunForClientErrorTest = "RUN_CLIENT_ERROR"
)

func getDefaultRun(id string, name string) *runmodel.APIRunDetail {
	return &runmodel.APIRunDetail{
		PipelineRuntime: &runmodel.APIPipelineRuntime{WorkflowManifest: getDefaultWorkflowAsString()},
		Run: &runmodel.APIRun{
			CreatedAt: strfmt.NewDateTime(),
			ID:        id,
			Name:      name,
			Metrics:   []*runmodel.APIRunMetric{},
		},
	}
}

type RunClientFake struct{}

func NewRunClientFake() *RunClientFake {
	return &RunClientFake{}
}

func (c *RunClientFake) Get(params *runparams.GetRunParams) (*runmodel.APIRunDetail,
	*workflowapi.Workflow, error) {
	switch params.RunID {
	case RunForClientErrorTest:
		return nil, nil, fmt.Errorf(ClientErrorString)
	default:
		return getDefaultRun(params.RunID, "RUN_NAME"), getDefaultWorkflow(), nil
	}
}

func (c *RunClientFake) List(params *runparams.ListRunsParams) (
	[]*runmodel.APIRun, int, string, error) {
	const (
		FirstToken  = ""
		SecondToken = "SECOND_TOKEN"
		FinalToken  = ""
	)

	token := ""
	if params.PageToken != nil {
		token = *params.PageToken
	}

	switch token {
	case FirstToken:
		return []*runmodel.APIRun{
			getDefaultRun("100", "MY_FIRST_RUN").Run,
			getDefaultRun("101", "MY_SECOND_RUN").Run,
		}, 2, SecondToken, nil
	case SecondToken:
		return []*runmodel.APIRun{
			getDefaultRun("102", "MY_THIRD_RUN").Run,
		}, 1, FinalToken, nil
	default:
		return nil, 0, "", fmt.Errorf(InvalidFakeRequest, token)
	}
}

func (c *RunClientFake) ListAll(params *runparams.ListRunsParams, maxResultSize int) (
	[]*runmodel.APIRun, error) {
	return listAllForRun(c, params, maxResultSize)
}

func (c *RunClientFake) Archive(params *runparams.ArchiveRunParams) error {
	return nil
}

func (c *RunClientFake) Unarchive(params *runparams.UnarchiveRunParams) error {
	return nil
}

func (c *RunClientFake) Terminate(params *runparams.TerminateRunParams) error {
	switch params.RunID {
	case RunForClientErrorTest:
		return fmt.Errorf(ClientErrorString)
	case RunForDefaultTest:
		return nil
	default:
		return fmt.Errorf(InvalidFakeRequest, params.RunID)
	}
}


text:
package io.github.binaryfoo.lagotto

import scala.collection.immutable.ListSet

/**
 * If aggregates is empty no aggregation needs to be done. Otherwise calculate a set of aggregates for each group
 * identified by a set of key values.
 */
case class AggregationSpec(keys: Seq[FieldExpr] = Seq(), aggregates: Set[AggregateExpr] = ListSet())

object AggregationSpec {

  def fromExpressions(expressions: Seq[FieldExpr]): AggregationSpec = {
    expressions.foldLeft(AggregationSpec()) { case (current, expr) =>
      expr match {
        case HasAggregateExpressions(moreAggregates) => current.copy(aggregates = current.aggregates ++ moreAggregates)
        case e: FieldExpr => current.copy(keys = current.keys :+ e)
      }
    }
  }
}


text:
package com.cienet.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.WeakHashMap;
import java.util.zip.GZIPOutputStream;

import com.cienet.commons.Constants;
import com.cienet.commons.DataColumn;
import com.cienet.model.Book;
import com.cienet.model.BorrowBookHistory;
import com.cienet.model.SearchPageData;
import com.cienet.model.User;

public class SHistoryUtil {

	public static final int TYPE_ALL = 1;
	public static final int TYPE_ACTION = 2;
	public static final int TYPE_BOOK_TYPE = 3;
	public static final int TYPE_KEY = 4;
	public static final int TYPE_ACTION_A_TYPE = 5;
	public static final int TYPE_ACTION_A_KEY = 6;
	public static final int TYPE_TYPE_KEY = 7;

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
			+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ?";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ? AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ? AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_KEY = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.Book.CO_USER_NAME + " like ? OR "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " like ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_KEY = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE "
									+ DataColumn.Book.CO_USER_NAME + " like ? OR "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " like ?";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " =? "
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " =? ";

	public static final String JDBC_QUERY_HIS_BY_SEARCH_TYPE_ALL = "SELECT * FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ? AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?"
									+ " LIMIT ?,?";

	public static final String JDBC_COUNT_HIS_BY_SEARCH_TYPE_ALL = "SELECT COUNT(*) FROM " + DataColumn.BorrowBookHistory.TABLE_NAME  + " WHERE ( "
									+ DataColumn.BorrowBookHistory.CO_BOOK_NAME + " LIKE ? OR "
									+ DataColumn.BorrowBookHistory.CO_USER_NAME + " LIKE ? ) AND "
									+ DataColumn.BorrowBookHistory.CO_BOOK_TYPE + " = ? AND "
									+ DataColumn.BorrowBookHistory.CO_ACTION_STATE + " = ?";

	public static ArrayList<BorrowBookHistory> getSearchHis(Connection conn, int type, SearchPageData spd) throws Exception {
		ArrayList<BorrowBookHistory> resultList = new ArrayList<>();
		PreparedStatement ps;
		ResultSet rs;
		switch (type) {
		case TYPE_ACTION:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION);
			ps.setInt(1, spd.getActionType());
			ps.setInt(2, spd.getPageNum() * spd.getPageSize());
			ps.setInt(3, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_BOOK_TYPE:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE);
			ps.setInt(1, spd.getBookType());
			ps.setInt(2, spd.getPageNum() * spd.getPageSize());
			ps.setInt(3, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_KEY:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_KEY);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getPageNum() * spd.getPageSize());
			ps.setInt(4, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_ACTION_A_TYPE:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION);
			ps.setInt(1, spd.getBookType());
			ps.setInt(2, spd.getActionType());
			ps.setInt(3, spd.getPageNum() * spd.getPageSize());
			ps.setInt(4, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_ACTION_A_KEY:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getActionType());
			ps.setInt(4, spd.getPageNum() * spd.getPageSize());
			ps.setInt(5, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_TYPE_KEY:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getBookType());
			ps.setInt(4, spd.getPageNum() * spd.getPageSize());
			ps.setInt(5, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;
		case TYPE_ALL:
			ps = conn.prepareStatement(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ALL);
			Log.d(JDBC_QUERY_HIS_BY_SEARCH_TYPE_ALL);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getBookType());
			ps.setInt(4, spd.getActionType());
			ps.setInt(5, spd.getPageNum() * spd.getPageSize());
			ps.setInt(6, spd.getPageSize());
			rs = ps.executeQuery();
			resultList.addAll(generateList(conn, rs));
			break;

		}
		return resultList;
	}

	public static int getSearchHisCount(Connection conn, int type, SearchPageData spd) throws Exception {
		int count = 0;
		PreparedStatement ps;
		ResultSet rs;
		switch (type) {
		case TYPE_ACTION:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION);
			ps.setInt(1, spd.getActionType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_BOOK_TYPE:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE);
			ps.setInt(1, spd.getBookType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_KEY:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_KEY);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_ACTION_A_TYPE:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_BOOK_TYPE_A_ACTION);
			ps.setInt(1, spd.getBookType());
			ps.setInt(2, spd.getActionType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_ACTION_A_KEY:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ACTION_AND_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getActionType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_TYPE_KEY:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_TYPE_AND_KEY);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getBookType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;
		case TYPE_ALL:
			ps = conn.prepareStatement(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ALL);
			Log.d(JDBC_COUNT_HIS_BY_SEARCH_TYPE_ALL);
			ps.setString(1, "%" + spd.getKeyword() + "%");
			ps.setString(2, "%" + spd.getKeyword() + "%");
			ps.setInt(3, spd.getBookType());
			ps.setInt(4, spd.getActionType());
			rs = ps.executeQuery();
			if (rs.first()) {
				count = rs.getInt(1);
			}
			break;

		}
		return count;
	}

	private static ArrayList<BorrowBookHistory> generateList(Connection conn, ResultSet rs) throws Exception{
		ArrayList<BorrowBookHistory> blist = new ArrayList<>();
		if (rs.first()) {
			do {
				BorrowBookHistory bbh = new BorrowBookHistory();
				Book book = ConnDbUtil.getBookCN(conn, rs.getInt(DataColumn.BorrowBookHistory.CO_BOOK_ID));
				bbh.setBookCode(book.getBookCode());
				bbh.setBookName(book.getBookName());
				User user = ConnDbUtil.getUserN(conn, rs.getInt(DataColumn.BorrowBookHistory.CO_USER_ID));
				bbh.setUserName(user.getUserName());
				bbh.setActionState(rs.getInt(DataColumn.BorrowBookHistory.CO_ACTION_STATE));
				bbh.setaTime(TransUtil.TransLong(rs.getLong(DataColumn.BorrowBookHistory.CO_ACTION_TIME)));
				bbh.setHistoryId(rs.getInt(DataColumn.BorrowBookHistory.CO_HISTORY_ID));
				blist.add(bbh);
			} while(rs.next());
		}
		return blist;
	}

}


text:
package com.peligro;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AlertMap
 */
public class AlertMap extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlertMap() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String phone=request.getParameter("phone");
		Connection connection=null;
		PrintWriter out=null;
		double lat, lon;
		out=response.getWriter();
		out.println("
Please wait while we transfer you the location of victim
");

try {

			//retrieving data of people around victim
			connection=ConnectionUtil.getconnection();
			Statement st=connection.createStatement();
			//some trouble here
			//rectify the query
			String querySender="select LAT_CUR, LONG_CUR, phone from USERDATA where phone=(select victim from" +
					" userdata where phone='"+phone+"')";
			ResultSet rs=st.executeQuery(querySender);
			rs.next();
			lat=rs.getDouble("lat_cur");
			lon=rs.getDouble("long_cur");
			String s=rs.getString("phone");
			if(s.length()>0){
			String url="http://192.168.14.245:9090/PeligroServer/alertmap.jsp?lats="+lat+"&lons="+lon+"&latr="+request.getParameter("lat")+
					"&lonr="+request.getParameter("lon");
			String query2="update userdata set victim=null where victim='"+s+"'";
			st.executeUpdate(query2);
			response.sendRedirect(url);
			}else{
			out.println("
Victim might be rescued

we appreciate your support
");
			}
}catch(Exception e){e.printStackTrace();
out.println("
Victim might be rescued

we appreciate your support
");}

	}

}


text:
package com.cisco.axl.api._8;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for XH323Line complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="XH323Line">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence minOccurs="0">
 *         <element name="index" type="{http://www.cisco.com/AXL/API/8.0}XInteger"/>
 *         <element name="label" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
 *         <element name="asciiLabel" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
 *         <element name="display" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
 *         <element name="dirn" type="{http://www.cisco.com/AXL/API/8.0}XDirn"/>
 *         <element name="displayAscii" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
 *         <element name="e164Mask" type="{http://www.cisco.com/AXL/API/8.0}String255" minOccurs="0"/>
 *         <element name="maxNumCalls" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
 *         <element name="busyTrigger" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
 *         <element name="callInfoDisplay" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence minOccurs="0">
 *                   <element name="callerName" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
 *                   <element name="callerNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
 *                   <element name="redirectedNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
 *                   <element name="dialedNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <element name="recordingProfileName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
 *         <element name="monitoringCssName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
 *         <element name="recordingFlag" type="{http://www.cisco.com/AXL/API/8.0}XRecordingFlag" minOccurs="0"/>
 *         <element name="audibleMwi" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/>
 *         <element name="speedDial" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="partitionUsage" type="{http://www.cisco.com/AXL/API/8.0}XPartitionUsage" minOccurs="0"/>
 *         <element name="associatedEndusers" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence minOccurs="0">
 *                   <element name="enduser" type="{http://www.cisco.com/AXL/API/8.0}XEnduserMember" maxOccurs="unbounded" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="ctiid" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "XH323Line", propOrder = {
    "index",
    "label",
    "asciiLabel",
    "display",
    "dirn",
    "displayAscii",
    "e164Mask",
    "maxNumCalls",
    "busyTrigger",
    "callInfoDisplay",
    "recordingProfileName",
    "monitoringCssName",
    "recordingFlag",
    "audibleMwi",
    "speedDial",
    "partitionUsage",
    "associatedEndusers"
})
public class XH323Line {

    protected String index;
    protected String label;
    protected String asciiLabel;
    protected String display;
    protected XDirn dirn;
    protected String displayAscii;
    @XmlElementRef(name = "e164Mask", type = JAXBElement.class)
    protected JAXBElement<String> e164Mask;
    @XmlElement(defaultValue = "2")
    protected String maxNumCalls;
    @XmlElement(defaultValue = "1")
    protected String busyTrigger;
    protected XH323Line.CallInfoDisplay callInfoDisplay;
    @XmlElementRef(name = "recordingProfileName", type = JAXBElement.class)
    protected JAXBElement<XFkType> recordingProfileName;
    @XmlElementRef(name = "monitoringCssName", type = JAXBElement.class)
    protected JAXBElement<XFkType> monitoringCssName;
    @XmlElement(defaultValue = "Call Recording Disabled")
    protected String recordingFlag;
    @XmlElement(defaultValue = "Default")
    protected String audibleMwi;
    @XmlElementRef(name = "speedDial", type = JAXBElement.class)
    protected JAXBElement<String> speedDial;
    @XmlElement(defaultValue = "General")
    protected String partitionUsage;
    protected XH323Line.AssociatedEndusers associatedEndusers;
    @XmlAttribute
    @XmlSchemaType(name = "nonNegativeInteger")
    protected BigInteger ctiid;

    /**
     * Gets the value of the index property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIndex() {
        return index;
    }

    /**
     * Sets the value of the index property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIndex(String value) {
        this.index = value;
    }

    /**
     * Gets the value of the label property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLabel() {
        return label;
    }

    /**
     * Sets the value of the label property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLabel(String value) {
        this.label = value;
    }

    /**
     * Gets the value of the asciiLabel property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAsciiLabel() {
        return asciiLabel;
    }

    /**
     * Sets the value of the asciiLabel property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAsciiLabel(String value) {
        this.asciiLabel = value;
    }

    /**
     * Gets the value of the display property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDisplay() {
        return display;
    }

    /**
     * Sets the value of the display property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDisplay(String value) {
        this.display = value;
    }

    /**
     * Gets the value of the dirn property.
     *
     * @return
     *     possible object is
     *     {@link XDirn }
     *
     */
    public XDirn getDirn() {
        return dirn;
    }

    /**
     * Sets the value of the dirn property.
     *
     * @param value
     *     allowed object is
     *     {@link XDirn }
     *
     */
    public void setDirn(XDirn value) {
        this.dirn = value;
    }

    /**
     * Gets the value of the displayAscii property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDisplayAscii() {
        return displayAscii;
    }

    /**
     * Sets the value of the displayAscii property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDisplayAscii(String value) {
        this.displayAscii = value;
    }

    /**
     * Gets the value of the e164Mask property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link String }{@code >}
     *
     */
    public JAXBElement<String> getE164Mask() {
        return e164Mask;
    }

    /**
     * Sets the value of the e164Mask property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link String }{@code >}
     *
     */
    public void setE164Mask(JAXBElement<String> value) {
        this.e164Mask = ((JAXBElement<String> ) value);
    }

    /**
     * Gets the value of the maxNumCalls property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getMaxNumCalls() {
        return maxNumCalls;
    }

    /**
     * Sets the value of the maxNumCalls property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMaxNumCalls(String value) {
        this.maxNumCalls = value;
    }

    /**
     * Gets the value of the busyTrigger property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBusyTrigger() {
        return busyTrigger;
    }

    /**
     * Sets the value of the busyTrigger property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBusyTrigger(String value) {
        this.busyTrigger = value;
    }

    /**
     * Gets the value of the callInfoDisplay property.
     *
     * @return
     *     possible object is
     *     {@link XH323Line.CallInfoDisplay }
     *
     */
    public XH323Line.CallInfoDisplay getCallInfoDisplay() {
        return callInfoDisplay;
    }

    /**
     * Sets the value of the callInfoDisplay property.
     *
     * @param value
     *     allowed object is
     *     {@link XH323Line.CallInfoDisplay }
     *
     */
    public void setCallInfoDisplay(XH323Line.CallInfoDisplay value) {
        this.callInfoDisplay = value;
    }

    /**
     * Gets the value of the recordingProfileName property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link XFkType }{@code >}
     *
     */
    public JAXBElement<XFkType> getRecordingProfileName() {
        return recordingProfileName;
    }

    /**
     * Sets the value of the recordingProfileName property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link XFkType }{@code >}
     *
     */
    public void setRecordingProfileName(JAXBElement<XFkType> value) {
        this.recordingProfileName = ((JAXBElement<XFkType> ) value);
    }

    /**
     * Gets the value of the monitoringCssName property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link XFkType }{@code >}
     *
     */
    public JAXBElement<XFkType> getMonitoringCssName() {
        return monitoringCssName;
    }

    /**
     * Sets the value of the monitoringCssName property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link XFkType }{@code >}
     *
     */
    public void setMonitoringCssName(JAXBElement<XFkType> value) {
        this.monitoringCssName = ((JAXBElement<XFkType> ) value);
    }

    /**
     * Gets the value of the recordingFlag property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRecordingFlag() {
        return recordingFlag;
    }

    /**
     * Sets the value of the recordingFlag property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRecordingFlag(String value) {
        this.recordingFlag = value;
    }

    /**
     * Gets the value of the audibleMwi property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAudibleMwi() {
        return audibleMwi;
    }

    /**
     * Sets the value of the audibleMwi property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAudibleMwi(String value) {
        this.audibleMwi = value;
    }

    /**
     * Gets the value of the speedDial property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link String }{@code >}
     *
     */
    public JAXBElement<String> getSpeedDial() {
        return speedDial;
    }

    /**
     * Sets the value of the speedDial property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link String }{@code >}
     *
     */
    public void setSpeedDial(JAXBElement<String> value) {
        this.speedDial = ((JAXBElement<String> ) value);
    }

    /**
     * Gets the value of the partitionUsage property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPartitionUsage() {
        return partitionUsage;
    }

    /**
     * Sets the value of the partitionUsage property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPartitionUsage(String value) {
        this.partitionUsage = value;
    }

    /**
     * Gets the value of the associatedEndusers property.
     *
     * @return
     *     possible object is
     *     {@link XH323Line.AssociatedEndusers }
     *
     */
    public XH323Line.AssociatedEndusers getAssociatedEndusers() {
        return associatedEndusers;
    }

    /**
     * Sets the value of the associatedEndusers property.
     *
     * @param value
     *     allowed object is
     *     {@link XH323Line.AssociatedEndusers }
     *
     */
    public void setAssociatedEndusers(XH323Line.AssociatedEndusers value) {
        this.associatedEndusers = value;
    }

    /**
     * Gets the value of the ctiid property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getCtiid() {
        return ctiid;
    }

    /**
     * Sets the value of the ctiid property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setCtiid(BigInteger value) {
        this.ctiid = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence minOccurs="0">
     *         <element name="enduser" type="{http://www.cisco.com/AXL/API/8.0}XEnduserMember" maxOccurs="unbounded" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "enduser"
    })
    public static class AssociatedEndusers {

        protected List<XEnduserMember> enduser;

        /**
         * Gets the value of the enduser property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the enduser property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getEnduser().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link XEnduserMember }
         *
         *
         */
        public List<XEnduserMember> getEnduser() {
            if (enduser == null) {
                enduser = new ArrayList<XEnduserMember>();
            }
            return this.enduser;
        }

    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence minOccurs="0">
     *         <element name="callerName" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
     *         <element name="callerNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
     *         <element name="redirectedNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
     *         <element name="dialedNumber" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "callerName",
        "callerNumber",
        "redirectedNumber",
        "dialedNumber"
    })
    public static class CallInfoDisplay {

        @XmlElement(defaultValue = "true")
        protected String callerName;
        @XmlElement(defaultValue = "false")
        protected String callerNumber;
        @XmlElement(defaultValue = "false")
        protected String redirectedNumber;
        @XmlElement(defaultValue = "true")
        protected String dialedNumber;

        /**
         * Gets the value of the callerName property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getCallerName() {
            return callerName;
        }

        /**
         * Sets the value of the callerName property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setCallerName(String value) {
            this.callerName = value;
        }

        /**
         * Gets the value of the callerNumber property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getCallerNumber() {
            return callerNumber;
        }

        /**
         * Sets the value of the callerNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setCallerNumber(String value) {
            this.callerNumber = value;
        }

        /**
         * Gets the value of the redirectedNumber property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getRedirectedNumber() {
            return redirectedNumber;
        }

        /**
         * Sets the value of the redirectedNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setRedirectedNumber(String value) {
            this.redirectedNumber = value;
        }

        /**
         * Gets the value of the dialedNumber property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getDialedNumber() {
            return dialedNumber;
        }

        /**
         * Sets the value of the dialedNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setDialedNumber(String value) {
            this.dialedNumber = value;
        }

    }

}


text:
import sys
import os.path
import os
import logging
from datetime import datetime
from settings import DIR_ROOT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD

logging.basicConfig(level=logging.WARN)

LOG_DIR = "%s/logs" % DIR_ROOT
MYSQL_CMD = 'mysqldump'
ZIP_CMD = 'zip'

def _setup():
    if not os.path.exists(LOG_DIR):
        logging.debug("Created log directory %s" % LOG_DIR)
        os.mkdir(LOG_DIR)
    else:
        logging.debug("Using log directory %s" % LOG_DIR)

def _backup_name():
    now = datetime.now()
    day_name = now.strftime("%A")
    file_name = "%s.sql" % day_name.lower()
    logging.debug("Setting backup name for day name %s as %s" % (day_name, file_name))
    return file_name

def _run_backup(file_name):
    cmd = "%(mysqldump)s -u %(user)s --password=%(password)s %(database)s > %(log_dir)s/%(file)s" % {
        'mysqldump' : MYSQL_CMD,
        'user' : DATABASE_USER,
        'password' : DATABASE_PASSWORD,
        'database' : DATABASE_NAME,
        'log_dir' : LOG_DIR,
        'file': file_name}
    logging.debug("Backing up with command %s " % cmd)
    return os.system(cmd)

def _zip_backup(file_name):
    backup = "%s/%s" % (LOG_DIR, file_name)
    zipfile_name = "%s.zip" % (backup)

    if os.path.exists(zipfile_name):
        logging.debug("Removing previous zip archive %s" % zipfile_name)
        os.remove(zipfile_name)
    zip_cmds = {'zip' : ZIP_CMD, 'zipfile' : zipfile_name, 'file' : backup }

    # Create the backup
    logging.debug("Making backup as %s " % zipfile_name)
    os.system("%(zip)s -q -9 %(zipfile)s %(file)s" % zip_cmds)

    # Test our archive
    logging.debug("Testing zip archive")
    if not os.system("%(zip)s -T -q %(zipfile)s" % zip_cmds):
        # If there was no problem, then delete the unzipped version
        os.remove(backup)
        return True
    else:
        return False

def main(*args):
    _setup()
    file_name = _backup_name()
    _run_backup(file_name)
    return(_zip_backup(file_name))

if __name__ == '__main__':
    sys.exit(main(*sys.argv))