text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import fnmatch
import functools
import itertools
import os
import shutil
import sys
from abc import abstractmethod
from contextlib import contextmanager

from six.moves import range
from twitter.common.collections import OrderedSet

from pants.backend.jvm import argfile
from pants.backend.jvm.subsystems.junit import JUnit
from pants.backend.jvm.subsystems.jvm_platform import JvmPlatform
from pants.backend.jvm.targets.junit_tests import JUnitTests
from pants.backend.jvm.targets.jvm_target import JvmTarget
from pants.backend.jvm.tasks.classpath_util import ClasspathUtil
from pants.backend.jvm.tasks.coverage.manager import CodeCoverage
from pants.backend.jvm.tasks.jvm_task import JvmTask
from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin
from pants.backend.jvm.tasks.reports.junit_html_report import JUnitHtmlReport, NoJunitHtmlReport
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TargetDefinitionException, TaskError
from pants.base.workunit import WorkUnitLabel
from pants.build_graph.files import Files
from pants.build_graph.target import Target
from pants.build_graph.target_scopes import Scopes
from pants.java.distribution.distribution import DistributionLocator
from pants.java.executor import SubprocessExecutor
from pants.java.junit.junit_xml_parser import RegistryOfTests, Test, parse_failed_targets
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.task.testrunner_task_mixin import PartitionedTestRunnerTaskMixin, TestResult
from pants.util import desktop
from pants.util.argutil import ensure_arg, remove_arg
from pants.util.contextutil import environment_as, temporary_dir
from pants.util.dirutil import safe_delete, safe_mkdir, safe_mkdir_for, safe_rmtree, safe_walk
from pants.util.memo import memoized_method
from pants.util.meta import AbstractClass
from pants.util.strutil import pluralize

class _TestSpecification(AbstractClass):
  """Models the string format used to specify which tests to run."""

  @classmethod
  def parse(cls, buildroot, test_spec):
    """Parses a test specification string into an object that can yield corresponding tests.

    Tests can be specified in one of four forms:

    * [classname]
    * [filename]
    * [classname]#[methodname]
    * [filename]#[methodname]

    The first two forms target one or more individual tests contained within a class or file whereas
    the final two forms specify an individual test method to execute.

    :param string buildroot: The path of the current build root directory.
    :param string test_spec: A test specification.
    :returns: A test specification object.
    :rtype: :class:`_TestSpecification`
    """
    components = test_spec.split('#', 2)
    classname_or_sourcefile = components[0]
    methodname = components[1] if len(components) == 2 else None

    if os.path.exists(classname_or_sourcefile):
      sourcefile = os.path.relpath(classname_or_sourcefile, buildroot)
      return _SourcefileSpec(sourcefile=sourcefile, methodname=methodname)
    else:
      return _ClassnameSpec(classname=classname_or_sourcefile, methodname=methodname)

  @abstractmethod
  def iter_possible_tests(self, context):
    """Return an iterator over the possible tests this test specification indicates.

    NB: At least one test yielded by the returned iterator will correspond to an available test,
    but other yielded tests may not exist.

    :param context: The pants execution context.
    :type context: :class:`pants.goal.context.Context`
    :returns: An iterator over possible tests.
    :rtype: iter of :class:`pants.java.junit.junit_xml_parser.Test`
    """

class _SourcefileSpec(_TestSpecification):
  """Models a test specification in [sourcefile]#[methodname] format."""

  def __init__(self, sourcefile, methodname):
    self._sourcefile = sourcefile
    self._methodname = methodname

  def iter_possible_tests(self, context):
    for classname in self._classnames_from_source_file(context):
      # Tack the methodname onto all classes in the source file, as we
      # can't know which method the user intended.
      yield Test(classname=classname, methodname=self._methodname)

  def _classnames_from_source_file(self, context):
    source_products = context.products.get_data('classes_by_source').get(self._sourcefile)
    if not source_products:
      # It's valid - if questionable - to have a source file with no classes when, for
      # example, the source file has all its code commented out.
      context.log.warn('Source file {0} generated no classes'.format(self._sourcefile))
    else:
      for _, classes in source_products.rel_paths():
        for cls in classes:
          yield ClasspathUtil.classname_for_rel_classfile(cls)

class _ClassnameSpec(_TestSpecification):
  """Models a test specification in [classname]#[methodnme] format."""

  def __init__(self, classname, methodname):
    self._classname = classname
    self._methodname = methodname

  def iter_possible_tests(self, context):
    yield Test(classname=self._classname, methodname=self._methodname)

class JUnitRun(PartitionedTestRunnerTaskMixin, JvmToolTaskMixin, JvmTask):
  """
  :API: public
  """

  @classmethod
  def implementation_version(cls):
    return super(JUnitRun, cls).implementation_version() + [('JUnitRun', 3)]

  _BATCH_ALL = sys.maxint

  @classmethod
  def register_options(cls, register):
    super(JUnitRun, cls).register_options(register)

    register('--batch-size', advanced=True, type=int, default=cls._BATCH_ALL, fingerprint=True,
             help='Run at most this many tests in a single test process.')
    register('--test', type=list, fingerprint=True,
             help='Force running of just these tests.  Tests can be specified using any of: '
                  '[classname], [classname]#[methodname], [filename] or [filename]#[methodname]')
    register('--per-test-timer', type=bool, help='Show progress and timer for each test.')
    register('--default-concurrency', advanced=True, fingerprint=True,
             choices=JUnitTests.VALID_CONCURRENCY_OPTS, default=JUnitTests.CONCURRENCY_SERIAL,
             help='Set the default concurrency mode for running tests not annotated with'
                  ' @TestParallel or @TestSerial.')
    register('--parallel-threads', advanced=True, type=int, default=0, fingerprint=True,
             help='Number of threads to run tests in parallel. 0 for autoset.')
    register('--test-shard', advanced=True, fingerprint=True,
             help='Subset of tests to run, in the form M/N, 0 <= M < N. '
                  'For example, 1/3 means run tests number 2, 5, 8, 11, ...')
    register('--output-mode', choices=['ALL', 'FAILURE_ONLY', 'NONE'], default='NONE',
             help='Specify what part of output should be passed to stdout. '
                  'In case of FAILURE_ONLY and parallel tests execution '
                  'output can be partial or even wrong. '
                  'All tests output also redirected to files in .pants.d/test/junit.')
    register('--cwd', advanced=True, fingerprint=True,
             help='Set the working directory. If no argument is passed, use the build root. '
                  'If cwd is set on a target, it will supersede this option. It is an error to '
                  'use this option in combination with `--chroot`')
    register('--strict-jvm-version', type=bool, advanced=True, fingerprint=True,
             help='If true, will strictly require running junits with the same version of java as '
                  'the platform -target level. Otherwise, the platform -target level will be '
                  'treated as the minimum jvm to run.')
    register('--failure-summary', type=bool, default=True,
             help='If true, includes a summary of which test-cases failed at the end of a failed '
                  'junit run.')
    register('--allow-empty-sources', type=bool, advanced=True, fingerprint=True,
             help='Allows a junit_tests() target to be defined with no sources.  Otherwise,'
                  'such a target will raise an error during the test run.')
    register('--use-experimental-runner', type=bool, advanced=True, fingerprint=True,
             help='Use experimental junit-runner logic for more options for parallelism.')
    register('--html-report', type=bool, fingerprint=True,
             help='If true, generate an html summary report of tests that were run.')
    register('--open', type=bool,
             help='Attempt to open the html summary report in a browser (implies --html-report)')
    register('--legacy-report-layout', type=bool, default=False, advanced=True,
             help='Used to link JUnit and coverage reports to the legacy location; now does '
                  'nothing.',
             removal_version='1.8.0.dev0',
             removal_hint='This option is no longer used and can be safely removed.')

    # TODO(jtrobec): Remove direct register when coverage steps are moved to their own subsystem.
    CodeCoverage.register_junit_options(register, cls.register_jvm_tool)

  @classmethod
  def subsystem_dependencies(cls):
    return super(JUnitRun, cls).subsystem_dependencies() + (CodeCoverage, DistributionLocator, JUnit)

  @classmethod
  def request_classes_by_source(cls, test_specs):
    """Returns true if the given test specs require the `classes_by_source` product to satisfy."""
    buildroot = get_buildroot()
    for test_spec in test_specs:
      if isinstance(_TestSpecification.parse(buildroot, test_spec), _SourcefileSpec):
        return True
    return False

  @classmethod
  def prepare(cls, options, round_manager):
    super(JUnitRun, cls).prepare(options, round_manager)

    # Compilation and resource preparation must have completed.
    round_manager.require_data('runtime_classpath')

    # If the given test specs require the classes_by_source product, request it.
    if cls.request_classes_by_source(options.test or ()):
      round_manager.require_data('classes_by_source')

  class OptionError(TaskError):
    """Indicates an invalid combination of options for this task."""

  def __init__(self, *args, **kwargs):
    super(JUnitRun, self).__init__(*args, **kwargs)

    options = self.get_options()
    self._tests_to_run = options.test
    self._batch_size = options.batch_size

    if options.cwd and self.run_tests_in_chroot:
      raise self.OptionError('Cannot set both `cwd` ({}) and ask for a `chroot` at the same time.'
                             .format(options.cwd))

    if self.run_tests_in_chroot:
      self._working_dir = None
    else:
      self._working_dir = options.cwd or get_buildroot()

    self._strict_jvm_version = options.strict_jvm_version
    self._failure_summary = options.failure_summary
    self._open = options.open
    self._html_report = self._open or options.html_report

  @memoized_method
  def _args(self, fail_fast, output_dir):
    args = self.args[:]

    options = self.get_options()
    if options.output_mode == 'ALL':
      args.append('-output-mode=ALL')
    elif options.output_mode == 'FAILURE_ONLY':
      args.append('-output-mode=FAILURE_ONLY')
    else:
      args.append('-output-mode=NONE')

    if fail_fast:
      args.append('-fail-fast')
    args.append('-outdir')
    args.append(output_dir)
    if options.per_test_timer:
      args.append('-per-test-timer')

    if options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES_AND_METHODS:
      if not options.use_experimental_runner:
        self.context.log.warn('--default-concurrency=PARALLEL_CLASSES_AND_METHODS is '
                              'experimental, use --use-experimental-runner.')
      args.append('-default-concurrency')
      args.append('PARALLEL_CLASSES_AND_METHODS')
    elif options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_METHODS:
      if not options.use_experimental_runner:
        self.context.log.warn('--default-concurrency=PARALLEL_METHODS is experimental, use '
                              '--use-experimental-runner.')
      if options.test_shard:
        # NB(zundel): The experimental junit runner doesn't support test sharding natively.  The
        # legacy junit runner allows both methods and classes to run in parallel with this option.
        self.context.log.warn('--default-concurrency=PARALLEL_METHODS with test sharding will '
                              'run classes in parallel too.')
      args.append('-default-concurrency')
      args.append('PARALLEL_METHODS')
    elif options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES:
      args.append('-default-concurrency')
      args.append('PARALLEL_CLASSES')
    elif options.default_concurrency == JUnitTests.CONCURRENCY_SERIAL:
      args.append('-default-concurrency')
      args.append('SERIAL')

    args.append('-parallel-threads')
    args.append(str(options.parallel_threads))

    if options.test_shard:
      args.append('-test-shard')
      args.append(options.test_shard)

    if options.use_experimental_runner:
      self.context.log.info('Using experimental junit-runner logic.')
      args.append('-use-experimental-runner')

    return args

  def classpath(self, targets, classpath_product=None, **kwargs):
    return super(JUnitRun, self).classpath(targets,
                                           classpath_product=classpath_product,
                                           include_scopes=Scopes.JVM_TEST_SCOPES,
                                           **kwargs)

  def preferred_jvm_distribution_for_targets(self, targets):
    return JvmPlatform.preferred_jvm_distribution([target.platform for target in targets
                                                  if isinstance(target, JvmTarget)],
                                                  self._strict_jvm_version)

  def _spawn(self, distribution, executor=None, *args, **kwargs):
    """Returns a processhandler to a process executing java.

    :param Executor executor: the java subprocess executor to use. If not specified, construct
      using the distribution.
    :param Distribution distribution: The JDK or JRE installed.
    :rtype: ProcessHandler
    """

    actual_executor = executor or SubprocessExecutor(distribution)
    return distribution.execute_java_async(*args,
                                           executor=actual_executor,
                                           **kwargs)

  def execute_java_for_coverage(self, targets, *args, **kwargs):
    """Execute java for targets directly and don't use the test mixin.

    This execution won't be wrapped with timeouts and other test mixin code common
    across test targets. Used for coverage instrumentation.
    """

    distribution = self.preferred_jvm_distribution_for_targets(targets)
    actual_executor = SubprocessExecutor(distribution)
    return distribution.execute_java(*args, executor=actual_executor, **kwargs)

  def _collect_test_targets(self, targets):
    """Return a test registry mapping the tests found in the given targets.

    If `self._tests_to_run` is set, return a registry of explicitly specified tests instead.

    :returns: A registry of tests to run.
    :rtype: :class:`pants.java.junit.junit_xml_parser.Test.RegistryOfTests`
    """

    test_registry = RegistryOfTests(tuple(self._calculate_tests_from_targets(targets)))

    if targets and self._tests_to_run:
      # If there are some junit_test targets in the graph, find ones that match the requested
      # test(s).
      possible_test_to_target = {}
      unknown_tests = []
      for possible_test in self._get_possible_tests_to_run():
        target = test_registry.get_owning_target(possible_test)
        if target is None:
          unknown_tests.append(possible_test)
        else:
          possible_test_to_target[possible_test] = target

      if len(unknown_tests) > 0:
        raise TaskError("No target found for test specifier(s):\n\n  '{}'\n\nPlease change "
                        "specifier or bring in the proper target(s)."
                        .format("'\n  '".join(t.render_test_spec() for t in unknown_tests)))

      return RegistryOfTests(possible_test_to_target)
    else:
      return test_registry

  @staticmethod
  def _copy_files(dest_dir, target):
    if isinstance(target, Files):
      for source in target.sources_relative_to_buildroot():
        src = os.path.join(get_buildroot(), source)
        dest = os.path.join(dest_dir, source)
        safe_mkdir_for(dest)
        shutil.copy(src, dest)

  @contextmanager
  def _chroot(self, targets, workdir):
    if workdir is not None:
      yield workdir
    else:
      root_dir = os.path.join(self.workdir, '_chroots')
      safe_mkdir(root_dir)
      with temporary_dir(root_dir=root_dir) as chroot:
        self.context.build_graph.walk_transitive_dependency_graph(
          addresses=[t.address for t in targets],
          work=functools.partial(self._copy_files, chroot)
        )
        yield chroot

  @property
  def _batched(self):
    return self._batch_size != self._BATCH_ALL

  def run_tests(self, fail_fast, test_targets, output_dir, coverage):
    test_registry = self._collect_test_targets(test_targets)
    if test_registry.empty:
      return TestResult.rc(0)

    coverage.instrument(output_dir)

    def parse_error_handler(parse_error):
      # Just log and move on since the result is only used to characterize failures, and raising
      # an error here would just distract from the underlying test failures.
      self.context.log.error('Error parsing test result file {path}: {cause}'
                             .format(path=parse_error.xml_path, cause=parse_error.cause))

    # The 'instrument_classpath' product below below will be `None` if not set, and we'll default
    # back to runtime_classpath
    classpath_product = self.context.products.get_data('instrument_classpath')

    result = 0
    for batch_id, (properties, batch) in enumerate(self._iter_batches(test_registry)):
      (workdir, platform, target_jvm_options, target_env_vars, concurrency, threads) = properties

      batch_output_dir = output_dir
      if self._batched:
        batch_output_dir = os.path.join(batch_output_dir, 'batch-{}'.format(batch_id))

      run_modifications = coverage.run_modifications(batch_output_dir)

      extra_jvm_options = run_modifications.extra_jvm_options

      # Batches of test classes will likely exist within the same targets: dedupe them.
      relevant_targets = {test_registry.get_owning_target(t) for t in batch}

      complete_classpath = OrderedSet()
      complete_classpath.update(run_modifications.classpath_prepend)
      complete_classpath.update(JUnit.global_instance().runner_classpath(self.context))
      complete_classpath.update(self.classpath(relevant_targets,
                                               classpath_product=classpath_product))

      distribution = JvmPlatform.preferred_jvm_distribution([platform], self._strict_jvm_version)

      # Override cmdline args with values from junit_test() target that specify concurrency:
      args = self._args(fail_fast, batch_output_dir) + [u'-xmlreport']

      if concurrency is not None:
        args = remove_arg(args, '-default-parallel')
        if concurrency == JUnitTests.CONCURRENCY_SERIAL:
          args = ensure_arg(args, '-default-concurrency', param='SERIAL')
        elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES:
          args = ensure_arg(args, '-default-concurrency', param='PARALLEL_CLASSES')
        elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_METHODS:
          args = ensure_arg(args, '-default-concurrency', param='PARALLEL_METHODS')
        elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES_AND_METHODS:
          args = ensure_arg(args, '-default-concurrency', param='PARALLEL_CLASSES_AND_METHODS')

      if threads is not None:
        args = remove_arg(args, '-parallel-threads', has_param=True)
        args += ['-parallel-threads', str(threads)]

      batch_test_specs = [test.render_test_spec() for test in batch]
      with argfile.safe_args(batch_test_specs, self.get_options()) as batch_tests:
        with self._chroot(relevant_targets, workdir) as chroot:
          self.context.log.debug('CWD = {}'.format(chroot))
          self.context.log.debug('platform = {}'.format(platform))
          with environment_as(**dict(target_env_vars)):
            subprocess_result = self._spawn_and_wait(
              executor=SubprocessExecutor(distribution),
              distribution=distribution,
              classpath=complete_classpath,
              main=JUnit.RUNNER_MAIN,
              jvm_options=self.jvm_options + extra_jvm_options + list(target_jvm_options),
              args=args + batch_tests,
              workunit_factory=self.context.new_workunit,
              workunit_name='run',
              workunit_labels=[WorkUnitLabel.TEST],
              cwd=chroot,
              synthetic_jar_dir=batch_output_dir,
              create_synthetic_jar=self.synthetic_classpath,
            )
            self.context.log.debug('JUnit subprocess exited with result ({})'
                                   .format(subprocess_result))
            result += abs(subprocess_result)

        tests_info = self.parse_test_info(batch_output_dir, parse_error_handler, ['classname'])
        for test_name, test_info in tests_info.items():
          test_item = Test(test_info['classname'], test_name)
          test_target = test_registry.get_owning_target(test_item)
          self.report_all_info_for_single_test(self.options_scope, test_target,
                                               test_name, test_info)

        if result != 0 and fail_fast:
          break

    if result == 0:
      return TestResult.rc(0)

    target_to_failed_test = parse_failed_targets(test_registry, output_dir, parse_error_handler)

    def sort_owning_target(t):
      return t.address.spec if t else None

    failed_targets = sorted(target_to_failed_test, key=sort_owning_target)
    error_message_lines = []
    if self._failure_summary:
      def render_owning_target(t):
        return t.address.reference() if t else '<Unknown Target>'

      for target in failed_targets:
        error_message_lines.append('\n{indent}{owner}'.format(indent=' ' * 4,
                                                              owner=render_owning_target(target)))
        for test in sorted(target_to_failed_test[target]):
          error_message_lines.append('{indent}{classname}#{methodname}'
                                     .format(indent=' ' * 8,
                                             classname=test.classname,
                                             methodname=test.methodname))
    error_message_lines.append(
      '\njava {main} ... exited non-zero ({code}); {failed} failed {targets}.'
        .format(main=JUnit.RUNNER_MAIN, code=result, failed=len(failed_targets),
                targets=pluralize(len(failed_targets), 'target'))
    )
    return TestResult(msg='\n'.join(error_message_lines), rc=result, failed_targets=failed_targets)

  def _iter_batches(self, test_registry):
    tests_by_properties = test_registry.index(
      lambda tgt: tgt.cwd if tgt.cwd is not None else self._working_dir,
      lambda tgt: tgt.test_platform,
      lambda tgt: tgt.payload.extra_jvm_options,
      lambda tgt: tgt.payload.extra_env_vars,
      lambda tgt: tgt.concurrency,
      lambda tgt: tgt.threads)

    for properties, tests in sorted(tests_by_properties.items()):
      sorted_tests = sorted(tests)
      stride = min(self._batch_size, len(sorted_tests))
      for i in range(0, len(sorted_tests), stride):
        yield properties, sorted_tests[i:i + stride]

  def _get_possible_tests_to_run(self):
    buildroot = get_buildroot()
    for test_spec in self._tests_to_run:
      for test in _TestSpecification.parse(buildroot, test_spec).iter_possible_tests(self.context):
        yield test

  def _calculate_tests_from_targets(self, targets):
    """
    :param list targets: list of targets to calculate test classes for.
    generates tuples (Test, Target).
    """
    classpath_products = self.context.products.get_data('runtime_classpath')
    for target in targets:
      contents = ClasspathUtil.classpath_contents((target,), classpath_products, confs=self.confs)
      for f in contents:
        classname = ClasspathUtil.classname_for_rel_classfile(f)
        if classname:
          yield Test(classname=classname), target

  def _test_target_filter(self):
    def target_filter(target):
      return isinstance(target, JUnitTests)
    return target_filter

  def _validate_target(self, target):
    # TODO: move this check to an optional phase in goal_runner, so
    # that missing sources can be detected early.
    if not target.payload.sources.source_paths and not self.get_options().allow_empty_sources:
      msg = 'JUnitTests target must include a non-empty set of sources.'
      raise TargetDefinitionException(target, msg)

  def collect_files(self, output_dir, coverage):
    def files_iter():
      for dir_path, _, file_names in os.walk(output_dir):
        for filename in file_names:
          yield os.path.join(dir_path, filename)
    return list(files_iter())

  @contextmanager
  def partitions(self, per_target, all_targets, test_targets):
    with self._isolation(per_target, all_targets) as (output_dir, reports, coverage):
      if per_target:
        def iter_partitions():
          for test_target in test_targets:
            partition = (test_target,)
            args = (os.path.join(output_dir, test_target.id), coverage)
            yield partition, args
      else:
        def iter_partitions():
          if test_targets:
            partition = tuple(test_targets)
            args = (output_dir, coverage)
            yield partition, args

      try:
        yield iter_partitions
      finally:
        _, error, _ = sys.exc_info()
        reports.generate(output_dir, exc=error)

  class Reports(object):
    def __init__(self, junit_html_report, coverage):
      self._junit_html_report = junit_html_report
      self._coverage = coverage

    def generate(self, output_dir, exc=None):
      junit_report_path = self._junit_html_report.report(output_dir)
      self._maybe_open_report(junit_report_path)

      coverage_report_path = self._coverage.report(output_dir, execution_failed_exception=exc)
      self._maybe_open_report(coverage_report_path)

    def _maybe_open_report(self, report_file_path):
      if report_file_path:
        try:
          desktop.ui_open(report_file_path)
        except desktop.OpenError as e:
          raise TaskError(e)

  @contextmanager
  def _isolation(self, per_target, all_targets):
    run_dir = '_runs'
    mode_dir = 'isolated' if per_target else 'combined'
    batch_dir = str(self._batch_size) if self._batched else 'all'
    output_dir = os.path.join(self.workdir,
                              run_dir,
                              Target.identify(all_targets),
                              mode_dir,
                              batch_dir)
    safe_mkdir(output_dir, clean=False)

    if self._html_report:
      junit_html_report = JUnitHtmlReport.create(xml_dir=output_dir,
                                                 open_report=self.get_options().open,
                                                 logger=self.context.log,
                                                 error_on_conflict=True)
    else:
      junit_html_report = NoJunitHtmlReport()

    coverage = CodeCoverage.global_instance().get_coverage_engine(
      self,
      output_dir,
      all_targets,
      self.execute_java_for_coverage)

    reports = self.Reports(junit_html_report, coverage)

    self.context.release_lock()
    try:
      yield output_dir, reports, coverage
    finally:
      lock_file = '.file_lock'
      preserve = (run_dir, lock_file)
      dist_dir = os.path.join(self.get_options().pants_distdir,
                              os.path.relpath(self.workdir, self.get_options().pants_workdir))

      with OwnerPrintingInterProcessFileLock(os.path.join(dist_dir, lock_file)):
        self._link_current_reports(report_dir=output_dir, link_dir=dist_dir,
                                   preserve=preserve)

  def _link_current_reports(self, report_dir, link_dir, preserve):
    # Kill everything not preserved.
    for name in os.listdir(link_dir):
      path = os.path.join(link_dir, name)
      if name not in preserve:
        if os.path.isdir(path):
          safe_rmtree(path)
        else:
          os.unlink(path)

    # Link ~all the isolated run/ dir contents back up to the stable workdir
    # NB: When batching is enabled, files can be emitted under different subdirs. If those files
    # have the like-names, the last file with a like-name will be the one that is used. This may
    # result in a loss of information from the ignored files. We're OK with this because:
    # a) We're planning on deprecating this loss of information.
    # b) It is the same behavior as existed before batching was added.
    for root, dirs, files in safe_walk(report_dir, topdown=True):
      dirs.sort()  # Ensure a consistent walk order for sanity sake.
      for f in itertools.chain(fnmatch.filter(files, '*.err.txt'),
                               fnmatch.filter(files, '*.out.txt'),
                               fnmatch.filter(files, 'TEST-*.xml')):
        src = os.path.join(root, f)
        dst = os.path.join(link_dir, f)
        safe_delete(dst)
        os.symlink(src, dst)

    for path in os.listdir(report_dir):
      if path in ('coverage', 'reports'):
        src = os.path.join(report_dir, path)
        dst = os.path.join(link_dir, path)
        os.symlink(src, dst)


text:
import { Cms } from "../../shared/cms/cms";
/**
 * Created by tran on 12/06/16.
 */
export declare class cmsSync {
    private cms;
    constructor(cms: Cms);
}

redpajama_set_name: RedPajamaGithub


text:
namespace Resources
{

class CTimelineTrackLoaderHRD : public CResourceLoader
{
public:

	CTimelineTrackLoaderHRD(CResourceManager& ResourceManager) : CResourceLoader(ResourceManager) {}

	virtual const Core::CRTTI& GetResultType() const override;
	virtual Core::PObject    CreateResource(CStrID UID) override;
};

typedef Ptr<CTimelineTrackLoaderHRD> PTimelineTrackLoaderHRD;

}


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Belote.Engine
{
    public class Carte : IEqualityComparer<Carte>
    {
        public Couleur Couleur { get; set; }
        public Valeur Valeur { get; set; }

        public Carte(Valeur valeur, Couleur couleur)
        {
            Couleur = couleur;
            Valeur = valeur;
        }

        #region IEqualityComparer members
        public bool Equals(Carte x, Carte y)
        {
            return x.Valeur == y.Valeur && x.Couleur == y.Couleur;
        }

        public int GetHashCode(Carte obj)
        {
            return obj.GetHashCode();
        }
        #endregion
    }

    public enum Valeur
    {
       Sept,
       Huit,
       Neuf,
       Dix,
       Valet,
       Dame,
       Roi,
       As
    }

    public enum Couleur
    {
        Pique,
        Coeur,
        Carreau,
        Trefle
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
namespace XBMCRPC.AudioLibrary
{
   public class GetRecentlyPlayedSongsResponse
   {
       public XBMCRPC.List.LimitsReturned limits { get; set; }
       public global::System.Collections.Generic.List<XBMCRPC.Audio.Details.Song> songs { get; set; }
    }
}


text:
.thesaas-sections-split .section,
.thesaas-sections-split .main-content .topbar,
.thesaas-sections-split .main-content .site-footer {
  margin: 30px 50px 100px;
  box-shadow: 0 0 35px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebebeb;
}

.thesaas-sections-split .main-content .topbar {
  position: static;
}

.thesaas-sections-split .main-content .topbar .topbar-toggler {
  display: none;
}

.thesaas-sections-split .section-info {
  text-align: center;
  text-transform: uppercase;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 1px;
  padding-top: 60px;
}

.thesaas-sections-split.topbar-reveal .main-content .topbar-nav {
  display: none;
}

@media (max-width: 768px) {

  .thesaas-sections-split .section,
  .thesaas-sections-split .main-content .site-footer {
    margin: 30px 0 100px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  }

}


text:
package com.nano.movies.data.review;

import java.util.Date;

import android.content.Context;
import android.content.ContentResolver;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.nano.movies.data.base.AbstractContentValues;

/**
 * Content values wrapper for the {@code review} table.
 */
public class ReviewContentValues extends AbstractContentValues {
    @Override
    public Uri uri() {
        return ReviewColumns.CONTENT_URI;
    }

    /**
     * Update row(s) using the values stored by this object and the given selection.
     *
     * @param contentResolver The content resolver to use.
     * @param where The selection to use (can be {@code null}).
     */
    public int update(ContentResolver contentResolver, @Nullable ReviewSelection where) {
        return contentResolver.update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args());
    }

    /**
     * Update row(s) using the values stored by this object and the given selection.
     *
     * @param contentResolver The content resolver to use.
     * @param where The selection to use (can be {@code null}).
     */
    public int update(Context context, @Nullable ReviewSelection where) {
        return context.getContentResolver().update(uri(), values(), where == null ? null : where.sel(), where == null ? null : where.args());
    }

    /**
     * Id of movie in movies table.
     */
    public ReviewContentValues putMovieId(long value) {
        mContentValues.put(ReviewColumns.MOVIE_ID, value);
        return this;
    }

    /**
     * https://www.themoviedb.org/review/<review_id>
     */
    public ReviewContentValues putReviewId(@NonNull String value) {
        if (value == null) throw new IllegalArgumentException("reviewId must not be null");
        mContentValues.put(ReviewColumns.REVIEW_ID, value);
        return this;
    }

    public ReviewContentValues putAuthor(@NonNull String value) {
        if (value == null) throw new IllegalArgumentException("author must not be null");
        mContentValues.put(ReviewColumns.AUTHOR, value);
        return this;
    }

    public ReviewContentValues putContent(@NonNull String value) {
        if (value == null) throw new IllegalArgumentException("content must not be null");
        mContentValues.put(ReviewColumns.CONTENT, value);
        return this;
    }

    /**
     * Links to https://www.themoviedb.org/review/<review_id>
     */
    public ReviewContentValues putUrl(@NonNull String value) {
        if (value == null) throw new IllegalArgumentException("url must not be null");
        mContentValues.put(ReviewColumns.URL, value);
        return this;
    }

}


text:
This plugin supports SAP Commerce (Hybris) versions 6.x

The plugin is using following adyen libraries and API.
- [adyen-java-api-library](https://github.com/Adyen/adyen-java-api-library) (v14.0.0)
- [adyen-web](https://github.com/Adyen/adyen-web) (v4.3.1)
- [Adyen Checkout API](https://docs.adyen.com/api-explorer/) (v67)

## Integration

The SAP Commerce integrates Adyen Checkout for all card payments and local/redirect payment methods.
Boleto, PayPal ECS and RatePay are routed over the old integration. When available in the new Checkout they will be migrated to the new flow.

## Requirements
SAP Commerce (Hybris) version 6.x or 1905

## Installation

### 1. Copy extension files to bin/custom directory

### 2. Add the Adyen extensions to the config/localextensions.xml file

Required for the checkout:
```
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6core"/>
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6b2ccheckoutaddon"/>
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6backoffice"/>
```
Required for the notifications:
```
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6notification"/>
```

Additionally, required when using yacceleratorordermanagement (b2c_acc_oms recipe for 6.x and b2c_b2b_acc_oms recipe for 1905) :
```
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6ordermanagement"/>
```

Additionally, required when using yacceleratorfulfilment (b2c_acc recipe for 6.x and b2c_acc_plus for 1905):
```
<extension dir="${HYBRIS_BIN_DIR}/custom/adyen-hybris/adyenv6fulfilmentprocess"/>
```

### 3. Modify local.properties

Modify config/local.properties file:

1. append ``` ,/[^/]+(/[^?]*)+(adyen-response)$,/adyen(/[^?]*)+$ ``` to the value of ```csrf.allowed.url.patterns```
2. add ```is3DS2allowed = true```

### 4. Build
```
cd bin/platform
. ./setantenv.sh
ant addoninstall -Daddonnames="adyenv6b2ccheckoutaddon" -DaddonStorefront.yacceleratorstorefront="yacceleratorstorefront"
ant clean all
```

### 5. Add your Adyen credentials to the BaseStore via Hybris backoffice

For more detailed instructions you can visit the [documentation page](https://docs.adyen.com/developers/plug-ins-and-partners/hybris)
Please make sure your merchant has Variant true in API and responses section so that you get paymentMethod back in response.

## Supported payment methods

### Credit Cards

Credit Card payments are supported using Checkout Components.

### Apple Pay

[Apple Pay](https://docs.adyen.com/payment-methods/apple-pay/) is supported using Checkout Components.

### Ratepay

Ratepay is supported via Adyen API.

### AfterPay

[AfterPay](https://docs.adyen.com/payment-methods/afterpay) is supported via Adyen component and API.

### Boleto

[Boleto](https://docs.adyen.com/payment-methods/boleto-bancario) is supported via Adyen API.

### Pix
[Pix](https://docs.adyen.com/payment-methods/pix) is supported via Adyen component and API.

### Other alternative payment methods

Supported via Adyen Checkout.

## Usage with OCC

The plugin supports the following OCC v2 compatible methods via [com.adyen.v6.facades.AdyenCheckoutFacade](adyenv6core/src/com/adyen/v6/facades/AdyenCheckoutFacade.java):

1. PaymentDetailsListWsDTO getPaymentDetails(String userId) throws IOException, ApiException;

```
    OCC controller: UsersController.getPaymentInfos
    Endpoint: GET /{userId}/paymentdetails
```

This method that will return the stored cards associated to the shopping cart user via Adyen API.

2. PaymentDetailsWsDTO addPaymentDetails(PaymentDetailsWsDTO paymentDetails, DataMapper dataMapper);

```
    OCC controller: CartsController.addPaymentDetails
    Endpoint: POST /{cartId}/paymentdetails
```

This method that will receive the payment method selection and rest of payment details and store them in the Cart.

For Credit Card payments - it expects encrypted card holder data obtained from your frontend implementation using Secured Fields

For Stored Cards payments - selected Adyen recurringReference of the card and encrypted cvc

For Boleto payments - social security number

3. OrderData authorisePayment(CartData cartData) throws Exception;

```
    OCC controller: OrdersController.placeOrder
    Endpoint: POST /users/{userId}/orders
```

This method will place the payment request using the previously stored payment method selection data. Upon successful response from Adyen API, it will register payment response in cart/order level.

It returns an instance of OrderWSDTO obtained from OrderData of the placed order.
For Boleto, it will contain the pdf url, the base64 encoded data, expiration date and due date
https://docs.adyen.com/developers/payment-methods/boleto-bancario/boleto-payment-request

## 3DS2 configuration
By default 3DS2 is enabled (Except for OCC). If you want to disable 3DS2 in your system, please set following property in local.properties file, build your environment and restart the server.
```
is3DS2allowed = false
```
## POS Timeout configuration
POS timeout (time calculated since initiating a payment) is max time to keep terminal connection open. It is set to 130 seconds by default already. If you want to change it, please add following property in local.properties file, build your environment and restart the server. (Change 130 to your desired time, in seconds).
```
pos.totaltimeout = 130
```
## Credit card holder name configuration
By default Credit card holder name is a mandatory field, You can disable it by setting following property in `local.properties` file.
```
isCardHolderNameRequired = false
```

## Pending Order Timeout configuration
By default, an order remains in PAYMENT_PENDING status in order management for 1 hour and it is configured in dynamic order process defintiion file.
Based on which extension you are using (fulfillment or ordermanangement) timeout value can be updated in corresponding order-process.xml file.

For example, following 2 files have 60 mins configuration under waitForAdyenPendingPayment process with delay value=PT60M

Fulfillment extension file - resources/adyenv6fulfilmentprocess/process/order-process.xml

OrderManagement extension file - resources/adyenv6ordermanagement/process/order-process.xml
```
<wait id="waitForAdyenPendingPayment" then="checkPendingOrder">
        <event>AdyenPaymentResult</event>
        <timeout delay="PT60M" then="checkPendingOrder"/>
    </wait>
```

## PayPal configuration
This plugin uses Adyen's Checkout Component for PayPal payments. To use that in a live environment, a PayPal Merchant Id is required [(check here how to get one)](https://docs.adyen.com/payment-methods/paypal/web-component#get-your-paypal-merchant-id). This id has to be provided when adding your Adyen credentials to the BaseStore via the backoffice [(installation step 5)](#installation).

## SameSite Cookie Handler configuration
On Google Chrome browser versions 80 or later, it might occur that an account is logged out after trying to place an order using a credit card that requires 3D Secure authentication or using other redirect payment methods.
This is a consequence of how newer versions of Chrome browsers handle the [SameSite attribute](https://web.dev/samesite-cookies-explained/) on cookies, invalidating the user session after a redirect to a third-party page happened.

To avoid those issues, for SAP Commerce versions 6.x or 1905, a cookie handler included in this plugin can be used. To enable it, add the following configuration to the config/local.properties file:

```
adyen.samesitecookie.handler.enabled=true
```

For SAP Commerce versions 2005 and above, check how to use [SAP's SameSite Cookie Attribute Handler](https://help.sap.com/viewer/d0224eca81e249cb821f2cdf45a82ace/2005/en-US/bde41b6a42c541a08eb2a3b1993fb097.html).

 ## Documentation
 https://docs.adyen.com/developers/plugins/hybris

 ## Support
If you have a feature request, or spotted a bug or a technical problem, create a GitHub issue. For other questions, contact our [support team](https://support.adyen.com/hc/en-us/requests/new?ticket_form_id=360000705420).

 ## Contributing
 We strongly encourage you to join us in contributing to this repository so everyone can benefit from:
 * New features and functionality
 * Resolved bug fixes and issues
 * Any general improvements

 Read our [**contribution guidelines**](CONTRIBUTING.md) to find out how.

 ## License
 MIT license. For more information, see the LICENSE file.


text:
"""
# test_utils_logger

@author: Jason Zhu
@email: jason_zhuyx@hotmail.com

"""
import unittest

from pyapi.utils.logger import get_logger
from pyapi.utils.logger import raise_ni

class LoggerTests(unittest.TestCase):
    """
    LoggerTests includes all unit tests for logger module
    """
    def setUp(self):
        return

    def tearDown(self):
        return

    def test_get_logger(self):
        """
        test_get_logger tests logger.get_logger() function
        """
        logger = get_logger(__name__)
        self.assertEqual(logger.propagate, True)
        self.assertEqual(logger.name, __name__)

    def test_raise_ni(self):
        """
        test_raise_ni tests logger.raise_ni() function
        """
        msg = 'must implement whatever_name in derived class'
        with self.assertRaises(NotImplementedError) as context:
            raise_ni("whatever_name")
        self.assertEqual(msg, context.exception.message)


text:
package javax.crypto;

public class Toto {

}


text:
#import <Foundation/Foundation.h>

#import "RCTBridgeModule.h"
#import "RCTInvalidating.h"

@interface RCTTiming : NSObject <RCTBridgeModule, RCTInvalidating>

@end


text:
module ChainLog

  # formatter for log messages that includes hash chaining.  Based on Logger.Formatter
  # Enable in config/environment.rb with:
  #
  # Rails.application.config.log_formatter = ChainLog::Formatter.new
  #
  class Formatter

    # Names of meta-data fields

    FIELD_NAMES=%w(pid,program,thread,line,chain)

    # Number of meta-data fields
    NUM_FIELDS=5

    # Number of hex chars of SHA digest to keep
    HASH_LEN=4

    attr_accessor :datetime_format

    def initialize
      @datetime_format = nil
      @lock = Mutex.new

      @dup_mode = true
      @last_hash = Formatter.hash_str('') # 52b855
      @last_message = nil
      @last_output = nil
      @num=0
    end

    #########
    # return HASH_LEN hex chars of SHA256(line)
    # @param line Formatted log entry without trailing newlines
    #########
    def self.hash_str(line)
      Digest::SHA256.hexdigest(line)[-HASH_LEN..-1]
    end

    #########
    # Called by Logger to format line
    #########
    def call(severity, time, progname, msg)
      @lock.synchronize {
        @num += 1

        if @dup_mode

          # by default, dup_mode is on, so check first several messages to see if it doesn't happen

          if @num < 10 && !@last_message.nil?

            # turn off dup mode if every other message is not the same
            @dup_mode = false  if (@num % 2 == 0) && @last_message != msg
          end
          return @last_output if @last_message == msg && (@num % 2 == 0)
        end

        tid = Thread.current.object_id.to_s(16)[-3..-1]
        lineno = @num
        lineno = (@num + 1) / 2 if @dup_mode    # without this, would read 1, 3, 5, 7, ...
        lineno = lineno.to_s[-1..-1]

        pname=progname
        # make sure program name, if present, does not have spaces. For parsing reasons
        pname=pname.gsub(' ','_') unless pname.nil?

        s= "%s %s [%d,%s,%s,%s,%s] : %s" % [
             severity[0..0], format_datetime(time),
             $$, pname, tid, lineno , @last_hash,
             msg2str(msg)]

        # create hash of this line for use next time

        @last_message = msg
        @last_hash = Formatter.hash_str(s)

        s << "\n"

        @last_output = s
      }
    end

    private

    def format_datetime(time)
      if @datetime_format.nil?
        time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d" % time.usec
      else
        time.strftime(@datetime_format)
      end
    end

    def msg2str(msg)
      case msg
        when ::String
          msg
        when ::Exception
          "#{ msg.message } (#{ msg.class })\n" <<
            (msg.backtrace || []).join("\n")
        else
          msg.to_json
      end
    end
  end

end


text:
package com.example.cache;

import lombok.NonNull;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.Validate;

import javax.annotation.concurrent.ThreadSafe;

/**
 * The class is intended to create instances of {@link CompressedLongObjectMap}.
 *
 * @param <T> type of items
 * @author Ruslan Sverchkov
 */
@ThreadSafe
@Log4j2
public class CompressedLongObjectMapFactory<T> {

    /**
     * @see CompressedLongObjectMap#CompressedLongObjectMap(Serializer, Archiver, int)
     */
    @NonNull
    private final Serializer<T> serializer;

    /**
     * @see CompressedLongObjectMap#CompressedLongObjectMap(Serializer, Archiver, int)
     */
    @NonNull
    private final Archiver archiver;

    /**
     * Initial size of the map.
     */
    private final int size;

    /**
     * Construct a CompressedLongObjectMapFactory instance.
     *
     * @param serializer to serialize an item
     * @param archiver   to archive an item
     * @param size       initial size of the map
     * @throws NullPointerException if:
     *                                        * serializer is null
     *                                        * archiver is null
     * @throws IllegalArgumentException       if size is not positive
     */
    public CompressedLongObjectMapFactory(@NonNull Serializer<T> serializer, @NonNull Archiver archiver, int size) {
        Validate.isTrue(size > 0);
        this.serializer = serializer;
        this.archiver = archiver;
        this.size = size;
    }

    /**
     * The method is intended to create an instance of {@link CompressedLongObjectMap <String, T>}, mostly for testing purposes.
     *
     * @return an instance of {@link CompressedLongObjectMap <String, T>}
     */
    public CompressedLongObjectMap<T> newInstance() {
        return new CompressedLongObjectMap<>(serializer, archiver, size);
    }

}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsCP869ToUnicode_h___
#define nsCP869ToUnicode_h___

#include "nsISupports.h"

/**
 * A character set converter from CP869 to Unicode.
 */
nsresult
nsCP869ToUnicodeConstructor(nsISupports *aOuter, REFNSIID aIID,
                            void **aResult);

#endif /* nsCP869ToUnicode_h___ */


text:
package windows

// STATUS: 1%
// Extensions: .cov
// ??? found on Windows 10, ProgramData/Microsoft/Windows NT/MSFax/Common Coverpages/en-GB/confident.cov

import (
	"os"

	"github.com/martinlindhe/formats/parse"
)

// FAXC parses the faxc format
func FAXC(c *parse.Checker) (*parse.ParsedLayout, error) {

	if !isFAXC(c.Header) {
		return nil, nil
	}
	return parseFAXC(c.File, c.ParsedLayout)
}

func isFAXC(b []byte) bool {

	s := string(b[0:12])
	return s == "FAXCOVER-VER"
}

func parseFAXC(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) {

	pos := int64(0)
	pl.FileKind = parse.WindowsResource
	pl.Layout = []parse.Layout{{
		Offset: pos,
		Length: 12, // XXX
		Info:   "header",
		Type:   parse.Group,
		Childs: []parse.Layout{
			{Offset: pos, Length: 12, Info: "magic", Type: parse.Bytes},
		}}}

	return &pl, nil
}


text:
namespace DAVA
{
class UIStyleSheetSelectorChain
{
public:
    UIStyleSheetSelectorChain();
    UIStyleSheetSelectorChain(const String& string);
    String ToString() const;

    Vector<UIStyleSheetSelector>::const_iterator begin() const;
    Vector<UIStyleSheetSelector>::const_iterator end() const;

    Vector<UIStyleSheetSelector>::const_reverse_iterator rbegin() const;
    Vector<UIStyleSheetSelector>::const_reverse_iterator rend() const;

    int32 GetSize() const;

private:
    Vector<UIStyleSheetSelector> selectors;
};
};

#endif


text:
md-card{
    margin-top:8px;
        display: inline-block;
        margin-right: 0px;
        margin-bottom:0px;
        border-radius:3px;
        margin-left:8px;
        margin-right:8px;
        height:20vh;
        padding-top:2.2vh;

}

md-card-title{
    font-size: 17px!important;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 50vw;
    margin-top: 16px;
    overflow: hidden;
}

md-card-subtitle{
        text-overflow: ellipsis;
    white-space: nowrap;
    width: 45vw;
    overflow: hidden;

}

:host{
    flex-direction: column;
    display: flex;

}

.header-image {
  background-size: cover;
      height: 21vh;
    width: 21vh;
    right: 10px;
    position: absolute;
    float: right;
}

md-card-header > div.mat-card-header-text{
    margin-top:16px!important;

}

#starsContainer{
    position: absolute;
    bottom: 24px;
    left: 24px;
    width: 90px;
    display: flex;
}

.stars{
    vertical-align: middle;
    display: inline-block;
    height: 18px;
    line-height: 18px;
    font-size: 18px;
    margin-top: 4px;
}


text:
/*
 * $Id$
 */
/*

/*

Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

/* Portions of this code are
 *
 * ====================================================================
 *
 *  Copyright 2002-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.lockss.util.urlconn;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import com.sun.net.ssl.TrustManagerFactory;
import com.sun.net.ssl.TrustManager;
import com.sun.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * PermissiveX509TrustManager accepts all server certificates.  It enables
 * collection from https: sites with the same level of trust at http: sites
 * (that is, none).  It is not intended for secure applications. */

public class PermissiveX509TrustManager implements X509TrustManager {
    private X509TrustManager standardTrustManager = null;

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(PermissiveX509TrustManager.class);

    /**
     * Constructor for PermissiveX509TrustManager.
     */
    public PermissiveX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
        super();
        TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509");
        factory.init(keystore);
        TrustManager[] trustmanagers = factory.getTrustManagers();
        if (trustmanagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        this.standardTrustManager = (X509TrustManager)trustmanagers[0];
    }

    /**
     * @see com.sun.net.ssl.X509TrustManager#isClientTrusted(X509Certificate[])
     */
    public boolean isClientTrusted(X509Certificate[] certificates) {
        return this.standardTrustManager.isClientTrusted(certificates);
    }

    /**
     * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
     */
    public boolean isServerTrusted(X509Certificate[] certificates) {
      return true;
    }

    /**
     * @see com.sun.net.ssl.X509TrustManager#getAcceptedIssuers()
     */
    public X509Certificate[] getAcceptedIssuers() {
        return this.standardTrustManager.getAcceptedIssuers();
    }
}


text:
package com.superSaller.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class CounterRowMapper implements RowMapper<Integer> {

	@Override
	public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
		return rs.getInt("counter");
	}

}


text:
with open('base.txt', 'w') as file:
    file.write("""
{{ myvar }}
You wanna hear a dirty joke?
{% include 'joke.txt' %}
""".strip())
with open('joke.txt', 'w') as file:
    file.write("""
A boy fell in a mud puddle. {{ myvar }}
""".strip())

from jinja2 import Environment, FileSystemLoader

env = Environment()
# tell the environment how to load templates
env.loader = FileSystemLoader('.')
print env.get_template('base.txt').render(myvar='Ha ha!')


text:
class Profile;
class TemplateURL;
class WDTypedResult;
class WebDataService;

// Returns the short name of the default search engine, or the empty string if
// none is set. |profile| may be NULL.
string16 GetDefaultSearchEngineName(Profile* profile);

// Returns a GURL that searches for |terms| using the default search engine of
// |profile|.
GURL GetDefaultSearchURLForSearchTerms(Profile* profile, const string16& terms);

// Modifies |prepopulated_url| so that it contains user-modified fields from
// |original_turl|. Both URLs must have the same prepopulate_id.
void MergeIntoPrepopulatedEngineData(TemplateURLData* prepopulated_url,
                                     const TemplateURL* original_turl);

// Processes the results of WebDataService::GetKeywords, combining it with
// prepopulated search providers to result in:
//  * a set of template_urls (search providers). The caller owns the
//    TemplateURL* returned in template_urls.
//  * the default search provider (and if *default_search_provider is not NULL,
//    it is contained in template_urls).
//  * whether there is a new resource keyword version (and the value).
//    |*new_resource_keyword_version| is set to 0 if no new value. Otherwise,
//    it is the new value.
// Only pass in a non-NULL value for service if the WebDataService should be
// updated. If |removed_keyword_guids| is not NULL, any TemplateURLs removed
// from the keyword table in the WebDataService will have their Sync GUIDs
// added to it.
void GetSearchProvidersUsingKeywordResult(
    const WDTypedResult& result,
    WebDataService* service,
    Profile* profile,
    TemplateURLService::TemplateURLVector* template_urls,
    TemplateURL** default_search_provider,
    int* new_resource_keyword_version,
    std::set<std::string>* removed_keyword_guids);

// Like GetSearchProvidersUsingKeywordResult(), but allows the caller to pass in
// engines in |template_urls| instead of getting them via processing a web data
// service request.
// |resource_keyword_version| should contain the version number of the current
// keyword data, i.e. the version number of the most recent prepopulate data
// that has been merged into the current keyword data.  On exit, this will be
// set as in GetSearchProvidersUsingKeywordResult().
void GetSearchProvidersUsingLoadedEngines(
    WebDataService* service,
    Profile* profile,
    TemplateURLService::TemplateURLVector* template_urls,
    TemplateURL** default_search_provider,
    int* resource_keyword_version,
    std::set<std::string>* removed_keyword_guids);

// Due to a bug, the |input_encodings| field of TemplateURLData could have
// contained duplicate entries.  This removes those entries and returns whether
// any were found.
bool DeDupeEncodings(std::vector<std::string>* encodings);

// Removes (and deletes) TemplateURLs from |template_urls| and |service| if they
// have duplicate prepopulate ids. If |removed_keyword_guids| is not NULL, the
// Sync GUID of each item removed from the DB will be added to it. This is a
// helper used by GetSearchProvidersUsingKeywordResult(), but is declared here
// so it's accessible by unittests.
void RemoveDuplicatePrepopulateIDs(
    WebDataService* service,
    const ScopedVector<TemplateURL>& prepopulated_urls,
    TemplateURL* default_search_provider,
    TemplateURLService::TemplateURLVector* template_urls,
    std::set<std::string>* removed_keyword_guids);

#endif  // CHROME_BROWSER_SEARCH_ENGINES_UTIL_H_


text:
namespace pipeline {

boost::shared_ptr<ProcessNode>
ProcessNodeTracking::getHolder() {

	return _holder->getSelfSharedPointer();
}

} // namespace pipeline


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*=====================================================================
**
** Source:  MoveFileExW.c
**
** Purpose: Tests the PAL implementation of the MoveFileExW function.
**
**
**===================================================================*/

#include <palsuite.h>

LPWSTR lpSource[4];
LPWSTR lpDestination[4];
LPWSTR lpFiles[14];

DWORD dwFlag[2] = {MOVEFILE_COPY_ALLOWED, MOVEFILE_REPLACE_EXISTING};

int createExisting(void)
{
    HANDLE tempFile  = NULL;
    HANDLE tempFile2 = NULL;

    /* create the src_existing file and dst_existing file */
    tempFile = CreateFileW(lpSource[0], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    tempFile2 = CreateFileW(lpDestination[0], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    CloseHandle(tempFile2);
    CloseHandle(tempFile);

    if ((tempFile == NULL) || (tempFile2 == NULL))
    {
        Trace("ERROR: couldn't create %S or %S\n", lpSource[0],
                lpDestination[0]);
        return FAIL;
    }

    /* create the src_dir_existing and dst_dir_existing directory and files */
    CreateDirectoryW(lpSource[2], NULL);

    tempFile = CreateFileW(lpFiles[0], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    tempFile2 = CreateFileW(lpFiles[1], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    CloseHandle(tempFile2);
    CloseHandle(tempFile);

    if ((tempFile == NULL) || (tempFile2 == NULL))
    {
        Trace("ERROR: couldn't create src_dir_existing\\test01.tmp\n");
        return FAIL;
    }

    CreateDirectoryW(lpDestination[2], NULL);
    tempFile = CreateFileW(lpFiles[2], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    tempFile2 = CreateFileW(lpFiles[3], GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);
    CloseHandle(tempFile2);
    CloseHandle(tempFile);

    if ((tempFile == NULL) || (tempFile2 == NULL))
    {
        Trace("ERROR: couldn't create dst_dir_existing\\test01.tmp\n");
        return FAIL;
    }
    return PASS;
}

void removeDirectoryHelper(LPWSTR dir, int location)
{
    DWORD dwAtt = GetFileAttributesW(dir);
//    Trace(" Value of location[%d], and directorye [%S]\n", location, dir);

    if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
    {
        if(!RemoveDirectoryW(dir))
        {
            Fail("ERROR: Failed to remove Directory [%S], Error Code [%d], location [%d]\n", dir, GetLastError(), location);
        }
    }
}

void removeFileHelper(LPWSTR wfile, int location)
{
    FILE *fp;
    char * pfile = convertC(wfile);

//    Trace(" Value of location[%d], and file [%s]\n", location, pfile);
    fp = fopen( pfile, "r");

    if (fp != NULL)
    {
        if(fclose(fp))
        {
          Fail("ERROR: Failed to close the file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location);
        }

        if(!DeleteFileW(wfile))
        {
            Fail("ERROR: Failed to delete file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location);
        }
        else
        {
    //       Trace("Success: deleted file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location);
        }
    }

    free(pfile);
}

void removeAll(void)
{
    DWORD dwAtt;
    /* get rid of destination dirs and files */
    removeFileHelper(lpSource[0], 11);
//    lpSource[0] = convert("src_existing.tmp");

    removeFileHelper(lpSource[1], 12);
  //lpSource[1] = convert("src_non-existant.tmp");

    removeFileHelper(lpFiles[0], 13);
//    lpFiles[0] = convert("src_dir_existing\\test01.tmp");

    removeFileHelper(lpFiles[1], 14);
//    lpFiles[1] = convert("src_dir_existing\\test02.tmp");

    removeDirectoryHelper(lpSource[2], 101);
//    lpSource[2] = convert("src_dir_existing");

    removeFileHelper(lpFiles[4], 15);
//    lpFiles[4] = convert("src_dir_non-existant\\test01.tmp");

    removeFileHelper(lpFiles[5], 16);
//    lpFiles[5] = convert("src_dir_non-existant\\test02.tmp");

    removeDirectoryHelper(lpSource[3], 102);
//    lpSource[3] = convert("src_dir_non-existant");

    /* get rid of destination dirs and files */
    dwAtt = GetFileAttributesW(lpDestination[0]);
    if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
    {
        removeFileHelper(lpFiles[6], 18);
    //    lpFiles[6] = convert("dst_existing.tmp\\test01.tmp");
        removeFileHelper(lpFiles[7], 19);
    //    lpFiles[7] = convert("dst_existing.tmp\\test02.tmp");
        removeDirectoryHelper(lpDestination[0], 103);
    //    lpDestination[0] = convert("dst_existing.tmp");

    }
    else
    {
        removeFileHelper(lpDestination[0], 17);
    //    lpDestination[0] = convert("dst_existing.tmp");
    }

    dwAtt = GetFileAttributesW(lpDestination[1]);
    if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
    {
        removeFileHelper(lpFiles[8], 21);
    //    lpFiles[8] = convert("dst_non-existant.tmp\\test01.tmp");
        removeFileHelper(lpFiles[9], 22);
    //    lpFiles[9] = convert("dst_non-existant.tmp\\test02.tmp");
        removeDirectoryHelper(lpDestination[1], 104);
    //    lpDestination[1] = convert("dst_non-existant.tmp");

    }
    else
    {
        removeFileHelper(lpDestination[1], 19);
            //lpDestination[1] = convert("dst_non-existant.tmp");
    }

    dwAtt = GetFileAttributesW(lpDestination[2]);
    if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
    {
        removeFileHelper(lpFiles[10], 24);
    //    lpFiles[10] = convert("dst_dir_existing\\test01.tmp");
        removeFileHelper(lpFiles[11], 25);
    //    lpFiles[11] = convert("dst_dir_existing\\test02.tmp");
        removeDirectoryHelper(lpDestination[2], 105);
    //    lpDestination[2] = convert("dst_dir_existing");

    }
    else
    {
        removeFileHelper(lpDestination[2], 23);
    //    lpDestination[2] = convert("dst_dir_existing");

    }

    dwAtt = GetFileAttributesW(lpDestination[3]);
    if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
    {
        removeFileHelper(lpFiles[12], 26);
    //    lpFiles[12] = convert("dst_dir_non-existant\\test01.tmp");
        removeFileHelper(lpFiles[13], 27);
    //    lpFiles[13] = convert("dst_dir_non-existant\\test02.tmp");
        removeDirectoryHelper(lpDestination[3], 106);
    //    lpDestination[3] = convert("dst_dir_non-existant");

    }
    else
    {
        removeFileHelper(lpDestination[3], 107);
    //    lpDestination[3] = convert("dst_dir_non-existant");

    }

}

int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = TRUE;
    char results[40];
    FILE* resultsFile = NULL;
    int i, j, k, nCounter = 0;
    int res = FAIL;
    WCHAR tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'};
    WCHAR tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'};
    HANDLE hFile;
    DWORD result;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    lpSource[0] = convert("src_existing.tmp");
    lpSource[1] = convert("src_non-existant.tmp");
    lpSource[2] = convert("src_dir_existing");
    lpSource[3] = convert("src_dir_non-existant");

    lpDestination[0] = convert("dst_existing.tmp");
    lpDestination[1] = convert("dst_non-existant.tmp");
    lpDestination[2] = convert("dst_dir_existing");
    lpDestination[3] = convert("dst_dir_non-existant");

    lpFiles[0] = convert("src_dir_existing\\test01.tmp");
    lpFiles[1] = convert("src_dir_existing\\test02.tmp");
    lpFiles[2] = convert("dst_dir_existing\\test01.tmp");
    lpFiles[3] = convert("dst_dir_existing\\test02.tmp");
    lpFiles[4] = convert("src_dir_non-existant\\test01.tmp");
    lpFiles[5] = convert("src_dir_non-existant\\test02.tmp");

    lpFiles[6] = convert("dst_existing.tmp\\test01.tmp");
    lpFiles[7] = convert("dst_existing.tmp\\test02.tmp");

    lpFiles[8] = convert("dst_non-existant.tmp\\test01.tmp");
    lpFiles[9] = convert("dst_non-existant.tmp\\test02.tmp");

    lpFiles[10] = convert("dst_dir_existing\\test01.tmp");
    lpFiles[11] = convert("dst_dir_existing\\test02.tmp");

    lpFiles[12] = convert("dst_dir_non-existant\\test01.tmp");
    lpFiles[13] = convert("dst_dir_non-existant\\test02.tmp");

    /* read in the expected results to compare with actual results */
    memset (results, 0, 34);
    resultsFile = fopen("expectedresults.txt", "r");
    if (resultsFile == NULL)
    {
        Trace("MoveFileExW ERROR: Unable to open \"expectedresults.txt\"\n");
        goto EXIT;
    }

    fgets(results, 34, resultsFile);
    fclose(resultsFile);

//    Trace("Value of results[%]=%s\n", i, results);
    for( i = 0; i < 32; i++)
    {
        Trace("Value of results[%d]=%c\n", i, results[i]);
    }
    nCounter = 0;

    /* clean the slate */
    removeAll();
    if (createExisting() != PASS)
    {
        goto EXIT;
    }

    /* lpSource loop */
    for (i = 0; i < 4; i++)
    {
        /* lpDestination loop */
        for (j = 0; j < 4; j++)
        {
            /* dwFlag loop */
            for (k = 0; k < 2; k++)
            {

                //if(nCounter == 22)
                //{
                //exit(1);
                //}
                /* move the file to the new location */
                bRc = MoveFileExW(lpSource[i], lpDestination[j], dwFlag[k]);

                if (!(
                    ((bRc == TRUE) && (results[nCounter] == '1'))
                    ||
                    ((bRc == FALSE ) && (results[nCounter] == '0'))                    )
                    )
                {
                    Trace("MoveFileExW(%S, %S, %s): Values of i[%d], j[%d], k [%d] and results[%d]=%c LastError[%d]Flag[%d]FAILED\n",
                        lpSource[i], lpDestination[j],
                        k == 1 ?
                        "MOVEFILE_REPLACE_EXISTING":"MOVEFILE_COPY_ALLOWED", i, j, k, nCounter, results[nCounter], GetLastError(), bRc);
                    goto EXIT;
                }

                //Trace("MoveFileExW(%S, %S, %s): Values of i[%d], j[%d], k [%d] and results[%d]=%c \n",
                //        lpSource[i], lpDestination[j],
                //        k == 1 ?
                //        "MOVEFILE_REPLACE_EXISTING":"MOVEFILE_COPY_ALLOWED", i, j, k, nCounter, results[nCounter]);

                /* undo the last move */
                removeAll();
                if (createExisting() != PASS)
                {
                    goto EXIT;
                }
                //Trace("Counter [%d] over \n", nCounter);
                nCounter++;
            }
        }
    }

    /* create the temp source file */
    hFile = CreateFileW(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, 0);

    if( hFile == INVALID_HANDLE_VALUE )
    {
        Trace("MoveFileExW: CreateFile failed to "
            "create the file correctly.\n");
        goto EXIT;
    }

    bRc = CloseHandle(hFile);
    if(!bRc)
    {
        Trace("MoveFileExW: CloseHandle failed to close the "
            "handle correctly. yo %u\n",GetLastError());
        goto EXIT;
    }

    /* set the file attributes to be readonly */
    bRc = SetFileAttributesW(tempSource, FILE_ATTRIBUTE_READONLY);
    if(!bRc)
    {
        Trace("MoveFileExW: SetFileAttributes failed to set file "
            "attributes correctly. ERROR:%u\n",GetLastError());
        goto EXIT;
    }

    /* move the file to the new location */
    bRc = MoveFileExW(tempSource, tempDest, MOVEFILE_COPY_ALLOWED );
    if(!bRc)
    {
        Trace("MoveFileExW(%S, %S, %s): GetFileAttributes "
            "failed to get the file's attributes.\n",
            tempSource, tempDest, "MOVEFILE_COPY_ALLOWED");
        goto EXIT;
    }

    /* check that the newly moved file has the same file attributes
    as the original */
    result = GetFileAttributesW(tempDest);
    if(result == 0)
    {
        Trace("MoveFileExW: GetFileAttributes failed to get "
            "the file's attributes.\n");
        goto EXIT;
    }

    if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
    {
        Trace("MoveFileExW: GetFileAttributes failed to get "
            "the correct file attributes.\n");
        goto EXIT;
    }

    /* set the file attributes back to normal, to be deleted */
    bRc = SetFileAttributesW(tempDest, FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        Trace("MoveFileExW: SetFileAttributes "
            "failed to set file attributes correctly.\n");
        goto EXIT;
    }

    /* delete the newly moved file */
    bRc = DeleteFileW(tempDest);
    if(!bRc)
    {
        Trace("MoveFileExW: DeleteFileW failed to delete the"
            "file correctly.\n");
        goto EXIT;
    }

    res = PASS;

EXIT:
    removeAll();
    for (i=0; i<4; i++)
    {
        free(lpSource[i]);
        free(lpDestination[i]);
    }
    for (i=0; i<14; i++)
    {
        free(lpFiles[i]);
    }

    PAL_TerminateEx(res);
    return res;
}


text:
var AuthenticationInitializer = {

    name: 'authentication',
    before: 'simple-auth',
    after: 'registerTrailingLocationHistory',

    initialize: function (container) {
        window.ENV = window.ENV || {};
        window.ENV['simple-auth'] = {
            authenticationRoute: 'signin',
            routeAfterAuthentication: 'content',
            authorizer: 'simple-auth-authorizer:oauth2-bearer'
        };
        SimpleAuth.Session.reopen({
            user: function () {
                return container.lookup('store:main').find('user', 'me');
            }.property()
        });
        SimpleAuth.Authenticators.OAuth2.reopen({
            serverTokenEndpoint: '/ghost/api/v0.1/authentication/token',
            refreshAccessTokens: true,
            makeRequest: function (url, data) {
                data.client_id = 'ghost-admin';
                return this._super(url, data);
            }
        });
    }
};

export default AuthenticationInitializer;


text:
package charts.reference;

import java.awt.Color;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import charts.ChartType;
import charts.builder.ChartTypeBuilder;
import charts.builder.spreadsheet.AbstractBuilder;
import charts.builder.spreadsheet.ChartConfigurationNotSupported;
import charts.builder.spreadsheet.SubstitutionKey;
import charts.jfree.Attribute;
import charts.jfree.AttributeMap;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class ChartRefConfig {

  private final ChartRefCache cache;

  @Inject
  public ChartRefConfig(ChartRefCache cache) {
    this.cache = cache;
  }

  public List<ChartReference> chartrefs() {
    List<ChartReference> result = Lists.newArrayList();
    for(ChartType type : ChartType.values()) {
      AbstractBuilder builder = getChartBuilder(type);
      if(builder != null) {
        result.add(new ChartReference(type.name(), type.getLabel(),
            defaults(builder, type), (defaults(builder, type) != null?substMap(builder):null),
            type.hasUniqueLabel()?type.getLabel():String.format("%s (%s)",
                type.getLabel(), type.name())));
      }
    }
    Collections.sort(result, new Comparator<ChartReference>() {
      @Override
      public int compare(ChartReference cr0, ChartReference cr1) {
        return cr0.getLabel().compareTo(cr1.getLabel());
      }});
    return result;
  }

  private AbstractBuilder getChartBuilder(ChartType type) {
    for(ChartTypeBuilder builder : cache.builder().builders()) {
      if(builder instanceof AbstractBuilder) {
        AbstractBuilder a = (AbstractBuilder)builder;
        if(a.supports(type)) {
          return a;
        }
      }
    }
    return null;
  }

  private Map<String, Object> defaults(AbstractBuilder builder, ChartType type) {
    try {
      return asMap(builder.defaults(type));
    } catch(ChartConfigurationNotSupported e) {
      return null;
    }
  }

  private Map<String, Object> asMap(AttributeMap map) {
    if(map == null) {
      return null;
    }
    Map<String, Object> m = Maps.newTreeMap();
    for(Attribute<?> a : map.keySet()) {
      Object o = map.get(a);
      if(o!=null) {
        if(o instanceof Color) {
          m.put(a.getName(), new Colors((Color)o));
        } else if(o instanceof Color[]) {
          m.put(a.getName(), new Colors((Color[])o));
        } else {
          m.put(a.getName(), o.toString());
        }
      } else {
        m.put(a.getName(), null);
      }
    }
    return m;
  }

  private Map<String, String> substMap(AbstractBuilder builder) {
    Map<String, String> m = Maps.newTreeMap();
    Set<SubstitutionKey> set = builder.substitutionKeys();
    for(SubstitutionKey s : set) {
      m.put(s.getName(), s.getDescription());
    }
    return m;
  }

}


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;

namespace IdentityServer4.Stores
{
    public interface ISigningCredentialStore
    {
        Task<SigningCredentials> GetSigningCredentialsAsync();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of PronType in UD_German-HDT</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_German-HDT: Features: PronType

This feature is universal.
It occurs with 8 different values: Art, Dem, Ind, Int, Neg, Prs, Rel, Tot.
Some words have combined values of the feature; 1 combinations have been observed: Ind|Neg|Tot.

582483 tokens (17%) have a non-empty value of PronType.
453 types (0%) occur at least once with a non-empty value of PronType.
318 lemmas (0%) occur at least once with a non-empty value of PronType.
The feature is used with 3 part-of-speech tags: <tt>DET</tt> (452103; 13% instances), <tt>PRON</tt> (125441; 4% instances), <tt>ADV</tt> (4939; 0% instances).

DET

452103 <tt>DET</tt> tokens (98% of all DET tokens) have a non-empty value of PronType.

The most frequent other feature values with which DET and PronType co-occurred: <tt>Definite</tt><tt>=EMPTY</tt> (395913; 88%), <tt>Number</tt><tt>=Sing</tt> (369216; 82%).

DET tokens may have the following values of PronType:

Art (427233; 94% of non-empty PronType): der, die, dem, den, das, des, eine, ein, einen, einem

Dem (12147; 3% of non-empty PronType): diese, dieser, diesem, dieses, diesen, deren, dessen, derselben, denselben, dieselbe

Ind,Neg,Tot (11302; 2% of non-empty PronType): keine, kein, einige, mehr, keinen, mehrere, einigen, jedem, weniger, einiger

Int (713; 0% of non-empty PronType): welche, welchen, welcher, welchem, wieviel, welches, welch, wieviele, wessen, wievielen

Rel (708; 0% of non-empty PronType): deren, dessen

EMPTY (7871): alle, aller, allen, beide, jeder, solche, jede, jeden, jedes, beiden

Paradigm deren	<tt>Rel</tt>	<tt>Dem</tt>

<tt></tt>	deren	deren, dessen

PronType seems to be lexical feature of DET. 98% lemmas (113) occur only with one value of PronType.

PRON

125441 <tt>PRON</tt> tokens (100% of all PRON tokens) have a non-empty value of PronType.

The most frequent other feature values with which PRON and PronType co-occurred: <tt>Person</tt><tt>=3</tt> (118586; 95%), <tt>Poss</tt><tt>=EMPTY</tt> (107071; 85%), <tt>Reflex</tt><tt>=EMPTY</tt> (104290; 83%), <tt>Number</tt><tt>=Sing</tt> (77359; 62%), <tt>Case</tt><tt>=Nom</tt> (64915; 52%).

PRON tokens may have the following values of PronType:

Dem (8455; 7% of non-empty PronType): das, dies, diese, die, dieser, dem, der, denen, diesen, dieses

Ind,Neg,Tot (18107; 14% of non-empty PronType): man, allem, anderem, mehr, nichts, einer, alles, etwas, eines, eine

Int (2468; 2% of non-empty PronType): wer, was, wem, wen, wieviel, welche, welcher, welchen, welches, wieviele

Prs (72578; 58% of non-empty PronType): sich, es, sie, er, wir, ihre, seine, seiner, seinen, ihrer

Rel (23833; 19% of non-empty PronType): die, der, das, dem, was, denen, den, welches, welche, derer

Paradigm was	<tt>Ind,Neg,Tot</tt>	<tt>Int</tt>	<tt>Rel</tt>

<tt><tt>Case</tt><tt>=Acc</tt>|<tt>Gender</tt><tt>=Neut</tt></tt>	was	was	was, watt

<tt><tt>Case</tt><tt>=Dat</tt>|<tt>Gender</tt><tt>=Neut</tt></tt>	was

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Gender</tt><tt>=Neut</tt></tt>	was	was	was

<tt><tt>Case</tt><tt>=Nom</tt></tt>	irgendwer

<tt><tt>Gender</tt><tt>=Neut</tt></tt>	was

<tt></tt>	irgendwas, E-irgendwas

PronType seems to be lexical feature of PRON. 94% lemmas (211) occur only with one value of PronType.

ADV

4939 <tt>ADV</tt> tokens (3% of all ADV tokens) have a non-empty value of PronType.

ADV tokens may have the following values of PronType:

Int (4939; 100% of non-empty PronType): wie, wo, wann, warum, wobei, wonach, wodurch, womit, inwieweit, weshalb

EMPTY (189409): auch, noch, nur, so, aber, bereits, allerdings, mehr, damit, schon

PronType seems to be lexical feature of ADV. 100% lemmas (51) occur only with one value of PronType.

Relations with Agreement in PronType

The 10 most frequent relations where parent and child node agree in PronType:
<tt>PRON –[<tt>conj</tt>]–> PRON</tt> (89; 92%),
<tt>DET –[<tt>conj</tt>]–> DET</tt> (22; 56%),
<tt>ADV –[<tt>conj</tt>]–> ADV</tt> (16; 84%),
<tt>DET –[<tt>reparandum</tt>]–> DET</tt> (12; 100%),
<tt>PRON –[<tt>amod</tt>]–> DET</tt> (8; 100%),
<tt>PRON –[<tt>reparandum</tt>]–> PRON</tt> (5; 100%),
<tt>DET –[<tt>obl</tt>]–> PRON</tt> (2; 100%),
<tt>ADV –[<tt>conj</tt>]–> DET</tt> (1; 100%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
'use strict';

var path = require('path');
var grunt = require('grunt');

var jshintBase = path.resolve(__dirname, 'jshint');

var jshintTask = require('../lib/grunt-benchmark').spawnTask('jshint', {
  base: jshintBase,
  gruntfile: path.resolve(jshintBase, 'Gruntfile.js')
});

module.exports = {
  'setUp': function(done) {
    grunt.file.write(path.join(jshintBase, 'jshint', 'test.js'), 'var nosemicolon = true');
    done();
  },
  'tearDown': function(done) {
    grunt.file.delete(path.join(jshintBase, 'jshint'));
    done();
  },
  'jshint task': function(done) {
    jshintTask(function() {}, function(result) {
      //console.log(result);
      done();
    });
  }
};


text:
'use strict';

const ccxt = require ('../../../ccxt');

(async () => {

    const streams = {
        'binance': 'BTC/USDT',
        'okex': 'BTC/USDT'
    };

    await Promise.all (Object.keys (streams).map (exchangeId =>

        (async () => {

             const exchange = new ccxt.pro[exchangeId] ({
                enableRateLimit: true,
                options: {
                    tradesLimit: 100, // lower = better, 1000 by default
                },
            })
            const symbol = streams[exchangeId]
            let lastId = ''
            while (true) {
                console.log ('---')
                try {
                    const trades = await exchange.watchTrades (symbol)
                    for (let i = 0; i < trades.length; i++) {
                        const trade = trades[i]
                        if (trade['id'] > lastId) {
                            console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, trade['symbol'], trade['id'], trade['datetime'], trade['price'], trade['amount'])
                            lastId = trade['id']
                        }
                    }
                } catch (e) {
                    console.log (symbol, e)
                }
            }

        }) ())
    )
}) ()


text:
import { IndexOfArity2 } from './types'
import { curry2 } from '../../function/curry'
import { equals } from '../../relation/equals'
import { findIndex } from '../findIndex'

/**
 * Returns the position of the first occurrence of an item in an array, or -1
 * if the item is not included in the array.
 */
export const indexOf: IndexOfArity2 =
  curry2(<A>(value: A, list: Array<A>) => findIndex(equals(value), list))


text:
import proto  # type: ignore

from google.ads.googleads.v11.enums.types import (
    response_content_type as gage_response_content_type,
)
from google.ads.googleads.v11.resources.types import (
    asset_group_listing_group_filter as gagr_asset_group_listing_group_filter,
)
from google.protobuf import field_mask_pb2  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v11.services",
    marshal="google.ads.googleads.v11",
    manifest={
        "MutateAssetGroupListingGroupFiltersRequest",
        "AssetGroupListingGroupFilterOperation",
        "MutateAssetGroupListingGroupFiltersResponse",
        "MutateAssetGroupListingGroupFilterResult",
    },
)

class MutateAssetGroupListingGroupFiltersRequest(proto.Message):
    r"""Request message for
    [AssetGroupListingGroupFilterService.MutateAssetGroupListingGroupFilters][google.ads.googleads.v11.services.AssetGroupListingGroupFilterService.MutateAssetGroupListingGroupFilters].
    partial_failure is not supported because the tree needs to be
    validated together.

    Attributes:
        customer_id (str):
            Required. The ID of the customer whose asset
            group listing group filters are being modified.
        operations (Sequence[google.ads.googleads.v11.services.types.AssetGroupListingGroupFilterOperation]):
            Required. The list of operations to perform
            on individual asset group listing group filters.
        validate_only (bool):
            If true, the request is validated but not
            executed. Only errors are returned, not results.
        response_content_type (google.ads.googleads.v11.enums.types.ResponseContentTypeEnum.ResponseContentType):
            The response content type setting. Determines
            whether the mutable resource or just the
            resource name should be returned post mutation.
    """

    customer_id = proto.Field(proto.STRING, number=1,)
    operations = proto.RepeatedField(
        proto.MESSAGE,
        number=2,
        message="AssetGroupListingGroupFilterOperation",
    )
    validate_only = proto.Field(proto.BOOL, number=3,)
    response_content_type = proto.Field(
        proto.ENUM,
        number=4,
        enum=gage_response_content_type.ResponseContentTypeEnum.ResponseContentType,
    )

class AssetGroupListingGroupFilterOperation(proto.Message):
    r"""A single operation (create, remove) on an asset group listing
    group filter.

    This message has `oneof`_ fields (mutually exclusive fields).
    For each oneof, at most one member field can be set at the same time.
    Setting any member of the oneof automatically clears all other
    members.

    .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields

    Attributes:
        update_mask (google.protobuf.field_mask_pb2.FieldMask):
            FieldMask that determines which resource
            fields are modified in an update.
        create (google.ads.googleads.v11.resources.types.AssetGroupListingGroupFilter):
            Create operation: No resource name is
            expected for the new asset group listing group
            filter.

            This field is a member of `oneof`_ ``operation``.
        update (google.ads.googleads.v11.resources.types.AssetGroupListingGroupFilter):
            Update operation: The asset group listing
            group filter is expected to have a valid
            resource name.

            This field is a member of `oneof`_ ``operation``.
        remove (str):
            Remove operation: A resource name for the removed asset
            group listing group filter is expected, in this format:
            ``customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}``
            An entity can be removed only if it's not referenced by
            other parent_listing_group_id. If multiple entities are
            being deleted, the mutates must be in the correct order.

            This field is a member of `oneof`_ ``operation``.
    """

    update_mask = proto.Field(
        proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask,
    )
    create = proto.Field(
        proto.MESSAGE,
        number=1,
        oneof="operation",
        message=gagr_asset_group_listing_group_filter.AssetGroupListingGroupFilter,
    )
    update = proto.Field(
        proto.MESSAGE,
        number=2,
        oneof="operation",
        message=gagr_asset_group_listing_group_filter.AssetGroupListingGroupFilter,
    )
    remove = proto.Field(proto.STRING, number=3, oneof="operation",)

class MutateAssetGroupListingGroupFiltersResponse(proto.Message):
    r"""Response message for an asset group listing group filter
    mutate.

    Attributes:
        results (Sequence[google.ads.googleads.v11.services.types.MutateAssetGroupListingGroupFilterResult]):
            All results for the mutate.
    """

    results = proto.RepeatedField(
        proto.MESSAGE,
        number=1,
        message="MutateAssetGroupListingGroupFilterResult",
    )

class MutateAssetGroupListingGroupFilterResult(proto.Message):
    r"""The result for the asset group listing group filter mutate.

    Attributes:
        resource_name (str):
            Returned for successful operations.
        asset_group_listing_group_filter (google.ads.googleads.v11.resources.types.AssetGroupListingGroupFilter):
            The mutated AssetGroupListingGroupFilter with only mutable
            fields after mutate. The field will only be returned when
            response_content_type is set to "MUTABLE_RESOURCE".
    """

    resource_name = proto.Field(proto.STRING, number=1,)
    asset_group_listing_group_filter = proto.Field(
        proto.MESSAGE,
        number=2,
        message=gagr_asset_group_listing_group_filter.AssetGroupListingGroupFilter,
    )

__all__ = tuple(sorted(__protobuf__.manifest))


text:
define(
   ({
    _widgetLabel: "Posizione",
    title: "Trova posizione personale",
    browserError: "Geolocalizzazione non supportata dal browser in uso.",
    failureFinding: "Impossibile trovare la posizione. Controllare il browser per verificare che la posizione sia condivisa."
  })
);


text:
/**
 *
 */
package com.baidu.rigel.biplatform.tesseract.isservice.event;

import org.springframework.context.ApplicationEvent;

/**
 * UpdateIndexByDatasourceEvent
 *
 * @author lijin
 *
 */
public class UpdateIndexByDatasourceEvent extends ApplicationEvent {

    /**
     * serialVersionUID long
     */
    private static final long serialVersionUID = 5000031730541321727L;
    /**
     * 要刷新的数据源Key信息
     */
    private String dataSourceKey;

    /**
     * Constructor by
     *
     * @param source
     */
    public UpdateIndexByDatasourceEvent(Object source) {
        super(source);
        if (source != null) {
            dataSourceKey = (String) source;
        }
    }

    /**
     * getter method for property dataSourceKey
     *
     * @return the dataSourceKey
     */
    public String getDataSourceKey() {
        return dataSourceKey;
    }

    /**
     * setter method for property dataSourceKey
     *
     * @param dataSourceKey
     *            the dataSourceKey to set
     */
    public void setDataSourceKey(String dataSourceKey) {
        this.dataSourceKey = dataSourceKey;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "UpdateIndexByDatasourceEvent [dataSourceKey=" + dataSourceKey + "]";
    }

}


text:
package bepler.lrpage.parser;

public enum Actions {

	ACCEPT,
	SHIFT,
	REDUCE,
	GOTO;

}


text:
package org.springframework.cloud.sleuth.log;

import org.slf4j.MDC;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.event.SpanAcquiredEvent;
import org.springframework.cloud.sleuth.event.SpanContinuedEvent;
import org.springframework.cloud.sleuth.event.SpanReleasedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Spencer Gibb
 */
@Slf4j
public class Slf4jSpanListener {

	@EventListener(SpanAcquiredEvent.class)
	@Order(Ordered.LOWEST_PRECEDENCE)
	public void start(SpanAcquiredEvent event) {
		Span span = event.getSpan();
		MDC.put(Trace.SPAN_ID_NAME, span.getSpanId());
		MDC.put(Trace.TRACE_ID_NAME, span.getTraceId());
		// TODO: what log level?
		log.info("Starting span: {}", span);
		if (event.getParent() != null) {
			log.info("With parent: {}", event.getParent());
		}
	}

	@EventListener(SpanContinuedEvent.class)
	@Order(Ordered.LOWEST_PRECEDENCE)
	public void continued(SpanContinuedEvent event) {
		Span span = event.getSpan();
		MDC.put(Trace.SPAN_ID_NAME, span.getSpanId());
		MDC.put(Trace.TRACE_ID_NAME, span.getTraceId());
		// TODO: what should this log level be?
		log.info("Continued span: {}", event.getSpan());
	}

	@EventListener(SpanReleasedEvent.class)
	@Order(Ordered.LOWEST_PRECEDENCE)
	public void stop(SpanReleasedEvent event) {
		// TODO: what should this log level be?
		log.info("Stopped span: {}", event.getSpan());
		if (event.getParent() != null) {
			log.info("With parent: {}", event.getParent());
			MDC.put(Trace.SPAN_ID_NAME, event.getParent().getSpanId());
		}
		else {
			MDC.remove(Trace.SPAN_ID_NAME);
			MDC.remove(Trace.TRACE_ID_NAME);
		}
	}

}