text:
<<<<<<< HEAD
<<<<<<< HEAD
#!/usr/bin/env python

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Utility functions for Windows builds.

These functions are executed via gyp-win-tool when using the ninja generator.
"""

import os
import re
import shutil
import subprocess
import string
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# A regex matching an argument corresponding to the output filename passed to
# link.exe.
_LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)

def main(args):
  executor = WinTool()
  exit_code = executor.Dispatch(args)
  if exit_code is not None:
    sys.exit(exit_code)

class WinTool(object):
  """This class performs all the Windows tooling steps. The methods can either
  be executed directly, or dispatched from an argument list."""

  def _UseSeparateMspdbsrv(self, env, args):
    """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
    shared one."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    if args[0] != 'link.exe':
      return

    # Use the output filename passed to the linker to generate an endpoint name
    # for mspdbsrv.exe.
    endpoint_name = None
    for arg in args:
      m = _LINK_EXE_OUT_ARG.match(arg)
      if m:
        endpoint_name = '%s_%d' % (m.group('out'), os.getpid())
        break

    if endpoint_name is None:
      return

    # Adds the appropriate environment variable. This will be read by link.exe
    # to know which instance of mspdbsrv.exe it should connect to (if it's
    # not set then the default endpoint is used).
    env['_MSPDBSRV_ENDPOINT_'] = endpoint_name

  def Dispatch(self, args):
    """Dispatches a string command to a method."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    method = "Exec%s" % self._CommandifyName(args[0])
    return getattr(self, method)(*args[1:])

  def _CommandifyName(self, name_string):
    """Transforms a tool name like recursive-mirror to RecursiveMirror."""
    return name_string.title().replace('-', '')

  def _GetEnv(self, arch):
    """Gets the saved environment from a file for a given architecture."""
    # The environment is saved as an "environment block" (see CreateProcess
    # and msvs_emulation for details). We convert to a dict here.
    # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
    pairs = open(arch).read()[:-2].split('\0')
    kvs = [item.split('=', 1) for item in pairs]
    return dict(kvs)

  def ExecStamp(self, path):
    """Simple stamp command."""
    open(path, 'w').close()

  def ExecRecursiveMirror(self, source, dest):
    """Emulation of rm -rf out && cp -af in out."""
    if os.path.exists(dest):
      if os.path.isdir(dest):
        shutil.rmtree(dest)
      else:
        os.unlink(dest)
    if os.path.isdir(source):
      shutil.copytree(source, dest)
    else:
      shutil.copy2(source, dest)

  def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
    """Filter diagnostic output from link that looks like:
    '   Creating library ui.dll.lib and object ui.dll.exp'
    This happens when there are exports from the dll or exe.
    """
    env = self._GetEnv(arch)
    if use_separate_mspdbsrv == 'True':
      self._UseSeparateMspdbsrv(env, args)
    link = subprocess.Popen(args,
                            shell=True,
                            env=env,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    out, _ = link.communicate()
    for line in out.splitlines():
      if not line.startswith('   Creating library '):
        print line
    return link.returncode

  def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
                            mt, rc, intermediate_manifest, *manifests):
    """A wrapper for handling creating a manifest resource and then executing
    a link command."""
    # The 'normal' way to do manifests is to have link generate a manifest
    # based on gathering dependencies from the object files, then merge that
    # manifest with other manifests supplied as sources, convert the merged
    # manifest to a resource, and then *relink*, including the compiled
    # version of the manifest resource. This breaks incremental linking, and
    # is generally overly complicated. Instead, we merge all the manifests
    # provided (along with one that includes what would normally be in the
    # linker-generated one, see msvs_emulation.py), and include that into the
    # first and only link. We still tell link to generate a manifest, but we
    # only use that to assert that our simpler process did not miss anything.
    variables = {
      'python': sys.executable,
      'arch': arch,
      'out': out,
      'ldcmd': ldcmd,
      'resname': resname,
      'mt': mt,
      'rc': rc,
      'intermediate_manifest': intermediate_manifest,
      'manifests': ' '.join(manifests),
    }
    add_to_ld = ''
    if manifests:
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
      if embed_manifest == 'True':
        subprocess.check_call(
            '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
          ' %(out)s.manifest.rc %(resname)s' % variables)
        subprocess.check_call(
            '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
            '%(out)s.manifest.rc' % variables)
        add_to_ld = ' %(out)s.manifest.res' % variables
    subprocess.check_call(ldcmd + add_to_ld)

    # Run mt.exe on the theoretically complete manifest we generated, merging
    # it with the one the linker generated to confirm that the linker
    # generated one does not add anything. This is strictly unnecessary for
    # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
    # used in a #pragma comment.
    if manifests:
      # Merge the intermediate one with ours to .assert.manifest, then check
      # that .assert.manifest is identical to ours.
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(out)s.manifest %(intermediate_manifest)s '
          '-out:%(out)s.assert.manifest' % variables)
      assert_manifest = '%(out)s.assert.manifest' % variables
      our_manifest = '%(out)s.manifest' % variables
      # Load and normalize the manifests. mt.exe sometimes removes whitespace,
      # and sometimes doesn't unfortunately.
      with open(our_manifest, 'rb') as our_f:
        with open(assert_manifest, 'rb') as assert_f:
          our_data = our_f.read().translate(None, string.whitespace)
          assert_data = assert_f.read().translate(None, string.whitespace)
      if our_data != assert_data:
        os.unlink(out)
        def dump(filename):
          sys.stderr.write('%s\n-----\n' % filename)
          with open(filename, 'rb') as f:
            sys.stderr.write(f.read() + '\n-----\n')
        dump(intermediate_manifest)
        dump(our_manifest)
        dump(assert_manifest)
        sys.stderr.write(
            'Linker generated manifest "%s" added to final manifest "%s" '
            '(result in "%s"). '
            'Were /MANIFEST switches used in #pragma statements? ' % (
              intermediate_manifest, our_manifest, assert_manifest))
        return 1

  def ExecManifestWrapper(self, arch, *args):
    """Run manifest tool with environment set. Strip out undesirable warning
    (some XML blocks are recognized by the OS loader, but not the manifest
    tool)."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if line and 'manifest authoring warning 81010002' not in line:
        print line
    return popen.returncode

  def ExecManifestToRc(self, arch, *args):
    """Creates a resource file pointing a SxS assembly manifest.
    |args| is tuple containing path to resource file, path to manifest file
    and resource name which can be "1" (for executables) or "2" (for DLLs)."""
    manifest_path, resource_path, resource_name = args
    with open(resource_path, 'wb') as output:
      output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
        resource_name,
        os.path.abspath(manifest_path).replace('\\', '/')))

  def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
                      *flags):
    """Filter noisy filenames output from MIDL compile step that isn't
    quietable via command line flags.
    """
    args = ['midl', '/nologo'] + list(flags) + [
        '/out', outdir,
        '/tlb', tlb,
        '/h', h,
        '/dlldata', dlldata,
        '/iid', iid,
        '/proxy', proxy,
        idl]
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    # Filter junk out of stdout, and write filtered versions. Output we want
    # to filter is pairs of lines that look like this:
    # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
    # objidl.idl
    lines = out.splitlines()
    prefix = 'Processing '
    processing = set(os.path.basename(x) for x in lines if x.startswith(prefix))
    for line in lines:
      if not line.startswith(prefix) and line not in processing:
        print line
    return popen.returncode

  def ExecAsmWrapper(self, arch, *args):
    """Filter logo banner from invocations of asm.exe."""
    env = self._GetEnv(arch)
    # MSVS doesn't assemble x64 asm files.
    if arch == 'environment.x64':
      return 0
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Copyright (C) Microsoft Corporation') and
          not line.startswith('Microsoft (R) Macro Assembler') and
          not line.startswith(' Assembling: ') and
          line):
        print line
    return popen.returncode

  def ExecRcWrapper(self, arch, *args):
    """Filter logo banner from invocations of rc.exe. Older versions of RC
    don't support the /nologo flag."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
          not line.startswith('Copyright (C) Microsoft Corporation') and
          line):
        print line
    return popen.returncode

  def ExecActionWrapper(self, arch, rspfile, *dir):
    """Runs an action command line from a response file using the environment
    for |arch|. If |dir| is supplied, use that as the working directory."""
    env = self._GetEnv(arch)
    # TODO(scottmg): This is a temporary hack to get some specific variables
    # through to actions that are set after gyp-time. http://crbug.com/333738.
    for k, v in os.environ.iteritems():
      if k not in env:
        env[k] = v
    args = open(rspfile).read()
    dir = dir[0] if dir else None
    return subprocess.call(args, shell=True, env=env, cwd=dir)

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))
=======
#!/usr/bin/env python

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Utility functions for Windows builds.

These functions are executed via gyp-win-tool when using the ninja generator.
"""

import os
import re
import shutil
import subprocess
import string
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# A regex matching an argument corresponding to the output filename passed to
# link.exe.
_LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)

def main(args):
  executor = WinTool()
  exit_code = executor.Dispatch(args)
  if exit_code is not None:
    sys.exit(exit_code)

class WinTool(object):
  """This class performs all the Windows tooling steps. The methods can either
  be executed directly, or dispatched from an argument list."""

  def _UseSeparateMspdbsrv(self, env, args):
    """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
    shared one."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    if args[0] != 'link.exe':
      return

    # Use the output filename passed to the linker to generate an endpoint name
    # for mspdbsrv.exe.
    endpoint_name = None
    for arg in args:
      m = _LINK_EXE_OUT_ARG.match(arg)
      if m:
        endpoint_name = '%s_%d' % (m.group('out'), os.getpid())
        break

    if endpoint_name is None:
      return

    # Adds the appropriate environment variable. This will be read by link.exe
    # to know which instance of mspdbsrv.exe it should connect to (if it's
    # not set then the default endpoint is used).
    env['_MSPDBSRV_ENDPOINT_'] = endpoint_name

  def Dispatch(self, args):
    """Dispatches a string command to a method."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    method = "Exec%s" % self._CommandifyName(args[0])
    return getattr(self, method)(*args[1:])

  def _CommandifyName(self, name_string):
    """Transforms a tool name like recursive-mirror to RecursiveMirror."""
    return name_string.title().replace('-', '')

  def _GetEnv(self, arch):
    """Gets the saved environment from a file for a given architecture."""
    # The environment is saved as an "environment block" (see CreateProcess
    # and msvs_emulation for details). We convert to a dict here.
    # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
    pairs = open(arch).read()[:-2].split('\0')
    kvs = [item.split('=', 1) for item in pairs]
    return dict(kvs)

  def ExecStamp(self, path):
    """Simple stamp command."""
    open(path, 'w').close()

  def ExecRecursiveMirror(self, source, dest):
    """Emulation of rm -rf out && cp -af in out."""
    if os.path.exists(dest):
      if os.path.isdir(dest):
        shutil.rmtree(dest)
      else:
        os.unlink(dest)
    if os.path.isdir(source):
      shutil.copytree(source, dest)
    else:
      shutil.copy2(source, dest)

  def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
    """Filter diagnostic output from link that looks like:
    '   Creating library ui.dll.lib and object ui.dll.exp'
    This happens when there are exports from the dll or exe.
    """
    env = self._GetEnv(arch)
    if use_separate_mspdbsrv == 'True':
      self._UseSeparateMspdbsrv(env, args)
    link = subprocess.Popen(args,
                            shell=True,
                            env=env,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    out, _ = link.communicate()
    for line in out.splitlines():
      if not line.startswith('   Creating library '):
        print line
    return link.returncode

  def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
                            mt, rc, intermediate_manifest, *manifests):
    """A wrapper for handling creating a manifest resource and then executing
    a link command."""
    # The 'normal' way to do manifests is to have link generate a manifest
    # based on gathering dependencies from the object files, then merge that
    # manifest with other manifests supplied as sources, convert the merged
    # manifest to a resource, and then *relink*, including the compiled
    # version of the manifest resource. This breaks incremental linking, and
    # is generally overly complicated. Instead, we merge all the manifests
    # provided (along with one that includes what would normally be in the
    # linker-generated one, see msvs_emulation.py), and include that into the
    # first and only link. We still tell link to generate a manifest, but we
    # only use that to assert that our simpler process did not miss anything.
    variables = {
      'python': sys.executable,
      'arch': arch,
      'out': out,
      'ldcmd': ldcmd,
      'resname': resname,
      'mt': mt,
      'rc': rc,
      'intermediate_manifest': intermediate_manifest,
      'manifests': ' '.join(manifests),
    }
    add_to_ld = ''
    if manifests:
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
      if embed_manifest == 'True':
        subprocess.check_call(
            '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
          ' %(out)s.manifest.rc %(resname)s' % variables)
        subprocess.check_call(
            '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
            '%(out)s.manifest.rc' % variables)
        add_to_ld = ' %(out)s.manifest.res' % variables
    subprocess.check_call(ldcmd + add_to_ld)

    # Run mt.exe on the theoretically complete manifest we generated, merging
    # it with the one the linker generated to confirm that the linker
    # generated one does not add anything. This is strictly unnecessary for
    # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
    # used in a #pragma comment.
    if manifests:
      # Merge the intermediate one with ours to .assert.manifest, then check
      # that .assert.manifest is identical to ours.
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(out)s.manifest %(intermediate_manifest)s '
          '-out:%(out)s.assert.manifest' % variables)
      assert_manifest = '%(out)s.assert.manifest' % variables
      our_manifest = '%(out)s.manifest' % variables
      # Load and normalize the manifests. mt.exe sometimes removes whitespace,
      # and sometimes doesn't unfortunately.
      with open(our_manifest, 'rb') as our_f:
        with open(assert_manifest, 'rb') as assert_f:
          our_data = our_f.read().translate(None, string.whitespace)
          assert_data = assert_f.read().translate(None, string.whitespace)
      if our_data != assert_data:
        os.unlink(out)
        def dump(filename):
          sys.stderr.write('%s\n-----\n' % filename)
          with open(filename, 'rb') as f:
            sys.stderr.write(f.read() + '\n-----\n')
        dump(intermediate_manifest)
        dump(our_manifest)
        dump(assert_manifest)
        sys.stderr.write(
            'Linker generated manifest "%s" added to final manifest "%s" '
            '(result in "%s"). '
            'Were /MANIFEST switches used in #pragma statements? ' % (
              intermediate_manifest, our_manifest, assert_manifest))
        return 1

  def ExecManifestWrapper(self, arch, *args):
    """Run manifest tool with environment set. Strip out undesirable warning
    (some XML blocks are recognized by the OS loader, but not the manifest
    tool)."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if line and 'manifest authoring warning 81010002' not in line:
        print line
    return popen.returncode

  def ExecManifestToRc(self, arch, *args):
    """Creates a resource file pointing a SxS assembly manifest.
    |args| is tuple containing path to resource file, path to manifest file
    and resource name which can be "1" (for executables) or "2" (for DLLs)."""
    manifest_path, resource_path, resource_name = args
    with open(resource_path, 'wb') as output:
      output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
        resource_name,
        os.path.abspath(manifest_path).replace('\\', '/')))

  def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
                      *flags):
    """Filter noisy filenames output from MIDL compile step that isn't
    quietable via command line flags.
    """
    args = ['midl', '/nologo'] + list(flags) + [
        '/out', outdir,
        '/tlb', tlb,
        '/h', h,
        '/dlldata', dlldata,
        '/iid', iid,
        '/proxy', proxy,
        idl]
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    # Filter junk out of stdout, and write filtered versions. Output we want
    # to filter is pairs of lines that look like this:
    # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
    # objidl.idl
    lines = out.splitlines()
    prefix = 'Processing '
    processing = set(os.path.basename(x) for x in lines if x.startswith(prefix))
    for line in lines:
      if not line.startswith(prefix) and line not in processing:
        print line
    return popen.returncode

  def ExecAsmWrapper(self, arch, *args):
    """Filter logo banner from invocations of asm.exe."""
    env = self._GetEnv(arch)
    # MSVS doesn't assemble x64 asm files.
    if arch == 'environment.x64':
      return 0
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Copyright (C) Microsoft Corporation') and
          not line.startswith('Microsoft (R) Macro Assembler') and
          not line.startswith(' Assembling: ') and
          line):
        print line
    return popen.returncode

  def ExecRcWrapper(self, arch, *args):
    """Filter logo banner from invocations of rc.exe. Older versions of RC
    don't support the /nologo flag."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
          not line.startswith('Copyright (C) Microsoft Corporation') and
          line):
        print line
    return popen.returncode

  def ExecActionWrapper(self, arch, rspfile, *dir):
    """Runs an action command line from a response file using the environment
    for |arch|. If |dir| is supplied, use that as the working directory."""
    env = self._GetEnv(arch)
    # TODO(scottmg): This is a temporary hack to get some specific variables
    # through to actions that are set after gyp-time. http://crbug.com/333738.
    for k, v in os.environ.iteritems():
      if k not in env:
        env[k] = v
    args = open(rspfile).read()
    dir = dir[0] if dir else None
    return subprocess.call(args, shell=True, env=env, cwd=dir)

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
#!/usr/bin/env python

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Utility functions for Windows builds.

These functions are executed via gyp-win-tool when using the ninja generator.
"""

import os
import re
import shutil
import subprocess
import string
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# A regex matching an argument corresponding to the output filename passed to
# link.exe.
_LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)

def main(args):
  executor = WinTool()
  exit_code = executor.Dispatch(args)
  if exit_code is not None:
    sys.exit(exit_code)

class WinTool(object):
  """This class performs all the Windows tooling steps. The methods can either
  be executed directly, or dispatched from an argument list."""

  def _UseSeparateMspdbsrv(self, env, args):
    """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
    shared one."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    if args[0] != 'link.exe':
      return

    # Use the output filename passed to the linker to generate an endpoint name
    # for mspdbsrv.exe.
    endpoint_name = None
    for arg in args:
      m = _LINK_EXE_OUT_ARG.match(arg)
      if m:
        endpoint_name = '%s_%d' % (m.group('out'), os.getpid())
        break

    if endpoint_name is None:
      return

    # Adds the appropriate environment variable. This will be read by link.exe
    # to know which instance of mspdbsrv.exe it should connect to (if it's
    # not set then the default endpoint is used).
    env['_MSPDBSRV_ENDPOINT_'] = endpoint_name

  def Dispatch(self, args):
    """Dispatches a string command to a method."""
    if len(args) < 1:
      raise Exception("Not enough arguments")

    method = "Exec%s" % self._CommandifyName(args[0])
    return getattr(self, method)(*args[1:])

  def _CommandifyName(self, name_string):
    """Transforms a tool name like recursive-mirror to RecursiveMirror."""
    return name_string.title().replace('-', '')

  def _GetEnv(self, arch):
    """Gets the saved environment from a file for a given architecture."""
    # The environment is saved as an "environment block" (see CreateProcess
    # and msvs_emulation for details). We convert to a dict here.
    # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
    pairs = open(arch).read()[:-2].split('\0')
    kvs = [item.split('=', 1) for item in pairs]
    return dict(kvs)

  def ExecStamp(self, path):
    """Simple stamp command."""
    open(path, 'w').close()

  def ExecRecursiveMirror(self, source, dest):
    """Emulation of rm -rf out && cp -af in out."""
    if os.path.exists(dest):
      if os.path.isdir(dest):
        shutil.rmtree(dest)
      else:
        os.unlink(dest)
    if os.path.isdir(source):
      shutil.copytree(source, dest)
    else:
      shutil.copy2(source, dest)

  def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
    """Filter diagnostic output from link that looks like:
    '   Creating library ui.dll.lib and object ui.dll.exp'
    This happens when there are exports from the dll or exe.
    """
    env = self._GetEnv(arch)
    if use_separate_mspdbsrv == 'True':
      self._UseSeparateMspdbsrv(env, args)
    link = subprocess.Popen(args,
                            shell=True,
                            env=env,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    out, _ = link.communicate()
    for line in out.splitlines():
      if not line.startswith('   Creating library '):
        print line
    return link.returncode

  def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
                            mt, rc, intermediate_manifest, *manifests):
    """A wrapper for handling creating a manifest resource and then executing
    a link command."""
    # The 'normal' way to do manifests is to have link generate a manifest
    # based on gathering dependencies from the object files, then merge that
    # manifest with other manifests supplied as sources, convert the merged
    # manifest to a resource, and then *relink*, including the compiled
    # version of the manifest resource. This breaks incremental linking, and
    # is generally overly complicated. Instead, we merge all the manifests
    # provided (along with one that includes what would normally be in the
    # linker-generated one, see msvs_emulation.py), and include that into the
    # first and only link. We still tell link to generate a manifest, but we
    # only use that to assert that our simpler process did not miss anything.
    variables = {
      'python': sys.executable,
      'arch': arch,
      'out': out,
      'ldcmd': ldcmd,
      'resname': resname,
      'mt': mt,
      'rc': rc,
      'intermediate_manifest': intermediate_manifest,
      'manifests': ' '.join(manifests),
    }
    add_to_ld = ''
    if manifests:
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
      if embed_manifest == 'True':
        subprocess.check_call(
            '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
          ' %(out)s.manifest.rc %(resname)s' % variables)
        subprocess.check_call(
            '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
            '%(out)s.manifest.rc' % variables)
        add_to_ld = ' %(out)s.manifest.res' % variables
    subprocess.check_call(ldcmd + add_to_ld)

    # Run mt.exe on the theoretically complete manifest we generated, merging
    # it with the one the linker generated to confirm that the linker
    # generated one does not add anything. This is strictly unnecessary for
    # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
    # used in a #pragma comment.
    if manifests:
      # Merge the intermediate one with ours to .assert.manifest, then check
      # that .assert.manifest is identical to ours.
      subprocess.check_call(
          '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
          '-manifest %(out)s.manifest %(intermediate_manifest)s '
          '-out:%(out)s.assert.manifest' % variables)
      assert_manifest = '%(out)s.assert.manifest' % variables
      our_manifest = '%(out)s.manifest' % variables
      # Load and normalize the manifests. mt.exe sometimes removes whitespace,
      # and sometimes doesn't unfortunately.
      with open(our_manifest, 'rb') as our_f:
        with open(assert_manifest, 'rb') as assert_f:
          our_data = our_f.read().translate(None, string.whitespace)
          assert_data = assert_f.read().translate(None, string.whitespace)
      if our_data != assert_data:
        os.unlink(out)
        def dump(filename):
          sys.stderr.write('%s\n-----\n' % filename)
          with open(filename, 'rb') as f:
            sys.stderr.write(f.read() + '\n-----\n')
        dump(intermediate_manifest)
        dump(our_manifest)
        dump(assert_manifest)
        sys.stderr.write(
            'Linker generated manifest "%s" added to final manifest "%s" '
            '(result in "%s"). '
            'Were /MANIFEST switches used in #pragma statements? ' % (
              intermediate_manifest, our_manifest, assert_manifest))
        return 1

  def ExecManifestWrapper(self, arch, *args):
    """Run manifest tool with environment set. Strip out undesirable warning
    (some XML blocks are recognized by the OS loader, but not the manifest
    tool)."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if line and 'manifest authoring warning 81010002' not in line:
        print line
    return popen.returncode

  def ExecManifestToRc(self, arch, *args):
    """Creates a resource file pointing a SxS assembly manifest.
    |args| is tuple containing path to resource file, path to manifest file
    and resource name which can be "1" (for executables) or "2" (for DLLs)."""
    manifest_path, resource_path, resource_name = args
    with open(resource_path, 'wb') as output:
      output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
        resource_name,
        os.path.abspath(manifest_path).replace('\\', '/')))

  def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
                      *flags):
    """Filter noisy filenames output from MIDL compile step that isn't
    quietable via command line flags.
    """
    args = ['midl', '/nologo'] + list(flags) + [
        '/out', outdir,
        '/tlb', tlb,
        '/h', h,
        '/dlldata', dlldata,
        '/iid', iid,
        '/proxy', proxy,
        idl]
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    # Filter junk out of stdout, and write filtered versions. Output we want
    # to filter is pairs of lines that look like this:
    # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
    # objidl.idl
    lines = out.splitlines()
    prefix = 'Processing '
    processing = set(os.path.basename(x) for x in lines if x.startswith(prefix))
    for line in lines:
      if not line.startswith(prefix) and line not in processing:
        print line
    return popen.returncode

  def ExecAsmWrapper(self, arch, *args):
    """Filter logo banner from invocations of asm.exe."""
    env = self._GetEnv(arch)
    # MSVS doesn't assemble x64 asm files.
    if arch == 'environment.x64':
      return 0
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Copyright (C) Microsoft Corporation') and
          not line.startswith('Microsoft (R) Macro Assembler') and
          not line.startswith(' Assembling: ') and
          line):
        print line
    return popen.returncode

  def ExecRcWrapper(self, arch, *args):
    """Filter logo banner from invocations of rc.exe. Older versions of RC
    don't support the /nologo flag."""
    env = self._GetEnv(arch)
    popen = subprocess.Popen(args, shell=True, env=env,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, _ = popen.communicate()
    for line in out.splitlines():
      if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
          not line.startswith('Copyright (C) Microsoft Corporation') and
          line):
        print line
    return popen.returncode

  def ExecActionWrapper(self, arch, rspfile, *dir):
    """Runs an action command line from a response file using the environment
    for |arch|. If |dir| is supplied, use that as the working directory."""
    env = self._GetEnv(arch)
    # TODO(scottmg): This is a temporary hack to get some specific variables
    # through to actions that are set after gyp-time. http://crbug.com/333738.
    for k, v in os.environ.iteritems():
      if k not in env:
        env[k] = v
    args = open(rspfile).read()
    dir = dir[0] if dir else None
    return subprocess.call(args, shell=True, env=env, cwd=dir)

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
from google.cloud import contact_center_insights_v1
from google.longrunning import operations_pb2

def get_operation(operation_name: str) -> operations_pb2.Operation:
    """Gets an operation.

    Args:
        operation_name:
            The operation name.
            Format is 'projects/{project_id}/locations/{location_id}/operations/{operation_id}'.
            For example, 'projects/my-project/locations/us-central1/operations/123456789'.

    Returns:
        An operation.
    """
    # Construct an Insights client that will authenticate via Application Default Credentials.
    # See authentication details at https://cloud.google.com/docs/authentication/production.
    insights_client = contact_center_insights_v1.ContactCenterInsightsClient()

    # Call the Insights client to get the operation.
    operation = insights_client.transport.operations_client.get_operation(
        operation_name
    )
    if operation.done:
        print("Operation is done")
    else:
        print("Operation is in progress")

# [END contactcenterinsights_get_operation]

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.util.containers;

import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Collection;

/**
 * Makes some THashSet methods open to the public.
 * Adds {@link #get(Object)} method useful to intern objects.
 *
* @author gregsh
*/
public class OpenTHashSet<T> extends THashSet<T> {
  public OpenTHashSet() {
    super();
  }

  public OpenTHashSet(final TObjectHashingStrategy<T> strategy) {
    super(strategy);
  }

  public OpenTHashSet(final int initialCapacity) {
    super(initialCapacity);
  }

  public OpenTHashSet(final int initialCapacity, final TObjectHashingStrategy<T> strategy) {
    super(initialCapacity, strategy);
  }

  public OpenTHashSet(final int initialCapacity, final float loadFactor) {
    super(initialCapacity, loadFactor);
  }

  public OpenTHashSet(final int initialCapacity, final float loadFactor, final TObjectHashingStrategy<T> strategy) {
    super(initialCapacity, loadFactor, strategy);
  }

  public OpenTHashSet(final Collection<? extends T> ts) {
    super(ts);
  }

  public OpenTHashSet(final Collection<? extends T> ts, final TObjectHashingStrategy<T> strategy) {
    super(ts, strategy);
  }

  public OpenTHashSet(final TObjectHashingStrategy<T> strategy, final T... ts) {
    super(Arrays.asList(ts), strategy);
  }

  @Override
  public int index(final T obj) {
    return super.index(obj);
  }

  public T get(final int index) {
    @SuppressWarnings("unchecked") T t = (T)_set[index];
    return t;
  }

  /**
   * Returns an element of this set equal to the given one. Can be used for interning objects to save memory.
   */
  @Nullable
  public T get(final T obj) {
    final int index = index(obj);
    return index < 0 ? null : get(index);
  }
}


text:
__author__ = 'pp'
__version__ = '1.0.0'

import calendar
import logging
import os
from babel.dates import format_date
from dateutil.rrule import rrule, MONTHLY
from datetime import date

from ccytsk.core.task.task import Task
from ccytsk.core.task.task_status import TaskStatus, TaskStatusCtrl
from ccytsk.core.task.task_queue import TaskExecQueue, TaskExecQueueStep
from ccytsk.scrapping.parser import ParserTask, ParserTaskConfig
from ccytsk.scrapping.spider import SpiderTask, SpiderTaskConfig
from ccytsk.scrapping.urls import Url

class WWeatherScrapperTaskConfig(SpiderTaskConfig):
    def __init__(
        self,
        name=None,
        task_module=None,
        task_class=None,
        loop_forever=None,
        execution_loop_interval=None,
        execution_id=None,
        execution_path=None,
        logging_flag=None,
        proxy=False,
        random_user_agent=False,
        max_level=5,
        pagination=False,
        all_or_nothing_on_pagination=False,
        reuse_url_as_first_page=False,
        http_request_interval=0,
        max_http_retries=0,
        debug_http=False,
        save_http_response=True,
        save_http_response_zipped=False,
        delete_files_on_execution=False,
        skip_url_already_downloaded=False,
        wwo_api_key=None,
        wwo_granularity=24,
        wwo_format='csv',
        wwo_n_columns=26,
        is_premium_api=1,
        locations=None
    ):
        super(WWeatherScrapperTaskConfig, self).__init__(
            name=name,
            task_module=task_module,
            task_class=task_class,
            loop_forever=loop_forever,
            execution_loop_interval=execution_loop_interval,
            execution_id=execution_id,
            execution_path=execution_path,
            logging_flag=logging_flag,
            proxy=proxy,
            random_user_agent=random_user_agent,
            max_level=max_level,
            pagination=pagination,
            all_or_nothing_on_pagination=all_or_nothing_on_pagination,
            reuse_url_as_first_page=reuse_url_as_first_page,
            http_request_interval=http_request_interval,
            max_http_retries=max_http_retries,
            debug_http=debug_http,
            save_http_response=save_http_response,
            save_http_response_zipped=save_http_response_zipped,
            delete_files_on_execution=delete_files_on_execution,
            skip_url_already_downloaded=skip_url_already_downloaded
        )

        self.wwo_api_key = wwo_api_key
        self.wwo_granularity = wwo_granularity
        self.wwo_format = wwo_format
        self.wwo_n_columns = wwo_n_columns
        self.is_premium_api = is_premium_api
        self.locations = [] if locations is None else locations

class WWeatherSpider(SpiderTask):
    def __init__(self, config, parent=None, logger=None):
        if config is not None and not isinstance(config, SpiderTaskConfig):
            raise Exception('config parameter in WWeatherSpider constructor must be a WWeatherScrapperTaskConfig instance')
        super(WWeatherSpider, self).__init__(config=config, parent=parent, logger=logger)
        self.base_url = 'http://api.worldweatheronline.com/%s/past-weather.ashx?key=%s&format=%s&%s&%s&%s&tp=%s' % (
            'premium/v1' if self.config.is_premium_api else 'free/v2',
            self.config.wwo_api_key,
            self.config.wwo_format,
            'q=___lat___,___lon___',
            'date=___start_date___',
            'enddate=___end_date___',
            self.config.wwo_granularity
        )

    def get_next_url_generator(self, **kwargs):
        for location in self.config.locations:
            start_date = date(
                int(location['start_year']),
                int(location['start_month']) if 'start_month' in location else 1,
                1
            )
            end_date = date(
                int(location['end_year']),
                int(location['end_month']) if 'end_month' in location else 12,
                1
            )
            for day in rrule(
                    MONTHLY,
                    dtstart=start_date,
                    until=end_date
            ):
                try:
                    url_data = {
                        'lat': location['lat'],
                        'lon': location['lon'],
                        'start_date': format_date(day, "yyyy-MM-dd"),
                        'end_date': format_date(date(day.year, day.month, calendar.monthrange(day.year, day.month)[1]), "yyyy-MM-dd")
                    }
                    download_url = Url(
                        self.base_url,
                        data=url_data,
                        filename='%s-%s%s%s-%s%s%s.csv' % (
                            location['id'],
                            day.year,
                            day.month,
                            day.day,
                            day.year,
                            day.month,
                            calendar.monthrange(day.year, day.month)[1]
                        )
                    )
                except Exception as e:
                    self.do_log(e.message, logging.ERROR)
                    download_url = None
                yield download_url

class WWeatherParser(ParserTask):
    def __init__(self, config, parent=None, logger=None):
        ParserTask.__init__(self, config=config, parent=parent, logger=logger)

    def on_content_parse(self, content, filepath):
        items = []
        for line in content.split('\n'):
            if len(line.strip()) == 0 or line[0] == '#' or ',' not in line:
                continue
            cols = line.strip().split(',')
            if len(cols) != 26:
                continue
            items += [cols]
        return items

class WWeatherScrapperTask(Task, TaskStatusCtrl):
    """
    Simple workflow to obtain data from the world weather online api
    """
    def __init__(self, config, parent=None, logger=None):
        if config is not None and not isinstance(config, SpiderTaskConfig):
            raise Exception('config parameter in WWeatherScrapperTask constructor must be a WWeatherScrapperTaskConfig instance')
        super(WWeatherScrapperTask, self).__init__(config=config, parent=parent, logger=logger)
        if not self.config.wwo_api_key:
            wwo_api_key = os.getenv('WWO_API_KEY')
            if not wwo_api_key:
                raise Exception('API key is required for getting data from WWO')
            else:
                self.config.wwo_api_key = wwo_api_key

    def _process(self, **kwargs):
        # task execution queue
        queue = TaskExecQueue(tsc=self)
        # make a task_config object to share between steps
        steps_config = self.get_config()
        # set the same execution path to all steps
        steps_config.execution_path = self.execution_path
        # add steps
        step_1 = TaskExecQueueStep(
            task=WWeatherSpider(steps_config, parent=self.__class__.__name__, logger=self.logger),
            step_id='wwo_download_step',
            execution_parameters=kwargs
        )
        queue.add_exec_step(step=step_1)
        # add parser specific task_config
        parser_config = ParserTaskConfig(
            file_iterator_include='.*\.csv$',
            execution_path=self.execution_path
        )
        step_2 = TaskExecQueueStep(
            task=WWeatherParser(parser_config, parent=self.__class__.__name__, logger=self.logger),
            step_id='wwo_parser_step',
            execution_parameters=kwargs
        )
        queue.add_exec_step(step=step_2)
        # run the tasks sequenece
        return queue.run()

    def on_step_executed(self, execution_result, step_id, task):
        step_status = TaskStatus(running_status=task.running_status, exit_code=execution_result.exit_code)
        if step_id == 'wwo_download_step':
            step_status.can_continue = True
        elif step_id == 'wwo_parser_step':
            step_status.can_continue = True
        return step_status

if __name__ == '__main__':
    """
    The WWO API key must exist as an environment variable (WWO_API_KEY).
    """
    task = WWeatherScrapperTask(config=WWeatherScrapperTaskConfig(locations=[
        {
            'id': 'zelzate',
            'lat': 51.1975,
            'lon': 3.8139,
            'start_year': 2015,
            'end_year': 2015,
            'end_month': 12,
            'end_day': 31
        }
    ]))
    task.execute()


text:
from .base import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('{{cookiecutter.author_name}}', '{{cookiecutter.email}}'),
)

MANAGERS = ADMINS


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <corners android:radius="2dp" />

            <solid android:color="#4ecad0" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <corners android:radius="2dp" />

            <solid android:color="#4ecad0" />

            <padding
                android:bottom="8dp"
                android:left="8dp"
                android:right="8dp"
                android:top="8dp" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <corners android:radius="2dp" />

            <solid android:color="#4ecad0" />

            <padding
                android:bottom="8dp"
                android:left="8dp"
                android:right="8dp"
                android:top="8dp" />
        </shape>
    </item>

</layer-list>
<!-- #64a5a8 -->
<!-- #E5E4E2 -->


text:
require 'spec_helper'

describe 'default recipe on CentOS 5' do
  let(:chef_run) do
    ChefSpec::ServerRunner.new(platform: 'centos', version: '5.11').converge('fail2ban::default')
  end

  it 'converges successfully' do
    expect { :chef_run }.to_not raise_error
  end
end

describe 'default recipe on CentOS 6' do
  let(:chef_run) do
    ChefSpec::ServerRunner.new(platform: 'centos', version: '6.6').converge('fail2ban::default')
  end

  it 'converges successfully' do
    expect { :chef_run }.to_not raise_error
  end
end

describe 'default recipe on CentOS 7' do
  let(:chef_run) do
    ChefSpec::ServerRunner.new(platform: 'centos', version: '7.1').converge('fail2ban::default')
  end

  it 'converges successfully' do
    expect { :chef_run }.to_not raise_error
  end
end


text:
<?php

namespace Tests\Hum2\BingApi\Module;

use BEAR\Resource\Code;
use Hum2\BingApi\Module\AccessTokenInterceptor;
use Ray\Aop\Arguments;
use Ray\Aop\ReflectiveMethodInvocation;
use Tests\Hum2\BingApi\Fake\FakeAccessTokenClient;
use Tests\Hum2\BingApi\Fake\FakeResource;

class AccessTokenInterceptorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AccessTokenInterceptor
     */
    private $accessTokenInterceptor;

    public function setup()
    {
        $client                       = new FakeAccessTokenClient();
        $this->accessTokenInterceptor = new AccessTokenInterceptor(
            $GLOBALS['azure_client_id'], $GLOBALS['azure_client_secret']);
        $this->accessTokenInterceptor->setClient($client);
    }

    /**
     * @param       $mock
     * @param array $server
     *
     * @return ReflectiveMethodInvocation
     */
    private function getInvocation($mock, array $server)
    {
        return new ReflectiveMethodInvocation(
            $mock,
            new \ReflectionMethod($mock, 'onGet'),
            new Arguments($server),
            [$this->accessTokenInterceptor]
        );
    }

    public function testAccessTokenResponse()
    {
        $method = new \ReflectionMethod($this->accessTokenInterceptor, 'getAccessTokenResponse');
        $method->setAccessible(true);
        $response = $method->invoke($this->accessTokenInterceptor);

        $this->assertEquals(600, $response['expires_in']);
        $this->assertEquals('hogehoge', $response['access_token']);
    }

    public function testProceedCode()
    {
        $mock       = new FakeResource();
        $invocation = $this->getInvocation($mock, []);
        /* @var $result FakeResource */
        $result = $invocation->proceed();
        $this->assertEquals(Code::OK, $result->code);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>
    <style name="Theme" parent="android:Theme">
        <item name="android:windowAnimationStyle">@style/Animation</item>
    </style>

    <style name="Animation">
        <item name="android:activityOpenEnterAnimation">@null</item>
        <item name="android:activityOpenExitAnimation">@null</item>
        <item name="android:activityCloseEnterAnimation">@null</item>
        <item name="android:activityCloseExitAnimation">@null</item>
        <item name="android:taskOpenEnterAnimation">@null</item>
        <item name="android:taskOpenExitAnimation">@null</item>
        <item name="android:taskCloseEnterAnimation">@null</item>
        <item name="android:taskCloseExitAnimation">@null</item>
        <item name="android:taskToFrontEnterAnimation">@null</item>
        <item name="android:taskToFrontExitAnimation">@null</item>
        <item name="android:taskToBackEnterAnimation">@null</item>
        <item name="android:taskToBackExitAnimation">@null</item>
    </style>
</resources>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-2-22.js
 * @description String.prototype.trim - argument 'this' is a number that converts to a string (value is 1e-6)
 */

function testcase() {
        return String.prototype.trim.call(1e-6) === "0.000001";
    }
runTestCase(testcase);


text:
#ifndef UTIL_H_
#define UTIL_H_

#include <vector>
#include "magic_types.h"

namespace magic_bean {

class Util {
 public:
  static int64_t GetMinimumSequence(const std::vector<SequencePtr>& sequences, int64_t minimum);
  static int Log2(int i);
};

} //end namespace

#endif //UTIL_H_


text:
<#

The function in this module determines the underlying system firmware (BIOS) type - either UEFI or Legacy BIOS.

The function can use one of three methods to determine the firmware type:

The first method relies on the fact that Windows setup detects the firmware type as a part of the Windows installation
routine and records its findings in the setupact.log file in the \Windows\Panther folder.  It's a trivial task to use
Select-String to extract the relevant line from this file and to pick off the (U)EFI or BIOS keyword it contains.

To do a proper job there are two choices; both involve using Win32 APIs which we call from PowerShell through a compiled
(Add-Type) class using P/Invoke.

For Windows 7/Server 2008R2 and above, the GetFirmwareEnvironmentVariable Win32 API (designed to extract firmware environment
variables) can be used.  This API is not supported on non-UEFI firmware and will fail in a predictable way when called - this
will identify a legacy BIOS.  On UEFI firmware, the API can be called with dummy parameters, and while it will still fail
(probably!) the resulting error code will be different from the legacy BIOS case.

For Windows 8/Server 2012 and above there's a more elegant solution in the form of the GetFirmwareType() API.  This
returns an enum (integer) indicating the underlying firmware type.

Chris Warwick, @cjwarwickps,  September 2013.   (This version, November 2015)
chrisjwarwick.wordpress.com

See all my PS Gallery modules:   Find-Module | Where Author -match 'Chris Warwick'

#>

#Requires -Version 2

#region Helper Functions

# The folowing function works on all Windows versions:

<#
.Synopsis
   Determines underlying firmware (BIOS) type and return an object describing the Firmware.
.DESCRIPTION
   This function seraches the windows Setup log file (setupact.log in the \Windows\Panther folder)
   to determine whether setup identified a UEFI environment or a legacy BIOS.
.EXAMPLE
   Get-LogFileFirmwareType  # Returns custom object describing firmware
.OUTPUTS
   'FirmwareType', object describing firmware type
.FUNCTIONALITY
   Determines underlying system firmware type
#>
Function Get-LogFileFirmwareType {
[OutputType('FirmwareType')]
Param()

    # Template object to return, modified below...
    $FirmwareType = [PsCustomObject]@{
        PsTypeName   = 'FirmwareType'
        IsUEFI       = $False
        IsBIOS       = $False
        Undetermined = $True
        FirmwareType = 'Undetermined'   # Set to 'BIOs' or 'UEFI' when found
    }

    # Extract the firmware type from the 'setupact.log' file - see what bios type was detected (EFI or BIOS) at install time

    $Panther = "$Env:windir\Panther\setupact.log"
    If (Test-Path -Path $Panther -PathType Leaf) {

        $FirmwareString = (Select-String 'Detected boot environment:' $Panther -AllMatches ).Line -replace '.*:\s+'

        Switch -Regex ($FirmwareString) {

            '^BIOS$'  {$FirmwareType.IsBIOS = $True
                       $FirmwareType.Undetermined = $False
                       $FirmwareType.FirmwareType = 'BIOS'
                      }
            '^U?EFI$' {$FirmwareType.IsUEFI = $True
                       $FirmwareType.Undetermined = $False
                       $FirmwareType.FirmwareType = 'UEFI'
                      }
            Default   {Break}      # Can't determine f/w type, just return the 'Undetermined' object defined above
        }
    }

    $FirmwareType
}

<#
(Windows 7/Server 2008R2 or above)
Use the GetFirmwareEnvironmentVariable Win32 API.

From MSDN (http://msdn.microsoft.com/en-ca/library/windows/desktop/ms724325%28v=vs.85%29.aspx):

"Firmware variables are not supported on a legacy BIOS-based system. The GetFirmwareEnvironmentVariable function will
always fail on a legacy BIOS-based system, or if Windows was installed using legacy BIOS on a system that supports both
legacy BIOS and UEFI.

"To identify these conditions, call the function with a dummy firmware environment name such as an empty string ("") for
the lpName parameter and a dummy GUID such as "{00000000-0000-0000-0000-000000000000}" for the lpGuid parameter.
On a legacy BIOS-based system, or on a system that supports both legacy BIOS and UEFI where Windows was installed using
legacy BIOS, the function will fail with ERROR_INVALID_FUNCTION. On a UEFI-based system, the function will fail with
an error specific to the firmware, such as ERROR_NOACCESS, to indicate that the dummy GUID namespace does not exist."

From PowerShell, we can call the API via P/Invoke from a compiled C# class using Add-Type.  In Win32 any resulting
API error is retrieved using GetLastError(), however, this is not reliable in .Net (see
blogs.msdn.com/b/adam_nathan/archive/2003/04/25/56643.aspx), instead we mark the pInvoke signature for
GetFirmwareEnvironmentVariableA with SetLastError=true and use Marshal.GetLastWin32Error()

Note: The GetFirmwareEnvironmentVariable API requires the SE_SYSTEM_ENVIRONMENT_NAME privilege.  In the Security
Policy editor this equates to "User Rights Assignment": "Modify firmware environment values" and is granted to
Administrators by default.  Because we don't actually read any variables this permission appears to be optional.

#>

<#
.Synopsis
   Determines underlying firmware (BIOS) type and return an object describing the Firmware.
.DESCRIPTION
   This function uses a complied Win32 API call to determine the underlying system firmware type.
.EXAMPLE
   Get-FirmwareEnvironmentVariableAPI  # Returns custom object describing firmware
.OUTPUTS
   'FirmwareType', object describing firmware type
.FUNCTIONALITY
   Determines underlying system firmware type
#>
Function Get-FirmwareEnvironmentVariableAPI {
[OutputType('FirmwareType')]
Param()

# Wrap the 'GetFirmwareEnvironmentVariableA' API...
Add-Type -Language CSharp -TypeDefinition @'

    using System;
    using System.Runtime.InteropServices;

    public class CheckUEFI
    {
        [DllImport("kernel32.dll", SetLastError=true)]
        static extern UInt32
        GetFirmwareEnvironmentVariableA(string lpName, string lpGuid, IntPtr pBuffer, UInt32 nSize);

        const int ERROR_INVALID_FUNCTION = 1;

        public static bool IsUEFI()
        {
            // Try to call the GetFirmwareEnvironmentVariable API.  This is invalid on legacy BIOS.

            GetFirmwareEnvironmentVariableA("","{00000000-0000-0000-0000-000000000000}",IntPtr.Zero,0);

            if (Marshal.GetLastWin32Error() == ERROR_INVALID_FUNCTION)

                return false;     // API not supported (INVALID_FUNCTION); this is a legacy BIOS

            else

                return true;      // Call to API is supported.  This is UEFI.
        }
    }
'@

    # Call API and return result

    If ([CheckUEFI]::IsUEFI()) {
        [PsCustomObject]@{
            PsTypeName   = 'FirmwareType'
            IsUEFI       = $True
            IsBIOS       = $False
            Undetermined = $False
            FirmwareType = 'UEFI'
        }
    }
    else {
        [PsCustomObject]@{
            PsTypeName   = 'FirmwareType'
            IsUEFI       = $False
            IsBIOS       = $True
            Undetermined = $False
            FirmwareType = 'BIOS'
        }
    }
}

<#
(Windows 8/Server 2012 or above)

Use GetFirmwareTtype() Win32 API.

In Windows 8/Server 2012 and above there's an API that directly returns the firmware type and doesn't rely on a hack.
GetFirmwareType() in kernel32.dll (http://msdn.microsoft.com/en-us/windows/desktop/hh848321%28v=vs.85%29.aspx) returns
a pointer to a FirmwareType enum that defines the following:

typedef enum _FIRMWARE_TYPE {
  FirmwareTypeUnknown  = 0,
  FirmwareTypeBios     = 1,
  FirmwareTypeUefi     = 2,
  FirmwareTypeMax      = 3
} FIRMWARE_TYPE, *PFIRMWARE_TYPE;

Once again, this API call can be called in .Net via P/Invoke.

#>

<#
.Synopsis
   Determines underlying firmware (BIOS) type and return an object describing the Firmware.
.DESCRIPTION
   This function uses a complied Win32 API call to determine the underlying system firmware type.
.EXAMPLE
   Get-FirmwareEnvironmentVariableAPI  # Returns custom object describing firmware
.OUTPUTS
   'FirmwareType', object describing firmware type
.FUNCTIONALITY
   Determines underlying system firmware type
#>
Function Get-FirmwareTypeAPI {
[OutputType('FirmwareType')]
Param()

# Wrap the 'GetFirmwareType' API...
Add-Type -Language CSharp -TypeDefinition @'

    using System;
    using System.Runtime.InteropServices;

    public class FirmwareType
    {
        [DllImport("kernel32.dll")]
        static extern bool GetFirmwareType(ref uint FirmwareType);

        public static uint GetFirmwareType()
        {
            uint firmwaretype = 0;
            if (GetFirmwareType(ref firmwaretype))
                return firmwaretype;
            else
                return 0;   // API call failed, just return 'unknown'
        }
    }
'@

    # Template object, modified below...
    $FirmwareType = [PsCustomObject]@{
        PsTypeName   = 'FirmwareType'
        IsUEFI       = $False
        IsBIOS       = $False
        Undetermined = $True
        FirmwareType = 'Undetermined'   # Set to 'BIOs' or 'UEFI' when found
    }

    Switch ([FirmwareType]::GetFirmwareType()) {

        0 {Break}      # Can't determine f/w type, just return the 'Undetermined' object defined above
        1  {$FirmwareType.IsBIOS = $True
            $FirmwareType.Undetermined = $False
            $FirmwareType.FirmwareType = 'BIOS'
           }
        2  {$FirmwareType.IsUEFI = $True
            $FirmwareType.Undetermined = $False
            $FirmwareType.FirmwareType = 'UEFI'
           }
    }

    $FirmwareType
}

# Determine the version of the host OS
# Windows 7,   Server 2008R2  -> 6.1.x
# Windows 8,   Server 2012    -> 6.2.x
# Windows 8.1, Server 2012R2  -> 6.3.x
# Windows 10,  Server 2016    -> 10.0.x

Function Get-OSVersion {
[OutputType([System.Version])]
Param()
    [System.Version](Get-WmiObject -Query 'Select Version from WIN32_OperatingSystem').Version
}

#endregion Helper Functions

# -------------------------------------------------------------------------------------------------------

# The following function wraps the helper functions above.  If the 'QueryType' parameter isn't specified
# the function will determine the most appropriate technique based on the current OS version

<#
.Synopsis
    This cmdlet determines the underlying system firmware (BIOS) type - either UEFI or Legacy BIOS.
.Description
    This cmdlet determines the underlying system firmware (BIOS) type - either UEFI or Legacy BIOS.

    The function will use one of three methods to determine the firmware type:

    The first method relies on the fact that Windows setup detects the firmware type as a part of the Windows installation
    routine and records its findings in the setupact.log file in the \Windows\Panther folder.  It's a trivial task to use
    Select-String to extract the relevant line from this file and to pick off the (U)EFI or BIOS keyword it contains.

    To do a proper job there are two choices; both involve using Win32 APIs which we call from PowerShell through a compiled
    (Add-Type) class using P/Invoke.

    For Windows 7/Server 2008R2 and above, the GetFirmwareEnvironmentVariable Win32 API (designed to extract firmware environment
    variables) can be used.  This API is not supported on non-UEFI firmware and will fail in a predictable way when called - this
    will identify a legacy BIOS.  On UEFI firmware, the API can be called with dummy parameters, and while it will still fail
    (probably!) the resulting error code will be different from the legacy BIOS case.

    For Windows 8/Server 2012 and above there's a more elegant solution in the form of the GetFirmwareType() API.  This
    returns an enum (integer) indicating the underlying firmware type.
.Example
    Get-FirmwareType
    Determines the firmware type of the current machine using the most appropriate technique based on OS version
.Example
    Get-FirmwareType -Auto
    Determines the firmware type of the current machine using the most appropriate technique based on OS version
.Example
    Get-FirmwareType -SetupLog
    Determines the firmware type of the current machine by reading the Setup log file
.Example
    Get-FirmwareType -GetFirmwareType
    Determines the firmware type of the current machine by using the GetFirmwareType() API call. (Windows 8+ only)
.Inputs
    None
.Outputs
    ['FirmwareType'] PS Custom object describing the machine firmware type
.Parameter QueryType
    Use this parameter to force a particular query type (if not specified this will default to 'Auto')
    Valid values are:
     SetupLog - look for the machine firmware type in the Windows Setup log file
     GetFirmwareEnvironmentVariable - uses the GetFirmwareEnvironmentVariable Win32 API call (Windows 7/Server 208R2 and above)
     GetFirmwareType - uses the GetFirmwareType Win32 API call (Windows 8/Server 2012R2 and above)
     Auto - uses the most appropriate technique depending on the underlying OS version
.Notes
    Can only run against the local machine currently
.Functionality
    Determine the firmware type of the current machine
#>

Function Get-FirmwareType {
[CmdletBinding()]
[OutputType('FirmwareType')]
Param(
    [Parameter()]
    [ValidateSet(
        'SetupLog',
        'GetFirmwareEnvironmentVariable',
        'GetFirmwareType',
        'Auto'
    )]
    [String]$QueryType='Auto'
)

    # Convert the 'Auto' query type into one of the three supported types based on OS Version:

    If ($QueryType -eq 'Auto') {

        Switch (Get-OSVersion) {
            {$_ -ge [System.Version]'6.2.0.0'} {
                Write-Verbose "OS Version $OSVersion, Windows 8.0, Server 2012 or above -> Using GetFirmwareType() API."
                $QueryType = 'GetFirmwareType'
                Break
            }

            {$_ -ge [System.Version]'6.1.0.0'} {
                Write-Verbose "OS Version $OSVersion, Windows 7, Server 2008R2 or above -> Using GetFirmwareEnvironmentVariable() API."
                $QueryType = 'GetFirmwareEnvironmentVariable'
                Break
            }
            Default {
                Write-Verbose "OS Version $OSVersion, Windows Vista, Server 2008 or below -> Using $Env:windir\Panther\setupact.log file."
                $QueryType = 'SetupLog'
                Break
            }
        }
    }

    # Determine the Firmware type using the specified method...

    Switch ($QueryType) {

        GetFirmwareType {
            Get-FirmwareTypeAPI
        }

        GetFirmwareEnvironmentVariable {
            Get-FirmwareEnvironmentVariableAPI
        }

        SetupLog {
            Get-LogFileFirmwareType
        }
    }
}

# An electron is pulled-up for speeding. The policeman says, "Sir, do you realise you were travelling at 130mph?" The electron says, "Oh great, now I'm lost."


text:
package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"unicode/utf8"

	"github.com/nsf/termbox-go"
	tb "github.com/tkyjhr/go-termboxutil"
)

type commandEntry struct {
	Title       string
	Description string
	Command     string
	Args        []string
}

func (ce *commandEntry) Run() error {
	runningCmd = exec.Command(ce.Command, ce.Args...)
	runningCmd.Stdout = os.Stdout
	runningCmd.Stderr = os.Stderr
	runningCmd.Stdin = os.Stdin // 入力が必要な項目の実行は未検証。
	if err := runningCmd.Run(); err != nil {
		return err
	}
	runningCmd = nil
	return nil
}

// cursorPos は文字の位置。バイト位置ではない。
func tryInsertChar(str string, ch rune, cursorPos, maxLen int) (string, int) {
	r := []rune(str)
	strLen := len(r)
	if strLen >= maxLen {
		return str, cursorPos
	}
	if cursorPos == strLen {
		return str + string(ch), cursorPos + 1
	}
	return string(r[:cursorPos]) + string(ch) + string(r[cursorPos:]), cursorPos + 1
}

// cursorPos は文字の位置。バイト位置ではない。
func processBackspace(str string, cursorPos int) (string, int) {
	r := []rune(str)
	strLen := len(r)
	if strLen == 0 || cursorPos == 0 {
		return str, cursorPos
	}
	if cursorPos == strLen {
		return string(r[:strLen-1]), cursorPos - 1
	}
	return string(r[:cursorPos-1]) + string(r[cursorPos:]), cursorPos - 1
}

// cursorPos は文字の位置。バイト位置ではない。
func processDelete(str string, cursorPos int) (string, int) {
	r := []rune(str)
	strLen := len(r)
	if strLen == 0 || cursorPos == strLen {
		return str, cursorPos
	}
	if cursorPos == 0 {
		return string(r[1:]), cursorPos
	}
	return string(r[:cursorPos]) + string(r[cursorPos+1:]), cursorPos
}

func containsAll(s string, substrs []string, ignoreCase bool) bool {
	if ignoreCase {
		s = strings.ToLower(s)
		for i := range substrs {
			substrs[i] = strings.ToLower(substrs[i])
		}
	}
	for _, sub := range substrs {
		if !strings.Contains(s, sub) {
			return false
		}
	}
	return true
}

func clampedIndex(index, arrayLength int) int {
	if arrayLength == 0 {
		return 0
	}

	if index < 0 {
		return 0
	} else if index >= arrayLength {
		return arrayLength - 1
	} else {
		return index
	}
}

func tryExecuteCommand(commandList []commandEntry, selectedIndex int) (bool, error) {
	if selectedIndex >= len(commandList) {
		return false, nil
	}
	// コマンドプロンプトへの出力を取り戻すため termbox を閉じてからコマンドを実行する
	termbox.Close()
	c := commandList[selectedIndex]
	if err := c.Run(); err != nil {
		return true, err
	}
	return true, nil
}

func processCursorMoveKeyForOneLineTextBox(key termbox.Key, currentCursorPos int, text string) int {
	textLen := utf8.RuneCountInString(text)
	switch key {
	case termbox.KeyArrowLeft:
		if currentCursorPos > 0 {
			return currentCursorPos - 1
		}
		return currentCursorPos
	case termbox.KeyArrowRight:
		if currentCursorPos < textLen {
			return currentCursorPos + 1
		}
		return currentCursorPos
	case termbox.KeyHome:
		return 0
	case termbox.KeyEnd:
		return textLen
	}
	return currentCursorPos
}

// 0~9, 10~19 という単位のページでカーソルを移動させる
func processArrowKeyInputForCommandListControl(key termbox.Key, currentSelectedIndex, selectionNum int) int {
	switch key {
	case termbox.KeyArrowUp:
		if currentSelectedIndex%10 == 0 {
			return currentSelectedIndex + 9
		}
		return currentSelectedIndex - 1
	case termbox.KeyArrowDown:
		if currentSelectedIndex%10 == 9 {
			return currentSelectedIndex - 9
		} else if currentSelectedIndex == selectionNum-1 {
			return (currentSelectedIndex / 10) * 10
		}
		return currentSelectedIndex + 1
	case termbox.KeyArrowLeft:
		// 前のページが存在するかの判定
		if currentSelectedIndex >= 10 {
			return currentSelectedIndex - 10
		}
		// 前のページが存在しない場合は最後のページに飛ぶ
		return (selectionNum/10)*10 + (currentSelectedIndex % 10)
	case termbox.KeyArrowRight:
		// 次のページが存在するかの判定
		if (currentSelectedIndex / 10) < (selectionNum / 10) {
			return currentSelectedIndex + 10
		}
		// 次のページがない場合は先頭のページに飛ぶ
		return currentSelectedIndex % 10
	default:
		return currentSelectedIndex
	}
}

func getBookSize() (int, int) {
	const minBookWidth = 50
	w, _ := termbox.Size()
	if w < minBookWidth {
		w = minBookWidth
	}
	h := 3 + 10 + 1 + 1 + 1 // 3 for top tabs, 10 for commands, 1 for space, 1 for page number, 1 for bottom line
	return w, h
}

func drawBookOutline() (int, int) {
	width, height := getBookSize()
	// 外枠の描画。幅、高さは枠を含んでの値なので、位置や長さは -1。
	tb.DrawVerticalLine(0, 0, height-1)         // 左端の垂直線
	tb.DrawVerticalLine(width-1, 0, height-1)   // 右端の垂直線
	tb.DrawHorizontalLine(0, 0, width-1)        // 上の水平線
	tb.DrawHorizontalLine(height-1, 0, width-1) // 下の水平線

	tb.DrawHorizontalLine(2, 0, width-1) // タブリスト/検索ボックス下の水平線

	return width, height
}

func drawHelpText(bookHeight int, help string, helpTexts ...string) {
	tb.DrawDefaultString(2, bookHeight+1, help)
	for i, help := range helpTexts {
		tb.DrawDefaultString(2, bookHeight+2+i, help)
	}
}

func drawCommandList(bookWidth, bookHeight, commandLength int, commandList []commandEntry, selectedCommand int) {
	CursorX := 2
	CommandTop := 3
	commandNum := len(commandList)
	page := selectedCommand / 10
	for i := 0; i < 10; i++ {
		index := (i + page*10)
		if index >= commandNum {
			break
		}
		// 表示上の index は、キーボードで選択した時に左にあるキーが上、という対応をつけるため 1, 2, 3, ..., 9, 0 と並べる。
		tb.DrawWrappedDefaultString(CursorX+2, CommandTop+i, commandLength, 1, fmt.Sprintf("[%d] %s", (i+1)%10, commandList[index].Title))
	}
	tb.DrawDefaultString(CursorX, CommandTop+selectedCommand%10, ">")

	var footer string
	if commandNum/10 >= 1 {
		footer = fmt.Sprintf("<- %d/%d ->", page+1, commandNum/10+1)
	} else {
		footer = fmt.Sprintf("%d/%d", page+1, commandNum/10+1)
	}

	tb.DrawDefaultString(commandLength+4-len(footer), bookHeight-2, footer)

	// コマンドリスト(左)と説明文(右)の境目の垂直線
	tb.DrawVerticalLine(commandLength+4+1, CommandTop, bookHeight-2)

	// 選択中のコマンドの説明の描画
	x := commandLength + 4 + 3 // 4 for left line + cursor, 3 for separator in the middle.
	cmd := commandList[selectedCommand]
	tb.DrawDefaultString(x, CommandTop, "<Description>")
	tb.DrawWrappedDefaultString(x, CommandTop+1, bookWidth-x-2, 4, cmd.Description)
	tb.DrawDefaultString(x, CommandTop+5, "<Command>")
	tb.DrawWrappedDefaultString(x, CommandTop+6, bookWidth-x-2, bookHeight-(CommandTop+6+1), fmt.Sprint(cmd.Command, " ", cmd.Args))
}


text:
package com.opengamma.provider.historicaltimeseries.impl;

import static org.testng.Assert.assertEquals;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.testng.annotations.Test;
import org.threeten.bp.LocalDate;

import com.opengamma.id.ExternalIdBundle;
import com.opengamma.provider.historicaltimeseries.HistoricalTimeSeriesProvider;
import com.opengamma.provider.historicaltimeseries.HistoricalTimeSeriesProviderGetRequest;
import com.opengamma.provider.historicaltimeseries.HistoricalTimeSeriesProviderGetResult;
import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.LocalDateRange;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;

/**
 * Tests for {@link DelegatingHistoricalTimeSeriesProvider}.
 */
@Test(groups = TestGroup.UNIT)
public class DelegatingHistoricalTimeSeriesProviderTest {
  private static final String SOURCE_1 = "source1";
  private static final String SOURCE_2 = "source2";
  private static final LocalDateDoubleTimeSeries TS_1 = ImmutableLocalDateDoubleTimeSeries.of(LocalDate.of(2019, 1, 1), 100);
  private static final LocalDateDoubleTimeSeries TS_2 = ImmutableLocalDateDoubleTimeSeries.of(LocalDate.of(2019, 1, 1), 200);
  private static final DelegatingHistoricalTimeSeriesProvider PROVIDER;
  static {
    final Map<String, HistoricalTimeSeriesProvider> map = new HashMap<>();
    map.put(SOURCE_1, new TestHistoricalTimeSeriesProvider(SOURCE_1, TS_1));
    map.put(SOURCE_2, new TestHistoricalTimeSeriesProvider(SOURCE_2, TS_2));
    PROVIDER = new DelegatingHistoricalTimeSeriesProvider(map);
  }

  /**
   * Tests that the providers map cannot be null.
   */
  @Test(expectedExceptions = NullPointerException.class)
  public void testNullProviders() {
    new DelegatingHistoricalTimeSeriesProvider(null);
  }

  /**
   * Tests toString.
   */
  public void testToString() {
    if (PROVIDER.toString().contains("source1, ")) {
      assertEquals(PROVIDER.toString(), "DelegatingHistoricalTimeSeriesProvider[source1, source2]");
    } else {
      assertEquals(PROVIDER.toString(), "DelegatingHistoricalTimeSeriesProvider[source2, source1]");
    }
  }

  /**
   * Tests the behaviour when there is no delegate for a data source.
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNoDelegate() {
    final HistoricalTimeSeriesProviderGetRequest request = HistoricalTimeSeriesProviderGetRequest.createGet(ExternalIdBundle.of("eid", "1"), "source3",
        "provider", "field");
    PROVIDER.doBulkGet(request);
  }

  /**
   * Tests that the correct delegate is selected.
   */
  public void testDelegation() {
    final ExternalIdBundle eid = ExternalIdBundle.of("eid", "1");
    final HistoricalTimeSeriesProviderGetRequest request = HistoricalTimeSeriesProviderGetRequest.createGet(eid, SOURCE_1, "provider", "field");
    assertEquals(PROVIDER.doBulkGet(request).getResultMap().get(eid), TS_1);
    request.setDataSource(SOURCE_2);
    assertEquals(PROVIDER.doBulkGet(request).getResultMap().get(eid), TS_2);
  }

  private static class TestHistoricalTimeSeriesProvider implements HistoricalTimeSeriesProvider {
    private final String _dataSource;
    private final LocalDateDoubleTimeSeries _ts;

    public TestHistoricalTimeSeriesProvider(final String dataSource, final LocalDateDoubleTimeSeries ts) {
      _dataSource = dataSource;
      _ts = ts;
    }

    @Override
    public LocalDateDoubleTimeSeries getHistoricalTimeSeries(final ExternalIdBundle externalIdBundle, final String dataSource, final String dataProvider,
        final String dataField) {
      if (dataSource.equals(_dataSource)) {
        return _ts;
      }
      throw new UnsupportedOperationException();
    }

    @Override
    public LocalDateDoubleTimeSeries getHistoricalTimeSeries(final ExternalIdBundle externalIdBundle, final String dataSource, final String dataProvider,
        final String dataField, final LocalDateRange dateRange) {
      if (dataSource.equals(_dataSource)) {
        return _ts;
      }
      throw new UnsupportedOperationException();
    }

    @Override
    public Pair<LocalDate, Double> getLatestDataPoint(final ExternalIdBundle externalIdBundle, final String dataSource, final String dataProvider,
        final String dataField) {
      if (dataSource.equals(_dataSource)) {
        return Pairs.of(_ts.getLatestTime(), _ts.getLatestValue());
      }
      throw new UnsupportedOperationException();
    }

    @Override
    public Map<ExternalIdBundle, LocalDateDoubleTimeSeries> getHistoricalTimeSeries(final Set<ExternalIdBundle> externalIdBundleSet, final String dataSource,
        final String dataProvider, final String dataField, final LocalDateRange dateRange) {
      if (dataSource.equals(_dataSource)) {
        return Collections.singletonMap(externalIdBundleSet.iterator().next(), _ts);
      }
      throw new UnsupportedOperationException();
    }

    @Override
    public HistoricalTimeSeriesProviderGetResult getHistoricalTimeSeries(final HistoricalTimeSeriesProviderGetRequest request) {
      return new HistoricalTimeSeriesProviderGetResult(getHistoricalTimeSeries(request.getExternalIdBundles(), request.getDataSource(),
          request.getDataProvider(), request.getDataField(), request.getDateRange()));
    }

  }
}


text:
/**
 * @fileoverview  Provide the room class.
 * @author scott@scottlininger.com (Scott Lininger)
 */

/**
 * Constructor for the room class, which stores everything we
 *   need to know about a LOZ dungeon room.
 * @param {number} roomX The roomX of the room in the grid.
 * @param {number} roomY The roomY of the room in the grid.
 * @constructor
 */
ace.Room = function(roomX, roomY) {
  var settings = settings || {};

  /**
   * The room's gridX position on the map.
   */
  this.x = roomX;

  /**
   * The room's gridY position on the map.
   */
  this.y = roomY;

	/**
	 * A boolean used by the game to differentiate this room from the
	 * overworld rooms that are constructed on the fly.
	 */
  this.isInUnderworld = true;

  /**
   * A collection of data structures, not of the spawned actors,
   * but describing what actors to spawn when the room is entered.
   */
  this.actors = [];

  /**
   * Any offset to the camera target to respect while inside this room.
   */
  this.cameraTargetOffset = [0,0,0];

  /**
   * Any offset to the camera eye to respect while inside this room.
   */
  this.cameraEyeOffset = [0,0,0];

  /**
   * Assume we're using that standard song.
   */
  this.song = 'underworld';

  /**
   * A collection of whether this room can be exited in various
   * directions.
   */
  this.exitByFacing = {};
  this.exitByFacing['left'] = ace.OPEN;
  this.exitByFacing['right'] = ace.OPEN;
  this.exitByFacing['up'] = ace.OPEN;
  this.exitByFacing['down'] = ace.OPEN;

};

/**
 * Adds an actor record to our collection.
 * @param {string} The type string of the actor, like 'Hurler'.
 * @param {Object} settings
 */
ace.Room.prototype.addActor = function(type, x, y, settings) {
  var actor = {};
  actor.type = type;
  actor.x = x;
  actor.y = y;
  actor.settings = settings || {};
  this.actors.push(actor);
};

/**
 * Stores a string that represents a series of walkable spots in
 * a room. Useful for underworld maps with mazes.
 * @param {string} walkMapString The
 */
ace.Room.prototype.addWalkMap = function(walkMap) {
  this.walkMap_ = walkMap;
};

/**
 * Gets a tile record at a given worldX and worldY position.
 * @param {number} worldX The x position.
 * @param {number} worldY The y position.
 */
ace.Room.prototype.getTileAt = function(worldX, worldY) {
  var tile = {
		'id': ace.tileIdsByName['ow_ground'],
		'name': 'ow_ground',
		'isWalkable': true,
		'walkSpeedFactor': 1
	};

  if (!this.walkMap_) {
    return tile;
  }

  var floorX = worldX - this.x * ace.UNDERWORLD_ROOM_PIXEL_WIDTH - 32;
  var floorY = worldY - this.y * ace.UNDERWORLD_ROOM_PIXEL_HEIGHT - 32;
  var tileX = Math.floor(floorX / 16);
  var tileY = Math.floor(floorY / 16);
  if (tileX < 0 || tileX > 11 || tileY < 0 || tileY > 6) {
    return tile;
  }
  var c = this.walkMap_.substr((6 - tileY) * 12 + tileX, 1);
  if (c == ' ') {
    tile.id = ace.tileIdsByName['ow_rock_br'];
    tile.name = 'ow_rock_br';
    tile.isWalkable = false;
    return tile;
  }
  return tile;
};


text:
<?php

// Start of hash v.1.0

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Generate a hash value (message digest)
 * @link http://php.net/manual/en/function.hash.php
 * @param string $algo

 * Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)
 *

 * @param string $data

 * Message to be hashed.
 *

 * @param bool $raw_output [optional]

 * When set to TRUE, outputs raw binary data.
 * FALSE outputs lowercase hexits.
 *

 * @return string a string containing the calculated message digest as lowercase hexits
 * unless raw_output is set to true in which case the raw
 * binary representation of the message digest is returned.
 * @jms-builtin
 */
function hash ($algo, $data, $raw_output = false) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Generate a hash value using the contents of a given file
 * @link http://php.net/manual/en/function.hash-file.php
 * @param string $algo

 * Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)
 *

 * @param string $filename

 * URL describing location of file to be hashed; Supports fopen wrappers.
 *

 * @param bool $raw_output [optional]

 * When set to TRUE, outputs raw binary data.
 * FALSE outputs lowercase hexits.
 *

 * @return string a string containing the calculated message digest as lowercase hexits
 * unless raw_output is set to true in which case the raw
 * binary representation of the message digest is returned.
 * @jms-builtin
 */
function hash_file ($algo, $filename, $raw_output = false) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Generate a keyed hash value using the HMAC method
 * @link http://php.net/manual/en/function.hash-hmac.php
 * @param string $algo

 * Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos for a list of supported algorithms.
 *

 * @param string $data

 * Message to be hashed.
 *

 * @param string $key

 * Shared secret key used for generating the HMAC variant of the message digest.
 *

 * @param bool $raw_output [optional]

 * When set to TRUE, outputs raw binary data.
 * FALSE outputs lowercase hexits.
 *

 * @return string a string containing the calculated message digest as lowercase hexits
 * unless raw_output is set to true in which case the raw
 * binary representation of the message digest is returned.
 * @jms-builtin
 */
function hash_hmac ($algo, $data, $key, $raw_output = false) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Generate a keyed hash value using the HMAC method and the contents of a given file
 * @link http://php.net/manual/en/function.hash-hmac-file.php
 * @param string $algo

 * Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos for a list of supported algorithms.
 *

 * @param string $filename

 * URL describing location of file to be hashed; Supports fopen wrappers.
 *

 * @param string $key

 * Shared secret key used for generating the HMAC variant of the message digest.
 *

 * @param bool $raw_output [optional]

 * When set to TRUE, outputs raw binary data.
 * FALSE outputs lowercase hexits.
 *

 * @return string a string containing the calculated message digest as lowercase hexits
 * unless raw_output is set to true in which case the raw
 * binary representation of the message digest is returned.
 * @jms-builtin
 */
function hash_hmac_file ($algo, $filename, $key, $raw_output = false) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Initialize an incremental hashing context
 * @link http://php.net/manual/en/function.hash-init.php
 * @param string $algo

 * Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)
 *

 * @param int $options [optional]

 * Optional settings for hash generation, currently supports only one option:
 * HASH_HMAC. When specified, the key
 * must be specified.
 *

 * @param string $key [optional]

 * When HASH_HMAC is specified for options,
 * a shared secret key to be used with the HMAC hashing method must be supplied in this
 * parameter.
 *

 * @return resource a Hashing Context resource for use with hash_update,
 * hash_update_stream, hash_update_file,
 * and hash_final.
 * @jms-builtin
 */
function hash_init ($algo, $options = 0, $key = null) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Pump data into an active hashing context
 * @link http://php.net/manual/en/function.hash-update.php
 * @param resource $context

 * Hashing context returned by hash_init.
 *

 * @param string $data

 * Message to be included in the hash digest.
 *

 * @return bool TRUE.
 * @jms-builtin
 */
function hash_update ($context, $data) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Pump data into an active hashing context from an open stream
 * @link http://php.net/manual/en/function.hash-update-stream.php
 * @param resource $context

 * Hashing context returned by hash_init.
 *

 * @param resource $handle

 * Open file handle as returned by any stream creation function.
 *

 * @param int $length [optional]

 * Maximum number of characters to copy from handle
 * into the hashing context.
 *

 * @return int Actual number of bytes added to the hashing context from handle.
 * @jms-builtin
 */
function hash_update_stream ($context, $handle, $length = -1) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Pump data into an active hashing context from a file
 * @link http://php.net/manual/en/function.hash-update-file.php
 * @param resource $context

 * Stream context as returned by stream_context_create.
 *

 * @param string $filename

 * URL describing location of file to be hashed; Supports fopen wrappers.
 *

 * @param resource $context [optional]
 * @return bool TRUE on success or FALSE on failure.
 * @jms-builtin
 */
function hash_update_file ($context, $filename, $context = null) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Finalize an incremental hash and return resulting digest
 * @link http://php.net/manual/en/function.hash-final.php
 * @param resource $context

 * Hashing context returned by hash_init.
 *

 * @param bool $raw_output [optional]

 * When set to TRUE, outputs raw binary data.
 * FALSE outputs lowercase hexits.
 *

 * @return string a string containing the calculated message digest as lowercase hexits
 * unless raw_output is set to true in which case the raw
 * binary representation of the message digest is returned.
 * @jms-builtin
 */
function hash_final ($context, $raw_output = false) {}

/**
 * (PHP 5 >= 5.3.0)

 * Copy hashing context
 * @link http://php.net/manual/en/function.hash-copy.php
 * @param resource $context

 * Hashing context returned by hash_init.
 *

 * @return resource a copy of Hashing Context resource.
 * @jms-builtin
 */
function hash_copy ($context) {}

/**
 * (PHP 5 >= 5.1.2, PECL hash >= 1.1)

 * Return a list of registered hashing algorithms
 * @link http://php.net/manual/en/function.hash-algos.php
 * @return array a numerically indexed array containing the list of supported
 * hashing algorithms.
 * @jms-builtin
 */
function hash_algos () {}

/**
 * (PHP 4 >= 4.0.4, PHP 5)

 * Generates a key
 * @link http://php.net/manual/en/function.mhash-keygen-s2k.php
 * @param int $hash

 * The hash ID used to create the key.
 * One of the MHASH_hashname constants.
 *

 * @param string $password

 * An user supplied password.
 *

 * @param string $salt

 * Must be different and random enough for every key you generate in
 * order to create different keys. Because salt
 * must be known when you check the keys, it is a good idea to append
 * the key to it. Salt has a fixed length of 8 bytes and will be padded
 * with zeros if you supply less bytes.
 *

 * @param int $bytes

 * The key length, in bytes.
 *

 * @return string the generated key as a string, or FALSE on error.
 * @jms-builtin
 */
function mhash_keygen_s2k ($hash, $password, $salt, $bytes) {}

/**
 * (PHP 4, PHP 5)

 * Gets the block size of the specified hash
 * @link http://php.net/manual/en/function.mhash-get-block-size.php
 * @param int $hash

 * The hash ID. One of the MHASH_hashname constants.
 *

 * @return int the size in bytes or FALSE, if the hash
 * does not exist.
 * @jms-builtin
 */
function mhash_get_block_size ($hash) {}

/**
 * (PHP 4, PHP 5)

 * Gets the name of the specified hash
 * @link http://php.net/manual/en/function.mhash-get-hash-name.php
 * @param int $hash

 * The hash ID. One of the MHASH_hashname constants.
 *

 * @return string the name of the hash or FALSE, if the hash does not exist.
 * @jms-builtin
 */
function mhash_get_hash_name ($hash) {}

/**
 * (PHP 4, PHP 5)

 * Gets the highest available hash ID
 * @link http://php.net/manual/en/function.mhash-count.php
 * @return int the highest available hash ID. Hashes are numbered from 0 to this
 * hash ID.
 * @jms-builtin
 */
function mhash_count () {}

/**
 * (PHP 4, PHP 5)

 * Computes hash
 * @link http://php.net/manual/en/function.mhash.php
 * @param int $hash

 * The hash ID. One of the MHASH_hashname constants.
 *

 * @param string $data

 * The user input, as a string.
 *

 * @param string $key [optional]

 * If specified, the function will return the resulting HMAC instead.
 * HMAC is keyed hashing for message authentication, or simply a message
 * digest that depends on the specified key. Not all algorithms
 * supported in mhash can be used in HMAC mode.
 *

 * @return string the resulting hash (also called digest) or HMAC as a string, or
 * FALSE on error.
 * @jms-builtin
 */
function mhash ($hash, $data, $key = null) {}

/**
 * Optional flag for hash_init.
 * Indicates that the HMAC digest-keying algorithm should be
 * applied to the current hashing context.
 * @link http://php.net/manual/en/hash.constants.php
 */
define ('HASH_HMAC', 1);
define ('MHASH_CRC32', 0);
define ('MHASH_MD5', 1);
define ('MHASH_SHA1', 2);
define ('MHASH_HAVAL256', 3);
define ('MHASH_RIPEMD160', 5);
define ('MHASH_TIGER', 7);
define ('MHASH_GOST', 8);
define ('MHASH_CRC32B', 9);
define ('MHASH_HAVAL224', 10);
define ('MHASH_HAVAL192', 11);
define ('MHASH_HAVAL160', 12);
define ('MHASH_HAVAL128', 13);
define ('MHASH_TIGER128', 14);
define ('MHASH_TIGER160', 15);
define ('MHASH_MD4', 16);
define ('MHASH_SHA256', 17);
define ('MHASH_ADLER32', 18);
define ('MHASH_SHA224', 19);
define ('MHASH_SHA512', 20);
define ('MHASH_SHA384', 21);
define ('MHASH_WHIRLPOOL', 22);
define ('MHASH_RIPEMD128', 23);
define ('MHASH_RIPEMD256', 24);
define ('MHASH_RIPEMD320', 25);
define ('MHASH_SNEFRU256', 27);
define ('MHASH_MD2', 28);
define ('MHASH_FNV132', 29);
define ('MHASH_FNV1A32', 30);
define ('MHASH_FNV164', 31);
define ('MHASH_FNV1A64', 32);
define ('MHASH_JOAAT', 33);

// End of hash v.1.0
?>