text:
<?php

namespace Kula\HEd\Bundle\SchedulingBundle\Chooser;

use Kula\Core\Component\Chooser\Chooser;

class SectionChooser extends Chooser {

  public function search($q) {

    $query_conditions = $this->db()->db_or();
    $query_conditions = $query_conditions->condition('COURSE_TITLE', '%'.$q.'%', 'LIKE');
    $query_conditions = $query_conditions->condition('COURSE_NUMBER', '%'.$q.'%', 'LIKE');
    $query_conditions = $query_conditions->condition('SHORT_TITLE', '%'.$q.'%', 'LIKE');
    $query_conditions = $query_conditions->condition('SECTION_NUMBER', '%'.$q.'%', 'LIKE');
    $query_conditions = $query_conditions->condition('SECTION_NAME', '%'.$q.'%', 'LIKE');

    $data = array();

    $search = $this->db()->db_select('STUD_SECTION', 'sec')
      ->fields('sec', array('SECTION_ID', 'SECTION_NUMBER', 'SECTION_NAME'))
      ->join('STUD_COURSE', 'course', 'course.COURSE_ID = sec.COURSE_ID')
      ->fields('course', array('COURSE_ID', 'COURSE_NUMBER', 'COURSE_TITLE'))
      ->condition($query_conditions)
      ->orderBy('COURSE_NUMBER', 'ASC');

    if ($this->focus()->getOrganizationTermIDs())
      $search = $search->condition('sec.ORGANIZATION_TERM_ID', $this->focus()->getOrganizationTermIDs());

    $search = $search->execute();
    while ($row = $search->fetch()) {
      if ($row['SECTION_NAME']) $title = $row['SECTION_NAME']; else $title = $row['COURSE_TITLE'];
      $this->addToChooserMenu($row['SECTION_ID'], $row['SECTION_NUMBER'].' / '.$title);
    }

  }

  public function choice($id) {
    $row = $this->db()->db_select('STUD_SECTION', 'sec')
      ->fields('sec', array('SECTION_ID', 'SECTION_NUMBER', 'SECTION_NAME'))
      ->join('STUD_COURSE', 'course', 'course.COURSE_ID = sec.COURSE_ID')
      ->fields('course', array('COURSE_ID', 'COURSE_NUMBER', 'COURSE_TITLE'))
      ->condition('sec.SECTION_ID', $id)
      ->execute()
      ->fetch();
    if ($row['SECTION_NAME']) $title = $row['SECTION_NAME']; else $title = $row['COURSE_TITLE'];
    return $this->currentValue($row['SECTION_ID'], $row['SECTION_NUMBER'].' / '.$title);
  }

  public function searchRoute() {
    return 'Core_HEd_Section_Chooser';
  }

}


text:
"""
%prog SUBMODULE...

Hack to pipe submodules of Numpy through 2to3 and build them in-place
one-by-one.

Example usage:

    python3 tools/py3tool.py testing distutils core

This will copy files to _py3k/numpy, add a dummy __init__.py and
version.py on the top level, and copy and 2to3 the files of the three
submodules.

When running py3tool again, only changed files are re-processed, which
makes the test-bugfix cycle faster.

"""
from optparse import OptionParser
import shutil
import os
import sys
import re
import subprocess
import fnmatch

if os.environ.get('USE_2TO3CACHE'):
    import lib2to3cache

BASE = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
TEMP = os.path.normpath(os.path.join(BASE, '_py3k'))

SCRIPT_2TO3 = os.path.join(BASE, 'tools', '2to3.py')

EXTRA_2TO3_FLAGS = {
    '*/setup.py': '-x import',
    #'numpy/core/code_generators/generate_umath.py': '-x import',
    #'numpy/core/code_generators/generate_numpy_api.py': '-x import',
    #'numpy/core/code_generators/generate_ufunc_api.py': '-x import',
    #'numpy/core/defchararray.py': '-x unicode',
    #'numpy/compat/py3k.py': '-x unicode',
    #'numpy/ma/timer_comparison.py': 'skip',
    #'numpy/distutils/system_info.py': '-x reduce',
    #'numpy/f2py/auxfuncs.py': '-x reduce',
    #'numpy/lib/arrayterator.py': '-x reduce',
    #'numpy/lib/tests/test_arrayterator.py': '-x reduce',
    #'numpy/ma/core.py': '-x reduce',
    #'numpy/ma/tests/test_core.py': '-x reduce',
    #'numpy/ma/tests/test_old_ma.py': '-x reduce',
    #'numpy/ma/timer_comparison.py': '-x reduce',
    #'numpy/oldnumeric/ma.py': '-x reduce',
}

def main():
    p = OptionParser(usage=__doc__.strip())
    p.add_option("--clean", "-c", action="store_true",
                 help="clean source directory")
    options, args = p.parse_args()

    if not args:
        p.error('no submodules given')
    else:
        dirs = ['scipy/%s' % x for x in map(os.path.basename, args)]

    # Prepare
    if not os.path.isdir(TEMP):
        os.makedirs(TEMP)

    # Set up dummy files (for building only submodules)
    dummy_files = {
        '__init__.py': 'from scipy.version import version as __version__',
        'version.py': 'version = "0.8.0.dev"'
    }

    for fn, content in dummy_files.items():
        fn = os.path.join(TEMP, 'scipy', fn)
        if not os.path.isfile(fn):
            try:
                os.makedirs(os.path.dirname(fn))
            except OSError:
                pass
            f = open(fn, 'wb+')
            f.write(content.encode('ascii'))
            f.close()

    # Environment
    pp = [os.path.abspath(TEMP)]
    def getenv():
        env = dict(os.environ)
        env.update({'PYTHONPATH': ':'.join(pp)})
        return env

    # Copy
    for d in dirs:
        src = os.path.join(BASE, d)
        dst = os.path.join(TEMP, d)

        # Run 2to3
        sync_2to3(dst=dst,
                  src=src,
                  patchfile=os.path.join(TEMP, os.path.basename(d) + '.patch'),
                  clean=options.clean)

        # Run setup.py, falling back to Pdb post-mortem on exceptions
        setup_py = os.path.join(dst, 'setup.py')
        if os.path.isfile(setup_py):
            code = """\
import pdb, sys, traceback
p = pdb.Pdb()
try:
    import __main__
    __main__.__dict__.update({
        "__name__": "__main__", "__file__": "setup.py",
        "__builtins__": __builtins__})
    fp = open("setup.py", "rb")
    try:
        exec(compile(fp.read(), "setup.py", 'exec'))
    finally:
        fp.close()
except SystemExit:
    raise
except:
    traceback.print_exc()
    t = sys.exc_info()[2]
    p.interaction(None, t)
"""
            ret = subprocess.call([sys.executable, '-c', code,
                                   'build_ext', '-i'],
                                  cwd=dst,
                                  env=getenv())
            if ret != 0:
                raise RuntimeError("Build failed.")

        # Run nosetests
        subprocess.call(['nosetests3', '-v', d], cwd=TEMP)

def custom_mangling(filename):
    import_mangling = [
        os.path.join('cluster', '__init__.py'),
        os.path.join('cluster', 'hierarchy.py'),
        os.path.join('cluster', 'vq.py'),
        os.path.join('fftpack', 'basic.py'),
        os.path.join('fftpack', 'pseudo_diffs.py'),
        os.path.join('integrate', 'odepack.py'),
        os.path.join('integrate', 'quadpack.py'),
        os.path.join('integrate', '_ode.py'),
        os.path.join('interpolate', 'fitpack.py'),
        os.path.join('interpolate', 'fitpack2.py'),
        os.path.join('interpolate', 'interpolate.py'),
        os.path.join('interpolate', 'interpolate_wrapper.py'),
        os.path.join('interpolate', 'ndgriddata.py'),
        os.path.join('io', 'array_import.py'),
        os.path.join('io', '__init__.py'),
        os.path.join('io', 'matlab', 'miobase.py'),
        os.path.join('io', 'matlab', 'mio4.py'),
        os.path.join('io', 'matlab', 'mio5.py'),
        os.path.join('io', 'matlab', 'mio5_params.py'),
        os.path.join('linalg', 'basic.py'),
        os.path.join('linalg', 'decomp.py'),
        os.path.join('linalg', 'lapack.py'),
        os.path.join('linalg', 'flinalg.py'),
        os.path.join('linalg', 'iterative.py'),
        os.path.join('linalg', 'misc.py'),
        os.path.join('lib', 'blas', '__init__.py'),
        os.path.join('lib', 'lapack', '__init__.py'),
        os.path.join('ndimage', 'filters.py'),
        os.path.join('ndimage', 'fourier.py'),
        os.path.join('ndimage', 'interpolation.py'),
        os.path.join('ndimage', 'measurements.py'),
        os.path.join('ndimage', 'morphology.py'),
        os.path.join('optimize', 'minpack.py'),
        os.path.join('optimize', 'zeros.py'),
        os.path.join('optimize', 'lbfgsb.py'),
        os.path.join('optimize', 'cobyla.py'),
        os.path.join('optimize', 'slsqp.py'),
        os.path.join('optimize', 'nnls.py'),
        os.path.join('signal', '__init__.py'),
        os.path.join('signal', 'bsplines.py'),
        os.path.join('signal', 'signaltools.py'),
        os.path.join('signal', 'fir_filter_design.py'),
        os.path.join('special', '__init__.py'),
        os.path.join('special', 'add_newdocs.py'),
        os.path.join('special', 'basic.py'),
        os.path.join('special', 'lambertw.py'),
        os.path.join('special', 'orthogonal.py'),
        os.path.join('spatial', '__init__.py'),
        os.path.join('spatial', 'distance.py'),
        os.path.join('sparse', 'linalg', 'isolve', 'iterative.py'),
        os.path.join('sparse', 'linalg', 'dsolve', 'linsolve.py'),
        os.path.join('sparse', 'linalg', 'dsolve', 'umfpack', 'umfpack.py'),
        os.path.join('sparse', 'linalg', 'eigen', 'arpack', 'arpack.py'),
        os.path.join('sparse', 'linalg', 'eigen', 'arpack', 'speigs.py'),
        os.path.join('sparse', 'linalg', 'iterative', 'isolve', 'iterative.py'),
        os.path.join('sparse', 'csgraph', '__init__.py'),
        os.path.join('sparse', 'csgraph', '_validation.py'),
        os.path.join('stats', 'stats.py'),
        os.path.join('stats', 'distributions.py'),
        os.path.join('stats', 'morestats.py'),
        os.path.join('stats', 'kde.py'),
        os.path.join('stats', 'mstats_basic.py'),
    ]

    if any(filename.endswith(x) for x in import_mangling):
        print(filename)
        f = open(filename, 'r', encoding='utf-8')
        text = f.read()
        f.close()
        for mod in ['_vq', '_hierarchy_wrap', '_fftpack', 'convolve',
                    '_flinalg', 'fblas', 'flapack', 'cblas', 'clapack',
                    'calc_lwork', '_cephes', 'specfun', 'orthogonal_eval',
                    'lambertw', 'ckdtree', '_distance_wrap', '_logit',
                    '_ufuncs', '_ufuncs_cxx',
                    '_minpack', '_zeros', '_lbfgsb', '_cobyla', '_slsqp',
                    '_nnls',
                    'sigtools', 'spline', 'spectral',
                    '_fitpack', 'dfitpack', '_interpolate',
                    '_odepack', '_quadpack', 'vode', '_dop', 'lsoda',
                    'vonmises_cython', '_rank',
                    'futil', 'mvn',
                    '_nd_image',
                    'numpyio',
                    '_superlu', '_arpack', '_iterative', '_umfpack',
                    'interpnd',
                    'mio_utils', 'mio5_utils', 'streams',
                    '_min_spanning_tree', '_shortest_path', '_tools', '_traversal'
                    ]:
            text = re.sub(r'^(\s*)import %s' % mod,
                          r'\1from . import %s' % mod,
                          text, flags=re.M)
            text = re.sub(r'^(\s*)from %s import' % mod,
                          r'\1from .%s import' % mod,
                          text, flags=re.M)
        #text = text.replace('from matrixlib', 'from .matrixlib')
        f = open(filename, 'w', encoding='utf-8')
        f.write(text)
        f.close()

def walk_sync(dir1, dir2, _seen=None):
    if _seen is None:
        seen = {}
    else:
        seen = _seen

    if not dir1.endswith(os.path.sep):
        dir1 = dir1 + os.path.sep

    # Walk through stuff (which we haven't yet gone through) in dir1
    for root, dirs, files in os.walk(dir1):
        sub = root[len(dir1):]
        if sub in seen:
            dirs = [x for x in dirs if x not in seen[sub][0]]
            files = [x for x in files if x not in seen[sub][1]]
            seen[sub][0].extend(dirs)
            seen[sub][1].extend(files)
        else:
            seen[sub] = (dirs, files)
        if not dirs and not files:
            continue
        yield os.path.join(dir1, sub), os.path.join(dir2, sub), dirs, files

    if _seen is None:
        # Walk through stuff (which we haven't yet gone through) in dir2
        for root2, root1, dirs, files in walk_sync(dir2, dir1, _seen=seen):
            yield root1, root2, dirs, files

def sync_2to3(src, dst, patchfile=None, clean=False):
    import lib2to3.main
    from io import StringIO

    to_convert = []

    for src_dir, dst_dir, dirs, files in walk_sync(src, dst):
        for fn in dirs + files:
            src_fn = os.path.join(src_dir, fn)
            dst_fn = os.path.join(dst_dir, fn)

            # skip temporary etc. files
            if fn.startswith('.#') or fn.endswith('~'):
                continue

            # remove non-existing
            if os.path.exists(dst_fn) and not os.path.exists(src_fn):
                if clean:
                    if os.path.isdir(dst_fn):
                        shutil.rmtree(dst_fn)
                    else:
                        os.unlink(dst_fn)
                continue

            # make directories
            if os.path.isdir(src_fn):
                if not os.path.isdir(dst_fn):
                    os.makedirs(dst_fn)
                continue

            dst_dir = os.path.dirname(dst_fn)
            if os.path.isfile(dst_fn) and not os.path.isdir(dst_dir):
                os.makedirs(dst_dir)

            # don't replace up-to-date files
            try:
                if os.path.isfile(dst_fn) and \
                       os.stat(dst_fn).st_mtime >= os.stat(src_fn).st_mtime:
                    continue
            except OSError:
                pass

            # copy file
            shutil.copyfile(src_fn, dst_fn)

            # add .py files to 2to3 list
            if dst_fn.endswith('.py'):
                to_convert.append((src_fn, dst_fn))

    # run 2to3
    flag_sets = {}
    for fn, dst_fn in to_convert:
        flag = ''
        for pat, opt in EXTRA_2TO3_FLAGS.items():
            if fnmatch.fnmatch(fn, pat):
                flag = opt
                break
        flag_sets.setdefault(flag, []).append(dst_fn)

    if patchfile:
        p = open(patchfile, 'wb+')
    else:
        p = open(os.devnull, 'wb')

    for flags, filenames in flag_sets.items():
        if flags == 'skip':
            continue

        _old_stdout = sys.stdout
        try:
            sys.stdout = StringIO()
            lib2to3.main.main("lib2to3.fixes", ['-w', '-n'] + flags.split()+filenames)
        finally:
            sys.stdout = _old_stdout

    for fn, dst_fn in to_convert:
        # perform custom mangling
        custom_mangling(dst_fn)

    p.close()

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
print('"Осел готов сносить все тяготы и огорчения. А упрямым его величает всяк, кому самому недостает выдержки и терпения."')
print("Леонардо Да Винчи")

input("Нажмите Enter для выхода.")


text:
class NotFoundError(Exception):
    def __init__(self, path):
        self.path = path

    def __str__(self):
        return "Error: %s not found." % self.path

class CmdError(Exception):
    def __init__(self, exitstatus, output):
        self.status = exitstatus
        self.output = output

    def __str__(self):
        return "Command Error: exit status: %d  Output:\n%s" % (self.status, self.output)

def runcmd(args, dir = None):
    import commands

    if dir:
        olddir = os.path.abspath(os.curdir)
        if not os.path.exists(dir):
            raise NotFoundError(dir)
        os.chdir(dir)
        # print("cwd: %s -> %s" % (olddir, dir))

    try:
        args = [ commands.mkarg(str(arg)) for arg in args ]
        cmd = " ".join(args)
        # print("cmd: %s" % cmd)
        (exitstatus, output) = commands.getstatusoutput(cmd)
        if exitstatus != 0:
            raise CmdError(exitstatus >> 8, output)
        return output

    finally:
        if dir:
            os.chdir(olddir)

class PatchError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return "Patch Error: %s" % self.msg

class PatchSet(object):
    defaults = {
        "strippath": 1
    }

    def __init__(self, dir, d):
        self.dir = dir
        self.d = d
        self.patches = []
        self._current = None

    def current(self):
        return self._current

    def Clean(self):
        """
        Clean out the patch set.  Generally includes unapplying all
        patches and wiping out all associated metadata.
        """
        raise NotImplementedError()

    def Import(self, patch, force):
        if not patch.get("file"):
            if not patch.get("remote"):
                raise PatchError("Patch file must be specified in patch import.")
            else:
                patch["file"] = bb.fetch.localpath(patch["remote"], self.d)

        for param in PatchSet.defaults:
            if not patch.get(param):
                patch[param] = PatchSet.defaults[param]

        if patch.get("remote"):
            patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)

        patch["filemd5"] = bb.utils.md5_file(patch["file"])

    def Push(self, force):
        raise NotImplementedError()

    def Pop(self, force):
        raise NotImplementedError()

    def Refresh(self, remote = None, all = None):
        raise NotImplementedError()

class PatchTree(PatchSet):
    def __init__(self, dir, d):
        PatchSet.__init__(self, dir, d)

    def Import(self, patch, force = None):
        """"""
        PatchSet.Import(self, patch, force)

        if self._current is not None:
            i = self._current + 1
        else:
            i = 0
        self.patches.insert(i, patch)

    def _applypatch(self, patch, force = False, reverse = False, run = True):
        shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
        if reverse:
            shellcmd.append('-R')

        if not run:
            return "sh" + "-c" + " ".join(shellcmd)

        if not force:
            shellcmd.append('--dry-run')

        output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)

        if force:
            return

        shellcmd.pop(len(shellcmd) - 1)
        output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
        return output

    def Push(self, force = False, all = False, run = True):
        bb.note("self._current is %s" % self._current)
        bb.note("patches is %s" % self.patches)
        if all:
            for i in self.patches:
                if self._current is not None:
                    self._current = self._current + 1
                else:
                    self._current = 0
                bb.note("applying patch %s" % i)
                self._applypatch(i, force)
        else:
            if self._current is not None:
                self._current = self._current + 1
            else:
                self._current = 0
            bb.note("applying patch %s" % self.patches[self._current])
            return self._applypatch(self.patches[self._current], force)

    def Pop(self, force = None, all = None):
        if all:
            for i in self.patches:
                self._applypatch(i, force, True)
        else:
            self._applypatch(self.patches[self._current], force, True)

    def Clean(self):
        """"""

class GitApplyTree(PatchTree):
    def __init__(self, dir, d):
        PatchTree.__init__(self, dir, d)

    def _applypatch(self, patch, force = False, reverse = False, run = True):
        shellcmd = ["git", "--git-dir=.", "apply", "-p%s" % patch['strippath']]

        if reverse:
            shellcmd.append('-R')

        shellcmd.append(patch['file'])

        if not run:
            return "sh" + "-c" + " ".join(shellcmd)

        return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)

class QuiltTree(PatchSet):
    def _runcmd(self, args, run = True):
        quiltrc = bb.data.getVar('QUILTRCFILE', self.d, 1)
        if not run:
            return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
        runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)

    def _quiltpatchpath(self, file):
        return os.path.join(self.dir, "patches", os.path.basename(file))

    def __init__(self, dir, d):
        PatchSet.__init__(self, dir, d)
        self.initialized = False
        p = os.path.join(self.dir, 'patches')
        if not os.path.exists(p):
            os.makedirs(p)

    def Clean(self):
        try:
            self._runcmd(["pop", "-a", "-f"])
        except Exception:
            pass
        self.initialized = True

    def InitFromDir(self):
        # read series -> self.patches
        seriespath = os.path.join(self.dir, 'patches', 'series')
        if not os.path.exists(self.dir):
            raise Exception("Error: %s does not exist." % self.dir)
        if os.path.exists(seriespath):
            series = file(seriespath, 'r')
            for line in series.readlines():
                patch = {}
                parts = line.strip().split()
                patch["quiltfile"] = self._quiltpatchpath(parts[0])
                patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
                if len(parts) > 1:
                    patch["strippath"] = parts[1][2:]
                self.patches.append(patch)
            series.close()

            # determine which patches are applied -> self._current
            try:
                output = runcmd(["quilt", "applied"], self.dir)
            except CmdError:
                import sys
                if sys.exc_value.output.strip() == "No patches applied":
                    return
                else:
                    raise sys.exc_value
            output = [val for val in output.split('\n') if not val.startswith('#')]
            for patch in self.patches:
                if os.path.basename(patch["quiltfile"]) == output[-1]:
                    self._current = self.patches.index(patch)
        self.initialized = True

    def Import(self, patch, force = None):
        if not self.initialized:
            self.InitFromDir()
        PatchSet.Import(self, patch, force)

        args = ["import", "-p", patch["strippath"]]
        if force:
            args.append("-f")
            args.append("-dn")
        args.append(patch["file"])

        self._runcmd(args)

        patch["quiltfile"] = self._quiltpatchpath(patch["file"])
        patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])

        # TODO: determine if the file being imported:
        #      1) is already imported, and is the same
        #      2) is already imported, but differs

        self.patches.insert(self._current or 0, patch)

    def Push(self, force = False, all = False, run = True):
        # quilt push [-f]

        args = ["push"]
        if force:
            args.append("-f")
        if all:
            args.append("-a")
        if not run:
            return self._runcmd(args, run)

        self._runcmd(args)

        if self._current is not None:
            self._current = self._current + 1
        else:
            self._current = 0

    def Pop(self, force = None, all = None):
        # quilt pop [-f]
        args = ["pop"]
        if force:
            args.append("-f")
        if all:
            args.append("-a")

        self._runcmd(args)

        if self._current == 0:
            self._current = None

        if self._current is not None:
            self._current = self._current - 1

    def Refresh(self, **kwargs):
        if kwargs.get("remote"):
            patch = self.patches[kwargs["patch"]]
            if not patch:
                raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
            (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
            if type == "file":
                import shutil
                if not patch.get("file") and patch.get("remote"):
                    patch["file"] = bb.fetch.localpath(patch["remote"], self.d)

                shutil.copyfile(patch["quiltfile"], patch["file"])
            else:
                raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
        else:
            # quilt refresh
            args = ["refresh"]
            if kwargs.get("quiltfile"):
                args.append(os.path.basename(kwargs["quiltfile"]))
            elif kwargs.get("patch"):
                args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
            self._runcmd(args)

class Resolver(object):
    def __init__(self, patchset):
        raise NotImplementedError()

    def Resolve(self):
        raise NotImplementedError()

    def Revert(self):
        raise NotImplementedError()

    def Finalize(self):
        raise NotImplementedError()

class NOOPResolver(Resolver):
    def __init__(self, patchset):
        self.patchset = patchset

    def Resolve(self):
        olddir = os.path.abspath(os.curdir)
        os.chdir(self.patchset.dir)
        try:
            self.patchset.Push()
        except Exception:
            import sys
            os.chdir(olddir)
            raise sys.exc_value

# Patch resolver which relies on the user doing all the work involved in the
# resolution, with the exception of refreshing the remote copy of the patch
# files (the urls).
class UserResolver(Resolver):
    def __init__(self, patchset):
        self.patchset = patchset

    # Force a push in the patchset, then drop to a shell for the user to
    # resolve any rejected hunks
    def Resolve(self):

        olddir = os.path.abspath(os.curdir)
        os.chdir(self.patchset.dir)
        try:
            self.patchset.Push(False)
        except CmdError, v:
            # Patch application failed
            patchcmd = self.patchset.Push(True, False, False)

            t = bb.data.getVar('T', d, 1)
            if not t:
                bb.msg.fatal(bb.msg.domain.Build, "T not set")
            bb.mkdirhier(t)
            import random
            rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
            f = open(rcfile, "w")
            f.write("echo '*** Manual patch resolution mode ***'\n")
            f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
            f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
            f.write("echo ''\n")
            f.write(" ".join(patchcmd) + "\n")
            f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
            f.close()
            os.chmod(rcfile, 0775)

            os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
            os.environ['TERMRCFILE'] = rcfile
            rc = os.system(bb.data.getVar('TERMCMDRUN', d, 1))
            if os.WIFEXITED(rc) and os.WEXITSTATUS(rc) != 0:
                bb.msg.fatal(bb.msg.domain.Build, ("Cannot proceed with manual patch resolution - '%s' not found. " \
                    + "Check TERMCMDRUN variable.") % bb.data.getVar('TERMCMDRUN', d, 1))

            # Construct a new PatchSet after the user's changes, compare the
            # sets, checking patches for modifications, and doing a remote
            # refresh on each.
            oldpatchset = self.patchset
            self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)

            for patch in self.patchset.patches:
                oldpatch = None
                for opatch in oldpatchset.patches:
                    if opatch["quiltfile"] == patch["quiltfile"]:
                        oldpatch = opatch

                if oldpatch:
                    patch["remote"] = oldpatch["remote"]
                    if patch["quiltfile"] == oldpatch["quiltfile"]:
                        if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
                            bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
                            # user change?  remote refresh
                            self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
                        else:
                            # User did not fix the problem.  Abort.
                            raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
        except Exception:
            os.chdir(olddir)
            raise
        os.chdir(olddir)


text:
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");

try{
     $name=stripslashes(htmlspecialchars(trim($_POST['appointment_hidden_name'])));
     $surname=stripslashes(htmlspecialchars(trim($_POST['appointment_hidden_surname'])));
     $telephone=stripslashes(htmlspecialchars(trim($_POST['appointment_telephone'])));
     $email=stripslashes(htmlspecialchars(trim($_POST['appointment_email'])));
     $userid=stripslashes(htmlspecialchars(trim($_POST['appointment_userid'])));
     $shopid=$_SESSION['shopid'];
     $tipo_attivita=stripslashes(htmlspecialchars(trim($_POST['tipo_attivita'])));
     $seconda_attivita=stripslashes(htmlspecialchars(trim($_POST['seconda_attivita'])));
     $appointment_end_date=stripslashes(htmlspecialchars(trim($_POST['appointment_end_date'])));
     $ora1=stripslashes(htmlspecialchars(trim($_POST['ora1'])));
     $ora2=stripslashes(htmlspecialchars(trim($_POST['ora2'])));
     $sms_service=stripslashes(htmlspecialchars(trim($_POST['sms_service'])));
     if($sms_service=='true'){
         $sms_service='Y';
     }else{
         $sms_service='N';
     }

    //Checking if supplied userid matches with name,surname,telephone and email
    //$userid_tocheck=checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email);

    //if($userid!=$userid_tocheck){
     //   $userid=trim('');
    //}

    //FOR APP USER
    if(!empty($userid)){

        $isUserAssociatedWithTheShop=checkIfUserDataIsAlreadyAssociated($shopid,$userid);

        if(!$isUserAssociatedWithTheShop){
             linkUserWithShop($userid,$shopid);
        }
    }
    //For SMS_USER
    if(empty($userid)){
        $isSMSUserIsAlreadyAssociatedWithTheShop=checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid);

        if(!$isSMSUserIsAlreadyAssociatedWithTheShop){

             $loginId=insertSMSUser($name,$surname,$telephone,$email,$shopid);
             $userid=insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId);
             linkUserWithShop($userid,$shopid);
        }else{
            $userid=getUserIdForExistingSmsUser($name,$surname,$telephone,$email,$shopid);
        }
    }

    $appointmentId=insertClientAppointmentDetails($shopid,$userid,$tipo_attivita,$seconda_attivita,$appointment_end_date,$ora1,$ora2,$sms_service);

    echo json_encode(['OPERATION'=>0,'USER_ID'=>$userid,'APPOINTMENT_ID'=>$appointmentId,'VALIDATION_ERROR'=>'NA']);

} catch(Exception $e){
    echo json_encode(['OPERATION'=>1,'USER_ID'=>'NA','APPOINTMENT_ID'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}

function checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email){
    try{
          $userid=-1;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="select x.user_id user_id from $dbname.User_Details x where x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email'";

           $result=mysqli_query($conn,$sql);
           if(!$result){
               throw new Exception("Database error::$sql");
           }
           $rowcount=mysqli_num_rows($result);

           if($rowcount>0){
                $row=mysqli_fetch_array($result);
                $user_id=$row['user_id'];

           }
          mysqli_close($conn);

          return $userid;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function getUserIdForExistingSmsUser($name,$surname,$telephone,$email,$shopid){

    try{

          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="select x.user_id user_id from $dbname.User_Details x,$dbname.User_Shop_Map x1 where x.user_id=x1.user_id and x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email' and x1.shop_id=$shopid";

           $result=mysqli_query($conn,$sql);
           if(!$result){
               throw new Exception("Database error::$sql");
           }
           $rowcount=mysqli_num_rows($result);

           if($rowcount>0){
                $row=mysqli_fetch_array($result);
                $user_id=$row['user_id'];

           }
          mysqli_close($conn);

          return $user_id;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }

}

function insertClientAppointmentDetails($shopid,$userid,$tipo_attivita,$seconda_attivita,$appointment_end_date,$ora1,$ora2,$sms_service){
    try{
          $appointmentId=-1;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }
           $sql="insert into $dbname.Client_Shop_Apnt (user_id,shop_id,user_apnt_dt,user_apnt_time,user_apnt_status,is_sms_active,first_line_activity,second_line_activity) values($userid,$shopid,STR_TO_DATE('$appointment_end_date','%Y-%m-%d'),STR_TO_DATE('$ora1:$ora2','%T:%i'),'BOOKED','$sms_service','$tipo_attivita','$seconda_attivita')";

           $result=mysqli_query($conn,$sql);
           if($result){
               $appointmentId=mysqli_insert_id($conn);
           }else{
               throw new Exception("Database error::$sql");
           }

           mysqli_close($conn);

           return $appointmentId;
      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid){

     try{
          $isUserAssociated=FALSE;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="select count(*) user_count from $dbname.User_Details x,$dbname.User_Shop_Map x1 where x.user_id=x1.user_id and x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email' and x1.shop_id=$shopid";

           $result=mysqli_query($conn,$sql);
           if(!$result){
               throw new Exception("Database error::$sql");
           }
           $rowcount=mysqli_num_rows($result);

           if($rowcount>0){
                $row=mysqli_fetch_array($result);
                $user_count=$row['user_count'];
                 if($user_count==1){
                      $isUserAssociated=TRUE;
                 }

           }
          mysqli_close($conn);

          return $isUserAssociated;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }

}

function insertSMSUser($name,$surname,$telephone,$email,$shopid){
    try{
          $loginId=-1;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="insert into $dbname.Login (login_username,login_password,login_mobile_no,login_type,client_login_type) value('$telephone','$telephone','NA','NA','SMS_USER')";

           $result=mysqli_query($conn,$sql);

           if($result){
               $loginId=mysqli_insert_id($conn);
           }else{
               throw new Exception("Database error::$sql");
           }

           mysqli_close($conn);
         return $loginId;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId){
    try{
          $userid=-1;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="insert into $dbname.User_Details (user_login_id,user_first_name,user_last_name,user_qr_code,user_login_mobile_no,user_alt_contact2,user_email_id1,User_Status) value($loginId,'$name','$surname','NA','$telephone','NA','$email','NA')";

           $result=mysqli_query($conn,$sql);
           if($result){
               $userid=mysqli_insert_id($conn);

           }else{
               throw new Exception("Database error::$sql");
           }

           mysqli_close($conn);

        return $userid;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function checkIfUserDataIsAlreadyAssociated($shopid,$userid){
    try{
          $isUserAssociated=FALSE;
          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="select count(*) user_shop_map_count from $dbname.User_Shop_Map where shop_id=$shopid and user_id=$userid";

           $result=mysqli_query($conn,$sql);
           if(!$result){
               throw new Exception("Database error::$sql");
           }
           $rowcount=mysqli_num_rows($result);

           if($rowcount>0){
               $row=mysqli_fetch_array($result);
                $user_count=$row['user_shop_map_count'];

                 if($user_count==1){
                      $isUserAssociated=TRUE;
                 }
           }
          mysqli_close($conn);
          return $isUserAssociated;

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function linkUserWithShop($userid,$shopid){
    try{

          $dbname=DATABASE_NAME;
          $conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
            if(!$conn){
                throw new Exception(DATABASE_CONNECTION_ERROR);
            }

           $sql="insert into $dbname.User_Shop_Map (shop_id,user_id,user_active_flag,is_shop_fav_flag) value($shopid,$userid,'Y','N')";

           $result=mysqli_query($conn,$sql);
           if($result){
               updateUserStatus($userid,$conn,$dbname);

           }else{
               throw new Exception("Database error::$sql");
           }

           mysqli_close($conn);

      }catch(Exception $e){
          mysqli_close($conn);
          throw $e;
      }
}

function updateUserStatus($userid,$conn,$dbname){
    try{

         $sql="update $dbname.User_Details set user_status='Connected',update_date=now() where user_id=$userid";
         $result=mysqli_query($conn,$sql);
         if(!$result){
             throw new Exception("Database error::$sql");
         }
    }catch(Exception $e){
         throw $e;
    }
}

?>


text:
'use strict';

/*exported drawModule */
var map; //map instance
var connectionsAPI;
var utils;
var drawModule = (function() {
  var MAXRATING = 5;
  var alreadyPartySizeInit = false;
  var minTime = {
    hours: 12,
    minutes: 30
  };
  var maxTime = {
    hours: 22,
    minutes: 30
  };

  // actions do nothing by default
  var NOP = function() {};
  var viewReservationAction, viewRestaurantReviewsAction,
    createNewReviewAction, createNewReservationAction,
    getReservationsByDateAction,
    viewReviewAction, deleteReviewAction,
    showEditReviewAction, updateReviewAction,
    cancelReservationAction = NOP;

  // functions to set up actions
  function setViewReservationAction(action) {
    viewReservationAction = action;
  }

  function setViewRestaurantReviewsAction(action) {
    viewRestaurantReviewsAction = action;
  }

  function setCreateNewReviewAction(action) {
    createNewReviewAction = action;
  }

  function setCreateNewReservationAction(action) {
    createNewReservationAction = action;
  }

  function setViewReviewAction(action) {
    viewReviewAction = action;
  }

  function setDeleteReviewAction(action) {
    deleteReviewAction = action;
  }

  function setGetReservationsByDateAction(action) {
    getReservationsByDateAction = action;
  }

  function setShowEditReviewAction(action) {
    showEditReviewAction = action;
  }

  function setUpdateReviewAction(action) {
    updateReviewAction = action;
  }

  function setCancelReservationAction(action) {
    cancelReservationAction = action;
  }

  /* this functions add the restaurants to the leaflet map */
  function addRestaurantstoMap(restaurants) {
    /* add marks with clustering approach */
    var markerClusters = L.markerClusterGroup({showCoverageOnHover: true});
    restaurants.forEach(function(currentMark) {
      addRestaurantMark(currentMark, markerClusters);
    });

    map.addLayer(markerClusters);
  }

  // create a restaurant mark and add it to the cluster.
  function addRestaurantMark(currentMark, markerCluster) {
    // add mark to map
    currentMark.mark = L.marker(currentMark.coords);

    var popHTML = generateMarkPopup(currentMark);
    currentMark.mark.bindPopup(popHTML);

    // reference all mark info to be used from leaflet
    currentMark.mark.extraInfo = currentMark;

    markerCluster.addLayer(currentMark.mark);
  }

  // set title for modal window
  function setPopupTitle(title) {
    document.getElementById('popTitle').textContent = title;
  }

  // set content for modal window
  function setPopupContent(contentDiv) {
    // remove previous content
    var content = document.getElementById('popContent');
    content.innerHTML = '';
    content.appendChild(contentDiv);
  }

  // generate a restaurant popup from a restaurant mark.
  function generateMarkPopup(mark) {
    var popHTML = document.createElement('DIV');
    popHTML.className = 'markPopUp';

    var restaurantName = document.createElement('B');
    restaurantName.textContent = mark.name;
    popHTML.appendChild(restaurantName);

    var ratingP = document.createElement('P');
    ratingP.textContent = 'Rating: ' + mark.ratingValue;
    popHTML.appendChild(ratingP);

    var addressP = document.createElement('P');
    addressP.textContent = 'Address: ' + mark.address;
    popHTML.appendChild(addressP);

    var phoneP = document.createElement('P');
    phoneP.textContent = 'Phone: ' + mark.telephone;
    popHTML.appendChild(phoneP);

    var showReviews = document.createElement('A');
    showReviews.textContent = 'Show reviews';
    showReviews.onclick = function() {
      viewRestaurantReviewsAction(mark.name);
    };

    popHTML.appendChild(showReviews);
    popHTML.appendChild(document.createElement('BR'));

    var showReservations = document.createElement('A');
    showReservations.textContent = 'Show reservations';
    showReservations.onclick = function() {
      viewReservationAction(mark.name);
    };

    popHTML.appendChild(showReservations);
    popHTML.appendChild(document.createElement('BR'));

    var createReview = addCreateReviewLink(mark.name);
    if (null != createReview) {
      popHTML.appendChild(createReview);
      popHTML.appendChild(document.createElement('BR'));
    }

    var createReservation = addCreateReservationLink(mark.name);
    if (null != createReservation) {
      popHTML.appendChild(createReservation);
    }

    return popHTML;
  }

  function createSpanElement(text, className) {
    var span = document.createElement('SPAN');
    if (className) {
      span.className = className;
    }
    span.textContent = text;
    return span;
  }

  /* Create a div with review information */
  function createSingleReviewDiv(reviewResponse) {
    var reviewElement = document.createElement('DIV');
    reviewElement.className = 'reviewElement';

    // top container
    var top = document.createElement('DIV');
    top.className = 'review-top';

    // rating
    var rating = document.createElement('DIV');
    rating.className = 'rating-div';

    var ratingLabel = createSpanElement('Rating: ', 'ratingLabel');

    var ratingValue = createSpanElement(
      reviewResponse.reviewRating.ratingValue, 'ratingValue');

    rating.appendChild(ratingLabel);
    rating.appendChild(ratingValue);

    top.appendChild(rating);

    // author
    var author = document.createElement('DIV');
    author.className = 'author-div';

    var authorLabel = createSpanElement('Author: ', 'authorLabel');

    var authorValue = createSpanElement(reviewResponse.author.name,
      'authorValue');

    author.appendChild(authorLabel);
    author.appendChild(authorValue);

    top.appendChild(author);

    reviewElement.appendChild(top);

    var hr = document.createElement('HR');
    reviewElement.appendChild(hr);
    // body
    var body = document.createElement('DIV');
    body.className = 'reviewBodyDiv';

    var bodyLabel = createSpanElement('', 'bodyLabel');

    var bodyValue = createSpanElement(reviewResponse.reviewBody, 'bodyValue');

    body.appendChild(bodyLabel);
    body.appendChild(bodyValue);

    reviewElement.appendChild(body);

    return reviewElement;
  }

  /* Show restaurant reviews from an API response. */
  /* At this moment, show all reviews without pagination */
  function createReviewsDiv(reviewsResponse) {
    reviewsResponse = JSON.parse(reviewsResponse);

    if (reviewsResponse.length < 1) {
      var error = document.createElement('H2');
      error.textContent = 'No reviews are available';
      return error;
    }

    var reviewList = document.createElement('DIV');
    reviewList.className = 'reviewList';

    reviewsResponse.forEach(function(reviewResponseElement) {
      reviewList.appendChild(createSingleReviewDiv(reviewResponseElement));
    });

    // return reviews div
    return reviewList;
  }

  // create a div that shows the reservations
  function createReservationsDiv(reservationsResponse) {
    reservationsResponse = JSON.parse(reservationsResponse);

    if (reservationsResponse.length < 1) {
      var error = document.createElement('H2');
      error.textContent = 'No reservations are available.';
      document.getElementById('popContent').appendChild(error);
      openPopUpWindow();
      return;
    }

    var reservationsTable = document.createElement('DIV');
    reservationsTable.classList.add('table', 'table-fixed', 'table-hover');

    var tableHead = document.createElement('THEAD');

    var row = document.createElement('TR');
    row.className = 'row';

    var underNameHead = document.createElement('TH');
    underNameHead.className = 'col-xs-6';
    underNameHead.textContent = 'Reserved by:';
    row.appendChild(underNameHead);

    var timeHead = document.createElement('TH');
    timeHead.className = 'col-xs-4';
    timeHead.textContent = 'Reservation time:';
    row.appendChild(timeHead);

    var dinersHead = document.createElement('TH');
    dinersHead.className = 'col-xs-2';
    dinersHead.textContent = 'Diners:';
    row.appendChild(dinersHead);

    tableHead.appendChild(row);
    reservationsTable.appendChild(tableHead);

    var tableBody = document.createElement('TBODY');

    reservationsResponse.forEach(function(reservationsResponseElement) {
      row = document.createElement('TR'); //defined previously

      var underName = document.createElement('TD');
      underName.classList.add('col-xs-6');
      underName.textContent = reservationsResponseElement.underName.name;
      row.appendChild(underName);

      var time = document.createElement('TD');
      time.classList.add('col-xs-4');
      time.textContent =
        utils.fixBookingTime(reservationsResponseElement.startTime);
      row.appendChild(time);

      var diners = document.createElement('TD');
      diners.classList.add('col-xs-2');
      diners.textContent = reservationsResponseElement.partySize;
      row.appendChild(diners);

      tableBody.appendChild(row);
    });

    reservationsTable.appendChild(tableBody);
    return reservationsTable;
  }

  function addCreateReviewLink(restaurantName) {
    var userInfo = JSON.parse(localStorage.getItem('userInfo'));

    if (! connectionsAPI.hasRole(userInfo,
      connectionsAPI.role.endUser)) {
      return null;
    }

    var createReviewLink = document.createElement('A');
    createReviewLink.textContent = 'Create review';

    createReviewLink.onclick = function(restaurantName) {
      return createAndShowReviewForm(restaurantName);
    }.bind(null, restaurantName);

    return createReviewLink;
  }

  function createAndShowReviewForm(restaurantName) {
    var reviewForm = createReviewForm(restaurantName);
    var title = 'Create review for: ' + restaurantName;
    setPopupTitle(title);
    setPopupContent(reviewForm);
    openPopUpWindow();
  }

  // create a form for creating or updating a review
  function createReviewForm(restaurantName, review) {
    var reviewForm = document.createElement('FORM');
    reviewForm.name = 'editReviewForm';
    reviewForm.className = 'editReviewForm';

    reviewForm.onsubmit = function() {
      var ratingValue =
        parseInt(document.forms.editReviewForm.ratingValue.value);

      var reviewBody = document.forms.editReviewForm.reviewBody.value;
      if (review) {
        updateReviewAction(review.name, ratingValue, reviewBody);
      }
      else {
        createNewReviewAction(restaurantName, ratingValue, reviewBody);
      }

      return false;
    };

    var reviewLabel = document.createElement('LABEL');
    reviewLabel.textContent = 'Your review: ';
    reviewForm.appendChild(reviewLabel);
    reviewForm.appendChild(document.createElement('BR'));

    var reviewBody = document.createElement('TEXTAREA');
    reviewBody.name = 'reviewBody';
    reviewForm.appendChild(reviewBody);
    reviewForm.appendChild(document.createElement('BR'));

    var ratingLabel = document.createElement('LABEL');
    ratingLabel.textContent = 'Rating value: ';
    reviewForm.appendChild(ratingLabel);

    var ratingValueSelect = document.createElement('SELECT');
    ratingValueSelect.name = 'ratingValue';

    var option;
    for (var i = 0; i <= MAXRATING; i++) {
      option = document.createElement('OPTION');
      option.value = i;
      option.textContent = i + ' Star' + (1 != i ? 's' : '');
      ratingValueSelect.appendChild(option);
    }

    reviewForm.appendChild(ratingValueSelect);

    var submit = document.createElement('INPUT');
    submit.type = 'submit';
    submit.value = 'Create Review';
    submit.name = 'submitReview';
    reviewForm.appendChild(submit);

    return reviewForm;
  }

  /* initialize a review form when updating a review
  instead of create a new one */
  function initializeReviewForm(review) {
    var reviewForm = document.forms.namedItem('editReviewForm');

    markSelectedValue(reviewForm.children.ratingValue,
      review.reviewRating.ratingValue);

    reviewForm.children.reviewBody.textContent =
      review.reviewBody;

    reviewForm.children.submitReview.value = 'Update review';
  }

  function addCreateReservationLink(restaurantName) {
    var userInfo = JSON.parse(localStorage.getItem('userInfo'));

    if (! connectionsAPI.hasRole(userInfo,
      connectionsAPI.role.endUser)) {
      return null;
    }

    var createReservationLink = document.createElement('A');
    createReservationLink.textContent = 'Make a reservation';
    createReservationLink.onclick = function(restaurantName) {
      createAndShowReservationForm(restaurantName);
    }.bind(null, restaurantName);

    return createReservationLink;
  }

  // make a form to create a reservation and initialize it
  function createAndShowReservationForm(restaurantName) {
    var reservationForm = createReservationForm(restaurantName);
    var title = 'Make reservation for: ' + restaurantName;
    setPopupTitle(title);
    setPopupContent(reservationForm);

    initReservationForm();
    openPopUpWindow();
  }

  function createReservationForm(restaurantName) {
    document.getElementById('popTitle').textContent = 'Reservation for ' +
       restaurantName;

    var reservationForm = document.createElement('FORM');
    reservationForm.name = 'editReservationForm';
    reservationForm.onsubmit = function() {
      // abort if not ready to submit
      if (document.getElementById('submitReservation').disabled) {
        return false;
      }

      // get values
      var partySize =
        document.forms.editReservationForm.partySize.valueAsNumber;
      var reservationDatetime =
        new Date(document.forms.editReservationForm.reservationDate.value);
      var reservationTime =
        new Date($('#reservationTime').timepicker('getTime'));

      reservationDatetime.setHours(reservationTime.getHours(),
                      reservationTime.getMinutes());

      if (!checkReservationInputs()) {
        return false;
      }

      createNewReservationAction(
        restaurantName, partySize, reservationDatetime);
      return false;
    };

    var name = document.createElement('INPUT');
    name.type = 'hidden';
    name.name = 'restaurantName';
    name.id = 'restaurantName';
    name.value = restaurantName;
    reservationForm.appendChild(name);

    var dinersLabel = document.createElement('SPAN');
    dinersLabel.textContent = 'Number of diners';
    reservationForm.appendChild(dinersLabel);

    reservationForm.appendChild(document.createElement('BR'));
    reservationForm.appendChild(document.createElement('BR'));
    var numDiners = document.createElement('INPUT');
    numDiners.name = 'partySize';
    numDiners.id = 'partySize';
    numDiners.type = 'number';
    numDiners.setAttribute('min', '1');
    reservationForm.appendChild(numDiners);

    reservationForm.appendChild(document.createElement('BR'));

    var dateLabel = document.createElement('SPAN');
    dateLabel.textContent = 'Date';
    reservationForm.appendChild(dateLabel);

    reservationForm.appendChild(document.createElement('BR'));

    var reservationDate = document.createElement('INPUT');
    reservationDate.type = 'date';
    reservationDate.id = 'reservationDate';
    reservationDate.disabled = true;
    reservationForm.appendChild(reservationDate);

    reservationForm.appendChild(document.createElement('BR'));

    var timeLabel = document.createElement('SPAN');
    timeLabel.textContent = 'Time:';
    reservationForm.appendChild(timeLabel);

    reservationForm.appendChild(document.createElement('BR'));

    var reservationTime = document.createElement('INPUT');
    reservationTime.type = 'time';
    reservationTime.id = 'reservationTime';
    reservationTime.disabled = true;
    reservationForm.appendChild(reservationTime);

    reservationForm.appendChild(document.createElement('BR'));

    var loadingTime = document.createElement('DIV');
    loadingTime.id = 'loadingTime';
    loadingTime.textContent = 'Calculating availability';
    loadingTime.style.visibility = 'hidden';

    var loadingTimeImg = document.createElement('IMG');
    loadingTimeImg.src = 'img/loading.gif';
    loadingTime.appendChild(loadingTimeImg);

    reservationForm.appendChild(loadingTime);

    var submit = document.createElement('INPUT');
    submit.type = 'submit';
    submit.id = 'submitReservation';
    submit.value = 'Create Reservation';
    submit.disabled = true;
    reservationForm.appendChild(submit);

    return reservationForm;
  }

  function initReservationForm() {
    // init elements
    $('#reservationDate').datepicker({
      dateFormat: 'yy-mm-dd',
      minDate: '-0d',// only allow future reservations
      maxDate: '+90d', // 3 month max
      firstDay: 0,
      beforeShowDay: function(date) {
        return dayAvailableForReservation(date);
      },
      onSelect: initReservationTime //enable select time
    });

    $('#reservationTime').timepicker({
        'timeFormat': 'H:i:s',
        'minTime': minTime.hours + ':' + minTime.minutes,
        'maxTime': maxTime.hours + ':' + maxTime.minutes,
        'disableTimeRanges': [
      ]
    });

    $('#reservationTime').on('changeTime', function() {
      calcAvailability();
    });

    // partySize does not fire initReservatiomTime yet
    alreadyPartySizeInit = false;

    document.getElementById('partySize').addEventListener('change',
                enableCalendar);
  }

  function dayAvailableForReservation(date, restaurantName) {
    if (date < new Date()) {
      return [false, 'pastDate', ''];
    }
      return [true, 'availableReservations', ''];
    }

  function enableCalendar() {
    document.getElementById('reservationDate').disabled = false;
  }

  function initReservationTime() {
    if (alreadyPartySizeInit === false) {
      alreadyPartySizeInit = true;
      enableAvailabilityCalculation();
      document.getElementById('partySize').addEventListener('change',
      initReservationTime);
    }

    document.getElementById('reservationTime').disabled = false;
  }

  function enableAvailabilityCalculation() {
    document.getElementById('partySize').addEventListener('change',
      calcAvailability);
    document.getElementById('reservationDate').addEventListener('change',
      calcAvailability);
    document.getElementById('reservationTime').addEventListener('change',
      calcAvailability);
  }

  function calcAvailability() {
    document.getElementById('submitReservation').disabled = true;
    // show loading
    document.getElementById('loadingTime').style.visibility = '';

    // get values
    var restaurantName =
      document.getElementById('restaurantName').value;
    var reservationDatetime =
      new Date(document.forms.editReservationForm.reservationDate.value);
    var reservationTime =
      $('#reservationTime').timepicker('getTime');

    if (!checkReservationInputs()) {
      return false;
    }

    reservationDatetime.setHours(reservationTime.getHours(),
      reservationTime.getMinutes());

    getReservationsByDateAction(restaurantName,
        reservationDatetime.toISOString(),
        _proceesAvailabilityResponse,
        _errorProcesingAvailability
      );
    return false;
  }

  function _proceesAvailabilityResponse(restaurantResponse) {
    restaurantResponse = JSON.parse(restaurantResponse);
    if (restaurantResponse.length != 1) {
      console.error('Not retrieved exactly one restaurant', restaurantResponse);
    }

    restaurantResponse = restaurantResponse[0];
    var properties = restaurantResponse.additionalProperty;
    var capacity, occupancyLevel, time;

    properties.forEach(function(property) {
      if ('capacity' == property.name) {
        capacity = property.value;
      }

      if ('occupancyLevels' == property.name) {
        occupancyLevel = property.value;
        time = property.timestamp;
      }
    });

    var numDiners = document.getElementById('partySize').valueAsNumber;

    var available = (capacity - occupancyLevel - numDiners) >= 0;

    document.getElementById('loadingTime').style.visibility = 'hidden';

    // if available allow to submit
    document.getElementById('submitReservation').disabled =
      !available;

    if (!available) {
      var errMsg =
        (capacity - occupancyLevel) +
        ' seats available for the specified date and time';
      utils.showMessage(errMsg, 'alert-warning');
    }
  }

  function _errorProcesingAvailability() {
    utils.showMessage('An error ocurred checking reservation availability',
      'alert-danger');
    document.getElementById('loadingTime').style.visibility = 'hidden';
  }

  function checkReservationInputs() {
    var error = false;
    var reservationDatetime =
      new Date(document.forms.editReservationForm.reservationDate.value);
    var reservationTime =
      $('#reservationTime').timepicker('getTime');

    if (isNaN(reservationDatetime) || (reservationDatetime == null)) {
      document.getElementById('loadingTime').style.visibility = 'hidden';
      document.getElementById('submitReservation').disabled = true;
      document.forms.editReservationForm.reservationDate.classList.add(
        'has-error');
      utils.showMessage('Invalid format for date', 'alert-warning');
      error = true;
    }

    if (isNaN(reservationTime) || (reservationTime == null)) {
      document.getElementById('loadingTime').style.visibility = 'hidden';
      document.getElementById('submitReservation').disabled = true;
      document.getElementById('reservationTime').classList.add('has-error');
      utils.showMessage('Invalid format for time', 'alert-warning');
      error = true;
    }

    if (error) {
      return false;
    }

    document.forms.editReservationForm.reservationDate.classList.remove(
      'has-error');
    document.getElementById('reservationTime').classList.remove('has-error');
    return true;
  }

  // create a table for displaying the reviews
  function createReviewsTable(reviewsResponse) {
    reviewsResponse = JSON.parse(reviewsResponse);

    // clean previous table content
    var myNode = document.getElementById('reviewsTableBody');
    myNode.innerHTML = '';

    if (reviewsResponse.length < 1) {
      var error = document.createElement('TR');
      error.textContent = 'No reviews are available.';
      document.getElementById('reviewsTableBody').appendChild(error);
      return;
    }

    // add entries
    reviewsResponse.forEach(createReviewsTableEntry);
  }

  function createReviewsTableEntry(review) {
    var row = document.createElement('TR');
    var name = document.createElement('TD');
    name.textContent = review.itemReviewed.name;
    name.className = 'col-xs-4';
    row.appendChild(name);

    var rating = document.createElement('TD');
    rating.textContent = review.reviewRating.ratingValue;
    rating.className = 'col-xs-2';
    row.appendChild(rating);

    var view = document.createElement('TD');
    view.className = 'col-xs-2';

    var viewLink = document.createElement('A');
    viewLink.textContent = 'View review';
    viewLink.onclick = createViewReviewLink(review.name);

    view.appendChild(viewLink);
    row.appendChild(view);

    var edit = document.createElement('TD');
    edit.className = 'col-xs-2';

    var editLink = document.createElement('A');
    editLink.textContent = 'Edit review';
    editLink.onclick = createEditReviewLink(review.name);

    edit.appendChild(editLink);
    row.appendChild(edit);

    var del = document.createElement('TD');
    del.className = 'col-xs-2';

    var delLink = document.createElement('A');
    delLink.textContent = 'Delete review';
    delLink.onclick = createDelReviewLink(review.name);

    del.appendChild(delLink);
    row.appendChild(del);

    document.getElementById('reviewsTableBody').appendChild(row);
  }

  /* Create a table for displaying the organization reviews.
  This table is different from the returned by createReviewsTable
  because this does not allow to modify or delete a review. */
  function createOrganizationReviewsTable(reviewsResponse) {
    reviewsResponse = JSON.parse(reviewsResponse);
    // clean previous table content
    var myNode = document.getElementById('reviewsTableBody');
    myNode.innerHTML = '';

    if (reviewsResponse.length < 1) {
      var error = document.createElement('TR');
      error.textContent = 'No reviews are available.';
      document.getElementById('reviewsTableBody').appendChild(error);
      return;
    }

    // add entries
    reviewsResponse.forEach(createOrganizationReviewsTableEntry);
  }

  function createOrganizationReviewsTableEntry(review) {
    var row = document.createElement('TR');
    var name = document.createElement('TD');
    name.textContent = review.itemReviewed.name;
    name.className = 'col-xs-6';
    row.appendChild(name);

    var rating = document.createElement('TD');
    rating.textContent = review.reviewRating.ratingValue;
    rating.className = 'col-xs-3';
    row.appendChild(rating);

    var view = document.createElement('TD');
    view.className = 'col-xs-3';

    var viewLink = document.createElement('A');
    viewLink.textContent = 'View review';
    viewLink.onclick = createViewReviewLink(review.name);

    view.appendChild(viewLink);
    row.appendChild(view);

    document.getElementById('reviewsTableBody').appendChild(row);
  }

  function createViewReviewLink(reviewId) {
    return function() {
      viewReviewAction(reviewId);
    };
  }

  function createEditReviewLink(reviewId) {
    return function() {
      showEditReviewAction(reviewId);
    };
  }

  function createDelReviewLink(reviewId) {
    return function() {
      if (!(window.confirm('Delete review?'))) {
        return;
      }
      deleteReviewAction(reviewId);
    };
  }

  function createCancelReservationLink(reservationId) {
    return function() {
      if (!(window.confirm('Cancel reservation?'))) {
        return;
      }
      cancelReservationAction(reservationId);
    };
  }

  // return a div with the review information from a reviewResponses
  function createViewReviewDiv(reviewResponse) {
    reviewResponse = JSON.parse(reviewResponse);
    if (reviewResponse.length != 1) {
      utils.showMessage('More than one review received.', 'alert-danger');
    }
    return createSingleReviewDiv(reviewResponse[0]);
  }

  function markSelectedValue(selectObject, value) {
    for (var i = 0; i < selectObject.options.length; i++) {
      if (String(selectObject.options[i].value) == String(value)) {
        selectObject.options[i].selected = true;
      }
      else {
        selectObject.options[i].selected = false;
      }
    }
  }

  // create a table for displaying reservations
  function createReservationsTable(reservationsResponse) {
    reservationsResponse = JSON.parse(reservationsResponse);

    // clean previous table content
    var myNode = document.getElementById('reservationsTableBody');
    myNode.innerHTML = '';

    if (reservationsResponse.length < 1) {
      var error = document.createElement('TR');
      error.textContent = 'No reservations are available';
      document.getElementById('reservationsTableBody').appendChild(error);
      return;
    }

    // add entries
    reservationsResponse.forEach(createReservationsTableEntry);
  }

  function createReservationsTableEntry(reservation) {
    var row = document.createElement('TR');

    var name = document.createElement('TD');
    name.textContent = reservation.reservationFor.name;
    row.appendChild(name);

    var time = document.createElement('TD');
    time.textContent = utils.fixBookingTime(reservation.startTime);
    row.appendChild(time);

    var diners = document.createElement('TD');
    diners.textContent = reservation.partySize;
    row.appendChild(diners);

    var cancel = document.createElement('TD');

    var cancelLink = document.createElement('A');
    cancelLink.textContent = 'Cancel reservation';
    cancelLink.onclick =
      createCancelReservationLink(reservation.reservationId);
    cancel.appendChild(cancelLink);
    row.appendChild(cancel);

    document.getElementById('reservationsTableBody').appendChild(row);
  }

  /* aux function that opens the PopUp windows */
  function openPopUpWindow() {
    $('#popWindow').modal('show');
  }

  /* aux function that closes the PopUp window */
  function closePopUpWindow() {
    $('#popWindow').modal('hide');
  }

  return {
    addRestaurantstoMap: addRestaurantstoMap,
    setPopupTitle: setPopupTitle,
    setPopupContent: setPopupContent,
    createReviewsDiv: createReviewsDiv,
    createReservationsDiv: createReservationsDiv,
    createReviewsTable: createReviewsTable,
    createOrganizationReviewsTable: createOrganizationReviewsTable,
    createReservationsTable: createReservationsTable,
    createReviewForm: createReviewForm,
    createViewReviewDiv: createViewReviewDiv,
    setViewReservationAction: setViewReservationAction,
    setViewRestaurantReviewsAction: setViewRestaurantReviewsAction,
    setCreateNewReviewAction: setCreateNewReviewAction,
    setCreateNewReservationAction: setCreateNewReservationAction,
    setGetReservationsByDateAction: setGetReservationsByDateAction,
    setViewReviewAction: setViewReviewAction,
    setShowEditReviewAction: setShowEditReviewAction,
    setUpdateReviewAction: setUpdateReviewAction,
    setCancelReservationAction: setCancelReservationAction,
    setDeleteReviewAction: setDeleteReviewAction,
    initializeReviewForm: initializeReviewForm,
    openPopUpWindow: openPopUpWindow,
    closePopUpWindow: closePopUpWindow
  };
})();

if (typeof exports !== 'undefined') {
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = drawModule;
    connectionsAPI = require('./connectionsAPI.js');
    utils = require('./utils.js');
    GLOBAL.localStorage = require('localStorage');
  }
}


text:
package edu.unapec.nomina.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class InicioController {

    @RequestMapping(value = "/")
    public String Inicio(Model model) {
        model.addAttribute("titulo", "Index");
        model.addAttribute("mensaje", "Mensaje");

        return "index";
    }
}


text:
package org.dictionary.service;

import java.time.LocalDate;

import org.dictionary.api.DashboardAPI;
import org.dictionary.api.DashboardStatAPI;

public interface DashboardService {

    DashboardAPI getDashboard();

    DashboardStatAPI getStats(String login, LocalDate startDate, LocalDate endDate);

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ukr. bot. Zh. 47(5): 81 (1990)

#### Original name
Sawadaea bifida V.P. Heluta

### Remarks
null


text:
Posts = new Meteor.Collection('posts');
Likes = new Meteor.Collection('likes');


text:
namespace content {

struct ServiceWorkerObjectInfo;
struct ServiceWorkerRegistrationObjectInfo;
struct ServiceWorkerVersionAttributes;

class CONTENT_EXPORT ServiceWorkerMessageFilter
    : public NON_EXPORTED_BASE(WorkerThreadMessageFilter) {
 public:
  explicit ServiceWorkerMessageFilter(ThreadSafeSender* thread_safe_sender);

 protected:
  ~ServiceWorkerMessageFilter() override;

 private:
  // WorkerThreadMessageFilter:
  bool ShouldHandleMessage(const IPC::Message& msg) const override;
  void OnFilteredMessageReceived(const IPC::Message& msg) override;
  bool GetWorkerThreadIdForMessage(const IPC::Message& msg,
                                   int* ipc_thread_id) override;

  // ChildMessageFilter:
  void OnStaleMessageReceived(const IPC::Message& msg) override;

  // Message handlers for stale messages.
  void OnStaleRegistered(
      int thread_id,
      int request_id,
      const ServiceWorkerRegistrationObjectInfo& info,
      const ServiceWorkerVersionAttributes& attrs);
  void OnStaleSetVersionAttributes(
      int thread_id,
      int provider_id,
      int registration_handle_id,
      int changed_mask,
      const ServiceWorkerVersionAttributes& attrs);
  void OnStaleSetControllerServiceWorker(
      int thread_id,
      int provider_id,
      const ServiceWorkerObjectInfo& info,
      bool should_notify_controllerchange);

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerMessageFilter);
};

}  // namespace content

#endif  // CONTENT_CHILD_SERVICE_WORKER_SERVICE_WORKER_MESSAGE_FILTER_H_


text:
let udContent="";
const maxTokensDisplayed=2000;
const fieldNames=["ID","FORM","LEMMA","UPOS","XPOS","FEATS","HEAD","DEPREL","DEPS","MISC"];
const nbFields=fieldNames.length;

let tokens,           // tokens must be global to get sentence info not in the table
    selectedTR,       // current selected if !=null (useful for arrow navigation)
    currentUD,        // current UD
    uds;             // all UDs read from the file

// this applies the initial filters
function loadTokens(uds){
    tokens=[]
    let nbTokensFiltered=0;
    // build initial filters
    let filters=[];
    for (var j = 0; j < nbFields; j++) {
        const fn=fieldNames[j];
        const jj=j; // save current j for internal closures
        const ignoreCase=d3.select("#ignoreCase").property("checked")?"i":""
        if (d3.select("#"+fn).classed("checked")){
            if (d3.select("#search-"+fn).property("value")!=""){
                filters.push( (fields)=>
                   new RegExp(d3.select("#search-"+fn).property("value"),ignoreCase).test(fields[jj]) )
            }
        } else if (d3.select("#"+fn).classed("inv-checked")){
            if (d3.select("#search-"+fn).property("value")!=""){
                filters.push( (fields)=>
                    !new RegExp(d3.select("#search-"+fn).property('value'),ignoreCase).test(fields[jj]) ) // negated regex
            }
        }
    }
    // should we have to check equality between lemma and form
    const eqFN=d3.select("#formEQlemma").property("checked")
                    ?(form,lemma)=>form.toLowerCase()==lemma.toLowerCase()
                    :d3.select("#formEQlemma").property("indeterminate")
                       ?(form,lemma)=>form.toLowerCase()!=lemma.toLowerCase()
                       :(form,lemma)=>true;

    uds.forEach(function(ud){
        const nbNodes=ud.nodes.length;
        for (let i = 1; i < nbNodes; i++) {
            let fields=ud.nodes[i].conll().split("\t")
            // "normalize" the fields of the current token
            for (var j = 0; j < nbFields; j++) {
                const f=fields[j].trim();
                if (f=="_")fields[j]="";
                else fields[j]=f;
            }
            // check all initial filters [fieldNo,Regex]
            if (eqFN(fields[1],fields[2]) && filters.every((f)=>f(fields))){
                nbTokensFiltered++;
                if (nbTokensFiltered<=maxTokensDisplayed){
                    fields.push(ud);// add reference to the sentence
                    tokens.push(fields)
                }
            }
        }

    })
    return nbTokensFiltered;
}

//   Parse the udContent and fill the table
function parse(){
    // clear previous info
    d3.select("#message").empty();
    d3.selectAll("#lineNo,#sentId,#tokenId,#text").text("");
    d3.selectAll("#tokens th").classed("colTri decroissant croissant",false);
    tree.style("display","none");
    dependencies.style("display","none");
    selectedTR=null;
    // insert new info
    let nbTokensFiltered=loadTokens(uds);
    let message=`${nbTokensFiltered.toLocaleString()} tokens`;
    if (nbTokensFiltered>maxTokensDisplayed)
        message+=` matched the initial filters,`+
        ` but only the first ${maxTokensDisplayed.toLocaleString()} are displayed`;
    d3.select("#message").text(message);
    fillTable(d3.select("#tokens"));
}

// function matchForm(form,text){
//     const formREw=new RegExp(`\\b${form}\\b`);
//     const formRE=new RegExp(form)
//     // search before as word otherwise search as a string
//     return formREw.exec(currentUD.text)||formRE.exec(currentUD.text)
//
// }

function showSentenceFromRow(tr){
    // change selection
    selectedTR=tr;
    let tbody=d3.select("#tokens tbody");
    tbody.selectAll("td").classed("selected-row",false);
    d3.select(tr).selectAll("td").classed("selected-row",true);
    // update sentence info
    const trUD=d3.select(tr).datum();
    if(trUD!=currentUD){
        currentUD=trUD;
        d3.select("#sentId").text(currentUD.sent_id);
        d3.select("#lineNo").text(currentUD.startLine);
        showSentenceParse(currentUD);
    }
    // highlight the form in the text
    let id=d3.select(tr).select("td").text()
    d3.select("#tokenId").text(id);
    let form=d3.select(tr).selectAll("td").nodes()[1].textContent;
    let selectedNode=currentUD.nodes[+id];
    d3.select("#text")
        .html(currentUD.text.substr(0,selectedNode.indexInText)+
            '<b>'+form+'</b>'+currentUD.text.substr(selectedNode.indexInText+form.length));

    // highlight word in the link and tree displays
    d3.selectAll("svg .selected-word").classed("selected-word",false);
    selectedNode.wordInLinks.classed("selected-word",true);
    selectedNode.wordInTree.classed("selected-word",true);
}

// fill the table
function fillTable(table){
    table.selectAll("tbody tr").remove();
    const tbody=table.select("tbody");
    // fill content with rows
    for (var i = 0; i < tokens.length; i++) {
        toks=tokens[i];
        let tr=tbody.append("tr");
        for (var j = 0; j < nbFields; j++) {
            tr.append("td").classed(fieldNames[j],true).text(toks[j]);
        }
        tr.datum(toks[nbFields]);
    }
    table.on ("click",function(e){
        const tgt=d3.event.target;
        if (tgt.nodeName == "TH")return;// click in the header, this will call the sort
        const tr=d3.select(tgt).node().parentNode;
        showSentenceFromRow(tr);
    })
}

// show/hide instructions
function toggleInstructions(){
    const me=d3.select(this);
    const val=me.property("value");
    if (val=="Hide instructions"){
        d3.select("#instructions").style("display","none");
        me.property("value","Show instructions");
    } else {
        d3.select("#instructions").style("display","block");
        me.property("value","Hide instructions");
    }
}

// deal with a three state checkbox
// adapted from https://css-tricks.com/indeterminate-checkboxes/
function threeStatesCB() {
  if (this.readOnly) this.checked=this.readOnly=false;
  else if (!this.checked) this.readOnly=this.indeterminate=true;
}

// Separates a single string into UDs separated at a blank line
// returns a list of dependencies
function parseUDs(groupVal,fileName){
    let udsStrings=groupVal.split("\n\n");
    let uds=[];
    let startLine=1;
    let sentence;
    udsStrings.forEach(function(string){
        if (string.trim().length==0){
            startLine++;
            return; // ignore empty uds
        }
        const ud=new UD(fileName,string,startLine);
        if (ud.nodes.length==1){// commented group
            startLine+=ud.nbLines;
            return;
        }
        uds.push(ud);
        startLine+=ud.nbLines+1;
    })
    return uds;
}

function getFile(){
    let file = d3.select("#file-input").node().files[0];
    if (file!==undefined){
        fileName=file.name
        d3.select("#fileName").text(file.name);
        // read the local file
    	let reader = new FileReader();
    	reader.addEventListener('load', function(e) {
            uds=parseUDs(e.target.result,file.name)
            parse();
            d3.select("#file-input").property("value",""); // so that we can reload the last file...
    	});
    	reader.readAsText(file);
    }
}

function createFilters(){
    const fieldSelect=d3.select("#fieldSelect");
    // create the initial filter textbox
    for (var j = 0; j < nbFields; j++) {
        const fName=fieldNames[j];
        const span=fieldSelect.append("span")
            .classed("fieldName",true)
            .attr("id",fName)
            .text(fName);
        const search = fieldSelect.append("input")
            .attr("type",text)
            .attr("id","search-"+fName)
            .attr("placeholder",fName=="ID"?"":"regex")
            .attr("size",fName=="ID"?3:20);
        search.style("display","none");
        span.on("click",function(){ // listener on the fieldName
            if (d3.select(this).classed("checked")){
                d3.select(this)
                    .classed("checked",false)
                    .classed("inv-checked",true);
                d3.select("#search-"+fName)
                    .property("placeholder","inv-regex");
            } else if (d3.select(this).classed("inv-checked")){
                d3.select("#search-"+fName).style("display","none");
                d3.select(this)
                    .classed("inv-checked",false);
            } else {
                d3.select("#"+fName).classed("checked",true)
                d3.select("#search-"+fName)
                    .property("placeholder","regex")
                    .style("display","inline");
            }
        });
        // add checkbox for equality between form and lemma
        if (j==1){
            fieldSelect.append("label")
                .classed("fieldName",true)
                .attr("for","formEQlemma")
                .attr("title","check if FORM and LEMMA are the same")
                .text("=")
            let cb = fieldSelect.append("input")
                .attr("type","checkbox")
                .attr("id","formEQlemma");
            cb.property("checked",false)
                .property("indeterminate",false).
                on("click",threeStatesCB);
        }
    }
    fieldSelect.append("input")
        .classed("right",true)
        .attr("type","checkbox")
        .attr("id","ignoreCase")
        .attr("checked",true);
    fieldSelect.append("label")
        .classed("right",true)
        .attr("for","ignoreCase")
        .attr("title","Are regexps case-insensitive?")
        .text("Ignore Case")
}

function initTable(){
    const table=d3.select("#tokens")
    // create headers of the table
    let tr = table.select("thead").append("tr");
    for (var j = 0; j < nbFields; j++) {
        tr.append("th")
            .classed(fieldNames[j],true)
            .text(fieldNames[j])
    }

    // Table sorting by clicking in the column heading
    // https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript/49041392#49041392
    //  quite subtle but it works efficiently
    const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
    const comparer = (idx, asc) => (a, b) => ((v1, v2) =>
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    // do the work...
    document.querySelectorAll('#tokens th').forEach(th => th.addEventListener('click', (() => {
        const noCol=Array.from(th.parentNode.children).indexOf(th);
        let ascending;
        let th1=table.select(`thead th:nth-child(${noCol+1})`);
        if (th1.classed("colTri")){        // changer l'ordre de tri
            if (th1.classed("croissant")){
               th1.classed("croissant",ascending=false);
               th1.classed("decroissant",true);
            } else {
                th1.classed("croissant",ascending=true);
                th1.classed("decroissant",false);
            }
        } else {
            table.selectAll("thead th").classed("colTri croissant decroissant",false);
            th1.classed("colTri",true).classed("croissant",true);
            ascending=true;
        }
        const tableNode=table.node();
        const tbody = document.querySelector("tbody",tableNode);
        Array.from(tableNode.querySelectorAll('tbody tr:nth-child(n+1)'))
            .sort(comparer(Array.from(th.parentNode.children).indexOf(th), ascending))
            .forEach(tr => tbody.appendChild(tr) );
    })));
}

function showSentenceParse(ud){
    const displayType=d3.select("#displayType").property("value");
    if (displayType=="hide"){
        tree.style("display","none");
        dependencies.style("display","none")
    } else if (displayType=="links"){
        tree.style("display","none");
        dependencies.style("display","block")
        showDependencies(ud);
    } else {
        tree.style("display","block");
        dependencies.style("display","none")
        showTree(ud);
    }
}

// redefine function from drawDependencies to ignore clicking on tokens to display
// in the table, because it is not guaranteed that the token is shown in the table
function drawSentence(display,ud){
    var endX=startX;
    // draw the words of the sentence and update width and x in deps
    for (var i = 1; i < ud.nodes.length; i++) {
        var udn=ud.nodes[i];
        var [width,word]=addWord(display,null,endX,startY,udn.form,
                         `${udn.id} ${udn.lemma} ${udn.upos} ${udn.options2feats(udn.feats)}`,
                          i==ud.root.id,udn.form!=ud.tokens[i]);
        udn.x=endX;
        udn.width=width;
        udn.mid=endX+width/2;
        udn.wordInTree=udn.wordInLinks=word;
        endX+=width+wordSpacing;
    }
    return endX;
}

function UDgrepLoad(){
    dependencies=d3.select("#dependencies");
    tree=d3.select("#tree");
    createFilters();
    initTable();
    d3.select("#maxTokens").text(maxTokensDisplayed.toLocaleString()); // insert current value in the web page
    uds=parseUDs(initUD,"initUDs");
    parse();
    d3.select("#file-input").on("change",getFile);
    d3.select("#parse").on("click",parse);
    d3.select("#showHideInstructions").on("click",toggleInstructions);
    d3.select("#displayType").on("change",function(){
        showSentenceParse(currentUD);
    });
    d3.select("#wordSpacing").on("change",function(){
        wordSpacing=+this.value;
        showSentenceParse(currentUD);
    });
    d3.select("#letterSpacing").on("change",function(){
        letterSpacing=+this.value;
        showSentenceParse(currentUD);
    });
    d3.select("body").on("keydown",function(){
        if (selectedTR==null)return;
        const key=d3.event.keyCode;
        if (key==38){// up
            if (selectedTR.previousSibling!=null){
                showSentenceFromRow(selectedTR.previousSibling);
                selectedTR.scrollIntoView(false);
                d3.event.preventDefault();
            }
        } else if (key==40) {// down
            if (selectedTR.nextSibling!=null){
                showSentenceFromRow(selectedTR.nextSibling);
                selectedTR.scrollIntoView(false)
                d3.event.preventDefault();
            }
        }
    })
    // allow file selection via drag and drop
    // adapted from https://stackoverflow.com/questions/47515232/how-to-set-file-input-value-when-dropping-file-on-page/47522812#47522812

    let docElem = document.documentElement;
    let body = document.body;
    let fileInput = document.querySelector('#file-input');

    docElem.addEventListener('dragover', (e) => {
      e.preventDefault();
      body.classList.add('dragging');
    });

    docElem.addEventListener('dragleave', () => {
      body.classList.remove('dragging');
    });

    docElem.addEventListener('drop', (e) => {
      e.preventDefault();
      body.classList.remove('dragging');

      fileInput.files = e.dataTransfer.files;
    });
}

d3.select(window).on("load",UDgrepLoad);


text:
.class synthetic Lcom/android/camera/ui/SettingSublistLayout$1;
.super Ljava/lang/Object;
.source "SettingSublistLayout.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/camera/ui/SettingSublistLayout;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1008
    name = null
.end annotation


text:
#import <UIKit/UIKit.h>
#import <ArcGIS/ArcGIS.h>
#import "RootViewController.h"

@interface CutterViewController : UIViewController <AGSMapViewLayerDelegate>
@property (nonatomic, strong) IBOutlet UIToolbar *toolbar;
@property (nonatomic, strong) IBOutlet AGSMapView *mapView;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *addButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *resetButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *polygonButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *cutButton;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *drawButton;
@property (nonatomic, strong) IBOutlet UILabel *userInstructions;

@property (nonatomic, strong) AGSGraphicsLayer *graphicsLayer;
@property (nonatomic, strong) AGSSketchGraphicsLayer *sketchLayer;

@end


text:
package com.example.on_deactivate;

import arez.annotations.ArezComponent;
import arez.annotations.Memoize;
import arez.annotations.OnDeactivate;

@ArezComponent
public abstract class OnDeactivateBadNameModel3
{
  @Memoize
  public int getMyValue()
  {
    return 0;
  }

  @OnDeactivate( name = "-a-" )
  void foo()
  {
  }
}


text:
package actions_on_google_golang

import "github.com/crezam/actions-on-google-golang/model"

type ApiAiAssistant struct {
	request model.ApiAiRequest
}


text:
<!DOCTYPE html>
<html>
    <head>
        <title>Test that the callback is not garbage collected if registered.</title>
        <script src="../../resources/testharness.js"></script>
        <script src="../../resources/testharnessreport.js"></script>
        <script src="../media-file.js"></script>
    </head>
    <body>
        <script>
            function gc() {
                if (window.GCController)
                    GCController.collect();
                else {
                    for (var i = 0; i < 10000; ++i) {
                        ({ });
                    }
                }
            }

            async_test(function(t)
            {
                var v = document.createElement('video');
                v.src = findMediaFile('video', 'content/test');
                document.body.appendChild(v);

                function callback(available) {}
                var callbackRef = t.step_func_done(callback);

                v.remote.watchAvailability(callbackRef).then(
                        function() { callbackRef = null; gc(); },
                        t.unreached_func());
            }, 'Test that the callback is not garbage collected if registered.');
        </script>
    </body>
</html>


text:
ActiveRecord::Schema.define(version: 20150929175437) do

  create_table "activities", force: :cascade do |t|
    t.string   "name"
    t.string   "location"
    t.string   "google_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "activity_tags", force: :cascade do |t|
    t.integer  "activity_id"
    t.integer  "tag_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "activity_tags", ["activity_id"], name: "index_activity_tags_on_activity_id"
  add_index "activity_tags", ["tag_id"], name: "index_activity_tags_on_tag_id"

  create_table "itineraries", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "itinerary_activities", force: :cascade do |t|
    t.integer  "itinerary_id"
    t.integer  "activity_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

  add_index "itinerary_activities", ["activity_id"], name: "index_itinerary_activities_on_activity_id"
  add_index "itinerary_activities", ["itinerary_id"], name: "index_itinerary_activities_on_itinerary_id"

  create_table "tags", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "alias"
  end

  create_table "user_tags", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "tag_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "user_tags", ["tag_id"], name: "index_user_tags_on_tag_id"
  add_index "user_tags", ["user_id"], name: "index_user_tags_on_user_id"

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
package org.apache.hyracks.storage.am.lsm.invertedindex.dataflow;

import java.util.Map;

import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationSchedulerProvider;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicyFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTrackerFactory;
import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCacheProvider;
import org.apache.hyracks.storage.am.lsm.common.dataflow.LsmResourceFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory;
import org.apache.hyracks.storage.common.IResource;
import org.apache.hyracks.storage.common.IStorageManager;

public class LSMInvertedIndexLocalResourceFactory extends LsmResourceFactory {

    private static final long serialVersionUID = 1L;
    private final ITypeTraits[] tokenTypeTraits;
    private final IBinaryComparatorFactory[] tokenCmpFactories;
    private final IBinaryTokenizerFactory tokenizerFactory;
    private final boolean isPartitioned;
    private final int[] invertedIndexFields;
    private final int[] filterFieldsForNonBulkLoadOps;
    private final int[] invertedIndexFieldsForNonBulkLoadOps;
    private final double bloomFilterFalsePositiveRate;

    public LSMInvertedIndexLocalResourceFactory(IStorageManager storageManager, ITypeTraits[] typeTraits,
            IBinaryComparatorFactory[] cmpFactories, ITypeTraits[] filterTypeTraits,
            IBinaryComparatorFactory[] filterCmpFactories, int[] filterFields,
            ILSMOperationTrackerFactory opTrackerFactory, ILSMIOOperationCallbackFactory ioOpCallbackFactory,
            IMetadataPageManagerFactory metadataPageManagerFactory, IVirtualBufferCacheProvider vbcProvider,
            ILSMIOOperationSchedulerProvider ioSchedulerProvider, ILSMMergePolicyFactory mergePolicyFactory,
            Map<String, String> mergePolicyProperties, boolean durable, ITypeTraits[] tokenTypeTraits,
            IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
            boolean isPartitioned, int[] invertedIndexFields, int[] filterFieldsForNonBulkLoadOps,
            int[] invertedIndexFieldsForNonBulkLoadOps, double bloomFilterFalsePositiveRate) {
        super(storageManager, typeTraits, cmpFactories, filterTypeTraits, filterCmpFactories, filterFields,
                opTrackerFactory, ioOpCallbackFactory, metadataPageManagerFactory, vbcProvider, ioSchedulerProvider,
                mergePolicyFactory, mergePolicyProperties, durable);
        this.tokenTypeTraits = tokenTypeTraits;
        this.tokenCmpFactories = tokenCmpFactories;
        this.tokenizerFactory = tokenizerFactory;
        this.isPartitioned = isPartitioned;
        this.invertedIndexFields = invertedIndexFields;
        this.filterFieldsForNonBulkLoadOps = filterFieldsForNonBulkLoadOps;
        this.invertedIndexFieldsForNonBulkLoadOps = invertedIndexFieldsForNonBulkLoadOps;
        this.bloomFilterFalsePositiveRate = bloomFilterFalsePositiveRate;
    }

    @Override
    public IResource createResource(FileReference fileRef) {
        return new LSMInvertedIndexLocalResource(fileRef.getRelativePath(), storageManager, typeTraits, cmpFactories,
                filterTypeTraits, filterCmpFactories, filterFields, opTrackerProvider, ioOpCallbackFactory,
                metadataPageManagerFactory, vbcProvider, ioSchedulerProvider, mergePolicyFactory, mergePolicyProperties,
                durable, tokenTypeTraits, tokenCmpFactories, tokenizerFactory, isPartitioned, invertedIndexFields,
                filterFieldsForNonBulkLoadOps, invertedIndexFieldsForNonBulkLoadOps, bloomFilterFalsePositiveRate);
    }

}


text:
Adaptor libraries to interface with external systems. More specifically, with Facebook.

   * facebook_graph: Provides read access to user messages using the [Facebook Graph API](https://developers.facebook.com/docs/graph-api/reference/v2.1/user/inbox)
   * facebook_page: Provides an API for posting messages to a conversation, using the [mobile Facebook site](https://m.facebook.com/messages/).