text:
"""Client-side script to send a try job to the try server. It communicates to
the try server by either writting to a svn repository or by directly connecting
to the server by HTTP.
"""

import datetime
import errno
import getpass
import json
import logging
import optparse
import os
import posixpath
import re
import shutil
import sys
import tempfile
import urllib

import breakpad  # pylint: disable=W0611

import gcl
import fix_encoding
import gclient_utils
import scm
import subprocess2

__version__ = '1.2'

# Constants
HELP_STRING = "Sorry, Tryserver is not available."
USAGE = r"""%prog [options]

Client-side script to send a try job to the try server. It communicates to
the try server by either writting to a svn repository or by directly connecting
to the server by HTTP."""

EPILOG = """
Examples:
  Send a patch directly from rietveld:
    %(prog)s -R codereview.chromium.org/1337
        --email recipient@example.com --root src

  Try a change against a particular revision:
    %(prog)s -r 123

  A git patch off a web site (git inserts a/ and b/) and fix the base dir:
    %(prog)s --url http://url/to/patch.diff --patchlevel 1 --root src

  Use svn to store the try job, specify an alternate email address and use a
  premade diff file on the local drive:
    %(prog)s --email user@example.com
            --svn_repo svn://svn.chromium.org/chrome-try/try --diff foo.diff

  Running only on a 'mac' slave with revision 123 and clobber first; specify
  manually the 3 source files to use for the try job:
    %(prog)s --bot mac --revision 123 --clobber -f src/a.cc -f src/a.h
            -f include/b.h
"""

def DieWithError(message):
  print >> sys.stderr, message
  sys.exit(1)

def RunCommand(args, error_ok=False, error_message=None, **kwargs):
  try:
    return subprocess2.check_output(args, shell=False, **kwargs)
  except subprocess2.CalledProcessError, e:
    if not error_ok:
      DieWithError(
          'Command "%s" failed.\n%s' % (
            ' '.join(args), error_message or e.stdout or ''))
    return e.stdout

def RunGit(args, **kwargs):
  """Returns stdout."""
  return RunCommand(['git'] + args, **kwargs)

class InvalidScript(Exception):
  def __str__(self):
    return self.args[0] + '\n' + HELP_STRING

class NoTryServerAccess(Exception):
  def __str__(self):
    return self.args[0] + '\n' + HELP_STRING

def Escape(name):
  """Escapes characters that could interfere with the file system or try job
  parsing.
  """
  return re.sub(r'[^\w#-]', '_', name)

class SCM(object):
  """Simplistic base class to implement one function: ProcessOptions."""
  def __init__(self, options, path, file_list):
    items = path.split('@')
    assert len(items) <= 2
    self.checkout_root = os.path.abspath(items[0])
    items.append(None)
    self.diff_against = items[1]
    self.options = options
    # Lazy-load file list from the SCM unless files were specified in options.
    self._files = None
    self._file_tuples = None
    if file_list:
      self._files = file_list
      self._file_tuples = [('M', f) for f in self.files]
    self.options.files = None
    self.codereview_settings = None
    self.codereview_settings_file = 'codereview.settings'
    self.toplevel_root = None

  def GetFileNames(self):
    """Return the list of files in the diff."""
    return self.files

  def GetCodeReviewSetting(self, key):
    """Returns a value for the given key for this repository.

    Uses gcl-style settings from the repository.
    """
    if gcl:
      gcl_setting = gcl.GetCodeReviewSetting(key)
      if gcl_setting != '':
        return gcl_setting
    if self.codereview_settings is None:
      self.codereview_settings = {}
      settings_file = self.ReadRootFile(self.codereview_settings_file)
      if settings_file:
        for line in settings_file.splitlines():
          if not line or line.lstrip().startswith('#'):
            continue
          k, v = line.split(":", 1)
          self.codereview_settings[k.strip()] = v.strip()
    return self.codereview_settings.get(key, '')

  def _GclStyleSettings(self):
    """Set default settings based on the gcl-style settings from the
    repository."""
    settings = {
      'port': self.GetCodeReviewSetting('TRYSERVER_HTTP_PORT'),
      'host': self.GetCodeReviewSetting('TRYSERVER_HTTP_HOST'),
      'svn_repo': self.GetCodeReviewSetting('TRYSERVER_SVN_URL'),
      'project': self.GetCodeReviewSetting('TRYSERVER_PROJECT'),
      'root': self.GetCodeReviewSetting('TRYSERVER_ROOT'),
      'patchlevel': self.GetCodeReviewSetting('TRYSERVER_PATCHLEVEL'),
    }
    logging.info('\n'.join(['%s: %s' % (k, v)
                            for (k, v) in settings.iteritems() if v]))
    for (k, v) in settings.iteritems():
      if v and getattr(self.options, k) is None:
        setattr(self.options, k, v)

  def AutomagicalSettings(self):
    """Determines settings based on supported code review and checkout tools.
    """
    # Try to find gclient or repo root first.
    if not self.options.no_search:
      self.toplevel_root = gclient_utils.FindGclientRoot(self.checkout_root)
      if self.toplevel_root:
        logging.info('Found .gclient at %s' % self.toplevel_root)
      else:
        self.toplevel_root = gclient_utils.FindFileUpwards(
            os.path.join('..', '.repo'), self.checkout_root)
        if self.toplevel_root:
          logging.info('Found .repo dir at %s'
                       % os.path.dirname(self.toplevel_root))

      if self.toplevel_root and not self.options.root:
        assert os.path.abspath(self.toplevel_root) == self.toplevel_root
        self.options.root = gclient_utils.PathDifference(self.toplevel_root,
                                                         self.checkout_root)

    self._GclStyleSettings()

  def ReadRootFile(self, filename):
    cur = self.checkout_root
    root = self.toplevel_root or self.checkout_root

    assert cur.startswith(root), (root, cur)
    while cur.startswith(root):
      filepath = os.path.join(cur, filename)
      if os.path.isfile(filepath):
        logging.info('Found %s at %s' % (filename, cur))
        return gclient_utils.FileRead(filepath)
      cur = os.path.dirname(cur)
    logging.warning('Didn\'t find %s' % filename)
    return None

  def _SetFileTuples(self, file_tuples):
    excluded = ['!', '?', 'X', ' ', '~']
    def Excluded(f):
      if f[0][0] in excluded:
        return True
      for r in self.options.exclude:
        if re.search(r, f[1]):
          logging.info('Ignoring "%s"' % f[1])
          return True
      return False

    self._file_tuples = [f for f in file_tuples if not Excluded(f)]
    self._files = [f[1] for f in self._file_tuples]

  def CaptureStatus(self):
    """Returns the 'svn status' emulated output as an array of (status, file)
       tuples."""
    raise NotImplementedError(
        "abstract method -- subclass %s must override" % self.__class__)

  @property
  def files(self):
    if self._files is None:
      self._SetFileTuples(self.CaptureStatus())
    return self._files

  @property
  def file_tuples(self):
    if self._file_tuples is None:
      self._SetFileTuples(self.CaptureStatus())
    return self._file_tuples

class SVN(SCM):
  """Gathers the options and diff for a subversion checkout."""
  def __init__(self, *args, **kwargs):
    SCM.__init__(self, *args, **kwargs)
    self.checkout_root = scm.SVN.GetCheckoutRoot(self.checkout_root)
    if not self.options.email:
      # Assumes the svn credential is an email address.
      self.options.email = scm.SVN.GetEmail(self.checkout_root)
    logging.info("SVN(%s)" % self.checkout_root)

  def ReadRootFile(self, filename):
    data = SCM.ReadRootFile(self, filename)
    if data:
      return data

    # Try to search on the subversion repository for the file.
    if not gcl:
      return None
    data = gcl.GetCachedFile(filename)
    logging.debug('%s:\n%s' % (filename, data))
    return data

  def CaptureStatus(self):
    return scm.SVN.CaptureStatus(None, self.checkout_root)

  def GenerateDiff(self):
    """Returns a string containing the diff for the given file list.

    The files in the list should either be absolute paths or relative to the
    given root.
    """
    return scm.SVN.GenerateDiff(self.files, self.checkout_root, full_move=True,
                                revision=self.diff_against)

class GIT(SCM):
  """Gathers the options and diff for a git checkout."""
  def __init__(self, *args, **kwargs):
    SCM.__init__(self, *args, **kwargs)
    self.checkout_root = scm.GIT.GetCheckoutRoot(self.checkout_root)
    if not self.options.name:
      self.options.name = scm.GIT.GetPatchName(self.checkout_root)
    if not self.options.email:
      self.options.email = scm.GIT.GetEmail(self.checkout_root)
    if not self.diff_against:
      self.diff_against = scm.GIT.GetUpstreamBranch(self.checkout_root)
      if not self.diff_against:
        raise NoTryServerAccess(
            "Unable to determine default branch to diff against. "
            "Verify this branch is set up to track another"
            "(via the --track argument to \"git checkout -b ...\"")
    logging.info("GIT(%s)" % self.checkout_root)

  def CaptureStatus(self):
    return scm.GIT.CaptureStatus(
        [],
        self.checkout_root.replace(os.sep, '/'),
        self.diff_against)

  def GenerateDiff(self):
    if RunGit(['diff-index', 'HEAD']):
      print 'Cannot try with a dirty tree.  You must commit locally first.'
      return None
    return scm.GIT.GenerateDiff(
        self.checkout_root,
        files=self.files,
        full_move=True,
        branch=self.diff_against)

def _ParseSendChangeOptions(options):
  """Parse common options passed to _SendChangeHTTP and _SendChangeSVN."""
  values = [
    ('user', options.user),
    ('name', options.name),
  ]
  if options.email:
    values.append(('email', options.email))
  if options.revision:
    values.append(('revision', options.revision))
  if options.clobber:
    values.append(('clobber', 'true'))
  if options.root:
    values.append(('root', options.root))
  if options.patchlevel:
    values.append(('patchlevel', options.patchlevel))
  if options.issue:
    values.append(('issue', options.issue))
  if options.patchset:
    values.append(('patchset', options.patchset))
  if options.target:
    values.append(('target', options.target))
  if options.project:
    values.append(('project', options.project))

  filters = ','.join(options.testfilter)
  if filters:
    for botlist in options.bot:
      for bot in botlist.split(','):
        if ':' in bot:
          raise ValueError(
              'Can\'t use both --testfilter and --bot builder:test formats '
              'at the same time')
        else:
          values.append(('bot', '%s:%s' % (bot, filters)))
  else:
    for bot in options.bot:
      values.append(('bot', bot))
  return values

def _SendChangeHTTP(options):
  """Send a change to the try server using the HTTP protocol."""
  if not options.host:
    raise NoTryServerAccess('Please use the --host option to specify the try '
        'server host to connect to.')
  if not options.port:
    raise NoTryServerAccess('Please use the --port option to specify the try '
        'server port to connect to.')

  values = _ParseSendChangeOptions(options)
  values.append(('patch', options.diff))

  url = 'http://%s:%s/send_try_patch' % (options.host, options.port)
  proxies = None
  if options.proxy:
    if options.proxy.lower() == 'none':
      # Effectively disable HTTP_PROXY or Internet settings proxy setup.
      proxies = {}
    else:
      proxies = {'http': options.proxy, 'https': options.proxy}

  logging.info('Sending by HTTP')
  logging.info(''.join("%s=%s\n" % (k, v) for k, v in values))
  logging.info(url)
  logging.info(options.diff)
  if options.dry_run:
    return

  try:
    logging.info('Opening connection...')
    connection = urllib.urlopen(url, urllib.urlencode(values), proxies=proxies)
    logging.info('Done')
  except IOError, e:
    logging.info(str(e))
    if options.bot and len(e.args) > 2 and e.args[2] == 'got a bad status line':
      raise NoTryServerAccess('%s is unaccessible. Bad --bot argument?' % url)
    else:
      raise NoTryServerAccess('%s is unaccessible. Reason: %s' % (url,
                                                                  str(e.args)))
  if not connection:
    raise NoTryServerAccess('%s is unaccessible.' % url)
  logging.info('Reading response...')
  response = connection.read()
  logging.info('Done')
  if response != 'OK':
    raise NoTryServerAccess('%s is unaccessible. Got:\n%s' % (url, response))

def _SendChangeSVN(options):
  """Send a change to the try server by committing a diff file on a subversion
  server."""
  if not options.svn_repo:
    raise NoTryServerAccess('Please use the --svn_repo option to specify the'
                            ' try server svn repository to connect to.')

  values = _ParseSendChangeOptions(options)
  description = ''.join("%s=%s\n" % (k, v) for k, v in values)
  logging.info('Sending by SVN')
  logging.info(description)
  logging.info(options.svn_repo)
  logging.info(options.diff)
  if options.dry_run:
    return

  # Create a temporary directory, put a uniquely named file in it with the diff
  # content and svn import that.
  temp_dir = tempfile.mkdtemp()
  temp_file = tempfile.NamedTemporaryFile()
  try:
    try:
      # Description
      temp_file.write(description)
      temp_file.flush()

      # Diff file
      current_time = str(datetime.datetime.now()).replace(':', '.')
      file_name = (Escape(options.user) + '.' + Escape(options.name) +
                   '.%s.diff' % current_time)
      full_path = os.path.join(temp_dir, file_name)
      with open(full_path, 'wb') as f:
        f.write(options.diff)

      # Committing it will trigger a try job.
      if sys.platform == "cygwin":
        # Small chromium-specific issue here:
        # git-try uses /usr/bin/python on cygwin but svn.bat will be used
        # instead of /usr/bin/svn by default. That causes bad things(tm) since
        # Windows' svn.exe has no clue about cygwin paths. Hence force to use
        # the cygwin version in this particular context.
        exe = "/usr/bin/svn"
      else:
        exe = "svn"
      command = [exe, 'import', '-q', temp_dir, options.svn_repo, '--file',
                 temp_file.name]
      if scm.SVN.AssertVersion("1.5")[0]:
        command.append('--no-ignore')

      subprocess2.check_call(command)
    except subprocess2.CalledProcessError, e:
      raise NoTryServerAccess(str(e))
  finally:
    temp_file.close()
    shutil.rmtree(temp_dir, True)

def PrintSuccess(options):
  if not options.dry_run:
    text = 'Patch \'%s\' sent to try server' % options.name
    if options.bot:
      text += ': %s' % ', '.join(options.bot)
    print(text)

def GuessVCS(options, path, file_list):
  """Helper to guess the version control system.

  NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't
  support it yet.

  This examines the path directory, guesses which SCM we're using, and
  returns an instance of the appropriate class.  Exit with an error if we can't
  figure it out.

  Returns:
    A SCM instance. Exits if the SCM can't be guessed.
  """
  __pychecker__ = 'no-returnvalues'
  real_path = path.split('@')[0]
  logging.info("GuessVCS(%s)" % path)
  # Subversion has a .svn in all working directories.
  if os.path.isdir(os.path.join(real_path, '.svn')):
    return SVN(options, path, file_list)

  # Git has a command to test if you're in a git tree.
  # Try running it, but don't die if we don't have git installed.
  try:
    subprocess2.check_output(
        ['git', 'rev-parse', '--is-inside-work-tree'], cwd=real_path,
        stderr=subprocess2.VOID)
    return GIT(options, path, file_list)
  except OSError, e:
    if e.errno != errno.ENOENT:
      raise
  except subprocess2.CalledProcessError, e:
    if e.returncode != errno.ENOENT and e.returncode != 128:
      # ENOENT == 2 = they don't have git installed.
      # 128 = git error code when not in a repo.
      logging.warning('Unexpected error code: %s' % e.returncode)
      raise
  raise NoTryServerAccess(
      ( 'Could not guess version control system for %s.\n'
        'Are you in a working copy directory?') % path)

def GetMungedDiff(path_diff, diff):
  # Munge paths to match svn.
  changed_files = []
  for i in range(len(diff)):
    if diff[i].startswith('--- ') or diff[i].startswith('+++ '):
      new_file = posixpath.join(path_diff, diff[i][4:]).replace('\\', '/')
      if diff[i].startswith('--- '):
        file_path = new_file.split('\t')[0].strip()
        if file_path.startswith('a/'):
          file_path = file_path[2:]
        changed_files.append(('M', file_path))
      diff[i] = diff[i][0:4] + new_file
  return (diff, changed_files)

def gen_parser(prog):
  # Parse argv
  parser = optparse.OptionParser(usage=USAGE,
                                 version=__version__,
                                 prog=prog)
  parser.add_option("-v", "--verbose", action="count", default=0,
                    help="Prints debugging infos")
  group = optparse.OptionGroup(parser, "Result and status")
  group.add_option("-u", "--user", default=getpass.getuser(),
                   help="Owner user name [default: %default]")
  group.add_option("-e", "--email",
                   default=os.environ.get('TRYBOT_RESULTS_EMAIL_ADDRESS',
                        os.environ.get('EMAIL_ADDRESS')),
                   help="Email address where to send the results. Use either "
                        "the TRYBOT_RESULTS_EMAIL_ADDRESS environment "
                        "variable or EMAIL_ADDRESS to set the email address "
                        "the try bots report results to [default: %default]")
  group.add_option("-n", "--name",
                   help="Descriptive name of the try job")
  group.add_option("--issue", type='int',
                   help="Update rietveld issue try job status")
  group.add_option("--patchset", type='int',
                   help="Update rietveld issue try job status. This is "
                        "optional if --issue is used, In that case, the "
                        "latest patchset will be used.")
  group.add_option("--dry_run", action='store_true',
                   help="Don't send the try job. This implies --verbose, so "
                        "it will print the diff.")
  parser.add_option_group(group)

  group = optparse.OptionGroup(parser, "Try job options")
  group.add_option(
      "-b", "--bot", action="append",
      help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple "
            "times to specify multiple builders. ex: "
            "'-bwin_rel:ui_tests,webkit_unit_tests -bwin_layout'. See "
            "the try server waterfall for the builders name and the tests "
            "available. Can also be used to specify gtest_filter, e.g. "
            "-bwin_rel:base_unittests:ValuesTest.*Value"))
  group.add_option("-B", "--print_bots", action="store_true",
                    help="Print bots we would use (e.g. from PRESUBMIT.py)"
                         " and exit.  Do not send patch.  Like --dry_run"
                         " but less verbose.")
  group.add_option("-r", "--revision",
                    help="Revision to use for the try job; default: the "
                         "revision will be determined by the try server; see "
                         "its waterfall for more info")
  group.add_option("-c", "--clobber", action="store_true",
                    help="Force a clobber before building; e.g. don't do an "
                         "incremental build")
  # TODO(maruel): help="Select a specific configuration, usually 'debug' or "
  #                    "'release'"
  group.add_option("--target", help=optparse.SUPPRESS_HELP)

  group.add_option("--project",
                   help="Override which project to use. Projects are defined "
                        "server-side to define what default bot set to use")

  group.add_option(
      "-t", "--testfilter", action="append", default=[],
      help=("Apply a testfilter to all the selected builders. Unless the "
            "builders configurations are similar, use multiple "
            "--bot <builder>:<test> arguments."))

  parser.add_option_group(group)

  group = optparse.OptionGroup(parser, "Patch to run")
  group.add_option("-f", "--file", default=[], dest="files",
                   metavar="FILE", action="append",
                   help="Use many times to list the files to include in the "
                        "try, relative to the repository root")
  group.add_option("--diff",
                   help="File containing the diff to try")
  group.add_option("--url",
                   help="Url where to grab a patch, e.g. "
                        "http://example.com/x.diff")
  group.add_option("-R", "--rietveld_url", default="codereview.appspot.com",
                   metavar="URL",
                   help="Has 2 usages, both refer to the rietveld instance: "
                        "Specify which code review patch to use as the try job "
                        "or rietveld instance to update the try job results "
                        "Default:%default")
  group.add_option("--root",
                   help="Root to use for the patch; base subdirectory for "
                        "patch created in a subdirectory")
  group.add_option("-p", "--patchlevel", type='int', metavar="LEVEL",
                   help="Used as -pN parameter to patch")
  group.add_option("-s", "--sub_rep", action="append", default=[],
                   help="Subcheckout to use in addition. This is mainly "
                        "useful for gclient-style checkouts. In git, checkout "
                        "the branch with changes first. Use @rev or "
                        "@branch to specify the "
                        "revision/branch to diff against. If no @branch is "
                        "given the diff will be against the upstream branch. "
                        "If @branch then the diff is branch..HEAD. "
                        "All edits must be checked in.")
  group.add_option("--no_search", action="store_true",
                   help=("Disable automatic search for gclient or repo "
                        "checkout root."))
  group.add_option("-E", "--exclude", action="append",
                   default=['ChangeLog'], metavar='REGEXP',
                   help="Regexp patterns to exclude files. Default: %default")
  group.add_option("--upstream_branch", action="store",
                   help="Specify the upstream branch to diff against in the "
                        "main checkout")
  parser.add_option_group(group)

  group = optparse.OptionGroup(parser, "Access the try server by HTTP")
  group.add_option("--use_http",
                   action="store_const",
                   const=_SendChangeHTTP,
                   dest="send_patch",
                   help="Use HTTP to talk to the try server [default]")
  group.add_option("-H", "--host",
                   help="Host address")
  group.add_option("-P", "--port", type="int",
                   help="HTTP port")
  group.add_option("--proxy",
                   help="HTTP proxy")
  parser.add_option_group(group)

  group = optparse.OptionGroup(parser, "Access the try server with SVN")
  group.add_option("--use_svn",
                   action="store_const",
                   const=_SendChangeSVN,
                   dest="send_patch",
                   help="Use SVN to talk to the try server")
  group.add_option("-S", "--svn_repo",
                   metavar="SVN_URL",
                   help="SVN url to use to write the changes in; --use_svn is "
                        "implied when using --svn_repo")
  parser.add_option_group(group)
  return parser

def TryChange(argv,
              change,
              swallow_exception,
              prog=None,
              extra_epilog=None):
  """
  Args:
    argv: Arguments and options.
    change: Change instance corresponding to the CL.
    swallow_exception: Whether we raise or swallow exceptions.
  """
  parser = gen_parser(prog)
  epilog = EPILOG % { 'prog': prog }
  if extra_epilog:
    epilog += extra_epilog
  parser.epilog = epilog
  # Remove epilog formatting
  parser.format_epilog = lambda x: parser.epilog

  options, args = parser.parse_args(argv)

  # If they've asked for help, give it to them
  if len(args) == 1 and args[0] == 'help':
    parser.print_help()
    return 0

  # If they've said something confusing, don't spawn a try job until you
  # understand what they want.
  if args:
    parser.error('Extra argument(s) "%s" not understood' % ' '.join(args))

  if options.dry_run:
    options.verbose += 1

  LOG_FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
  if not swallow_exception:
    if options.verbose == 0:
      logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT)
    elif options.verbose == 1:
      logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
    elif options.verbose > 1:
      logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)

  logging.debug(argv)

  if (options.patchlevel is not None and
      (options.patchlevel < 0 or options.patchlevel > 10)):
    parser.error(
        'Have you tried --port instead? You probably confused -p and -P.')

  # Strip off any @ in the user, otherwise svn gets confused.
  options.user = options.user.split('@', 1)[0]

  if options.rietveld_url:
    # Try to extract the review number if possible and fix the protocol.
    if not '://' in options.rietveld_url:
      options.rietveld_url = 'http://' + options.rietveld_url
    match = re.match(r'^(.*)/(\d+)/?$', options.rietveld_url)
    if match:
      if options.issue or options.patchset:
        parser.error('Cannot use both --issue and use a review number url')
      options.issue = int(match.group(2))
      options.rietveld_url = match.group(1)

  try:
    changed_files = None
    # Always include os.getcwd() in the checkout settings.
    checkouts = []
    path = os.getcwd()

    file_list = []
    if options.files:
      file_list = options.files
    elif change:
      file_list = [f.LocalPath() for f in change.AffectedFiles()]

    if options.upstream_branch:
      path += '@' + options.upstream_branch
      # Clear file list so that the correct list will be retrieved from the
      # upstream branch.
      file_list = []
    checkouts.append(GuessVCS(options, path, file_list))
    checkouts[0].AutomagicalSettings()
    for item in options.sub_rep:
      # Pass file_list=None because we don't know the sub repo's file list.
      checkout = GuessVCS(options,
                          os.path.join(checkouts[0].checkout_root, item),
                          None)
      if checkout.checkout_root in [c.checkout_root for c in checkouts]:
        parser.error('Specified the root %s two times.' %
                     checkout.checkout_root)
      checkouts.append(checkout)

    can_http = options.port and options.host
    can_svn = options.svn_repo
    # If there was no transport selected yet, now we must have enough data to
    # select one.
    if not options.send_patch and not (can_http or can_svn):
      parser.error('Please specify an access method.')

    # Convert options.diff into the content of the diff.
    if options.url:
      if options.files:
        parser.error('You cannot specify files and --url at the same time.')
      options.diff = urllib.urlopen(options.url).read()
    elif options.diff:
      if options.files:
        parser.error('You cannot specify files and --diff at the same time.')
      options.diff = gclient_utils.FileRead(options.diff, 'rb')
    elif options.issue and options.patchset is None:
      # Retrieve the patch from rietveld when the diff is not specified.
      # When patchset is specified, it's because it's done by gcl/git-try.
      api_url = '%s/api/%d' % (options.rietveld_url, options.issue)
      logging.debug(api_url)
      contents = json.loads(urllib.urlopen(api_url).read())
      options.patchset = contents['patchsets'][-1]
      diff_url = ('%s/download/issue%d_%d.diff' %
          (options.rietveld_url,  options.issue, options.patchset))
      diff = GetMungedDiff('', urllib.urlopen(diff_url).readlines())
      options.diff = ''.join(diff[0])
      changed_files = diff[1]
    else:
      # Use this as the base.
      root = checkouts[0].checkout_root
      diffs = []
      for checkout in checkouts:
        raw_diff = checkout.GenerateDiff()
        if not raw_diff:
          logging.error('Empty or non-existant diff, exiting.')
          return 1
        diff = raw_diff.splitlines(True)
        path_diff = gclient_utils.PathDifference(root, checkout.checkout_root)
        # Munge it.
        diffs.extend(GetMungedDiff(path_diff, diff)[0])
      options.diff = ''.join(diffs)

    if not options.name:
      if options.issue:
        options.name = 'Issue %s' % options.issue
      else:
        options.name = 'Unnamed'
        print('Note: use --name NAME to change the try job name.')

    if not options.email:
      parser.error('Using an anonymous checkout. Please use --email or set '
                   'the TRYBOT_RESULTS_EMAIL_ADDRESS environment variable.')
    print('Results will be emailed to: ' + options.email)

    if not options.bot:
      # Get try slaves from PRESUBMIT.py files if not specified.
      # Even if the diff comes from options.url, use the local checkout for bot
      # selection.
      try:
        import presubmit_support
        root_presubmit = checkouts[0].ReadRootFile('PRESUBMIT.py')
        if not change:
          if not changed_files:
            changed_files = checkouts[0].file_tuples
          change = presubmit_support.Change(options.name,
                                            '',
                                            checkouts[0].checkout_root,
                                            changed_files,
                                            options.issue,
                                            options.patchset,
                                            options.email)
        options.bot = presubmit_support.DoGetTrySlaves(
            change,
            checkouts[0].GetFileNames(),
            checkouts[0].checkout_root,
            root_presubmit,
            options.project,
            options.verbose,
            sys.stdout)
      except ImportError:
        pass
      if options.testfilter:
        bots = set()
        for bot in options.bot:
          assert ',' not in bot
          if bot.endswith(':compile'):
            # Skip over compile-only builders for now.
            continue
          bots.add(bot.split(':', 1)[0])
        options.bot = list(bots)

      # If no bot is specified, either the default pool will be selected or the
      # try server will refuse the job. Either case we don't need to interfere.

    if any('triggered' in b.split(':', 1)[0] for b in options.bot):
      print >> sys.stderr, (
          'ERROR You are trying to send a job to a triggered bot.  This type of'
          ' bot requires an\ninitial job from a parent (usually a builder).  '
          'Instead send your job to the parent.\nBot list: %s' % options.bot)
      return 1

    if options.print_bots:
      print 'Bots which would be used:'
      for bot in options.bot:
        print '  %s' % bot
      return 0

    # Send the patch.
    if options.send_patch:
      # If forced.
      options.send_patch(options)
      PrintSuccess(options)
      return 0
    try:
      if can_http:
        _SendChangeHTTP(options)
        PrintSuccess(options)
        return 0
    except NoTryServerAccess:
      if not can_svn:
        raise
    _SendChangeSVN(options)
    PrintSuccess(options)
    return 0
  except (InvalidScript, NoTryServerAccess), e:
    if swallow_exception:
      return 1
    print >> sys.stderr, e
    return 1
  except (gclient_utils.Error, subprocess2.CalledProcessError), e:
    print >> sys.stderr, e
    return 1
  return 0

if __name__ == "__main__":
  fix_encoding.fix_encoding()
  sys.exit(TryChange(None, None, False))


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////

package com.gemstone.gnu.trove;

/**
 * Iterator for long collections.
 *
 * @author Eric D. Friedman
 * @version $Id: TLongIterator.java,v 1.2 2003/03/19 04:41:29 ericdf Exp $
 */

public class TLongIterator extends TPrimitiveIterator {
    /** the collection on which the iterator operates */
    private final TLongHash _hash;

    /**
     * Creates a TLongIterator for the elements in the specified collection.
     */
    public TLongIterator(TLongHash hash) {
	super(hash);
	this._hash = hash;
    }

    /**
     * Advances the iterator to the next element in the underlying collection
     * and returns it.
     *
     * @return the next long in the collection
     * @exception java.util.NoSuchElementException if the iterator is already exhausted
     */
    public long next() {
	moveToNextIndex();
	return _hash._set[_index];
    }
}// TLongIterator

redpajama_set_name: RedPajamaGithub


text:
package hudson.plugins.ec2;

import hudson.model.Descriptor;
import hudson.model.AbstractDescribableImpl;
import hudson.Extension;
import hudson.Util;
import org.kohsuke.stapler.DataBoundConstructor;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;

import com.amazonaws.services.ec2.model.Filter;

public class EC2Filter extends AbstractDescribableImpl<EC2Filter> {
    @NonNull
    private final String name;

    /* FIXME: Ideally this would be List<String>, but Jenkins currently
     * doesn't offer a usable way to represent those in forms. Instead
     * the values are interpreted as a comma separated list.
     *
     * https://issues.jenkins.io/browse/JENKINS-27901
     */
    @NonNull
    private final String values;

    @DataBoundConstructor
    public EC2Filter(@NonNull String name, @NonNull String values) {
        this.name = Objects.requireNonNull(name);
        this.values = Objects.requireNonNull(values);
    }

    @Override
    public String toString() {
        return "EC2Filter{name=\"" + name + "\", values=\"" + values + "\"}";
    }

    @Override
    public boolean equals(Object o) {
        if (o == null)
            return false;
        if (this.getClass() != o.getClass())
            return false;

        EC2Filter other = (EC2Filter) o;
        return name.equals(other.name) && getValuesList().equals(other.getValuesList());
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, values);
    }

    @NonNull
    public String getName() {
        return name;
    }

    @NonNull
    public String getValues() {
        return values;
    }

    @NonNull
    private List<String> getValuesList() {
        return Stream.of(Util.tokenize(values))
            .collect(Collectors.toList());
    }

    /* Helper method to convert EC2Filter to Filter */
    @NonNull
    public Filter toFilter() {
        return new Filter(name, getValuesList());
    }

    /* Helper method to convert list of EC2Filter to list of Filter */
    @NonNull
    public static List<Filter> toFilterList(@CheckForNull List<EC2Filter> filters) {
        return Util.fixNull(filters).stream()
            .map(EC2Filter::toFilter)
            .collect(Collectors.toList());
    }

    @Extension
    public static class DescriptorImpl extends Descriptor<EC2Filter> {
        @Override
        public String getDisplayName() {
            return "";
        }
    }
}


text:
Code used in Unsupervised Terminological Ontology Learning based on Hierarchical Topic Modeling (Submitted to IEEE IRI 2017)

## Data
Publications from IEEE Manufacturing (Due to copyright issues, theses documents will not be released in here. Please access them from IEEE website.)

Wikipedia articles regarding semiconductor manufacturing (https://en.wikipedia.org/wiki/Category:Semiconductors)

## Setting
The code partially relies on MALLET(http://mallet.cs.umass.edu/), Stanford NLP packages(https://nlp.stanford.edu/software/),and OLLIE(https://github.com/knowitall/ollie). Please see our paper for citations.

A detail readme and the explanation of the libraries in the lib folder will be added after the review process.

This project is licensed under the terms of the Apache license.


text:
module.exports = function ( grunt ) {
	grunt.registerTask( 'unit', function () {
		var assert = require( 'assert' ),
			cssjanus = require( '../../src/cssjanus' ),
			testData = require( '../../test/data.json' ),
			failures = 0,
			tests = 0,
			name, test, settings, i, input, noop, output;

		for ( name in testData ) {
			tests++;
			test = testData[ name ];
			settings = test.settings || {};

			try {
				for ( i = 0; i < test.cases.length; i++ ) {
					input = test.cases[ i ][ 0 ];
					noop = test.cases[ i ][ 1 ] === undefined;
					output = noop ? input : test.cases[ i ][ 1 ];

					assert.equal(
						cssjanus.transform(
							input,
							settings.swapLtrRtlInUrl,
							settings.swapLeftRightInUrl
						),
						output
					);

					if ( !noop ) {
						// Round-trip
						assert.equal(
							cssjanus.transform(
								output,
								settings.swapLtrRtlInUrl,
								settings.swapLeftRightInUrl
							),
							input
						);

						// Keep test data clean
						assert(
							test.cases[ i ][ 1 ] !== input,
							'case #' + ( i + 1 ) + ' should not specify output if it matches the input'
						);
						output = test.cases[ i ][ 1 ];
					}
				}
				grunt.verbose.write( name + '...' );
				grunt.verbose.ok();
			} catch ( e ) {
				grunt.log.error( name );
				// grunt.log has a markup formatter that strips star ("*") and underscore ("_")
				// characters in favour of console escape sequences for bold and underline
				// formatting. Use console instead to avoid mangling strings like "/* @noflip */"
				// and "[attr*=value]" in AssertionError messages.
				console.log( e.stack );
				failures++;
			}
		}

		if ( failures === 1 ) {
			grunt.log.error( failures + ' test failed.' );
			return false;
		}
		if ( failures > 1 ) {
			grunt.log.error( failures + ' tests failed.' );
			return false;
		}
		grunt.log.ok( tests + ' tests passed.' );
	} );
};


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

<title>dan200.computercraft.api.peripheral (ComputerCraft 1.63)</title>
<meta name="date" content="2014-04-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

dan200.computercraft.api.peripheral

Interfaces

IComputerAccess

IPeripheral

IPeripheralProvider


text:
class AutocompleteController;
class CloudPrintSetupHandler;
class CustomHomePagesTableModel;
class TemplateURLService;

namespace options {

// Chrome browser options page UI handler.
class BrowserOptionsHandler
    : public OptionsPageUIHandler,
      public CloudPrintSetupHandlerDelegate,
      public ProfileSyncServiceObserver,
      public ui::SelectFileDialog::Listener,
      public ShellIntegration::DefaultWebClientObserver,
#if defined(OS_CHROMEOS)
      public chromeos::system::PointerDeviceObserver::Observer,
#endif
      public TemplateURLServiceObserver {
 public:
  BrowserOptionsHandler();
  virtual ~BrowserOptionsHandler();

  // OptionsPageUIHandler implementation.
  virtual void GetLocalizedValues(DictionaryValue* values) OVERRIDE;
  virtual void PageLoadStarted() OVERRIDE;
  virtual void InitializeHandler() OVERRIDE;
  virtual void InitializePage() OVERRIDE;
  virtual void RegisterMessages() OVERRIDE;

  // ProfileSyncServiceObserver implementation.
  virtual void OnStateChanged() OVERRIDE;

  // Will be called when the kSigninAllowed pref has changed.
  void OnSigninAllowedPrefChange();

  // Will be called when the kSearchSuggestEnabled pref has changed.
  void OnSearchSuggestPrefChange();

  // ShellIntegration::DefaultWebClientObserver implementation.
  virtual void SetDefaultWebClientUIState(
      ShellIntegration::DefaultWebClientUIState state) OVERRIDE;
  virtual bool IsInteractiveSetDefaultPermitted() OVERRIDE;

  // TemplateURLServiceObserver implementation.
  virtual void OnTemplateURLServiceChanged() OVERRIDE;

  // Create a Windows' profile specific desktop shortcut.
  static void CreateDesktopShortcutForProfile(
      Profile* profile, Profile::CreateStatus status);

 private:
  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  void OnCloudPrintPrefsChanged();

  // SelectFileDialog::Listener implementation
  virtual void FileSelected(const base::FilePath& path,
                            int index,
                            void* params) OVERRIDE;

  // CloudPrintSetupHandler::Delegate implementation.
  virtual void OnCloudPrintSetupClosed() OVERRIDE;

#if defined(OS_CHROMEOS)
  // PointerDeviceObserver::Observer implementation.
  virtual void TouchpadExists(bool exists) OVERRIDE;
  virtual void MouseExists(bool exists) OVERRIDE;
#endif

  // Makes this the default browser. Called from WebUI.
  void BecomeDefaultBrowser(const base::ListValue* args);

  // Sets the search engine at the given index to be default. Called from WebUI.
  void SetDefaultSearchEngine(const base::ListValue* args);

  // Enables/disables auto-launching of Chrome on computer startup.
  void ToggleAutoLaunch(const base::ListValue* args);

  // Checks (on the file thread) whether the user is in the auto-launch trial
  // and whether Chrome is set to auto-launch at login. Gets a reply on the UI
  // thread (see CheckAutoLaunchCallback). A weak pointer to this is passed in
  // as a parameter to avoid the need to lock between this function and the
  // destructor. |profile_path| is the full path to the current profile.
  static void CheckAutoLaunch(base::WeakPtr<BrowserOptionsHandler> weak_this,
                              const base::FilePath& profile_path);

  // Sets up (on the UI thread) the necessary bindings for toggling auto-launch
  // (if the user is part of the auto-launch and makes sure the HTML UI knows
  // whether Chrome will auto-launch at login.
  void CheckAutoLaunchCallback(bool is_in_auto_launch_group,
                               bool will_launch_at_login);

  // Returns the string ID for the given default browser state.
  int StatusStringIdForState(ShellIntegration::DefaultWebClientState state);

  // Gets the current default browser state, and asynchronously reports it to
  // the WebUI page.
  void UpdateDefaultBrowserState();

  // Updates the UI with the given state for the default browser.
  void SetDefaultBrowserUIString(int status_string_id);

  // Loads the possible default search engine list and reports it to the WebUI.
  void AddTemplateUrlServiceObserver();

  // Creates a list of dictionaries where each dictionary is of the form:
  //   profileInfo = {
  //     name: "Profile Name",
  //     iconURL: "chrome://path/to/icon/image",
  //     filePath: "/path/to/profile/data/on/disk",
  //     isCurrentProfile: false
  //   };
  scoped_ptr<ListValue> GetProfilesInfoList();

  // Sends an array of Profile objects to javascript.
  void SendProfilesInfo();

  // Asynchronously opens a new browser window to create a new profile.
  void CreateProfile(const base::ListValue* args);

  void ObserveThemeChanged();
  void ThemesReset(const base::ListValue* args);
#if defined(TOOLKIT_GTK)
  void ThemesSetGTK(const base::ListValue* args);
#endif

#if defined(OS_CHROMEOS)
  void UpdateAccountPicture();
#endif

  // Callback for the "selectDownloadLocation" message. This will prompt the
  // user for a destination folder using platform-specific APIs.
  void HandleSelectDownloadLocation(const ListValue* args);

  // Callback for the "autoOpenFileTypesResetToDefault" message. This will
  // remove all auto-open file-type settings.
  void HandleAutoOpenButton(const ListValue* args);

  // Callback for the "defaultFontSizeAction" message. This is called if the
  // user changes the default font size. |args| is an array that contains
  // one item, the font size as a numeric value.
  void HandleDefaultFontSize(const ListValue* args);

  // Callback for the "defaultZoomFactorAction" message. This is called if the
  // user changes the default zoom factor. |args| is an array that contains
  // one item, the zoom factor as a numeric value.
  void HandleDefaultZoomFactor(const ListValue* args);

  // Callback for the "Use SSL 3.0" checkbox. This is called if the user toggles
  // the "Use SSL 3.0" checkbox.
  void HandleUseSSL3Checkbox(const ListValue* args);

  // Callback for the "Use TLS 1.0" checkbox. This is called if the user toggles
  // the "Use TLS 1.0" checkbox.
  void HandleUseTLS1Checkbox(const ListValue* args);

  // Callback for the "restartBrowser" message. Restores all tabs on restart.
  void HandleRestartBrowser(const ListValue* args);

#if !defined(OS_CHROMEOS)
  // Callback for the "showNetworkProxySettings" message. This will invoke
  // an appropriate dialog for configuring proxy settings.
  void ShowNetworkProxySettings(const ListValue* args);
#endif

#if !defined(USE_NSS)
  // Callback for the "showManageSSLCertificates" message. This will invoke
  // an appropriate certificate management action based on the platform.
  void ShowManageSSLCertificates(const ListValue* args);
#endif

  // Callback for the Cloud Print manage button. This will open a new
  // tab pointed at the management URL.
  void ShowCloudPrintManagePage(const ListValue* args);

  // Register localized values used by Cloud Print
  void RegisterCloudPrintValues(DictionaryValue* values);

#if !defined(OS_CHROMEOS)
  // Callback for the Sign in to Cloud Print button. This will start
  // the authentication process.
  void ShowCloudPrintSetupDialog(const ListValue* args);

  // Callback for the Disable Cloud Print button. This will sign out
  // of cloud print.
  void HandleDisableCloudPrintConnector(const ListValue* args);

  // Pings the service to send us it's current notion of the enabled state.
  void RefreshCloudPrintStatusFromService();

  // Setup the enabled or disabled state of the cloud print connector
  // management UI.
  void SetupCloudPrintConnectorSection();

  // Remove cloud print connector section if cloud print connector management
  //  UI is disabled.
  void RemoveCloudPrintConnectorSection();
#endif

#if defined(OS_CHROMEOS)
  // Opens the wallpaper manager component extension.
  void HandleOpenWallpaperManager(const base::ListValue* args);

  // Called when the accessibility checkbox values are changed.
  // |args| will contain the checkbox checked state as a string
  // ("true" or "false").
  void SpokenFeedbackChangeCallback(const base::ListValue* args);
  void HighContrastChangeCallback(const base::ListValue* args);
  void VirtualKeyboardChangeCallback(const base::ListValue* args);

  // Called when the user confirmed factory reset. Chrome will
  // initiate asynchronous file operation and then log out.
  void PerformFactoryResetRestart(const base::ListValue* args);
#endif

  // Setup the visibility for the metrics reporting setting.
  void SetupMetricsReportingSettingVisibility();

  // Setup the visibility for the password generation setting.
  void SetupPasswordGenerationSettingVisibility();

  // Setup the font size selector control.
  void SetupFontSizeSelector();

  // Setup the page zoom selector control.
  void SetupPageZoomSelector();

  // Setup the visibility of the reset button.
  void SetupAutoOpenFileTypes();

  // Setup the proxy settings section UI.
  void SetupProxySettingsSection();

#if defined(OS_CHROMEOS)
  // Setup the accessibility features for ChromeOS.
  void SetupAccessibilityFeatures();
#endif

  // Returns a newly created dictionary with a number of properties that
  // correspond to the status of sync.
  scoped_ptr<DictionaryValue> GetSyncStateDictionary();

  scoped_refptr<ShellIntegration::DefaultBrowserWorker> default_browser_worker_;

  bool page_initialized_;

  StringPrefMember homepage_;
  BooleanPrefMember default_browser_policy_;

  TemplateURLService* template_url_service_;  // Weak.

  // Used to get WeakPtr to self for use on the UI thread.
  base::WeakPtrFactory<BrowserOptionsHandler> weak_ptr_factory_;

  scoped_refptr<ui::SelectFileDialog> select_folder_dialog_;

#if !defined(OS_CHROMEOS)
  StringPrefMember cloud_print_connector_email_;
  BooleanPrefMember cloud_print_connector_enabled_;
  bool cloud_print_connector_ui_enabled_;
  scoped_ptr<CloudPrintSetupHandler> cloud_print_setup_handler_;
#endif

  StringPrefMember auto_open_files_;
  IntegerPrefMember default_font_size_;
  DoublePrefMember default_zoom_level_;

  PrefChangeRegistrar profile_pref_registrar_;

  DISALLOW_COPY_AND_ASSIGN(BrowserOptionsHandler);
};

}  // namespace options

#endif  // CHROME_BROWSER_UI_WEBUI_OPTIONS_BROWSER_OPTIONS_HANDLER_H_


text:
package org.apache.wicket.util.lang;

/**
 * Utilities for working with primitives types and values.
 *
 * @author Jonathan Locke
 */
public final class Primitives
{
	/**
	 * Returns a basic integer hash code for a long value.
	 *
	 * @param value
	 *            The long value
	 * @return The hash code
	 */
	public static int hashCode(final long value)
	{
		return (int)value ^ (int)(value >> 32);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=6, user-scalable=1">
    <title>SwipeVideo Player</title>


text:
Project Setup
=============

On Linux:
=========
`yum install leveldb-devel`

On Windows:
===========

To build and run locally, you need to clone and build https://github.com/neo-project/leveldb first,
then copy `libleveldb.dll` to the working directory (i.e. /bin/Debug, /bin/Release)

Note: When building, the project file settings must be changed from static library (lib) to dynamic linked library (dll).


text:
package uk.ac.aber.mwg2.cs123.patience.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * ScorePanel is a JPanel located on the top area of the Game JFrame.
 * Its purpose is to display player's current score, the highest score
 * ever recorder in the past and an invalid move notification (whenever
 * user makes a move not permitted in the game).
 *
 * @since 1 April 2015
 * @author mwg2
 */
public class ScorePanel extends JPanel {

	private String currentScore;
	private String highScore;
	private Font font;
	private boolean invalidMove;

	private final String CURRENT_SCORE_LABEL = "SCORE:";
	private final String HIGH_SCORE_LABEL = "HIGH SCORE:";
	private final String SCORES_FILE = "scores.txt";
	private final String INVALID_MOVE_LABEL = "INVALID MOVE";

	private final int DEFAULT_WIDTH;
	private final int DEFAULT_HEIGHT = 30;

	/**
	 * Constructs the ScorePanel object which paints player's current score,
	 * highest score ever recorded in the past and occasionally a warning
	 * message when an invalid move is made.
	 */
	public ScorePanel() {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		DEFAULT_WIDTH = screenSize.width / 2;
		currentScore = "0";
		font = new Font("SansSerif", Font.BOLD, 18);
		invalidMove = false;
		highScore = loadHighScore();

		setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
		setBackground(new Color(10, 103, 103));
	}

	/**
	 * Adds 10 point to the current score and updates the view.
	 */
	public void addPoints() {
		int intScore = Integer.parseInt(currentScore);
		currentScore = (intScore + 10) + "";
		repaint();
	}

	/**
	 * By setting the 'invalidMove' boolean value to true, you can notify
	 * the user when he makes an invalid move in the game. Subsequently,
	 * approriate label will be print within the panel.
	 * By setting the value to false you can clear the notification.
	 *
	 * @param invalidMove true to notify about invalid move, false to clear panel
	 */
	public void setInvalidMove(boolean invalidMove) {
		this.invalidMove = invalidMove;
		repaint();
	}

	/**
	 * @return Player's current score
	 */
	public String getCurrentScore() {
		return currentScore;
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;

		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setFont(font);
		g2.setColor(new Color(151, 199, 199));
		g2.drawString(CURRENT_SCORE_LABEL, 5, 20);
		g2.drawString(currentScore, 100, 20);
		g2.drawString(HIGH_SCORE_LABEL, 200, 20);
		g2.drawString(highScore, 355, 20);

		if (invalidMove) {
			g2.setColor(new Color(255, 213, 87));
			g2.drawString(INVALID_MOVE_LABEL, 450, 20);
		}
	}

	/*
	 * Loads the high score from the text file which contains previously
	 * recorded scores and determines which one is the highest. Returns "0"
	 * String if there is a problem with loading from the txt file or there are
	 * no scores recorded.
	 */
	private String loadHighScore() {
		String result = "0";
		try (Scanner in = new Scanner(new File(SCORES_FILE))) {
			int num = Integer.parseInt(in.nextLine());
			List<Integer> results = new ArrayList<Integer>();

			// retrieve high scores
			for (int i = 0; i < num; i++) {
				String[] tokens = in.nextLine().split(":");
				results.add(Integer.parseInt(tokens[0]));
			}

			// determine the highest one
			result = Collections.max(results) + "";
		} catch (IOException e) {
			// in case there is a problem with loading high scores or there
			// isn't one, we leave the result as 0
			JOptionPane.showMessageDialog(getParent(),"There was a problem with"
					+ "retrieving high score. File 'scores.txt' may be corrupted");
		}
		return result;
	}
}


text:
package eu.scape_project.pit.tools;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 * @author  Andrew Jackson
 */
@XmlType( namespace=ToolSpec.NS )
@XmlAccessorType( XmlAccessType.FIELD )
public class Var {

	@XmlAttribute
	String name;

	@XmlAttribute
	String value;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the value
	 */
	public String getValue() {
		return value;
	}

	/**
	 * @param value the value to set
	 */
	public void setValue(String value) {
		this.value = value;
	}

}


text:
import React, { Component } from 'react';
import I18n from 'react-native-i18n'
import { connect } from 'react-redux';
import {
  CameraRoll,
  Platform,
  SectionList,
  Image,
  FlatList,
  Dimensions
} from 'react-native';
import { StyleProvider, Container, Content, Footer, FooterTab, Button, Icon, Badge, Header, Title, Text, View, Tabs, Spinner } from 'native-base';
import _ from 'lodash';
import PhotoAccess from '../Services/PhotoAccess'

var {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get('window');

const styles = {

}

class LoadingView extends Component {
    render() {
      return (
        <Container>

          <Content></Content>

        </Container>
      )
    }
}

export default LoadingView


text:
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Mafia.Package
  ( PackageName
  , mkPackageName
  , unPackageName

  , PackageId(..)
  , Version
  , packageId
  , renderPackageId
  , renderShortPackageId
  , renderVersion
  , packageIdTuple
  , parsePackageId
  , parseVersion
  , makeVersion
  , versionNumbers
  ) where

import           Data.Aeson (Value(..), ToJSON(..), FromJSON(..))
import           Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import qualified Data.Char as Char
import qualified Data.Text as T

import           Distribution.Version (Version, versionNumbers)
import qualified Distribution.Version as DistVersion

import           Mafia.P

import qualified Data.Attoparsec.Text as Parse

-- Similar to Cabal's Distribution.Package

newtype PackageName =
  PackageName {
      ciPackageName :: CI Text
    } deriving (Eq, Ord, Show)

mkPackageName :: Text -> PackageName
mkPackageName =
  PackageName . CI.mk

unPackageName :: PackageName -> Text
unPackageName =
  CI.original . ciPackageName

data PackageId =
  PackageId {
      pkgName :: !PackageName
    , pkgVersion :: !Version
    } deriving (Eq, Show)

instance Ord PackageId where
  compare (PackageId xn xv) (PackageId yn yv) =
    compare
      (ciPackageName xn, xv)
      (ciPackageName yn, yv)

packageId :: Text -> [Int] -> PackageId
packageId n v =
  PackageId (mkPackageName n) (makeVersion v)

renderPackageId :: PackageId -> Text
renderPackageId (PackageId name version) =
  unPackageName name <> "-" <> renderVersion version

renderShortPackageId :: PackageId -> Text
renderShortPackageId (PackageId name version) =
  let a = unPackageName name in
  T.filter (not . flip elem ("aeiou" :: [Char])) a <> "-" <> renderVersion version

renderVersion :: Version -> Text
renderVersion =
  T.pack . DistVersion.showVersion

packageIdTuple :: PackageId -> (PackageName, Version)
packageIdTuple (PackageId n v) =
  (n, v)

-- Extract name from `$name-$version`, but consider `unordered-containers-1.2.3`
parsePackageId :: Text -> Maybe PackageId
parsePackageId =
  let parser =
        PackageId
          <$> (PackageName . CI.mk . T.intercalate "-" <$> Parse.sepBy1 component (Parse.char '-'))
          <* Parse.char '-'
          <*> pVersion
          <* Parse.endOfInput
  in rightToMaybe . Parse.parseOnly parser
  where
    component = do
      cs <- Parse.takeWhile1 Char.isAlphaNum
      if T.all Char.isDigit cs then fail "" else return cs

parseVersion :: Text -> Maybe Version
parseVersion =
  rightToMaybe . Parse.parseOnly (pVersion <* Parse.endOfInput)

pVersion :: Parse.Parser Version
pVersion = makeVersion <$> Parse.sepBy Parse.decimal (Parse.char '.')

makeVersion :: [Int] -> Version
makeVersion xs =
  DistVersion.mkVersion xs

------------------------------------------------------------------------

instance ToJSON PackageId where
  toJSON =
    String . renderPackageId

instance FromJSON PackageId where
  parseJSON = \case
    String txt ->
      case parsePackageId txt of
        Nothing  -> fail ("invalid package-id: " <> T.unpack txt)
        Just pid -> pure pid
    _ ->
      mzero


text:
<?php
$myHeaderClass = "hero about";
$pageTitle = "Jackson Jacob | About";
$pageHeading = "A little more about me";
include("inc/header.php");
?>

BSc Computer Science

University of Portsmouth

Through the study of computer hardware, software, programming, computation and information processing, this course enables me to specialise in the more technical aspects of computer systems design.

Skillset

I am proficient with...

Java – Command Line and IDE such as NetBeans, Eclipse.

Large scale team projects using version control such as Git, GitHub and SVN.

XML, HTML, XHTML, CSS, JavaScript, AJAX, JSON, PHP, JQuery.

SQL, MySQL for database management.

Haskell function language.

Python

So what interests me?

Avid technology enthusiast.

Travelling; visiting countries to experience culture and lifestyle diversities

Learning new languages and applying those skills to projects

Mountain biking; riding different tracks across the UK.

Artificial Intelligence (A.I); how they work, how to make up and machine learning.

Flying drones/Learning to build R.C drones and FPV racing.

    <?php include("inc/banner.php"); ?>

    <?php include("inc/footer.php"); ?>

    <?php include("inc/scripts.php"); ?>


text:
using Orchard.ContentManagement.Drivers;
using Orchard.MediaLibrary.Models;

namespace Orchard.MediaLibrary.Drivers {
    public class VideoPartDriver : ContentPartDriver<VideoPart> {
        protected override DriverResult Display(VideoPart part, string displayType, dynamic shapeHelper) {
            return Combined(
                ContentShape("Parts_Video_Metadata", () => shapeHelper.Parts_Video_Metadata()),
                ContentShape("Parts_Video_SummaryAdmin", () => shapeHelper.Parts_Video_SummaryAdmin()),
                ContentShape("Parts_Video_Summary", () => shapeHelper.Parts_Video_Summary()),
                ContentShape("Parts_Video", () => shapeHelper.Parts_Video())
                );
        }

        protected override void Exporting(VideoPart part, ContentManagement.Handlers.ExportContentContext context) {
            context.Element(part.PartDefinition.Name).SetAttributeValue("Length", part.Length);
        }

        protected override void Importing(VideoPart part, ContentManagement.Handlers.ImportContentContext context) {
            // Don't do anything if the tag is not specified.
            if (context.Data.Element(part.PartDefinition.Name) == null) {
                return;
            }

            context.ImportAttribute(part.PartDefinition.Name, "Length", length =>
                part.Length = int.Parse(length)
            );
        }
    }
}


text:
<?php
/**
 * This file is part of Union.
 * (c) 2016 Union maintainers, All rights reserved.
 *
 * The applied license is stored at the root directory of this package.
 */

namespace Union\Exceptions;

use MongoDB\Driver\Exception\RuntimeException;

class IncompatibilityException extends RuntimeException
{

}


text:
#region License(Apache Version 2.0)

#endregion
#region ChangeLog
/******************************************
 * 2017-10-7 OutMan Create
 *
 * ***************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using WitsWay.Utilities.Attributes;

namespace WitsWay.Utilities.Extends
{
    /// <summary>
    /// 字符串扩展
    /// </summary>
    public static class EnumExtends
    {

        /// <summary>
        /// 获取"枚举值"描述信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举值描述</returns>
        public static string GetDescription(this Enum enumValue)
        {
            return EnumFieldAttribute.GetFieldText(enumValue);
        }

        /// <summary>
        /// 获取"枚举"描述信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举描述</returns>
        public static string GetEnumDescription(this Enum enumValue)
        {
            return EnumFieldAttribute.GetEnumText(enumValue.GetType());
        }

        /// <summary>
        /// 获取"枚举"字段信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举字段信息</returns>
        public static EnumFieldAttribute GetFieldInfo(this Enum enumValue)
        {
            return EnumFieldAttribute.GetFieldInfo(enumValue);
        }

        /// <summary>
        /// 取得枚举值
        /// </summary>
        /// <param name="enumValue">枚举</param>
        /// <returns>枚举值</returns>
        public static int GetValue(this Enum enumValue)
        {
            return enumValue.GetFieldInfo().EnumValue;
        }

        /// <summary>
        /// 获取"枚举"所有字段信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举所有字段信息</returns>
        public static List<EnumFieldAttribute> GetFieldInfos(this Enum enumValue)
        {
            return EnumFieldAttribute.GetFieldInfos(enumValue.GetType());
        }

        /// <summary>
        /// 转换为Int值
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>Int值</returns>
        public static int ToInt(this Enum enumValue)
        {
            return enumValue.CastTo<int>();
        }

        /// <summary>
        /// 转换为对应Int值的String
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>Int值对应的String</returns>
        public static string ToIntString(this Enum enumValue)
        {
            return enumValue.CastTo<int>().ToString();
        }

        /// <summary>
        /// 转换为对应Int值的String
        /// </summary>
        /// <param name="enum">枚举</param>
        /// <param name="enumValue">枚举值</param>
        /// <returns>Int值对应的String</returns>
        public static string GetFlagDescriptions<TEnum>(this Enum @enum, int enumValue) where TEnum : struct
        {
            return @enum.GetFieldInfos().FindAll(fi => (enumValue & fi.EnumValue) > 0).Select(one => one.DisplayText).Join(",");
        }

    }
}


text:
import ListStore from 'focus-core/store/list';
export default new ListStore({identifier: 'activityExecutionsList'});


text:
package edns

import (
	"errors"

	"github.com/miekg/dns"
)

// Version checks the EDNS version in the request. If error
// is nil everything is OK and we can invoke the plugin. If non-nil, the
// returned Msg is valid to be returned to the client (and should). For some
// reason this response should not contain a question RR in the question section.
func Version(req *dns.Msg) (*dns.Msg, error) {
	opt := req.IsEdns0()
	if opt == nil {
		return nil, nil
	}
	if opt.Version() == 0 {
		return nil, nil
	}
	m := new(dns.Msg)
	m.SetReply(req)
	// zero out question section, wtf.
	m.Question = nil

	o := new(dns.OPT)
	o.Hdr.Name = "."
	o.Hdr.Rrtype = dns.TypeOPT
	o.SetVersion(0)
	o.SetExtendedRcode(dns.RcodeBadVers)
	m.Extra = []dns.RR{o}

	return m, errors.New("EDNS0 BADVERS")
}

// Size returns a normalized size based on proto.
func Size(proto string, size int) int {
	if proto == "tcp" {
		return dns.MaxMsgSize
	}
	if size < dns.MinMsgSize {
		return dns.MinMsgSize
	}
	return size
}


text:
<?php

/**
 * Parses a user agent string into its important parts
 *
 * @param string|null $u_agent User agent string to parse or null. Uses $_SERVER['HTTP_USER_AGENT'] on NULL
 * @return string[] an array with browser, version and platform keys
 * @throws \InvalidArgumentException on not having a proper user agent to parse.
 *
 * @author Jesse G. Donat <donatj@gmail.com>
 *
 * @link https://donatstudios.com/PHP-Parser-HTTP_USER_AGENT
 * @link https://github.com/donatj/PhpUserAgent
 *
 * @license MIT
 */
function parse_user_agent( $u_agent = null ) {
	if( $u_agent === null && isset($_SERVER['HTTP_USER_AGENT']) ) {
		$u_agent = $_SERVER['HTTP_USER_AGENT'];
	}

	if( $u_agent === null ) {
		throw new \InvalidArgumentException('parse_user_agent requires a user agent');
	}

	$platform = null;
	$browser  = null;
	$version  = null;

	$empty = array( 'platform' => $platform, 'browser' => $browser, 'version' => $version );

	if( !$u_agent ) {
		return $empty;
	}

	if( preg_match('/\((.*?)\)/m', $u_agent, $parent_matches) ) {
		preg_match_all('/(?P<platform>BB\d+;|Android|CrOS|Tizen|iPhone|iPad|iPod|Linux|(Open|Net|Free)BSD|Macintosh|Windows(\ Phone)?|Silk|linux-gnu|BlackBerry|PlayBook|X11|(New\ )?Nintendo\ (WiiU?|3?DS|Switch)|Xbox(\ One)?)
				(?:\ [^;]*)?
				(?:;|$)/imx', $parent_matches[1], $result);

		$priority = array( 'Xbox One', 'Xbox', 'Windows Phone', 'Tizen', 'Android', 'FreeBSD', 'NetBSD', 'OpenBSD', 'CrOS', 'X11' );

		$result['platform'] = array_unique($result['platform']);
		if( count($result['platform']) > 1 ) {
			if( $keys = array_intersect($priority, $result['platform']) ) {
				$platform = reset($keys);
			} else {
				$platform = $result['platform'][0];
			}
		} elseif( isset($result['platform'][0]) ) {
			$platform = $result['platform'][0];
		}
	}

	if( $platform == 'linux-gnu' || $platform == 'X11' ) {
		$platform = 'Linux';
	} elseif( $platform == 'CrOS' ) {
		$platform = 'Chrome OS';
	}

	preg_match_all('%(?P<browser>Camino|Kindle(\ Fire)?|Firefox|Iceweasel|IceCat|Safari|MSIE|Trident|AppleWebKit|
				TizenBrowser|(?:Headless)?Chrome|YaBrowser|Vivaldi|IEMobile|Opera|OPR|Silk|Midori|Edge|Edg|CriOS|UCBrowser|Puffin|OculusBrowser|SamsungBrowser|
				Baiduspider|Googlebot|YandexBot|bingbot|Lynx|Version|Wget|curl|
				Valve\ Steam\ Tenfoot|
				NintendoBrowser|PLAYSTATION\ (\d|Vita)+)
				(?:\)?;?)
				(?:(?:[:/ ])(?P<version>[0-9A-Z.]+)|/(?:[A-Z]*))%ix',
		$u_agent, $result);

	// If nothing matched, return null (to avoid undefined index errors)
	if( !isset($result['browser'][0]) || !isset($result['version'][0]) ) {
		if( preg_match('%^(?!Mozilla)(?P<browser>[A-Z0-9\-]+)(/(?P<version>[0-9A-Z.]+))?%ix', $u_agent, $result) ) {
			return array( 'platform' => $platform ?: null, 'browser' => $result['browser'], 'version' => isset($result['version']) ? $result['version'] ?: null : null );
		}

		return $empty;
	}

	if( preg_match('/rv:(?P<version>[0-9A-Z.]+)/i', $u_agent, $rv_result) ) {
		$rv_result = $rv_result['version'];
	}

	$browser = $result['browser'][0];
	$version = $result['version'][0];

	$lowerBrowser = array_map('strtolower', $result['browser']);

	$find = function ( $search, &$key, &$value = null ) use ( $lowerBrowser ) {
		$search = (array)$search;

		foreach( $search as $val ) {
			$xkey = array_search(strtolower($val), $lowerBrowser);
			if( $xkey !== false ) {
				$value = $val;
				$key   = $xkey;

				return true;
			}
		}

		return false;
	};

	$key = 0;
	$val = '';
	if( $browser == 'Iceweasel' || strtolower($browser) == 'icecat' ) {
		$browser = 'Firefox';
	} elseif( $find('Playstation Vita', $key) ) {
		$platform = 'PlayStation Vita';
		$browser  = 'Browser';
	} elseif( $find(array( 'Kindle Fire', 'Silk' ), $key, $val) ) {
		$browser  = $val == 'Silk' ? 'Silk' : 'Kindle';
		$platform = 'Kindle Fire';
		if( !($version = $result['version'][$key]) || !is_numeric($version[0]) ) {
			$version = $result['version'][array_search('Version', $result['browser'])];
		}
	} elseif( $find('NintendoBrowser', $key) || $platform == 'Nintendo 3DS' ) {
		$browser = 'NintendoBrowser';
		$version = $result['version'][$key];
	} elseif( $find('Kindle', $key, $platform) ) {
		$browser = $result['browser'][$key];
		$version = $result['version'][$key];
	} elseif( $find('OPR', $key) ) {
		$browser = 'Opera Next';
		$version = $result['version'][$key];
	} elseif( $find('Opera', $key, $browser) ) {
		$find('Version', $key);
		$version = $result['version'][$key];
	} elseif( $find('Puffin', $key, $browser) ) {
		$version = $result['version'][$key];
		if( strlen($version) > 3 ) {
			$part = substr($version, -2);
			if( ctype_upper($part) ) {
				$version = substr($version, 0, -2);

				$flags = array( 'IP' => 'iPhone', 'IT' => 'iPad', 'AP' => 'Android', 'AT' => 'Android', 'WP' => 'Windows Phone', 'WT' => 'Windows' );
				if( isset($flags[$part]) ) {
					$platform = $flags[$part];
				}
			}
		}
	} elseif( $find('YaBrowser', $key, $browser) ) {
		$browser = 'Yandex';
		$version = $result['version'][$key];
	} elseif( $find(array( 'Edge', 'Edg' ), $key, $browser) ) {
		$browser = 'Edge';
		$version = $result['version'][$key];
	} elseif( $find(array( 'IEMobile', 'Midori', 'Vivaldi', 'OculusBrowser', 'SamsungBrowser', 'Valve Steam Tenfoot', 'Chrome', 'HeadlessChrome' ), $key, $browser) ) {
		$version = $result['version'][$key];
	} elseif( $rv_result && $find('Trident', $key) ) {
		$browser = 'MSIE';
		$version = $rv_result;
	} elseif( $find('UCBrowser', $key) ) {
		$browser = 'UC Browser';
		$version = $result['version'][$key];
	} elseif( $find('CriOS', $key) ) {
		$browser = 'Chrome';
		$version = $result['version'][$key];
	} elseif( $browser == 'AppleWebKit' ) {
		if( $platform == 'Android' ) {
			$browser = 'Android Browser';
		} elseif( strpos($platform, 'BB') === 0 ) {
			$browser  = 'BlackBerry Browser';
			$platform = 'BlackBerry';
		} elseif( $platform == 'BlackBerry' || $platform == 'PlayBook' ) {
			$browser = 'BlackBerry Browser';
		} else {
			$find('Safari', $key, $browser) || $find('TizenBrowser', $key, $browser);
		}

		$find('Version', $key);
		$version = $result['version'][$key];
	} elseif( $pKey = preg_grep('/playstation \d/i', $result['browser']) ) {
		$pKey = reset($pKey);

		$platform = 'PlayStation ' . preg_replace('/\D/', '', $pKey);
		$browser  = 'NetFront';
	}

	return array( 'platform' => $platform ?: null, 'browser' => $browser ?: null, 'version' => $version ?: null );
}


text:
import * as Data from "./standardRule/data"
import * as OrderModule from "./standardRule/order"
import * as ErrorModule from "./standardRule/error"
import * as Types from "./standardRule/types"
import * as UtilsModule from "./standardRule/utils"
import * as HelperModule from "./standardRule/helper"
import * as RuleModule from "./standardRule/rule"

export namespace standardRule {
  export declare type Location<Power> = Types.Location<Power>
  export const Location = Types.Location

  export declare type Unit<Power> = Types.Unit<Power>
  export const Unit = Types.Unit

  export declare type DiplomacyMap<Power> = Types.DiplomacyMap<Power>
  export const DiplomacyMap = Types.DiplomacyMap

  export declare type Board<Power> = Types.Board<Power>
  export const Board = Types.Board

  export declare type MilitaryBranch = Data.MilitaryBranch
  export const MilitaryBranch = Data.MilitaryBranch

  export declare type Phase = Data.Phase
  export const Phase = Data.Phase

  export declare type Turn = Data.Turn

  export declare type State = Data.State
  export const State = Data.State

  export declare type Dislodged<Power> = Data.Dislodged<Power>
  export const Dislodged = Data.Dislodged

  export declare type ProvinceStatus<Power> = Data.ProvinceStatus<Power>
  export const ProvinceStatus = Data.ProvinceStatus

  export declare type Result = Data.Result
  export const Result = Data.Result

  export namespace Order {
    export declare type OrderType = OrderModule.OrderType
    export const OrderType = OrderModule.OrderType
    export declare type Order<Power> = OrderModule.Order<Power>
    export const Order = OrderModule.Order
    export declare type Hold<Power> = OrderModule.Hold<Power>
    export const Hold = OrderModule.Hold
    export declare type Move<Power> = OrderModule.Move<Power>
    export const Move = OrderModule.Move
    export declare type Support<Power> = OrderModule.Support<Power>
    export const Support = OrderModule.Support
    export declare type Convoy<Power> = OrderModule.Convoy<Power>
    export const Convoy = OrderModule.Convoy
    export declare type Retreat<Power> = OrderModule.Retreat<Power>
    export const Retreat = OrderModule.Retreat
    export declare type Disband<Power> = OrderModule.Disband<Power>
    export const Disband = OrderModule.Disband
    export declare type Build<Power> = OrderModule.Build<Power>
    export const Build = OrderModule.Build
  }

  export namespace Error {
    export declare type ErrorType = ErrorModule.ErrorType
    export const ErrorType = ErrorModule.ErrorType
    export declare type Error = ErrorModule.Error
    export const Error = ErrorModule.Error
    export declare type PowerWithProblem<Power> = ErrorModule.PowerWithProblem<Power>
    export const PowerWithProblem = ErrorModule.PowerWithProblem
    export declare type UnmovableLocation<Power> = ErrorModule.UnmovableLocation<Power>
    export const UnmovableLocation = ErrorModule.UnmovableLocation
    export declare type UnsupportableLocation<Power> = ErrorModule.UnsupportableLocation<Power>
    export const UnsupportableLocation = ErrorModule.UnsupportableLocation
    export declare type UnconvoyableLocation<Power> = ErrorModule.UnconvoyableLocation<Power>
    export const UnconvoyableLocation = ErrorModule.UnconvoyableLocation
    export declare type UnbuildableLocation<Power> = ErrorModule.UnbuildableLocation<Power>
    export const UnbuildableLocation = ErrorModule.UnbuildableLocation
    export declare type UnitNotExisted<Power> = ErrorModule.UnitNotExisted<Power>
    export const UnitNotExisted = ErrorModule.UnitNotExisted
    export declare type CannotBeOrdered<Power> = ErrorModule.CannotBeOrdered<Power>
    export const CannotBeOrdered = ErrorModule.CannotBeOrdered
    export declare type InvalidPhase<Power> = ErrorModule.InvalidPhase<Power>
    export const InvalidPhase = ErrorModule.InvalidPhase
    export declare type SeveralOrders<Power> = ErrorModule.SeveralOrders<Power>
    export const SeveralOrders = ErrorModule.SeveralOrders
    export declare type OrderNotExisted<Power> = ErrorModule.OrderNotExisted<Power>
    export const OrderNotExisted = ErrorModule.OrderNotExisted
  }

  export declare type Utils = UtilsModule.Utils
  export const Utils = UtilsModule.Utils

  export declare type Helper<Power> = HelperModule.Helper<Power>
  export const Helper = HelperModule.Helper

  export declare type Rule<Power> = RuleModule.Rule<Power>
  export const Rule = RuleModule.Rule
}


text:
<!DOCTYPE html>

	<title>Dynamic Task with vuejs</title>
	<link rel="stylesheet" type="text/css" href="vendor/bootstrap/dist/css/bootstrap.min.css">

Task List

		<tasks></tasks>

	<template id="task-template">

			@{{note.body}} X

	</template>


text:
module SupportSegment
  module MethodDecorator

    def before(method, &block)
      decorate(method, :before, block)
    end

    def after(method, &block)
      decorate(method, :after, block)
    end

    def around(method, &block)
      decorate(method, :around, block)
    end

  private
    def decorate(method, callback, block)
      old_method = instance_method(method)

      define_method(method) do |*args|
        if [:before, :around].include? callback
          self.instance_eval &block
        end

        old_method.bind(self).call(*args)

        if [:after, :around].include? callback
          self.instance_eval &block
        end
      end
    end
  end
end


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Creates a profile that contains information about the virtual machine which will be provisioned automatically by autoscale feature.
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/createAutoScaleVmProfile.html]
        def create_auto_scale_vm_profile(serviceofferingid, templateid, zoneid, options={})
          options.merge!(
            'command' => 'createAutoScaleVmProfile',
            'serviceofferingid' => serviceofferingid,
            'templateid' => templateid,
            'zoneid' => zoneid
          )
          request(options)
        end
      end

    end
  end
end


text:
using System;

namespace Nethereum.JsonRpc.Client
{
    public class RpcClientUnknownException : Exception
    {
        public RpcClientUnknownException(string message) : base(message)
        {

        }

        public RpcClientUnknownException(string message, Exception innerException) : base(message, innerException)
        {

        }
    }
}


text:
/**
 * When searching a table with accented characters, it can be frustrating to have
 * an input such as _Zurich_ not match _Zürich_ in the table (`u !== ü`). This
 * type based search plug-in replaces the built-in string formatter in
 * DataTables with a function that will replace the accented characters
 * with their unaccented counterparts for fast and easy filtering.
 *
 * Note that this plug-in uses the Javascript I18n API that was introduced in
 * ES6. For older browser's this plug-in will have no effect.
 *
 *  @summary Replace accented characters with unaccented counterparts
 *  @name Accent neutralise
 *  @author Allan Jardine
 *
 *  @example
 *    $(document).ready(function() {
 *        $('#example').dataTable();
 *    } );
 */

(function(){

function removeAccents ( data ) {
    if ( data.normalize ) {
        // Use I18n API if avaiable to split characters and accents, then remove
        // the accents wholesale. Note that we use the original data as well as
        // the new to allow for searching of either form.
        return data +' '+ data
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '');
    }

    return data;
}

var searchType = jQuery.fn.DataTable.ext.type.search;

searchType.string = function ( data ) {
    return ! data ?
        '' :
        typeof data === 'string' ?
            removeAccents( data ) :
            data;
};

searchType.html = function ( data ) {
    return ! data ?
        '' :
        typeof data === 'string' ?
            removeAccents( data.replace( /<.*?>/g, '' ) ) :
            data;
};

}());


text:
using namespace seqan;

int main()
{
	typedef Index<CharString> TIndex;
	TIndex index("tobeornottobe");
	Iterator<TIndex,TopDown<>>::Type it(index);

	std::cout << representative(it)  std::endl;
	goDown(it)

	return 0;

}


text:
__ace_shadowed__.define('ace/snippets/ftl', ['require', 'exports', 'module' ], function(require, exports, module) {

exports.snippetText = "";
exports.scope = "ftl";

});


text:
@implementation UnitList

@end


text:
module TroleGroups::Storage
  class RefMany < BaseMany
    def initialize rolegroup_subject
      super
    end

    def display_roles
      display_roles_for rolegroup_list
    end

    def display_roles_for *names
      groups = find_rolegroups names.to_symbols_uniq
      groups.inject([]) {|res, group| res << group.roles }.flat_uniq
    end

    # display the roles as a list of symbols
    # @return [Array<Symbol>] roles list
    def display_rolegroups
      return [] if !ds_field_value?
      ds_field_value.flatten.map do |rolegroup|
        rolegroup.name.to_sym
      end
    end

    # is it set?
    def ds_field_value?
      ds_field_value && !ds_field_value.empty?
    end

    # saves the role for the user in the data store
    def set_rolegroups *rolegroups
      # finds and sets references to existing Role instances from symbols
      found = find_rolegroups(*rolegroups)
      set_ds_field found
    end

    # clears the role of the user in the data store
    def clear!
      set_ds_field []
    end

    # sets the role to default setting
    def set_default_role!
      clear!
    end
  end
end


text:
```ruby
ActiveRecord::Base.connection.tables
```

#### excute mysql query directly

```ruby
ActiveRecord::Base.connection.execute("showtables").values
```

#### ActiveRecord::Store

```ruby
class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ], coder: JSON
end

u = User.new(color: 'black', homepage: '37signals.com')
u.color                          # Accessor stored attribute
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor

# There is no difference between strings and symbols for accessing custom attributes
u.settings[:country]  # => 'Denmark'
u.settings['country'] # => 'Denmark'

# Add additional accessors to an existing store through store_accessor
class SuperUser < User
  store_accessor :settings, :privileges, :servants
end
```

```ruby
classUser < ActiveRecord::Base
  store :preferences
end
```

#### Establish_connection

```ruby
class LegacyProjectBase < ActiveRecord::Base
  establish_connection :legacy_database
  #establish_connection adapter: 'sqlite3', database: ':memory:'
  self.abstract_class = true
end
```

#### Enhanced Eager and Lazy Loading

```ruby
Client.eager_load( users: [:avatar, { timesheets: :billable_weeks }])
Client.preload( users: [:avatar, { timesheets: :billable_weeks }])
```

```ruby
Client.includes(users: [:avatar, { timesheets: :billable_weeks }] )
# clients has_many :users
# User has_many :avatar
# User has_many :timesheets
# Timesheet has_many billable_weeks
```
So, same level will be `Array`, lower one level will be `Hash`

```ruby
clients = Client.includes(users: [:avatar])
```

#### Eager loading eliminate 'N+1'

```ruby
users = User.where(login: "mack").includes(:billable_weeks)
users.first.billable_weeks.each{ |week| puts week}
```

#### Where

```ruby
Message.where("subject LIKE: foo OR body LIKE :foo", foo:'%woah%')
```
where and like with prarameter

#### StaleObjectError

```ruby
def update
  timesheet = Timesheet.find(params[:id]) timesheet.update(params[:timesheet])
  # redirect somewhere
rescue ActiveRecord::StaleObjectError
  flash[:error] = "Timesheet was modified while you were editing it."
  redirect_to [:edit, timesheet]
end
```

#### Readonly Attributes

```ruby
class Customer < ActiveRecord::Base
  attr_readonly :social_security_number
end
```

#### updating by condition

```ruby
Project.update_all({manager:'RonCampbell'}, technology: 'Rails')
Project.update_all("cost=cost*3", "lower(technology) LIKE '%microsoft%'")
```

#### instance attributes

```ruby
>>  first_client.attributes
=> {"name" => "PaperJamPrinters", "code" => "PJP","id" => 1}
```

#### new record instance

```ruby
c = Client.new
c.new_record?
c.persisted?
```

#### default attribute value

some trick to set default value by read and write

```ruby
def preferences
  read_attribute(:preferences) || write_attribute(:preferences, {})
end
```

```ruby
class Specification < ActiveRecord::Base
  def tolerance
    self[:tolerance] || 'n/a'
  end
end

class SillyFortuneCookie < ActiveRecord::Base
  def message=(txt)
    self[:message] = txt + ' in bed'
  end
end
```

#### Set name manually

```ruby
class Client < ActiveRecord::Base
  self.table_name = "CLIENT"
  self.primary_key = "CLIENT_ID"
end
```

#### Serialized Attributes

```ruby
class User < ActiveRecord::Base
  serialize :preferences, Hash
end
```

### migration

```ruby
add_column :users, :preferences, :text, default:"---{}"
```

```ruby
#fall back default serialized attributes
def preferences
  read_attribute(:preferences) || write_attribute(:preferences, {})
end
```

```ruby
class User < ActiveRecord::Base
  store :preferences
end
```

Enter text in [Markdown](http://daringfireball.net/projects/markdown/). Use the toolbar above, or click the **?** button for formatting help.


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>gifsocket chat</title>
</head>
<body>

<img src="socket.gif">

<form action="/message">
    <input type="text" name="message" autocomplete="off">
    <input type="submit" value="Submit">
</form>

<script>
document.querySelector('form').addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();

    var form = event.target;
    var input = form.querySelector('[name=message]');
    var message = input.value;

    var xhr = new XMLHttpRequest();
    xhr.open(form.method, form.action+'?message='+escape(message));
    xhr.send();

    input.value = '';
});
</script>

</body>
</html>


text:
package de.drippinger.job;

import de.drippinger.crawler.impl.MonsterCrawler;
import de.drippinger.dto.Company;
import de.drippinger.repository.CompanyRepository;
import de.drippinger.repository.TagRepository;
import de.drippinger.util.TfIdfCalculator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

@Slf4j
@Named
public class CrawlerJob {

	@Inject
	private ApplicationContext applicationContext;

	@Inject
	private transient TfIdfCalculator tfIdfCalculator;

	@Inject
	private transient TagRepository tagRepository;

	@Inject
	private transient CompanyRepository companyRepository;

	@Scheduled(cron = "0 0 4 ? * MON-FRI")
	public void execute() {

		// It's a prototype
		MonsterCrawler monsterCrawler = applicationContext.getBean(MonsterCrawler.class);

		log.info("Started Crawling Job");

		List<Company> companies = companyRepository.findAll();

		monsterCrawler.crawlJobs(companies, "");

		log.info("Truncating former Tags");

		tagRepository.truncateTags();

		log.info("Calculating TF/IDF for companies");

		tfIdfCalculator.calculateTfIdfForCompany(companies);
	}
}


text:
package view;

import controllers.Main_Controller;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Screen;
import javafx.stage.Stage;

/**
 * Created by marcin on 24/05/2016.
 *
 * Main Application Class
 * Calls other classes to compose the main window
 */
public class MainWindow extends Application{
    @Override
    public void start(Stage stage) throws Exception {
        BorderPane rootNode = new BorderPane();
        stage.setTitle("JCommunicator");
        rootNode.setTop(new MainWindow_TopLogo().getTopLogo(rootNode));
        rootNode.setCenter(new MainWindow_CenterPane_Contacts().getCenterPane());
        rootNode.setBottom(new MainWindow_BottomPane().getBottomPane());
        Scene myScene = new Scene(rootNode, 296, 600);
        stage.setScene(myScene);

        //gets a screen boundaries
        Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
        //set Stage boundaries to top right part of the screen
        stage.setX(primaryScreenBounds.getMinX() + primaryScreenBounds.getWidth()-320);
        stage.setY(primaryScreenBounds.getMinY() + 45);

        stage.show();

    }
    public void stop(){
        Main_Controller.getInstance().closeThread();
    }

    //Application starter
    public static void main(String[] args){
        launch(args);
    }

}


text:
layout: post
date: 2018-03-15
title: "The Dessy Group Dessy - Lela Rose Style LR190 Sleeveless Asymmetrical Aline/Princess High Low"
category: The Dessy Group
tags: [The Dessy Group,Aline/Princess ,High Low,Sweetheart,Asymmetrical,Sleeveless]
---
### The Dessy Group Dessy - Lela Rose Style LR190
Just **$269.99**
###   Sleeveless Asymmetrical Aline/Princess  High Low

BRANDS	The Dessy Group

Silhouette	Aline/Princess

Trend	High Low

Neckline	Sweetheart

Hemline/Train	Asymmetrical

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/the-dessy-group/13080-the-dessy-group-lela-rose-style-lr190.html](https://www.readybrides.com/en/the-dessy-group/13080-the-dessy-group-lela-rose-style-lr190.html)


text:
<!DOCTYPE html>

		<title>Prometheus</title>
		<link rel="stylesheet" type="text/css" href="style/reset.css">
		<link rel="stylesheet" type="text/css" href="style/main.css">

		<link href='https://fonts.googleapis.com/css?family=Graduate|Gafata' rel='stylesheet' type='text/css'>

Payment

This is where you pay us for things.

		<button>Contact Us</button>


text:
package myArrayList;

/**
 * Criteria 1: Yes
 * Criteria 2: Yes
 * Criteria 3: Yes
 * Criteria 4: Yes
 * Criteria 5: Yes
 * Criteria 6: Yes
 * Criteria 7: Yes
 * Criteria 8: Yes
 * Criteria 9: Yes
 * Criteria 10: Yes
 */
public class MyArrayList<E>
{
	private Object[] a;
	private int size;

	public MyArrayList()
	{
	    size = 0;
	    a = new Object[10];
	}

	public MyArrayList(int initialCapacity)
	{
		if (initialCapacity < 0)
			throw new IllegalArgumentException();
		else{
			size = 0;
			a = new Object[initialCapacity];
		}
	}

	public int size()
	{
		return size;
	}

    @SuppressWarnings("unchecked")
	public E get(int index)
	{
		if (index < 0 || index >= size())
			throw new IndexOutOfBoundsException();

		return (E) a[index];
	}

	public E set(int index, E element)
	{
		if (index < 0 || index >= size())
			throw new IndexOutOfBoundsException();
		@SuppressWarnings("unchecked")
		E returnValue = (E)a[index];
		a[index] = element;
		return returnValue;
	}

	public boolean contains(Object elem)
	{
		if(elem == null)
			for(int i = 0; i < size; i++)
				if(a[i] == null)
					return true;
		for(int i = 0; i < size; i++)
			if(a[i].equals(elem))
				return true;
		return false;
	}

	public void trimToSize()
	{
		Object[] temp = new Object[size];
		System.arraycopy(a, 0, temp, 0, size);
		a = new Object[size];
		System.arraycopy(temp, 0, a, 0, size);
	}

	public void add(E elem)
	{
		add(size, elem);
	}

	public void add(int index, E element)
	{
		if (index < 0 || index > size())
			throw new IndexOutOfBoundsException();
		Object[] temp = new Object[a.length + 1];
		System.arraycopy(a, 0, temp, 0, index);
		temp[index] = element;
		System.arraycopy(a, index, temp, index + 1, a.length - index);
		if(temp.length > a.length)
			a = new Object[a.length + 1];	//(2*a.length + 1)  gave OutOfMemoryException so I changed it to a.length + 1;
		System.arraycopy(temp, 0, a, 0, temp.length);
		size++;
	}

	@SuppressWarnings("unchecked")
	public E remove(int index)
	{
		if (index < 0 || index >= size())
			throw new IndexOutOfBoundsException();
		E removed = (E) a[index];

		Object[] temp = new Object[a.length - 1];
		System.arraycopy(a, 0, temp, 0, index);
		System.arraycopy(a, index + 1, temp, index, size - index - 1);
		System.arraycopy(temp, 0, a, 0, temp.length);

		size--;
		return removed;
	}

	public boolean remove(Object elem)
	{
		for(int i = 0; i < size; i++)
			if(elem == null){
				if(a[i] == null){
					remove(i);
					return true;
				}
			}
			else
				if(a[i].equals(elem)){
					remove(i);
					return true;
				}
		return false;
	}
}


text:
package edu.columbia.cs.psl.phosphor.struct.multid;

import java.io.IOException;
import java.io.Serializable;

import edu.columbia.cs.psl.phosphor.TaintUtils;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Type;

public final class MultiDTaintedCharArrayWithObjTag extends MultiDTaintedArrayWithObjTag implements Serializable {

	private static final long serialVersionUID = -6808286317985074403L;
	public char[] val;

	public MultiDTaintedCharArrayWithObjTag() {
		super(null, Type.CHAR);
	}

	public MultiDTaintedCharArrayWithObjTag(Object[] taint, char[] val) {
		super(taint, Type.CHAR);
		this.val = val;
	}

	@Override
	public Object getVal() {
		return val;
	}

	@Override
	public Object clone() {
		return new MultiDTaintedCharArrayWithObjTag(taint.clone(), val.clone());
	}

	private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
		if (val == null) {
			stream.writeObject(null);
			return;
		}
		if (TaintUtils.TAINT_THROUGH_SERIALIZATION)
			System.out.println("Tainting into serialization");
		stream.writeInt(val.length);
		for (int i = 0; i < val.length; i++) {
			if (TaintUtils.TAINT_THROUGH_SERIALIZATION)
				stream.writeObject(taint[i]);
			stream.writeChar(val[i]);
		}
	}

	private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
		int len = stream.readInt();
		val = new char[len];
		taint = TaintUtils.newTaintArray(len);
		for (int i = 0; i < len; i++) {
			if (TaintUtils.TAINT_THROUGH_SERIALIZATION)
				taint[i] = stream.readObject();
			val[i] = stream.readChar();
		}
	}
}