text:
import getopt
import glob
import os
import re
import stat
import sys
import time

try:
    import threading
    import Queue                # 2to3: rename to queue
    threading_ok = True
except ImportError:
    print "Can't import threading or queue"
    threading_ok = False

cwd = os.getcwd()

baseline = 0
builddir = os.path.join(cwd, 'build')
external = 0
debug = ''
execute_tests = 1
jobs = 1
list_only = None
printcommand = 1
package = None
print_passed_summary = None
python3incompatibilities = None
scons = None
scons_exec = None
qmtest = None
testlistfile = None
version = ''
print_times = None
python = None
sp = []
print_progress = 1
suppress_stdout = False
suppress_stderr = False
allow_pipe_files = True

helpstr = """\
Usage: runtest.py [OPTIONS] [TEST ...]
Options:
  -3                          Warn about Python 3.x incompatibilities.
  -a, --all                   Run all tests.
  -b BASE, --baseline BASE    Run test scripts against baseline BASE.
  --builddir DIR              Directory in which packages were built.
  -d, --debug                 Run test scripts under the Python debugger.
  -e, --external              Run the script in external mode (for testing separate Tools)
  -f FILE, --file FILE        Run tests in specified FILE.
  -h, --help                  Print this message and exit.
  -k, --no-progress           Suppress count and percent progress messages.
  -l, --list                  List available tests and exit.
  -n, --no-exec               No execute, just print command lines.
  --nopipefiles               Doesn't use the "file pipe" workaround for subprocess.Popen()
                              for starting tests. WARNING: Only use this when too much file
                              traffic is giving you trouble AND you can be sure that none of
                              your tests create output that exceed 65K chars! You might
                              run into some deadlocks else.
  -o FILE, --output FILE      Save the output from a test run to the log file.
  -P Python                   Use the specified Python interpreter.
  -p PACKAGE, --package PACKAGE
                              Test against the specified PACKAGE:
                                deb           Debian
                                local-tar-gz  .tar.gz standalone package
                                local-zip     .zip standalone package
                                rpm           Red Hat
                                src-tar-gz    .tar.gz source package
                                src-zip       .zip source package
                                tar-gz        .tar.gz distribution
                                zip           .zip distribution
  --passed                    Summarize which tests passed.
  --qmtest                    Run using the QMTest harness (deprecated).
  -q, --quiet                 Don't print the test being executed.
  -s, --short-progress        Short progress, prints only the command line
                              and a percentage value, based on the total and
                              current number of tests.
  -t, --time                  Print test execution time.
  -v version                  Specify the SCons version.
  --verbose=LEVEL             Set verbose level: 1 = print executed commands,
                                2 = print commands and non-zero output,
                                3 = print commands and all output.
  -X                          Test script is executable, don't feed to Python.
  -x SCRIPT, --exec SCRIPT    Test SCRIPT.
  --xml file                  Save results to file in SCons XML format.

Environment Variables:

  PRESERVE, PRESERVE_{PASS,FAIL,NO_RESULT}: preserve test subdirs
  TESTCMD_VERBOSE: turn on verbosity in TestCommand
"""

# "Pass-through" option parsing -- an OptionParser that ignores
# unknown options and lets them pile up in the leftover argument
# list.  Useful to gradually port getopt to optparse.

from optparse import OptionParser, BadOptionError

class PassThroughOptionParser(OptionParser):
    def _process_long_opt(self, rargs, values):
        try:
            OptionParser._process_long_opt(self, rargs, values)
        except BadOptionError, err:
            self.largs.append(err.opt_str)
    def _process_short_opts(self, rargs, values):
        try:
            OptionParser._process_short_opts(self, rargs, values)
        except BadOptionError, err:
            self.largs.append(err.opt_str)

parser = PassThroughOptionParser(add_help_option=False)
parser.add_option('-a', '--all', action='store_true',
                      help="Run all tests.")
parser.add_option('-o', '--output',
                      help="Save the output from a test run to the log file.")
parser.add_option('--xml',
                      help="Save results to file in SCons XML format.")
(options, args) = parser.parse_args()

#print "options:", options
#print "args:", args

opts, args = getopt.getopt(args, "3b:def:hj:klnP:p:qsv:Xx:t",
                            ['baseline=', 'builddir=',
                             'debug', 'external', 'file=', 'help', 'no-progress',
                             'jobs=',
                             'list', 'no-exec', 'nopipefiles',
                             'package=', 'passed', 'python=', 'qmtest',
                             'quiet', 'short-progress', 'time',
                             'version=', 'exec=',
                             'verbose='])

for o, a in opts:
    if o in ['-3']:
        python3incompatibilities = 1
    elif o in ['-b', '--baseline']:
        baseline = a
    elif o in ['--builddir']:
        builddir = a
        if not os.path.isabs(builddir):
            builddir = os.path.normpath(os.path.join(cwd, builddir))
    elif o in ['-d', '--debug']:
        for dir in sys.path:
            pdb = os.path.join(dir, 'pdb.py')
            if os.path.exists(pdb):
                debug = pdb
                break
    elif o in ['-e', '--external']:
        external = 1
    elif o in ['-f', '--file']:
        if not os.path.isabs(a):
            a = os.path.join(cwd, a)
        testlistfile = a
    elif o in ['-h', '--help']:
        print helpstr
        sys.exit(0)
    elif o in ['-j', '--jobs']:
        jobs = int(a)
    elif o in ['-k', '--no-progress']:
        print_progress = 0
    elif o in ['-l', '--list']:
        list_only = 1
    elif o in ['-n', '--no-exec']:
        execute_tests = None
    elif o in ['--nopipefiles']:
        allow_pipe_files = False
    elif o in ['-p', '--package']:
        package = a
    elif o in ['--passed']:
        print_passed_summary = 1
    elif o in ['-P', '--python']:
        python = a
    elif o in ['--qmtest']:
        if sys.platform == 'win32':
            # typically in c:/PythonXX/Scripts
            qmtest = 'qmtest.py'
        else:
            qmtest = 'qmtest'
    elif o in ['-q', '--quiet']:
        printcommand = 0
        suppress_stdout = True
        suppress_stderr = True
    elif o in ['-s', '--short-progress']:
        print_progress = 1
        suppress_stdout = True
        suppress_stderr = True
    elif o in ['-t', '--time']:
        print_times = 1
    elif o in ['--verbose']:
        os.environ['TESTCMD_VERBOSE'] = a
    elif o in ['-v', '--version']:
        version = a
    elif o in ['-X']:
        scons_exec = 1
    elif o in ['-x', '--exec']:
        scons = a

if not args and not options.all and not testlistfile:
    sys.stderr.write("""\
runtest.py:  No tests were specified.
             List one or more tests on the command line, use the
             -f option to specify a file containing a list of tests,
             or use the -a option to find and run all tests.

""")
    sys.exit(1)

# --- setup stdout/stderr ---
class Unbuffered(object):
    def __init__(self, file):
        self.file = file
        self.softspace = 0  ## backward compatibility; not supported in Py3k
    def write(self, arg):
        self.file.write(arg)
        self.file.flush()
    def __getattr__(self, attr):
        return getattr(self.file, attr)

sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)

if options.output:
    logfile = open(options.output, 'w')
    class Tee(object):
        def __init__(self, openfile, stream):
            self.file = openfile
            self.stream = stream
        def write(self, data):
            self.file.write(data)
            self.stream.write(data)
    sys.stdout = Tee(logfile, sys.stdout)
    sys.stderr = Tee(logfile, sys.stderr)

# --- define helpers ----
if sys.platform in ('win32', 'cygwin'):

    def whereis(file):
        pathext = [''] + os.environ['PATHEXT'].split(os.pathsep)
        for dir in os.environ['PATH'].split(os.pathsep):
            f = os.path.join(dir, file)
            for ext in pathext:
                fext = f + ext
                if os.path.isfile(fext):
                    return fext
        return None

else:

    def whereis(file):
        for dir in os.environ['PATH'].split(os.pathsep):
            f = os.path.join(dir, file)
            if os.path.isfile(f):
                try:
                    st = os.stat(f)
                except OSError:
                    continue
                if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
                    return f
        return None

sp.append(builddir)
sp.append(cwd)

#
_ws = re.compile('\s')

def escape(s):
    if _ws.search(s):
        s = '"' + s + '"'
    s = s.replace('\\', '\\\\')
    return s

import subprocess

if not suppress_stdout and not suppress_stderr:
    # Without any output suppressed, we let the subprocess
    # write its stuff freely to stdout/stderr.
    def spawn_it(command_args):
        p = subprocess.Popen(' '.join(command_args),
                             shell=True)
        return (None, None, p.wait())
else:
    # Else, we catch the output of both pipes...
    if allow_pipe_files:
        # The subprocess.Popen() suffers from a well-known
        # problem. Data for stdout/stderr is read into a
        # memory buffer of fixed size, 65K which is not very much.
        # When it fills up, it simply stops letting the child process
        # write to it. The child will then sit and patiently wait to
        # be able to write the rest of its output. Hang!
        # In order to work around this, we follow a suggestion
        # by Anders Pearson in
        #   http://http://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
        # and pass temp file objects to Popen() instead of the ubiquitous
        # subprocess.PIPE.
        def spawn_it(command_args):
            # Create temporary files
            import tempfile
            tmp_stdout = tempfile.TemporaryFile(mode='w+t')
            tmp_stderr = tempfile.TemporaryFile(mode='w+t')
            # Start subprocess...
            p = subprocess.Popen(' '.join(command_args),
                                 stdout=tmp_stdout,
                                 stderr=tmp_stderr,
                                 shell=True)
            # ... and wait for it to finish.
            ret = p.wait()

            try:
                # Rewind to start of files
                tmp_stdout.seek(0)
                tmp_stderr.seek(0)
                # Read output
                spawned_stdout = tmp_stdout.read()
                spawned_stderr = tmp_stderr.read()
            finally:
                # Remove temp files by closing them
                tmp_stdout.close()
                tmp_stderr.close()

            # Return values
            return (spawned_stderr, spawned_stdout, ret)

    else:
        # We get here only if the user gave the '--nopipefiles'
        # option, meaning the "temp file" approach for
        # subprocess.communicate() above shouldn't be used.
        # He hopefully knows what he's doing, but again we have a
        # potential deadlock situation in the following code:
        #   If the subprocess writes a lot of data to its stderr,
        #   the pipe will fill up (nobody's reading it yet) and the
        #   subprocess will wait for someone to read it.
        #   But the parent process is trying to read from stdin
        #   (but the subprocess isn't writing anything there).
        #   Hence a deadlock.
        # Be dragons here! Better don't use this!
        def spawn_it(command_args):
            p = subprocess.Popen(' '.join(command_args),
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
            spawned_stdout = p.stdout.read()
            spawned_stderr = p.stderr.read()
            return (spawned_stderr, spawned_stdout, p.wait())

class Base(object):
    def __init__(self, path, spe=None):
        self.path = path
        self.abspath = os.path.abspath(path)
        if spe:
            for dir in spe:
                f = os.path.join(dir, path)
                if os.path.isfile(f):
                    self.abspath = f
                    break
        self.status = None

class SystemExecutor(Base):
    def execute(self):
        self.stderr, self.stdout, s = spawn_it(self.command_args)
        self.status = s
        if s < 0 or s > 2:
            sys.stdout.write("Unexpected exit status %d\n" % s)

class PopenExecutor(Base):
    # For an explanation of the following 'if ... else'
    # and the 'allow_pipe_files' option, please check out the
    # definition of spawn_it() above.
    if allow_pipe_files:
        def execute(self):
            # Create temporary files
            import tempfile
            tmp_stdout = tempfile.TemporaryFile(mode='w+t')
            tmp_stderr = tempfile.TemporaryFile(mode='w+t')
            # Start subprocess...
            p = subprocess.Popen(self.command_str,
                                 stdout=tmp_stdout,
                                 stderr=tmp_stderr,
                                 shell=True)
            # ... and wait for it to finish.
            self.status = p.wait()

            try:
                # Rewind to start of files
                tmp_stdout.seek(0)
                tmp_stderr.seek(0)
                # Read output
                self.stdout = tmp_stdout.read()
                self.stderr = tmp_stderr.read()
            finally:
                # Remove temp files by closing them
                tmp_stdout.close()
                tmp_stderr.close()
    else:
        def execute(self):
            p = subprocess.Popen(self.command_str,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
            self.stdout = p.stdout.read()
            self.stderr = p.stderr.read()
            self.status = p.wait()

class XML(PopenExecutor):
    def header(self, f):
        f.write('  <results>\n')
    def write(self, f):
        f.write('    <test>\n')
        f.write('      <file_name>%s</file_name>\n' % self.path)
        f.write('      <command_line>%s</command_line>\n' % self.command_str)
        f.write('      <exit_status>%s</exit_status>\n' % self.status)
        f.write('      <stdout>%s</stdout>\n' % self.stdout)
        f.write('      <stderr>%s</stderr>\n' % self.stderr)
        f.write('      <time>%.1f</time>\n' % self.test_time)
        f.write('    </test>\n')
    def footer(self, f):
        f.write('  <time>%.1f</time>\n' % self.total_time)
        f.write('  </results>\n')

if options.xml:
    Test = XML
else:
    Test = SystemExecutor

# --- start processing ---
if package:

    dir = {
        'deb'          : 'usr',
        'local-tar-gz' : None,
        'local-zip'    : None,
        'rpm'          : 'usr',
        'src-tar-gz'   : '',
        'src-zip'      : '',
        'tar-gz'       : '',
        'zip'          : '',
    }

    # The hard-coded "python2.1" here is the library directory
    # name on Debian systems, not an executable, so it's all right.
    lib = {
        'deb'        : os.path.join('python2.1', 'site-packages')
    }

    if package not in dir:
        sys.stderr.write("Unknown package '%s'\n" % package)
        sys.exit(2)

    test_dir = os.path.join(builddir, 'test-%s' % package)

    if dir[package] is None:
        scons_script_dir = test_dir
        globs = glob.glob(os.path.join(test_dir, 'scons-local-*'))
        if not globs:
            sys.stderr.write("No `scons-local-*' dir in `%s'\n" % test_dir)
            sys.exit(2)
        scons_lib_dir = None
        pythonpath_dir = globs[len(globs)-1]
    elif sys.platform == 'win32':
        scons_script_dir = os.path.join(test_dir, dir[package], 'Scripts')
        scons_lib_dir = os.path.join(test_dir, dir[package])
        pythonpath_dir = scons_lib_dir
    else:
        scons_script_dir = os.path.join(test_dir, dir[package], 'bin')
        l = lib.get(package, 'scons')
        scons_lib_dir = os.path.join(test_dir, dir[package], 'lib', l)
        pythonpath_dir = scons_lib_dir

    scons_runtest_dir = builddir

else:
    sd = None
    ld = None

    if not baseline or baseline == '.':
        base = cwd
    elif baseline == '-':
        # Tentative code for fetching information directly from the
        # QMTest context file.
        #
        #import qm.common
        #import qm.test.context
        #qm.rc.Load("test")
        #context = qm.test.context.Context()
        #context.Read('context')

        url = None
        svn_info =  os.popen("svn info 2>&1", "r").read()
        match = re.search('URL: (.*)', svn_info)
        if match:
            url = match.group(1)
        if not url:
            sys.stderr.write('runtest.py: could not find a URL:\n')
            sys.stderr.write(svn_info)
            sys.exit(1)
        import tempfile
        base = tempfile.mkdtemp(prefix='runtest-tmp-')

        command = 'cd %s && svn co -q %s' % (base, url)

        base = os.path.join(base, os.path.split(url)[1])
        if printcommand:
            print command
        if execute_tests:
            os.system(command)
    else:
        base = baseline

    scons_runtest_dir = base

    if not external:
        scons_script_dir = sd or os.path.join(base, 'src', 'script')
        scons_lib_dir = ld or os.path.join(base, 'src', 'engine')
    else:
        scons_script_dir = sd or ''
        scons_lib_dir = ld or ''

    pythonpath_dir = scons_lib_dir

if scons:
    # Let the version of SCons that the -x option pointed to find
    # its own modules.
    os.environ['SCONS'] = scons
elif scons_lib_dir:
    # Because SCons is really aggressive about finding its modules,
    # it sometimes finds SCons modules elsewhere on the system.
    # This forces SCons to use the modules that are being tested.
    os.environ['SCONS_LIB_DIR'] = scons_lib_dir

if scons_exec:
    os.environ['SCONS_EXEC'] = '1'

if external:
    os.environ['SCONS_EXTERNAL_TEST'] = '1'

os.environ['SCONS_RUNTEST_DIR'] = scons_runtest_dir
os.environ['SCONS_SCRIPT_DIR'] = scons_script_dir
os.environ['SCONS_CWD'] = cwd

os.environ['SCONS_VERSION'] = version

old_pythonpath = os.environ.get('PYTHONPATH')

# FIXME: the following is necessary to pull in half of the testing
#        harness from $srcdir/etc. Those modules should be transfered
#        to QMTest/ once we completely cut over to using that as
#        the harness, in which case this manipulation of PYTHONPATH
#        should be able to go away.
pythonpaths = [ pythonpath_dir ]

# Add path of the QMTest folder to PYTHONPATH
scriptpath = os.path.dirname(os.path.realpath(__file__))
pythonpaths.append(os.path.join(scriptpath, 'QMTest'))

os.environ['PYTHONPATH'] = os.pathsep.join(pythonpaths)

if old_pythonpath:
    os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + \
                               os.pathsep + \
                               old_pythonpath

if python3incompatibilities:
    os.environ['SCONS_HORRIBLE_REGRESSION_TEST_HACK'] = '1'

tests = []

def find_Tests_py(directory):
    result = []
    for dirpath, dirnames, filenames in os.walk(directory):
        # Skip folders containing a sconstest.skip file
        if 'sconstest.skip' in filenames:
            continue
        for fname in filenames:
            if fname.endswith("Tests.py"):
                result.append(os.path.join(dirpath, fname))
    return sorted(result)

def find_py(directory):
    result = []
    for dirpath, dirnames, filenames in os.walk(directory):
        # Skip folders containing a sconstest.skip file
        if 'sconstest.skip' in filenames:
            continue
        try:
            exclude_fp = open(os.path.join(dirpath, ".exclude_tests"))
        except EnvironmentError:
            excludes = []
        else:
            excludes = [ e.split('#', 1)[0].strip()
                         for e in exclude_fp.readlines() ]
        for fname in filenames:
            if fname.endswith(".py") and fname not in excludes:
                result.append(os.path.join(dirpath, fname))
    return sorted(result)

if args:
    for a in args:
        for path in glob.glob(a):
            if os.path.isdir(path):
                if path[:3] == 'src':
                    tests.extend(find_Tests_py(path))

                elif path[:4] == 'test':
                    tests.extend(find_py(path))
            else:
                tests.append(path)
elif testlistfile:
    tests = open(testlistfile, 'r').readlines()
    tests = [x for x in tests if x[0] != '#']
    tests = [x[:-1] for x in tests]
    tests = [x.strip() for x in tests]
elif options.all and not qmtest:
    # Find all of the SCons functional tests in the local directory
    # tree.  This is anything under the 'src' subdirectory that ends
    # with 'Tests.py', or any Python script (*.py) under the 'test'
    # subdirectory.
    #
    # Note that there are some tests under 'src' that *begin* with
    # 'test_', but they're packaging and installation tests, not
    # functional tests, so we don't execute them by default.  (They can
    # still be executed by hand, though, and are routinely executed
    # by the Aegis packaging build to make sure that we're building
    # things correctly.)
    tests.extend(find_Tests_py('src'))
    tests.extend(find_py('test'))
    tests.sort()

if not tests:
    sys.stderr.write("""\
runtest.py:  No tests were found.
""")
    sys.exit(1)

if qmtest:
    if baseline:
        aegis_result_stream = 'scons_tdb.AegisBaselineStream'
        qmr_file = 'baseline.qmr'
    else:
        aegis_result_stream = 'scons_tdb.AegisChangeStream'
        qmr_file = 'results.qmr'

    if print_times:
        aegis_result_stream = aegis_result_stream + "(print_time='1')"

    qmtest_args = [ qmtest, ]

    qmtest_args.extend([
                'run',
                '--output %s' % qmr_file,
                '--format none',
                '--result-stream="%s"' % aegis_result_stream,
              ])

    if python:
        qmtest_args.append('--context python="%s"' % python)

    if options.xml:
        rsclass = 'scons_tdb.SConsXMLResultStream'
        qof = "r'" + options.xml + "'"
        rs = '--result-stream="%s(filename=%s)"' % (rsclass, qof)
        qmtest_args.append(rs)

    os.environ['SCONS'] = os.path.join(cwd, 'src', 'script', 'scons.py')

    cmd = ' '.join(qmtest_args + tests)
    if printcommand:
        sys.stdout.write(cmd + '\n')
        sys.stdout.flush()
    status = 0
    if execute_tests:
        status = os.system(cmd)
        try:
            wexitstatus = os.WEXITSTATUS
        except AttributeError:
            pass
        else:
            status = wexitstatus(status)
    sys.exit(status)

#try:
#    os.chdir(scons_script_dir)
#except OSError:
#    pass

tests = [Test(t) for t in tests]

if list_only:
    for t in tests:
        sys.stdout.write(t.path + "\n")
    sys.exit(0)

#
if not python:
    if os.name == 'java':
        python = os.path.join(sys.prefix, 'jython')
    else:
        python = sys.executable
os.environ["python_executable"] = python

# time.clock() is the suggested interface for doing benchmarking timings,
# but time.time() does a better job on Linux systems, so let that be
# the non-Windows default.

if sys.platform == 'win32':
    time_func = time.clock
else:
    time_func = time.time

if print_times:
    print_time_func = lambda fmt, time: sys.stdout.write(fmt % time)
else:
    print_time_func = lambda fmt, time: None

total_start_time = time_func()
total_num_tests = len(tests)
tests_completed = 0

def run_test(t, io_lock, async=True):
    global tests_completed
    header = ""
    command_args = ['-tt']
    if python3incompatibilities:
        command_args.append('-3')
    if debug:
        command_args.append(debug)
    command_args.append(t.path)
    t.command_args = [python] + command_args
    t.command_str = " ".join([escape(python)] + command_args)
    if printcommand:
        if print_progress:
            tests_completed += 1
            n = tests_completed # approx indicator of where we are
            header += ("%d/%d (%.2f%s) %s\n" % (n, total_num_tests,
                                                float(n)*100.0/float(total_num_tests),
                                                '%',
                                                t.command_str))
        else:
            header += t.command_str + "\n"
    if not suppress_stdout and not suppress_stderr:
        sys.stdout.write(header)
    head, tail = os.path.split(t.abspath)
    if head:
        os.environ['PYTHON_SCRIPT_DIR'] = head
    else:
        os.environ['PYTHON_SCRIPT_DIR'] = ''
    test_start_time = time_func()
    if execute_tests:
        t.execute()

    t.test_time = time_func() - test_start_time
    if io_lock:
        io_lock.acquire()
    if suppress_stdout or suppress_stderr:
        sys.stdout.write(header)
    if not suppress_stdout and t.stdout:
        print t.stdout
    if not suppress_stderr and t.stderr:
        print t.stderr
    print_time_func("Test execution time: %.1f seconds\n", t.test_time)
    if io_lock:
        io_lock.release()

class RunTest(threading.Thread):
    def __init__(self, queue, io_lock):
        threading.Thread.__init__(self)
        self.queue = queue
        self.io_lock = io_lock

    def run(self):
        while True:
            t = self.queue.get()
            run_test(t, io_lock, True)
            self.queue.task_done()

if jobs > 1 and threading_ok:
    print "Running tests using %d jobs"%jobs
    # Start worker threads
    queue = Queue.Queue()
    io_lock = threading.Lock()
    for i in range(1, jobs):
        t = RunTest(queue, io_lock)
        t.daemon = True
        t.start()
    # Give tasks to workers
    for t in tests:
        queue.put(t)
    queue.join()
else:
    # Run tests serially
    if jobs > 1:
        print "Ignoring -j%d option; no python threading module available."%jobs
    for t in tests:
        run_test(t, None, False)

# --- all tests are complete by the time we get here ---
if len(tests) > 0:
    tests[0].total_time = time_func() - total_start_time
    print_time_func("Total execution time for all tests: %.1f seconds\n", tests[0].total_time)

passed = [t for t in tests if t.status == 0]
fail = [t for t in tests if t.status == 1]
no_result = [t for t in tests if t.status == 2]

if len(tests) != 1 and execute_tests:
    if passed and print_passed_summary:
        if len(passed) == 1:
            sys.stdout.write("\nPassed the following test:\n")
        else:
            sys.stdout.write("\nPassed the following %d tests:\n" % len(passed))
        paths = [x.path for x in passed]
        sys.stdout.write("\t" + "\n\t".join(paths) + "\n")
    if fail:
        if len(fail) == 1:
            sys.stdout.write("\nFailed the following test:\n")
        else:
            sys.stdout.write("\nFailed the following %d tests:\n" % len(fail))
        paths = [x.path for x in fail]
        sys.stdout.write("\t" + "\n\t".join(paths) + "\n")
    if no_result:
        if len(no_result) == 1:
            sys.stdout.write("\nNO RESULT from the following test:\n")
        else:
            sys.stdout.write("\nNO RESULT from the following %d tests:\n" % len(no_result))
        paths = [x.path for x in no_result]
        sys.stdout.write("\t" + "\n\t".join(paths) + "\n")

if options.xml:
    if options.xml == '-':
        f = sys.stdout
    else:
        f = open(options.xml, 'w')
    tests[0].header(f)
    #f.write("test_result = [\n")
    for t in tests:
        t.write(f)
    tests[0].footer(f)
    #f.write("];\n")
    if options.xml != '-':
        f.close()

if len(fail):
    sys.exit(1)
elif len(no_result):
    sys.exit(2)
else:
    sys.exit(0)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
//
//  ALPHAStatePlugin.h
//  Alpha
//
//  Created by Dal Rupnik on 24/11/14.
//  Copyright (c) 2014 Unified Sense. All rights reserved.
//

#import "ALPHAPlugin.h"

/*!
 *  Plugin works with device state and notifications
 */
@interface ALPHAStatePlugin : ALPHAPlugin

@end

redpajama_set_name: RedPajamaGithub


text:
var request = require('request');
var testport = 8080;

var Mesh = require('../../lib/system/mesh');

var maximumPings = 1000;

var config = {
  name:"componentWebTestMesh",
  dataLayer: {
    authTokenSecret: 'a256a2fd43bf441483c5177fc85fd9d3',
    systemSecret: 'mesh',
    log_level: 'info|error|warning',
    port:testport,
    setOptions:{}
  }
};

var mesh = new Mesh();

mesh.initialize(config, function(err) {

  if (err)
    console.error(err);

  mesh.api.exchange.api.test('message', function(e, response){

    console.log('ran test arguments');
    console.log(arguments);

    console.log('mesh initialized and started, here are the paths for the api:');
    console.log('http://127.0.0.1:' + testport + '/' + config.name + '/api/client');
    console.log('http://127.0.0.1:' + testport + '/' + config.name + '/api/app/describe.html');
  });

});


text:
-- WSO2 Message Broker MS SQL Database schema --

-- Start of Message Store Tables --

--create table queues
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_QUEUE_MAPPING]') AND TYPE IN (N'U'))
CREATE TABLE MB_QUEUE_MAPPING (
                QUEUE_ID INTEGER IDENTITY(1,1),
                QUEUE_NAME VARCHAR(512) NOT NULL,
                PRIMARY KEY(QUEUE_ID),
                UNIQUE (QUEUE_ID),
                CONSTRAINT const UNIQUE (QUEUE_NAME)
);

--create table metadata
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_METADATA]') AND TYPE IN (N'U'))
CREATE TABLE MB_METADATA (
                MESSAGE_ID BIGINT,
                QUEUE_ID INTEGER,
                MESSAGE_METADATA VARBINARY(MAX),
                PRIMARY KEY (MESSAGE_ID, QUEUE_ID),
                UNIQUE (MESSAGE_ID),
                FOREIGN KEY (QUEUE_ID) REFERENCES MB_QUEUE_MAPPING (QUEUE_ID)
);

--create table messages
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_CONTENT]') AND TYPE IN (N'U'))
CREATE TABLE MB_CONTENT (
                MESSAGE_ID BIGINT,
                CONTENT_OFFSET INTEGER,
                MESSAGE_CONTENT VARBINARY(MAX),
                PRIMARY KEY (MESSAGE_ID,CONTENT_OFFSET),
                FOREIGN KEY (MESSAGE_ID) REFERENCES MB_METADATA (MESSAGE_ID)
                ON DELETE CASCADE
);

--create table expiration_data
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_EXPIRATION_DATA]') AND TYPE IN (N'U'))
CREATE TABLE MB_EXPIRATION_DATA (
                MESSAGE_ID BIGINT UNIQUE,
                EXPIRATION_TIME BIGINT,
                MESSAGE_DESTINATION VARCHAR(512) NOT NULL,
                FOREIGN KEY (MESSAGE_ID) REFERENCES MB_METADATA (MESSAGE_ID)
);

-- create table retained metadata
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_RETAINED_METADATA]') AND TYPE IN (N'U'))
CREATE TABLE MB_RETAINED_METADATA (
                TOPIC_ID INTEGER,
                TOPIC_NAME VARCHAR(512) NOT NULL,
                MESSAGE_ID BIGINT,
                MESSAGE_METADATA VARBINARY(MAX),
                PRIMARY KEY (TOPIC_ID)
);

-- End of Message Store Tables --

-- Start of Andes Context Store Tables --

--create table durable_subscriptions
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_DURABLE_SUBSCRIPTION]') AND TYPE IN (N'U'))
CREATE TABLE MB_DURABLE_SUBSCRIPTION (
                        SUBSCRIPTION_ID VARCHAR(512) NOT NULL,
                        DESTINATION_IDENTIFIER VARCHAR(512) NOT NULL,
                        SUBSCRIPTION_DATA VARCHAR(2048) NOT NULL
);

--create table node_info
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_NODE]') AND TYPE IN (N'U'))
CREATE TABLE MB_NODE (
                        NODE_ID VARCHAR(512) NOT NULL,
                        NODE_DATA VARCHAR(2048) NOT NULL,
                        PRIMARY KEY(NODE_ID)
);

--create table exchanges
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_EXCHANGE]') AND TYPE IN (N'U'))
CREATE TABLE MB_EXCHANGE (
                        EXCHANGE_NAME VARCHAR(512) NOT NULL,
                        EXCHANGE_DATA VARCHAR(2048) NOT NULL,
                        PRIMARY KEY(EXCHANGE_NAME)
);

--create table queue_info
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_QUEUE]') AND TYPE IN (N'U'))
CREATE TABLE MB_QUEUE (
                        QUEUE_NAME VARCHAR(512) NOT NULL,
                        QUEUE_DATA VARCHAR(2048) NOT NULL,
                        PRIMARY KEY(QUEUE_NAME)
);

--create table bindings
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_BINDING]') AND TYPE IN (N'U'))
CREATE TABLE MB_BINDING (
                        EXCHANGE_NAME VARCHAR(512) NOT NULL,
                        QUEUE_NAME VARCHAR(512) NOT NULL,
                        BINDING_DETAILS VARCHAR(2048) NOT NULL,
                        FOREIGN KEY (EXCHANGE_NAME) REFERENCES MB_EXCHANGE (EXCHANGE_NAME),
                        FOREIGN KEY (QUEUE_NAME) REFERENCES MB_QUEUE (QUEUE_NAME)
                               ON DELETE CASCADE
);

--create table queue_counter
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_QUEUE_COUNTER]') AND TYPE IN (N'U'))
CREATE TABLE MB_QUEUE_COUNTER (
                        QUEUE_NAME VARCHAR(512) NOT NULL,
                        MESSAGE_COUNT BIGINT,
                        PRIMARY KEY (QUEUE_NAME)
);

-- create table retained_content
IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_RETAINED_CONTENT]') AND TYPE IN (N'U'))
CREATE TABLE MB_RETAINED_CONTENT (
                MESSAGE_ID BIGINT,
                CONTENT_OFFSET INTEGER,
                MESSAGE_CONTENT VARBINARY(MAX) NOT NULL,
                PRIMARY KEY (MESSAGE_ID,CONTENT_OFFSET)
);

IF NOT EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[DB0].[MB_MSG_STORE_STATUS]') AND TYPE IN (N'U'))
CREATE TABLE MB_MSG_STORE_STATUS (
                        NODE_ID VARCHAR(512) NOT NULL,
                        TIME_STAMP BIGINT,
                        PRIMARY KEY(NODE_ID, TIME_STAMP)
);

-- End of Andes Context Store Tables --


text:
require 'spec_helper'
require 'custom_errors.rb'

describe CustomErrors, type: 'controller' do
  controller do
    include CustomErrors

    def raise_404
      raise ActiveRecord::RecordNotFound
    end

    def raise_500
      raise Exception
    end
  end

  before(:each) do
    Rails.stub_chain(:env, :production?).and_return(true)
  end

  context '404 errors' do
    before(:each) do
      routes.draw { get 'raise_404' => 'anonymous#raise_404' }
    end

    it 'should catch 404 errors' do

      get :raise_404
      expect(response).to render_template 'pages/404'
      expect(response.status).to eq 404
    end
  end

  context '500 errors' do
    before(:each) do
      routes.draw { get 'raise_500' => 'anonymous#raise_500' }
    end

    it 'should catch 500 errors' do
      get :raise_500
      expect(response).to render_template 'pages/500'
      expect(response.status).to eq 500
    end

    it 'should be able to adjust log stack trace limit' do
      dummy = Class.new
      Rails.stub(logger: dummy)
      dummy.should_receive(:error).exactly(7)
      get :raise_500
    end
  end
end


text:
package androidx.credentials;

import static org.junit.Assert.assertThrows;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

/**
 * Combines with {@link CreatePublicKeyCredentialRequestPrivilegedJavaTest} for full tests.
 */
@RunWith(Parameterized.class)
public class CreatePublicKeyCredentialRequestPrivilegedFailureInputsJavaTest {
    private String mRequestJson;
    private String mRp;
    private String mClientDataHash;

    private String mNullRequestJson;
    private String mNullRp;
    private String mNullClientDataHash;

    public CreatePublicKeyCredentialRequestPrivilegedFailureInputsJavaTest(String requestJson,
            String rp, String clientDataHash, String mNullRequestJson, String mNullRp,
            String mNullClientDataHash) {
        this.mRequestJson = requestJson;
        this.mRp = rp;
        this.mClientDataHash = clientDataHash;
        this.mNullRequestJson = mNullRequestJson;
        this.mNullRp = mNullRp;
        this.mNullClientDataHash = mNullClientDataHash;
    }

    @Parameterized.Parameters
    public static Iterable<String[]> failureCases() {
        // Allows checking improper formations for builder and normal construction.
        // Handles both null and empty cases.
        // For successful cases, see the non parameterized tests.
        return Arrays.asList(new String[][] {
                { "{\"hi\":21}", "rp", "", null, "rp", "hash"},
                { "", "rp", "clientDataHash", "{\"hi\":21}", null, "hash"},
                { "{\"hi\":21}", "", "clientDataHash", "{\"hi\":21}", "rp", null}
        });
    }

    @Test
    public void constructor_emptyInput_throwsIllegalArgumentException() {
        assertThrows("If at least one arg empty, should throw IllegalArgumentException",
                IllegalArgumentException.class,
                () -> new CreatePublicKeyCredentialRequestPrivileged(this.mRequestJson, this.mRp,
                        this.mClientDataHash)
        );
    }

    @Test
    public void builder_build_emptyInput_IllegalArgumentException() {
        CreatePublicKeyCredentialRequestPrivileged.Builder builder =
                new CreatePublicKeyCredentialRequestPrivileged.Builder(mRequestJson, mRp,
                        mClientDataHash);
        assertThrows("If at least one arg empty to builder, should throw "
                        + "IllegalArgumentException",
                IllegalArgumentException.class,
                () -> builder.build()
        );
    }

    @Test
    public void constructor_nullInput_throwsNullPointerException() {
        convertAPIIssueToProperNull();
        assertThrows("If at least one arg null, should throw NullPointerException",
                NullPointerException.class,
                () -> new CreatePublicKeyCredentialRequestPrivileged(this.mNullRequestJson,
                        this.mNullRp,
                        this.mNullClientDataHash)
        );
    }

    @Test
    public void builder_build_nullInput_throwsNullPointerException() {
        convertAPIIssueToProperNull();
        assertThrows(
                "If at least one arg null to builder, should throw NullPointerException",
                NullPointerException.class,
                () -> new CreatePublicKeyCredentialRequestPrivileged.Builder(mNullRequestJson,
                                mNullRp, mNullClientDataHash).build()
        );
    }

    // Certain API levels have parameterized tests that automatically convert null to a string
    // 'null' causing test failures. Until Parameterized tests fixes this bug, this is the
    // workaround. Note this is *not* always the case but only for certain API levels (we have
    // recorded 21, 22, and 23 as such levels).
    private void convertAPIIssueToProperNull() {
        if (mNullRequestJson != null && mNullRequestJson.equals("null")) {
            mNullRequestJson = null;
        }
        if (mNullRp != null && mNullRp.equals("null")) {
            mNullRp = null;
        }
        if (mNullClientDataHash != null && mNullClientDataHash.equals("null")) {
            mNullClientDataHash = null;
        }
    }
}


text:
layout: post
title: Pervcity s dirty slut Tori Lux anal play
titleinfo: pornvd
desc: Watch Pervcity s dirty slut Tori Lux anal play. Pornhub is the ultimate xxx porn and sex site.
---

Pervcity s dirty slut Tori Lux anal play

Watch Pervcity s dirty slut Tori Lux anal play. Pornhub is the ultimate xxx porn and sex site.


text:
package io.gravitee.definition.jackson.datatype;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.gravitee.definition.jackson.datatype.api.ApiModule;
import io.gravitee.definition.jackson.datatype.api.DebugApiModule;
import io.gravitee.definition.jackson.datatype.plugins.resource.ResourceModule;
import io.gravitee.definition.jackson.datatype.services.core.ServiceModule;
import io.gravitee.definition.jackson.datatype.services.discovery.EndpointDiscoveryModule;
import io.gravitee.definition.jackson.datatype.services.dynamicproperty.DynamicPropertyModule;
import io.gravitee.definition.jackson.datatype.services.healthcheck.HealthCheckModule;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class GraviteeMapper extends ObjectMapper {

    private static final long serialVersionUID = 1L;

    public GraviteeMapper() {
        registerModule(new ApiModule(this));
        registerModule(new ServiceModule());
        registerModule(new HealthCheckModule());
        registerModule(new DynamicPropertyModule());
        registerModule(new EndpointDiscoveryModule());
        registerModule(new ResourceModule());
        registerModule(new DebugApiModule());

        enable(SerializationFeature.INDENT_OUTPUT);
        enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        setSerializationInclusion(JsonInclude.Include.NON_NULL);
        enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
        enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
        disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
        disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }
}


text:
require 'workbench/string_helpers'

module Workbench
  COUNTERS = Hash.new(0)

  module InstanceMethods
    def assign_model_attributes(model, attributes)
      attributes.each do |k, v|
        model.send("#{k}=", v)
      end
    end

    def save_model(model)
      if model.respond_to?(:save!) # save should raise if unsuccessful
        model.save!
      else
        model.save
      end
    end

    def find_model_by_attributes(klass, attributes)
      klass.where(attributes).first
    end

    def new_model(klass)
      klass.new
    end
  end

  def self.extended(klass)
    klass.send :include, InstanceMethods
  end

  # Declare that the next builder method is to use the said class
  #
  #   module Builders
  #     extend Workbench
  #
  #     def user_defaults(u)
  #       ...
  #     end
  #
  #     use_class :User
  #     def admin_user_defaults(u)
  #       ...
  #     end
  #   end
  #
  # === Parameters:
  #
  # name:: - Symbol such as :User or string such as "Models::User" are
  #          acceptable
  def use_class(name)
    @next_class = name
  end

  # Declare that the next builder method is to count scoped to the following class
  #
  #   module Builders
  #     extend Workbench
  #
  #     def book_defaults(u, n)
  #       ...
  #     end
  #
  #     count_with :Book
  #     def article_defaults(u, n)
  #       ...
  #     end
  #   end
  #
  #   new_book        # n = 1
  #   new_publication # n = 2
  #   new_book        # n = 3
  #
  # === Parameters:
  #
  # +name+:: - a Symbol (ie :User) or string (is "Models::User") that
  #            maps to a valid class name.
  def count_with(name)
    @next_count_with = name
  end

  # The counter routine. Provide a key, get back an incrementer.
  def self.counter(key)
    COUNTERS[key] += 1
  end

  # Reset all counters. It doesn't happen automatically, you'll likley
  # want to call this method before or after each test is run
  def self.reset_counters!
    COUNTERS.clear
  end

private
  def method_added(name)
    if builder_name = inferred_builder_class_name(name)
      klass         = StringHelpers.constantize(@next_class || builder_name)
      counter_klass = StringHelpers.constantize(@next_count_with || klass)
      define_builder_methods(builder_name, klass, counter_klass)
      @next_class, @next_count_with = nil
    end
    super
  end

  def define_builder_methods(name, klass, counter_klass)
    define_method("new_#{name}") do |*args|
      attributes = args[0] || { }
      new_model(klass).tap do |model|
        assign_model_attributes(model, attributes)
        build_method = method("#{name}_defaults")
        p = [model]
        p << Workbench.counter(counter_klass) if build_method.arity >= 2 || build_method.arity <= -1
        p << attributes                       if build_method.arity >= 3 || build_method.arity <= -1
        build_method.call *p
      end
    end

    define_method("create_#{name}") do |*args|
      send("new_#{name}", *args).tap { |model| save_model(model) }
    end

    define_method("find_or_create_#{name}") do |*args|
      attrs = args[0] || { }
      find_model_by_attributes(klass, attrs) || send("create_#{name}", attrs)
    end
  end

  def inferred_builder_class_name(name)
    if name.to_s.match(/^(.+)_defaults$/)
      $1.to_sym
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Azure.Core;

namespace Azure.Identity
{
    /// <summary>
    /// An exception indicating that interactive authentication is required.
    /// </summary>
    public class AuthenticationRequiredException : CredentialUnavailableException
    {
        /// <summary>
        /// Creates a new <see cref="AuthenticationRequiredException"/> with the specified message and context.
        /// </summary>
        /// <param name="message">The message describing the authentication failure.</param>
        /// <param name="context">The details of the authentication request.</param>
        public AuthenticationRequiredException(string message, TokenRequestContext context)
            : this(message, context, default)
        {

        }

        /// <summary>
        /// Creates a new <see cref="AuthenticationRequiredException"/> with the specified message, context and inner exception.
        /// </summary>
        /// <param name="message">The message describing the authentication failure.</param>
        /// <param name="context">The details of the authentication request.</param>
        /// <param name="innerException">The exception underlying the authentication failure.</param>
        public AuthenticationRequiredException(string message, TokenRequestContext context, Exception innerException)
            : base(message, innerException)
        {
            TokenRequestContext = context;
        }

        /// <summary>
        /// The details of the authentication request which resulted in the authentication failure.
        /// </summary>
        public TokenRequestContext TokenRequestContext { get; }
    }
}


text:
window.DTTREE = (function(window, document) {

    var EXPANDED_TOGGLER_CLASS = "fa fa-minus-square-o";
    var COLLAPSED_TOGGLER_CLASS = "fa fa-plus-square-o";
    var NODE_TOGGLER_CLASS = 'dttree-node-toggler';
    var NODES_ELEMENT = 'UL';
    var NODE_ELEMENT = 'LI';
    var NODE_CLASS = 'dttree-node';

    // render single node to node element
    // if node contains nodes, then it will
    // recursively rendered as well
    var _renderNode = function(node, parent) {

          var text = node.text;

          // @todo replace special char
          node.id = '_'+node.text.replace(" ", "_");

          if(typeof(parent) !== 'undefined') {
            node.id = parent.id+node.id;
          }

          var path = node.path;

          var a = _create('A', {href: path})
              .addClass(NODE_CLASS)
              .append(' '+text);

          $(a).data('node', node);

          var li = _create(NODE_ELEMENT, {id: node.id});

          if($.isArray(node.nodes)) {
            var toggler = _createNodeToggler(node, node.expanded);
            toggler.data('node', node);
            li.append(toggler);
          }

          li.append(a);

          if($.isArray(node.nodes)) {
              var ul = _renderNodes(node.nodes, node);
              li.append(ul);

              if(!node.expanded) {
                $(ul).hide();
              }
          }

          node.HTMLNode = li;

          return li;
    };

    // data prototype: // var nodes = [{path: '/', text: '/'}]
    // path and text is mandatory
    var _renderNodes = function (nodes, parent){

          if(nodes.length > 0) {
              var ul =  _create(NODES_ELEMENT);
              $(ul).css('padding-left', "15px");
              $(ul).css('list-style', "none");

              for(i=0; i<nodes.length; i++) {

                if(DTTREE.options.filterNode(nodes[i])) {
                  var li = _renderNode(nodes[i], parent);
                  $(ul).append(li);
                }
              }

              return ul;
          }

          return null;
    };

    var _createNodeToggler = function(node, expanded) {
        var togglerClass = expanded ? EXPANDED_TOGGLER_CLASS
            : COLLAPSED_TOGGLER_CLASS;

        var togglerIcon = _create('I').addClass(togglerClass);

        var toggler = _create('A', {href: 'javascript:;'})
            .addClass(NODE_TOGGLER_CLASS)
            .append(togglerIcon)
            .data('node', node);

        return toggler;
    }

    var _validateNode= function(node) {
        if (typeof node.text == "undefined" ||
            typeof node.path == "undefined"
            ) {

            throw new TypeError("Node is not contain required properties");
        }

        return true;
    };

    // Create element
    var _create = function(name, attr) {
        var el = document.createElement(name);

        if(typeof attr != 'undefined') {
            $.each( attr, function( key, value ) {
                $(el).attr(key, value);
            });
        }

        return $(el);
    };

    // Default Options
    var _OPTIONS = {
        nodes: [{path: "/", text: "/"}],
        filterNode: function(node) {
          return true;
        },
        onBeforeExpand: false
    }

    var ret = {
        el: null,
        $el: null,
        options: _OPTIONS,

        init: function(el, options) {
            this.el = el;
            this.$el = $(el);
            this.options = $.extend(true, _OPTIONS, options);

            var root = _renderNodes(this.options.nodes);
            $(this.el).append(root);

            this.listen();
        },

        expand: function(node) {

            if($.isFunction(this.options.onBeforeExpand)) {
                this.options.onBeforeExpand(node, this);
            }

            var path = node.path

            var li =  node.HTMLNode;

            var i = $(li).children('.'+NODE_TOGGLER_CLASS).children('i');

            i.removeClass(COLLAPSED_TOGGLER_CLASS);
            i.addClass(EXPANDED_TOGGLER_CLASS);

            $(li).children(NODES_ELEMENT).slideDown('fast');

            node.collapsed = false;
        },

        collapse: function(node) {

            var li =  node.HTMLNode;
            var i = $(li).children('.'+NODE_TOGGLER_CLASS).children('i');

            i.removeClass(EXPANDED_TOGGLER_CLASS);
            i.addClass(COLLAPSED_TOGGLER_CLASS);

            $(li).children(NODES_ELEMENT).slideUp('fast');

            node.collapsed = true;
        },

        listen: function() {

            var _this = this;

            $(this.el).on('click', 'a.'+NODE_TOGGLER_CLASS, function(e){
                e.preventDefault();

                var toggler = $(this);

                var node = toggler.data('node');

                if(typeof node.collapsed === 'undefined') {
                    _this.expand(node);
                } else {
                    if(node.collapsed) {
                        _this.expand(node);
                    } else {
                        _this.collapse(node);
                    }
                }
            });
        },

        redraw: function(node) {

          var li = node.HTMLNode;
          var html = _renderNodes(node.nodes, node);

          $(html).hide();
          li.append(html);
        },
    }

    // We return private if its test
    if(typeof window.DTTREE_TEST != 'undefined') {
        ret = $.extend(ret, {
            create: _create,
            validateNode: _validateNode,
            createNodeToggler: _createNodeToggler,
            renderNode: _renderNode,
        });
    }

    return ret;

})(window, document);


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseIsNullCheck;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIsNullCheck
{
    using VerifyCS = CSharpCodeFixVerifier<CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer, CSharpUseNullCheckOverTypeCheckCodeFixProvider>;

    [Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNullCheck)]
    public class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzerTests
    {
        private static async Task VerifyAsync(string source, string fixedSource, LanguageVersion languageVersion)
        {
            await new VerifyCS.Test
            {
                TestCode = source,
                FixedCode = fixedSource,
                LanguageVersion = languageVersion,
            }.RunAsync();
        }

        private static async Task VerifyCSharp9Async(string source, string fixedSource)
            => await VerifyAsync(source, fixedSource, LanguageVersion.CSharp9);

        private static async Task VerifyCSharp8Async(string source, string fixedSource)
            => await VerifyAsync(source, fixedSource, LanguageVersion.CSharp8);

        [Fact]
        public async Task TestIsObjectCSharp8()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return value is object;
    }
}
";
            await VerifyCSharp8Async(source, source);
        }

        [Fact]
        public async Task TestIsObject()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return [|value is object|]/*comment*/;
    }
}
";
            var fixedSource = @"
public class C
{
    public bool M(string value)
    {
        return value is not null/*comment*/;
    }
}
";
            await VerifyCSharp9Async(source, fixedSource);
        }

        [Fact]
        public async Task TestIsObject2()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return value is object x;
    }
}
";
            await VerifyCSharp9Async(source, source);
        }

        [Fact]
        public async Task TestIsNotObject()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return value is [|not object|];
    }
}
";
            var fixedSource = @"
public class C
{
    public bool M(string value)
    {
        return value is null;
    }
}
";
            await VerifyCSharp9Async(source, fixedSource);
        }

        [Fact]
        public async Task TestIsNotObject2()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return value is not object o;
    }
}
";
            await VerifyCSharp9Async(source, source);
        }

        [Fact]
        public async Task TestIsStringAgainstObject_NoDiagnostic()
        {
            var source = @"
public class C
{
    public bool M(object value)
    {
        return value is string;
    }
}
";
            await VerifyCSharp9Async(source, source);
        }

        [Fact]
        public async Task TestIsStringAgainstString()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return [|value is string|];
    }
}
";
            var fixedSource = @"
public class C
{
    public bool M(string value)
    {
        return value is not null;
    }
}
";
            await VerifyCSharp9Async(source, fixedSource);
        }

        [Fact]
        public async Task TestIsNotStringAgainstObject_NoDiagnostic()
        {
            var source = @"
public class C
{
    public bool M(object value)
    {
        return value is string;
    }
}
";
            await VerifyCSharp9Async(source, source);
        }

        [Fact]
        public async Task TestIsNotStringAgainstString()
        {
            var source = @"
public class C
{
    public bool M(string value)
    {
        return value is [|not string|];
    }
}
";
            var fixedSource = @"
public class C
{
    public bool M(string value)
    {
        return value is null;
    }
}
";
            await VerifyCSharp9Async(source, fixedSource);
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product_model extends CI_Model {

	public function product_insert($data)
	{
		echo '<pre>';
		print_r($data);
		$this->db->insert('photos', $data);
	}
}

/* End of file Product.php */
/* Location: ./application/models/Product.php */


text:
namespace gil = boost::gil;

#ifdef BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES

// CHH - not supported palette
//BOOST_PP_REPEAT_FROM_TO(9, 17, GENERATE_TILE_STRIP_COMPARISON_PALETTE, palette )

int main()
{
    // TODO: Make sure generated test cases are executed. See tiff_subimage_test.cpp. ~mloskot

    return boost::report_errors();
}

#else
int main() {}
#endif // BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES


text:
package com.wills.help.person.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.wills.help.R;
import com.wills.help.base.App;
import com.wills.help.base.BaseActivity;
import com.wills.help.net.HttpMap;
import com.wills.help.person.presenter.IdCheckPresenterImpl;
import com.wills.help.person.view.IdCheckView;
import com.wills.help.photo.model.PhotoModel;
import com.wills.help.photo.ui.PhotoSelectorActivity;
import com.wills.help.utils.AppConfig;
import com.wills.help.utils.GlideUtils;
import com.wills.help.utils.IntentUtils;
import com.wills.help.utils.StringUtils;
import com.wills.help.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Map;

/**
 * com.wills.help.person.ui
 * Created by lizhaoyong
 * 2016/11/17.
 */

public class IdentificationActivity extends BaseActivity implements View.OnClickListener , IdCheckView{

    private EditText et_name, et_sno;
    private TextView tv_grade, tv_specialty;
    private ImageView iv_photo;
    private Button btn_upload, btn_submit;
    private IdCheckPresenterImpl idCheckPresenter;
    String[] grade = new String[]{"本科一年级","本科二年级","本科三年级","本科四年级","研究生一年级","研究生二年级","研究生三年级"};
    String[] specialty = new String[]{"机械工程","金融","计算机科学与技术","马克思","会计","物联网","通信","医学","环境","水利","土木","美术"};

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setBaseView(R.layout.activity_identification);
        setBaseTitle(getString(R.string.identification));
        et_name = (EditText) findViewById(R.id.et_name);
        et_name.setText(App.getApp().getUser().getNickname());
        et_name.setEnabled(false);
        et_sno = (EditText) findViewById(R.id.et_sno);
        tv_grade = (TextView) findViewById(R.id.tv_grade);
        tv_specialty = (TextView) findViewById(R.id.tv_specialty);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        btn_upload = (Button) findViewById(R.id.btn_upload);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        tv_grade.setOnClickListener(this);
        tv_specialty.setOnClickListener(this);
        btn_upload.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        if (App.getApp().getUser().getUsertype().equals("1")){
            et_sno.setText(App.getApp().getUser().getSchool_num());
            et_sno.setEnabled(false);
            btn_submit.setText(getString(R.string.approved));
            btn_submit.setEnabled(false);
        }else {
            et_sno.addTextChangedListener(new EditTextChange());
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_grade:
                showAlert(grade,tv_grade);
                break;
            case R.id.tv_specialty:
                showAlert(specialty,tv_specialty);
                break;
            case R.id.btn_upload:
                Bundle bundle = new Bundle();
                bundle.putInt("action", AppConfig.PHOTO);
                bundle.putInt("size", 1);
                IntentUtils.startActivityForResult(IdentificationActivity.this, PhotoSelectorActivity.class,bundle,AppConfig.PHOTO);
                break;
            case R.id.btn_submit:
                if (btn_submit.getText().equals(getString(R.string.approve))){
                    if (idCheckPresenter == null){
                        idCheckPresenter = new IdCheckPresenterImpl(IdentificationActivity.this);
                    }
                    idCheckPresenter.idCheck(getMap());
                }else {
                    if (App.getApp().getUser().getUsertype().equals("1")){
                        btn_submit.setText(getString(R.string.approved));
                        btn_submit.setEnabled(false);
                    }else {
                        ToastUtils.toast(getString(R.string.identification_warn));
                    }
                }
                break;
        }
    }

    private Map<String ,String> getMap(){
        HttpMap map = new HttpMap();
        map.put("userid", App.getApp().getUser().getUserid());
        map.put("email", et_sno.getText().toString()+"@bjtu.edu.cn");
        return map.getMap();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConfig.PHOTO&&resultCode == RESULT_OK){
            ArrayList<PhotoModel> arrayList = new ArrayList<>();
            Bundle bundle = data.getExtras();
            arrayList = (ArrayList<PhotoModel>) bundle.getSerializable("photos");
            if (arrayList!=null&&arrayList.size()>0){
                GlideUtils.getInstance().displayImage(context,arrayList.get(0).getOriginalPath(),iv_photo);
                btn_upload.setText(getString(R.string.reupload));
            }
        }
    }

    private void showAlert(final String[] strings , final TextView textView){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setItems(strings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(strings[i]);
            }
        }).show();
    }

    @Override
    public void setIdCheck() {
        ToastUtils.toast(getString(R.string.identification_toast));
        btn_submit.setText(getString(R.string.identification_email));
    }

    public class EditTextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!StringUtils.isNullOrEmpty(et_sno.getText().toString())) {
                btn_submit.setEnabled(true);
                btn_submit.setBackgroundResource(R.drawable.btn_selector);
            } else {
                btn_submit.setEnabled(false);
                btn_submit.setBackgroundResource(R.color.button_gray);
            }
        }
    }
}


text:
"""
OEShape utilities.
"""

__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "3-clause BSD"

import numpy as np

from openeye.oechem import *
from openeye.oeshape import *

from oe_utils.chem import transform

class ROCS(OEBestOverlay):
    """
    Rapid overlay of chemical structures.

    Parameters
    ----------
    use_hydrogens : bool, optional (default False)
        Include hydrogens in shape overlap.
    color_ff : int, optional (default OEColorFFType_ImplicitMillsDean)
        Color force field.
    color_opt : bool, optional (default True)
        Include color in overlap optimization.
    all_color : bool, optional (default True)
        Calculate full pairwise color atom overlaps.
    radii_approx : int, optional (default OEOverlapRadii_All)
        Radii approximation method.
    overlap_method : int, optional (default OEOverlapMethod_Analytic)
        Overlap method.
    initial_orientation : int, optional (default OEBOOrientation_Inertial)
        Method for generating initial overlap orientations.
    """
    def __init__(
            self, use_hydrogens=False,
            color_ff=OEColorFFType_ImplicitMillsDean, color_opt=True,
            all_color=True, radii_approx=OEOverlapRadii_All,
            overlap_method=OEOverlapMethod_Analytic,
            initial_orientation=OEBOOrientation_Inertial):
        super(ROCS, self).__init__()
        self.SetUseHydrogens(use_hydrogens)
        self.SetColorForceField(color_ff)
        self.SetColorOptimize(color_opt)
        self.SetAllColor(all_color)
        self.SetRadiiApproximation(radii_approx)
        self.SetMethod(overlap_method)
        self.SetInitialOrientation(initial_orientation)

    def overlay(self, fit_mol, sort=OEHighestTanimotoCombo(), n_best=None):
        """
        Perform ROCS alignment and scoring.

        Parameters
        ----------
        fit_mol : OEMol
            Fit molecule.
        sort : OEBinaryPredicate, optional (default OEHighestTanimotoCombo())
            Sort predicate.
        n_best : int, optional
            Number of results to return after sorting. If None, all results are
            returned.
        """
        assert n_best is None or n_best > 0
        result = self.Overlay(fit_mol)
        for i, this_result in enumerate(
                self.parse_overlay_results(result, sort)):
            if n_best is not None and i >= n_best:
                break
            yield this_result

    def get_best_overlay(self, fit_mol, sort=OEHighestTanimotoCombo()):
        """
        Perform ROCS alignment and scoring and return the best result.

        Parameters
        ----------
        fit_mol : OEMol
            Fit molecule.
        sort : OEBinaryPredicate, optional (default OEHighestTanimotoCombo())
            Sort predicate.
        """
        results = list(self.overlay(fit_mol, sort=sort, n_best=1))
        assert len(results) == 1  # sanity check
        return results[0]

    @staticmethod
    def parse_overlay_results(result, sort=OEHighestTanimotoCombo()):
        """
        Parse overlay results.

        Parameters
        ----------
        result : OEBestOverlayResultIter
            Overlay result returned by OEBestOverlay.Overlay.
        sort : OEBinaryPredicate, optional (default OEHighestTanimotoCombo())
            Sort predicate.
        """
        score_iter = OEBestOverlayScoreIter()
        OESortOverlayScores(score_iter, result, sort)
        for score in score_iter:
            yield ROCSResult(score)

    @staticmethod
    def get_aligned_confs(ref_mol, fit_mol, result, copy=True):
        """
        Get aligned conformers matching a given result.

        Parameters
        ----------
        ref_mol : OEMol
            Reference molecule.
        fit_mol : OEMol
            Fit molecule.
        result : ROCSResult
            Overlay result.
        copy : bool, optional (default True)
            Create a copy of the fit conformer before transforming.
        """
        ref_conf = ref_mol.GetConf(OEHasConfIdx(result.ref_conf_idx))
        fit_conf = fit_mol.GetConf(OEHasConfIdx(result.fit_conf_idx))
        fit_conf = result.transform(fit_conf, copy=copy)
        return ref_conf, fit_conf

    @staticmethod
    def group_results(results):
        """
        Extract scores from each overlay into arrays for each score type.

        Parameters
        ----------
        scores : array_like
            2D array containing overlay results.
        """
        results = np.atleast_2d(results)
        shape = results.shape
        scalar_keys = [
            'ref_conf_idx', 'fit_conf_idx', 'shape_tanimoto', 'shape_overlap',
            'ref_self_shape', 'fit_self_shape', 'color_tanimoto',
            'color_overlap', 'ref_self_color', 'fit_self_color']
        data = {key: np.zeros(shape, dtype=float) for key in scalar_keys}
        data['rotation'] = np.zeros(shape + (9,), dtype=float)
        data['translation'] = np.zeros(shape + (3,), dtype=float)
        for i, this_results in enumerate(results):
            for j, result in enumerate(this_results):
                for key in scalar_keys + ['rotation', 'translation']:
                    data[key][i, j] = getattr(result, key)
        return data

class ROCSResult(object):
    """
    ROCS overlay result.

    Parameters
    ----------
    result : OEBestOverlayScore
        Overlay result from OEBestOverlayScoreIter.
    """
    def __init__(self, result):

        # conformer indices
        self.ref_conf_idx = result.refconfidx
        self.fit_conf_idx = result.fitconfidx

        # shape
        self.shape_tanimoto = result.GetShapeTanimoto()
        self.shape_overlap = result.overlap
        self.ref_self_shape = result.refSelfOverlap
        self.fit_self_shape = result.fitSelfOverlap

        # color
        self.color_tanimoto = result.GetColorTanimoto()
        self.color_overlap = result.colorscore
        self.ref_self_color = result.refSelfColor
        self.fit_self_color = result.fitSelfColor

        # overlay
        rotation = OEFloatArray(9)
        result.GetRotMatrix(rotation)
        self.rotation = np.asarray(rotation, dtype=float)
        translation = OEFloatArray(3)
        result.GetTranslation(translation)
        self.translation = np.asarray(translation, dtype=float)
        self.transformer = transform.MolTransform(
            rotation=self.rotation, translation=self.translation)

    def transform(self, fit_mol, copy=True):
        """
        Transform fit_mol into alignment with ref_mol.

        Parameters
        ----------
        fit_mol : OEMol
            Fit molecule.
        copy : bool, optional (default True)
            Create a copy of the fit conformer before transforming.
        """
        return self.transformer.transform(fit_mol, copy=copy)


text:
import { DefaultPipe } from './Default';

describe('Pipe: Default', () => {
  let pipe;

  beforeEach(() => {
    pipe = new DefaultPipe();
  });

  describe('When rendering', () => {
    it('should use default when null', () => {
      const val = pipe.transform(null, 'default');
      expect(val).toBe('default');
    });
    it('should use default when undefined', () => {
      const val = pipe.transform(undefined, 'default');
      expect(val).toBe('default');
    });
    it('should not use default when has value', () => {
      const val = pipe.transform('value', 'default');
      expect(val).toBe('value');
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivisionByZeroLevelBuilder
{
    public class RecentFile
    {
        public string fileName;
        public string levelName;
        public string fullPath;
    }

    public class RecentList
    {
        private static RecentList instance;

        private const string FILE_RECENT = "recent";
        private const int MAX_RECENT = 5;

        private List<RecentFile> recentFiles = new List<RecentFile>(MAX_RECENT);
        // path, index
        private Dictionary<String, RecentFile> set = new Dictionary<String, RecentFile>();

        private RecentList() { }

        public static RecentList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RecentList();
                }
                return instance;
            }
        }

        public void Load(string folder)
        {
            string file = folder + "\\" + FILE_RECENT;
            if (!System.IO.File.Exists(file))
            {
                return;
            }

            using (System.IO.StreamReader reader = new System.IO.StreamReader(file))
            {
                string line = "";
                for (int i = 0; i < MAX_RECENT && (line = reader.ReadLine()) != null; i++)
                {
                    line = line.Trim();
                    if (line.Length == 0)
                    {
                        i--;
                        continue;
                    }
                    else
                    {
                        string[] tokens = line.Split('|');
                        if (tokens.Length != 2)
                        {
                            // something is wrong... we are only expecting two tokens
                            // crash quietly...
                            return;
                        }
                        else
                        {
                            AddRecent(tokens[0], tokens[1]);
                        }
                    }
                }
            }
        }

        public void Save(string folder)
        {
            string file = folder + "\\" + FILE_RECENT;
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(file))
            {
                foreach (RecentFile f in recentFiles)
                {
                    writer.WriteLine("{0}|{1}", f.fullPath, f.levelName);
                }
            }
        }

        public List<RecentFile> GetRecentFiles()
        {
            return recentFiles;
        }

        public void AddRecent(string path, string levelName)
        {
            RecentFile val;
            if (set.TryGetValue(path, out val))
            {
                recentFiles.Remove(val);
            }

            string name = levelName;
            RecentFile recent = new RecentFile();
            recent.fullPath = path;
            recent.levelName = name;

            int start = path.LastIndexOf('\\');
            int end = path.LastIndexOf('.');
            string fileName = path.Substring(start + 1, (end - start) - 1);
            recent.fileName = fileName;

            recentFiles.Add(recent);
            if (!set.ContainsKey(path))
            {
                set.Add(path, recent);
                if (recentFiles.Count > MAX_RECENT)
                {
                    set.Remove(recentFiles[0].fullPath);
                    recentFiles.RemoveAt(0);
                }
            }
            else
            {
                set[path] = recent;
            }
        }
    }
}


text:
using UnityEngine;
using UnityEngine.EventSystems;

public class EditableListItem : MonoBehaviour, IDragHandler
{
  [SerializeField] RectTransform container;
  [SerializeField] RectTransform contentContainer;
  [SerializeField] UnityEngine.UI.Button deleteButton;
  [SerializeField] RectTransform disabledOverlay;

  public event System.Action<EditableListItem> onRequestDelete;
  public event System.Action<EditableListItem> onDrag;

  void Awake()
  {
    deleteButton.onClick.AddListener(() =>
    {
      onRequestDelete?.Invoke(this);
    });
  }

  public RectTransform GetContainer()
  {
    return container;
  }

  public RectTransform GetContentContainer()
  {
    return contentContainer;
  }

  public void RequestDestroy()
  {
    Destroy(gameObject);
  }

  public void OnDrag(PointerEventData data)
  {
    onDrag?.Invoke(this);
  }

  public void SetDraggingFeedback(bool visible)
  {
    disabledOverlay.gameObject.SetActive(visible);
  }

}


text:
layout: post
title: "DNE 352 - O frontend dentro dos ecommerces"
home-title: "O frontend dentro dos ecommerces"
type: "Pauta"
cast: "DNE_352.mp3"
cast-length: "78462498"
cast-time: "01:21:40"
description: |
  Neste episódio o assunto é sobre "O frontend dentro dos ecommerces", Emilio Aiolfi com os convidados Adriano Azevedo (frontend no Tok%26Stok) e Carlysson Oliveira (frontend no Grupo SBF) conversam sobre os tipos de arquiteturas, abordagens, problemas, desafios e "Black Friday"
libsyn-image: "dne352.jpeg"
lybsyn-id: "24388965"
participants:
  -
    name: Emilio Aiolfi
    twitter: EmilioAiolfi
  -
    name: Adriano Azevedo
    twitter: drianoaz
  -
    name: Carlysson Oliveira
    twitter: Carlysson21

links:
  -
    name: "DNE no Twitter"
    url: https://twitter.com/devnaestrada
  -
    name: "DNE no Instagram"
    url: https://www.instagram.com/devnaestrada/

---

Neste episódio o assunto é sobre "O frontend dentro dos ecommerces", Emilio Aiolfi com os convidados Adriano Azevedo (frontend no Tok%26Stok) e Carlysson Oliveira (frontend no Grupo SBF) conversam sobre os tipos de arquiteturas, abordagens, problemas, desafios e "Black Friday"

CUPOM STICKERSDEVS 15%: DEVNAESTRADA

---

{% include modules/post-extras.html data=page %}


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

#include "UNIX_VirtualComputerSystemFixture.h"
#include "MockMethodResultResponseHandler.h"

#include <VirtualComputerSystem/UNIX_VirtualComputerSystemProvider.h>

UNIX_VirtualComputerSystemFixture::UNIX_VirtualComputerSystemFixture(const char *target)
{
	realTarget = target;
}

UNIX_VirtualComputerSystemFixture::~UNIX_VirtualComputerSystemFixture()
{
}

void UNIX_VirtualComputerSystemFixture::Run()
{
	CIMName className(realTarget);
	CIMNamespaceName nameSpace("root/cimv2");
	UNIX_VirtualComputerSystem _p;
	UNIX_VirtualComputerSystemProvider _provider;
	UNIX_VirtualComputerSystemProvider _provider2;
	Uint32 propertyCount;
	CIMOMHandle omHandle;

	OperationContext operationContext;

	_provider.initialize(omHandle);
	_p.initialize();

	for(int pIndex = 0; _p.load(pIndex); pIndex++)
	{
		CIMInstance instance = _provider.constructInstance(className,
					nameSpace,
					_p);
		CIMObjectPath path = instance.getPath();
		cout << path.toString() << endl;
		propertyCount = instance.getPropertyCount();
		for(Uint32 i = 0; i < propertyCount; i++)
		{

			CIMProperty propertyItem = instance.getProperty(i);
			cout << "	Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;

		}
		cout << "------------------------------------" << endl;
		cout << endl;

		/* TESTING INVOKE METHOD */
		/* SHUTTINGDOWN JAIL */
		/*
		Array<CIMParamValue> inParameters;
		inParameters.append(CIMParamValue(String("RequestedState"), CIMValue(Uint32(6))));
		inParameters.append(CIMParamValue(String("TimeoutPeriod"), CIMValue(CIMDateTime(10, true))));
		MockMethodResultResponseHandler handler;
		_provider2.invokeMethod(
			operationContext,
			path,
			CIMName("RequestStateChange"),
			inParameters,
			handler
		);
		*/
	}
	_p.finalize();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <TITLE>
            org.encog.neural.freeform.task (Encog Core 3.2.0-SNAPSHOT API)
        </TITLE>

        <META NAME="date" CONTENT="2013-04-17">

        <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

            org.encog.neural.freeform.task

                        Interfaces

                        ConnectionTask

                        NeuronTask


text:
<?php

	//Conectando ao banco de dados
	include "conexao.php";

    $query =  "SELECT ani_id, ani_latitude , ani_longitude, ani_nome, ani_imgpath, raca.raca_nome, tipo_animal.tipoani_nome, ani_porte, situacao.sit_nome FROM animal
	INNER JOIN raca ON animal.ani_raca = raca.raca_id
	INNER JOIN tipo_animal ON tipo_animal.tipoani_id = raca.raca_tipoanimal
	INNER JOIN situacao ON situacao.sit_id = animal.ani_situacao";

	// -- Variavel $con é retorno de conexao.php
	$retorno = mysqli_query($con,$query);

	 while($resultado = mysqli_fetch_assoc($retorno)){
        $vetor[] = array_map('utf8_encode', $resultado);
    }

    //Passando vetor em forma de json
    echo json_encode($vetor);

?>


text:
<?php

namespace App\Containers\AppSection\Authorization\Actions;

use App\Containers\AppSection\Authorization\Exceptions\RoleNotFoundException;
use App\Containers\AppSection\Authorization\Models\Role;
use App\Containers\AppSection\Authorization\Tasks\FindRoleTask;
use App\Containers\AppSection\Authorization\UI\API\Requests\FindRoleRequest;
use App\Ship\Parents\Actions\Action;

class FindRoleAction extends Action
{
    public function run(FindRoleRequest $request): Role
    {
        $role = app(FindRoleTask::class)->run($request->id);

        if (!$role) {
            throw new RoleNotFoundException();
        }

        return $role;
    }
}


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.RemoveVmTemplateInterfaceParameters;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmInterfaceType;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;

public class RemoveVmTemplateInterfaceCommand<T extends RemoveVmTemplateInterfaceParameters> extends VmTemplateCommand<T> {

    public RemoveVmTemplateInterfaceCommand(T parameters) {
        super(parameters);
    }

    @Override
    protected void executeCommand() {
        AddCustomValue("InterfaceName", ((getParameters().getInterface().getName())));
        AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString());
        DbFacade.getInstance().getVmDeviceDAO().remove(
                new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmTemplateId()));
        DbFacade.getInstance().getVmNetworkInterfaceDAO().remove(getParameters().getInterface().getId());
        setSucceeded(true);
    }

    @Override
    protected boolean canDoAction() {
        return true;
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        return getSucceeded() ? AuditLogType.NETWORK_REMOVE_TEMPLATE_INTERFACE
                : AuditLogType.NETWORK_REMOVE_TEMPLATE_INTERFACE_FAILED;
    }
}


text:
.. include:: references.txt

.. _working_with_angles:

Working with Angles
*******************

The angular components of the various coordinate objects are represented
by objects of the |Angle| class. While most likely to be encountered in
the context of coordinate objects, |Angle| objects can also be used on
their own wherever a representation of an angle is needed.

.. _angle-creation:

Creation
========

The creation of an |Angle| object is quite flexible and supports a wide
variety of input object types and formats.  The type of the input angle(s)
can be an array, scalar, tuple, string, `~astropy.units.Quantity` or another
|Angle|.  This is best illustrated with a number of examples of valid ways
to create an |Angle|::

    >>> import numpy as np
    >>> from astropy import units as u
    >>> from astropy.coordinates import Angle

    >>> Angle('10.2345d')              # String with 'd' abbreviation for degrees  # doctest: +FLOAT_CMP
    <Angle 10.2345 deg>
    >>> Angle(['10.2345d', '-20d'])    # Array of strings  # doctest: +FLOAT_CMP
    <Angle [ 10.2345, -20.    ] deg>
    >>> Angle('1:2:30.43 degrees')     # Sexagesimal degrees  # doctest: +FLOAT_CMP
    <Angle 1.04178611 deg>
    >>> Angle('1 2 0 hours')           # Sexagesimal hours  # doctest: +FLOAT_CMP
    <Angle 1.03333333 hourangle>
    >>> Angle(np.arange(1., 8.), unit=u.deg)  # Numpy array from 1..7 in degrees  # doctest: +FLOAT_CMP
    <Angle [1., 2., 3., 4., 5., 6., 7.] deg>
    >>> Angle('1°2′3″')               # Unicode degree, arcmin and arcsec symbols  # doctest: +FLOAT_CMP
    <Angle 1.03416667 deg>
    >>> Angle('1d2m3.4s')              # Degree, arcmin, arcsec.  # doctest: +FLOAT_CMP
    <Angle 1.03427778 deg>
    >>> Angle('-1h2m3s')               # Hour, minute, second  # doctest: +FLOAT_CMP
    <Angle -1.03416667 hourangle>
    >>> Angle((-1, 2, 3), unit=u.deg)  # (degree, arcmin, arcsec)  # doctest: +FLOAT_CMP
    <Angle -1.03416667 deg>
    >>> Angle(10.2345 * u.deg)         # From a Quantity object in degrees  # doctest: +FLOAT_CMP
    <Angle 10.2345 deg>
    >>> Angle(Angle(10.2345 * u.deg))  # From another Angle object  # doctest: +FLOAT_CMP
    <Angle 10.2345 deg>

Representation
==============

The |Angle| object also supports a variety of ways of representing the value
of the angle, both as a floating point number and as a string::

    >>> a = Angle(1, u.radian)
    >>> a  # doctest: +FLOAT_CMP
    <Angle 1. rad>
    >>> a.radian
    1.0
    >>> a.degree  # doctest: +FLOAT_CMP
    57.29577951308232
    >>> a.hour  # doctest: +FLOAT_CMP
    3.8197186342054885
    >>> a.hms  # doctest: +FLOAT_CMP
    hms_tuple(h=3.0, m=49.0, s=10.987083139758766)
    >>> a.dms  # doctest: +FLOAT_CMP
    dms_tuple(d=57.0, m=17.0, s=44.806247096362313)
    >>> a.signed_dms  # doctest: +FLOAT_CMP
    signed_dms_tuple(sign=1.0, d=57.0, m=17.0, s=44.806247096362313)
    >>> (-a).dms  # doctest: +FLOAT_CMP
    dms_tuple(d=-57.0, m=-17.0, s=-44.806247096362313)
    >>> (-a).signed_dms  # doctest: +FLOAT_CMP
    signed_dms_tuple(sign=-1.0, d=57.0, m=17.0, s=44.806247096362313)
    >>> a.arcminute  # doctest: +FLOAT_CMP
    3437.7467707849396
    >>> a.to_string()
    '1rad'
    >>> a.to_string(unit=u.degree)
    '57d17m44.8062s'
    >>> a.to_string(unit=u.degree, sep=':')
    '57:17:44.8062'
    >>> a.to_string(unit=u.degree, sep=('deg', 'm', 's'))
    '57deg17m44.8062s'
    >>> a.to_string(unit=u.hour)
    '3h49m10.9871s'
    >>> a.to_string(unit=u.hour, decimal=True)
    '3.81972'

Usage
=====

Angles will also behave correctly for appropriate arithmetic operations::

    >>> a = Angle(1.0, u.radian)
    >>> a + 0.5 * u.radian + 2 * a  # doctest: +FLOAT_CMP
    <Angle 3.5 rad>
    >>> np.sin(a / 2)  # doctest: +FLOAT_CMP
    <Quantity 0.47942554>
    >>> a == a  # doctest: +SKIP
    array(True, dtype=bool)
    >>> a == (a + a)    # doctest: +SKIP
    array(False, dtype=bool)

|Angle| objects can also be used for creating coordinate objects::

    >>> from astropy.coordinates import ICRS
    >>> ICRS(Angle(1, u.deg), Angle(0.5, u.deg))  # doctest: +FLOAT_CMP
    <ICRS Coordinate: (ra, dec) in deg
        (1., 0.5)>

Wrapping and bounds
===================

There are two utility methods that simplify working with angles that should
have bounds.  The :meth:`~astropy.coordinates.Angle.wrap_at` method allows
taking an angle or angles and wrapping to be within a single 360 degree slice.
The :meth:`~astropy.coordinates.Angle.is_within_bounds` method returns a
boolean indicating whether an angle or angles is within the specified bounds.

Longitude and Latitude objects
==============================

|Longitude| and |Latitude| are two specialized subclasses of the |Angle|
class that are used for all of the spherical coordinate classes.
|Longitude| is used to represent values like right ascension, Galactic
longitude, and azimuth (for Equatorial, Galactic, and Alt-Az coordinates,
respectively).  |Latitude| is used for declination, Galactic latitude, and
elevation.

Longitude
---------

A |Longitude| object is distinguished from a pure |Angle| by virtue of a
``wrap_angle`` property.  The ``wrap_angle`` specifies that all angle values
represented by the object will be in the range::

  wrap_angle - 360 * u.deg <= angle(s) < wrap_angle

The default ``wrap_angle`` is 360 deg.  Setting ``'wrap_angle=180 * u.deg'``
would instead result in values between -180 and +180 deg.  Setting the
``wrap_angle`` attribute of an existing ``Longitude`` object will result in
re-wrapping the angle values in-place.  For example::

    >>> from astropy.coordinates import Longitude
    >>> a = Longitude([-20, 150, 350, 360] * u.deg)
    >>> a.degree  # doctest: +FLOAT_CMP
    array([340., 150., 350.,   0.])
    >>> a.wrap_angle = 180 * u.deg
    >>> a.degree  # doctest: +FLOAT_CMP
    array([-20., 150., -10.,   0.])

Latitude
--------

A Latitude object is distinguished from a pure |Angle| by virtue
of being bounded so that::

  -90.0 * u.deg <= angle(s) <= +90.0 * u.deg

Any attempt to set a value outside that range will result in a
`ValueError`.


text:
package com.ctrip.xpipe.config;

import java.util.LinkedList;
import java.util.List;

import com.ctrip.xpipe.api.config.Config;

/**
 * @author wenchao.meng
 *
 * Aug 9, 2016
 */
public class CompositeConfig extends AbstractConfig{

	private List<Config> configs = new LinkedList<>();

	public CompositeConfig(Config ... configsArgu) {
		for(Config config : configsArgu){
			configs.add(config);
		}
	}

	public void addConfig(Config config){

		configs.add(config);
	}

	@Override
	public String get(String key) {

		for(Config config : configs){
			String value = config.get(key);
			if( value != null){
				return value;
			}
		}
		return null;
	}

}


text:
layout: page
title: Guardian Chrome Electronics Seminar
date: 2016-05-24
author: Joseph Foster
tags: weekly links, java
status: published
summary: Nunc consectetur suscipit massa, quis fringilla ex porta at.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 07/29/2017
  endDate: 07/31/2017
  ctyhocn: FATCLHX
  groupCode: GCES
published: true
---
Nulla ut leo metus. Vivamus sit amet tincidunt odio. Proin consequat cursus nisi, ut pretium est dapibus at. Nam placerat nisl eu nibh molestie, non ultrices leo eleifend. Nulla ut dapibus nunc. Donec felis turpis, ullamcorper eget urna eu, vestibulum accumsan massa. Sed facilisis, massa quis cursus congue, ipsum dolor lacinia magna, sit amet aliquam nisi dui vel lectus. Phasellus vitae porta libero. Pellentesque iaculis risus at felis tempus, et feugiat purus egestas. Morbi et congue est. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam urna urna, sagittis ut nunc sit amet, efficitur mattis orci.
Aenean massa lorem, gravida sed semper at, molestie nec ante. Aliquam erat volutpat. Morbi a sodales erat. Nam lectus quam, imperdiet id neque eu, rhoncus placerat velit. Vivamus ut orci a dui rhoncus aliquet. Fusce pretium turpis nec commodo porta. Duis quis nulla ut augue pharetra porta id non nisl. Mauris aliquet hendrerit congue. Integer porttitor posuere sagittis. Integer vitae purus felis.

* Vestibulum sit amet eros eget nulla rhoncus semper
* Nunc luctus urna quis purus cursus, vitae luctus nulla accumsan
* Proin interdum sem et gravida accumsan
* Phasellus sed eros quis velit pretium scelerisque.

In pretium hendrerit dui, ac sodales libero laoreet at. Integer tincidunt mattis nulla, in suscipit urna placerat et. Nulla tellus lacus, iaculis eu ultrices ut, pulvinar a diam. Phasellus in neque et dolor pretium pellentesque eget quis tortor. Donec eget leo sed odio tincidunt ultrices. Mauris a neque ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce sollicitudin a mauris ut vehicula. Vestibulum a bibendum risus. Pellentesque volutpat enim nunc, faucibus scelerisque neque venenatis id. Morbi quam turpis, consectetur eget rhoncus eu, tincidunt egestas ligula.


text:
import DS from 'ember-data';
import DomainResource from 'ember-fhir/models/domain-resource';

const { attr, belongsTo, hasMany } = DS;

export default DomainResource.extend({
  url: attr('string'),
  identifier: hasMany('identifier', { async: true }),
  version: attr('string'),
  name: attr('string'),
  title: attr('string'),
  status: attr('string'),
  experimental: attr('boolean', { allowNull: true }),
  date: attr('date'),
  publisher: attr('string'),
  contact: hasMany('contact-detail', { async: true }),
  description: attr('string'),
  useContext: hasMany('usage-context', { async: true }),
  jurisdiction: hasMany('codeable-concept', { async: true }),
  immutable: attr('boolean', { allowNull: true }),
  purpose: attr('string'),
  copyright: attr('string'),
  extensible: attr('boolean', { allowNull: true }),
  compose: belongsTo('value-set-compose', { async: false }),
  expansion: belongsTo('value-set-expansion', { async: false })
});


text:
package nl.rivm.cib.epidemes.rest;

import java.util.Set;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;

import org.apache.logging.log4j.Logger;

import io.coala.log.LogUtil;

/**
 * {@link TestInitializer}
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
@HandlesTypes( value = { Object.class } )
public class TestInitializer implements ServletContainerInitializer
{

	/** */
	private static final Logger LOG = LogUtil
			.getLogger( TestInitializer.class );

	@Override
	public void onStartup( final Set<Class<?>> c, final ServletContext ctx )
		throws ServletException
	{
		LOG.trace( "Initializing classes: {}, path: {}", c,
				ctx.getContextPath() );
	}

}


text:
package org.nemanjamarjanovic.rekomendator.presentation;

import java.io.Serializable;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.nemanjamarjanovic.rekomendator.bussines.movie.boundary.CommentDao;

/**
 *
 * @author nemanja
 */
@Named
@ViewScoped
public class CommentEdit implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private CommentDao commentDao;

    @Inject
    private CurrentUser currentUser;

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String doCreate(String movie) {
        commentDao.create(movie, currentUser.getId(), this.text);
        return "movie-view?faces-redirect=true&id=" + movie;
    }

    public String doRemove(String comment) {
        commentDao.remove(comment);
        return "comment-list?faces-redirect=true";
    }

    public boolean isCommented(String movie) {
        return commentDao
                .findByUser(currentUser.getId())
                .parallelStream()
                .map(f -> f.getMovie().getId())
                .anyMatch(f -> (f.equals(movie)));
    }

}


text:
package org.apache.commons.compress.archivers.dump;

/**
 * Unrecognized Format Exception. This is either not a recognized dump archive or there's
 * a bad tape segment header.
 */
public class UnrecognizedFormatException extends DumpArchiveException {
    private static final long serialVersionUID = 1L;

    public UnrecognizedFormatException() {
        super("this is not a recognized format.");
    }
}