text:
"""A utility script to perform code coverage analysis."""
import glob
import logging
import optparse
import os
import shutil
import subprocess
import sys
import tempfile

# The list of DLLs we want to instrument in addition to _unittests executables.
_DLLS_TO_INSTRUMENT = [
    'basic_block_entry_client.dll',
    'call_trace_client.dll',
    'coverage_client.dll',
    'kasko.dll',
    'profile_client.dll',
    'syzyasan_rtl.dll',
]

# The list of file patterns to copy to the staging/coverage area.
_FILE_PATTERNS_TO_COPY = [
    '*_harness.exe',
    '*_tests.exe',
    '*_unittests.exe',
    '*.dll',
    '*.pdb',
    'agent_logger.exe',
    'call_trace_service.exe',
    'test_data',
]

_SYZYGY_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

# This is hardcoded to the Visual Studio default install location.
_PERF_TOOLS_DIR = ('C:/Program Files (x86)/Microsoft Visual Studio 9.0/'
                   'Team Tools/Performance Tools')

_COVERAGE_ANALYZER_DIR = os.path.normpath(
    os.path.join(_SYZYGY_DIR, '../third_party/coverage_analyzer/bin'))

_LOGGER = logging.getLogger(os.path.basename(__file__))

def _Subprocess(command, failure_msg, **kw):
  _LOGGER.info('Executing command line %s.', command)
  ret = subprocess.call(command, **kw)
  if ret != 0:
    _LOGGER.error(failure_msg)
    raise RuntimeError(failure_msg)

class _ScopedTempDir(object):
  """A utility class for creating a scoped temporary directory."""
  def __init__(self):
    self._path = None

  def Create(self):
    self._path = tempfile.mkdtemp()

  def path(self):
    return self._path

  def __del__(self):
    if self._path:
      shutil.rmtree(self._path)

class _CodeCoverageRunnerBase(object):
  """A worker class to take care of running through instrumentation,
  profiling and coverage generation. This base class expects derived
  classes to implement the following (see class definition for details):

    _InstrumentOneFile(self, file_path)
    _StartCoverageCapture(self)
    _StopCoverageCapture(self)
    _ProcessCoverage(self, output_path)
  """

  _COVERAGE_FILE = 'unittests'

  def __init__(self, build_dir, keep_work_dir):
    build_dir = os.path.abspath(build_dir)
    self._build_dir = build_dir
    self._keep_work_dir = keep_work_dir
    self._work_dir = None
    self._html_dir = os.path.join(self._build_dir, 'cov')

  def __del__(self):
    self._CleanupWorkdir()

  def Run(self):
    """Performs the code coverage capture for all unittests."""
    self._CreateWorkdir()
    try:
      self._CaptureCoverage()
    finally:
      self._CleanupWorkdir()

  def _InstrumentOneFile(self, file_path):
    """Instruments the provided module for coverage, in place.

    Args:
      file_path: The path of the module to be instrumented.
    """
    raise NotImplementedError()

  def _StartCoverageCapture(self):
    """Starts the coverage capture process."""
    raise NotImplementedError()

  def _StopCoverageCapture(self):
    """Stops the coverage capture process."""
    raise NotImplementedError()

  def _ProcessCoverage(self, output_path):
    """Processes coverage results and produces an GCOV/LCOV formatted
    coverage results file in |output_path|.

    Args:
      output_path: The path of the output file to produce.
    """
    raise NotImplementedError()

  def _CreateWorkdir(self):
    assert(self._work_dir == None)
    # The work dir must be a sibling to build_dir, as unittests refer
    # to test data through relative paths from their own executable.
    work_parent = os.path.abspath(os.path.join(self._build_dir, '..'))
    self._work_dir = tempfile.mkdtemp(prefix='instr-', dir=work_parent)
    _LOGGER.info('Created working directory "%s".', self._work_dir)

  def _CleanupWorkdir(self):
    # Clean up our working directory if it still exists.
    work_dir = self._work_dir
    self._work_dir = None

    if not work_dir:
      return

    if self._keep_work_dir:
      _LOGGER.info('Keeping working directory "%s".', work_dir)
    else:
      _LOGGER.info('Removing working directory "%s".', work_dir)
      shutil.rmtree(work_dir, ignore_errors=True)

  def _InstrumentExecutables(self):
    build_dir = self._build_dir
    work_dir = self._work_dir
    _LOGGER.info('Build dir "%s".', build_dir)

    # Copy all unittest related files to work_dir.
    for pattern in _FILE_PATTERNS_TO_COPY:
      files = glob.glob(os.path.join(build_dir, pattern))
      for path in files:
        _LOGGER.info('Copying "%s" to "%s".', path, work_dir)
        if os.path.isdir(path):
          # If the source file is a directory, do a recursive copy.
          dst = os.path.join(work_dir, os.path.basename(path))
          shutil.copytree(path, dst)
        else:
          shutil.copy(path, work_dir)

    # Instrument all EXEs in the work dir.
    for exe in glob.glob(os.path.join(work_dir, '*.exe')):
      self._InstrumentOneFile(exe)

    # And the DLLs we've specified.
    for dll in _DLLS_TO_INSTRUMENT:
      self._InstrumentOneFile(os.path.join(work_dir, dll))

  def _RunUnittests(self):
    unittests = (glob.glob(os.path.join(self._work_dir, '*_unittests.exe')) +
        glob.glob(os.path.join(self._work_dir, '*_tests.exe')))
    for unittest in unittests:
      _LOGGER.info('Running unittest "%s".', unittest)
      # Run single threaded, and with a 5 minute (in ms) timeout. This
      # conserves existing buildbot behaviour with the new sharded tests.
      _Subprocess([unittest,
                   '--single-process-tests',
                   '--test-launcher-timeout=300000'],
                  'Unittests "%s" failed.' % os.path.basename(unittest))

  def _GenerateHtml(self, input_path):
    croc = os.path.abspath(
        os.path.join(_SYZYGY_DIR, '../tools/code_coverage/croc.py'))
    config = os.path.join(_SYZYGY_DIR, 'build/syzygy.croc')

    # The HTML directory is already deleted. Create it now.
    os.makedirs(self._html_dir)

    cmd = [sys.executable, croc,
           '--tree',
           '--config', config,
           '--input', input_path,
           '--html', self._html_dir]

    # The coverage html generator wants to run in the directory
    # containing our src root.
    cwd = os.path.abspath(os.path.join(_SYZYGY_DIR, '../..'))
    _LOGGER.info('Generating HTML report')
    _Subprocess(cmd, 'Failed to generate HTML coverage report.', cwd=cwd)

  def _CaptureCoverage(self):
    # Clean up old coverage results. We do this immediately so that previous
    # coverage results won't still be around if this script fails.
    shutil.rmtree(self._html_dir, ignore_errors=True)

    self._InstrumentExecutables()
    self._StartCoverageCapture()
    try:
      self._RunUnittests()
    finally:
      self._StopCoverageCapture()

    output_path = os.path.join(self._work_dir,
                              '%s.coverage.lcov' % self._COVERAGE_FILE)
    self._ProcessCoverage(output_path)
    self._GenerateHtml(output_path)

class _CodeCoverageRunnerVS(_CodeCoverageRunnerBase):
  """Code coverage runner that uses the Microsoft Visual Studio Team Tools
  instrumenter.
  """

  def __init__(self, build_dir, perf_tools_dir, coverage_analyzer_dir,
               keep_work_dir):
    super(_CodeCoverageRunnerVS, self).__init__(build_dir, keep_work_dir)
    self._perf_tools_dir = os.path.abspath(perf_tools_dir)
    self._coverage_analyzer_dir = os.path.abspath(coverage_analyzer_dir)

  def _InstrumentOneFile(self, file_path):
    cmd = [os.path.join(self._perf_tools_dir, 'vsinstr.exe'),
           '/coverage',
           '/verbose',
           file_path]
    _LOGGER.info('Instrumenting "%s".', file_path)
    _Subprocess(cmd, 'Failed to instrument "%s"' % file_path)

  def _StartCoverageCapture(self):
    cmd = [os.path.join(self._perf_tools_dir, 'vsperfcmd.exe'),
           '/start:coverage',
           '/output:"%s"' % os.path.join(self._work_dir, self._COVERAGE_FILE)]
    _LOGGER.info('Starting coverage capture.')
    _Subprocess(cmd, 'Failed to start coverage capture.')

  def _StopCoverageCapture(self):
    cmd = [os.path.join(self._perf_tools_dir, 'vsperfcmd.exe'), '/shutdown']
    _LOGGER.info('Halting coverage capture.')
    _Subprocess(cmd, 'Failed to stop coverage capture.')

  def _ProcessCoverage(self, output_path):
    # The vsperf tool creates an output with suffix '.coverage'.
    input_path = os.path.join(self._work_dir,
                              '%s.coverage' % self._COVERAGE_FILE)

    # Coverage analyzer will go ahead and place its output in
    # input_file + '.lcov'.
    default_output_path = input_path + '.lcov'

    cmd = [os.path.join(self._coverage_analyzer_dir, 'coverage_analyzer.exe'),
           '-noxml', '-sym_path=%s' % self._work_dir,
           input_path]
    _LOGGER.info('Generating LCOV file.')
    _Subprocess(cmd, 'LCOV generation failed.')

    # Move the default output location if necessary.
    if default_output_path != output_path:
      shutil.move(default_output_path, output_path)

class _CodeCoverageRunnerSyzygy(_CodeCoverageRunnerBase):
  """Code coverage runner that uses the Syzygy code coverage client."""

  _SYZYCOVER = 'syzycover'

  def __init__(self, build_dir, keep_work_dir):
    super(_CodeCoverageRunnerSyzygy, self).__init__(build_dir, keep_work_dir)
    self._temp_dir = _ScopedTempDir()
    self._temp_dir.Create()

  def _InstrumentOneFile(self, file_path):
    temp_path = os.path.join(self._temp_dir.path(),
                             os.path.basename(file_path))
    shutil.copy(file_path, temp_path)
    cmd = [os.path.join(self._build_dir, 'instrument.exe'),
           '--mode=COVERAGE',
           '--agent=%s.dll' % self._SYZYCOVER,
           '--input-image=%s' % temp_path,
           '--output-image=%s' % file_path,
           '--no-augment-pdb',
           '--overwrite']
    _LOGGER.info('Instrumenting "%s".', file_path)
    _Subprocess(cmd, 'Failed to instrument "%s"' % file_path)

  def _StartCoverageCapture(self):
    # Grab a copy of the coverage client and place it in the work directory.
    # We give it a different name so that it doesn't conflict with the
    # instrumented coverage_client.dll.
    syzycover = os.path.abspath(os.path.join(
        self._work_dir, '%s.dll' % self._SYZYCOVER))
    shutil.copy(os.path.join(self._build_dir, 'coverage_client.dll'),
                syzycover)

    # Set up the environment so that the coverage client will connect to
    # the appropriate call trace client. Also make it so that it will crash if
    # the RPC connection is unable to be made.
    os.environ['SYZYGY_RPC_INSTANCE_ID'] = '%s,%s' % (syzycover,
                                                      self._SYZYCOVER)
    os.environ['SYZYGY_RPC_SESSION_MANDATORY'] = '%s,1' % (syzycover)

    # Start an instance of the call-trace service in the background.
    cmd = [os.path.join(self._build_dir, 'call_trace_service.exe'),
           'spawn',
           '--instance-id=%s' % self._SYZYCOVER,
           '--trace-dir=%s' % self._work_dir]
    _LOGGER.info('Starting coverage capture.')
    _Subprocess(cmd, 'Failed to start coverage capture.')

  def _StopCoverageCapture(self):
    cmd = [os.path.join(self._build_dir, 'call_trace_service.exe'),
           'stop',
           '--instance-id=%s' % self._SYZYCOVER]
    _LOGGER.info('Halting coverage capture.')
    _Subprocess(cmd, 'Failed to stop coverage capture.')

  def _ProcessCoverage(self, output_path):
    _LOGGER.info('Generating LCOV file.')
    cmd = [os.path.join(self._build_dir, 'grinder.exe'),
           '--mode=coverage',
           '--output-file=%s' % output_path,
           os.path.join(self._work_dir, 'trace-*.bin')]
    _Subprocess(cmd, 'LCOV generation failed.')

_USAGE = """\
%prog [options]

Generates a code coverage report for unittests in a given build directory.
On a successful run, the HTML report will be produced in a subdirectory
of the given build directory named "cov".
"""

def _ParseArguments():
  parser = optparse.OptionParser()
  parser.add_option('-v', '--verbose', dest='verbose',
                    action='store_true', default=False,
                    help='Enable verbose logging.')
  parser.add_option('--build-dir', dest='build_dir',
                    help='The directory where build output is placed.')
  parser.add_option('--target', dest='target',
                    help='The build profile for which coverage is being '
                         'generated. If not specified, default to None. '
                         'Will be appended to --build-dir to generate the '
                         'name of the directory containing the binaries '
                         'to analyze.')
  parser.add_option('--perf-tools-dir', dest='perf_tools_dir',
                    default=_PERF_TOOLS_DIR,
                    help='The directory where the VS performance tools, '
                         '"vsinstr.exe" and "vsperfcmd.exe" are found. '
                         'Ignored if --syzygy is specified.')
  parser.add_option('--coverage-analyzer-dir', dest='coverage_analyzer_dir',
                    default=_COVERAGE_ANALYZER_DIR,
                    help='The directory where "coverage_analyzer.exe" '
                         'is found. Ignored if --syzygy is specified.')
  parser.add_option('--keep-work-dir', action='store_true', default=False,
                    help='Keep temporary directory after run.')
  parser.add_option('--syzygy', action='store_true', default=False,
                    help='Use Syzygy coverage tools.')

  (opts, args) = parser.parse_args()
  if args:
    parser.error('This script does not accept any arguments.')

  if not opts.build_dir:
    parser.error('You must provide a build directory.')
  opts.build_dir = os.path.abspath(opts.build_dir)

  # If a target name was specified, then refine the build path with that.
  if opts.target:
    opts.build_dir = os.path.abspath(os.path.join(opts.build_dir, opts.target))
  if not os.path.isdir(opts.build_dir):
    parser.error('Path does not exist: %s' % opts.build_dir)

  if opts.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.ERROR)

  return opts

def main():
  opts = _ParseArguments()

  if opts.syzygy:
    runner = _CodeCoverageRunnerSyzygy(opts.build_dir,
                                       opts.keep_work_dir)
  else:
    runner = _CodeCoverageRunnerVS(opts.build_dir,
                                   opts.perf_tools_dir,
                                   opts.coverage_analyzer_dir,
                                   opts.keep_work_dir)

  runner.Run()

if __name__ == '__main__':
  sys.exit(main())


text:
## Whta's this?

"libdecodeqr" is a C/C++ library for docoding QR code, which based on JIS X 0510 and ISO/IEC18004.

This library is able to decode miscellaneous images those are taken with a file, with a webcam, with a scanner, and so on.

## Features

 * Supports miscellaneous image formats and input devices.
 * Hi-Speed decoding.
 * Completely Free.

## Requirements

 * g++ / VC++6
 * [OpenCV](http://www.sourceforge.net/projects/opencvlibrary/) 0.9.7 or later
 * Gtk2 for UN*X (required by OpenCV)

## Download

### Binary Release

Sorry, Not available yet.

### Latest Stable Source Code

 * version 0.9.3 http://trac.koka-in.org/libdecodeqr/attachment/wiki/WikiStart/libdecodeqr-0.9.3.tar.bz2

### Latest Development Source Code

We use Subversion for source revision control and code sharing.

	svn co svn://svn.koka-in.org/libdecodeqr/trunk

## How to use

### Build and Intstall

see BuildAndInstall for detail.

#### Windows

 1. open $(archive_dir)/src/libdecodeqr/libdecodeqr.dsw
 1. build the project (press [F7] key)

or

 1. start command prompt
 1. run VCVARS32.BAT
 1. nmake libdecodeqr.mak

The Libraly file and header files are NOT installed automaticaly.
After building, set places of decodeqr.h, qrtypes.h, qrerror.h and libdecodeqr.lib to your environments if you need.

#### UN*X

 1. $ cd $(archive_dir)/src/
 1. $ ./configure
 1. $ make
 1. $ sudo make install

### API Reference

see [ApiReference](https://github.com/chai2010/qrcode/blob/master/internal/libdecodeqr/doc/ApiReference.ja)

### Sample Codes

 * [latest simple usage](https://github.com/chai2010/qrcode/tree/master/internal/libdecodeqr/examples/simple/simpletest.cpp)
 * [latest with webcam](https://github.com/chai2010/qrcode/tree/master/internal/libdecodeqr/examples/webcam/webcam.cpp)

## How to Hack

see [HackingGuide](https://github.com/chai2010/qrcode/blob/master/internal/libdecodeqr/doc/HackingGuide.ja)

## Contact Us

### Web Page

http://trac.koka-in.org/libdecodeqr

### Mailing List

mailto:libdecodeqr@koka-in.org

To subscribe this list, please send the following phrase

	subscribe Your-Last-Name Your-First-Name

e.g.

	subscribe NISHI Takao

in the mail body (not subject) to the address <libdecodeqr-ctl@koka-in.org>.

## Copying

```
Copyright (c) 2007 NISHI Takao <zophos@koka-in.org>,
JMA (Japan Medical Association) and
!NaCl (Network Applied Communication Laboratory Ltd.) All rights reserved.[[BR]]
This is free software with ABSOLUTELY NO WARRANTY.

You can redistribute and/or modify it under the terms of LGPL.
```

redpajama_set_name: RedPajamaGithub


text:
@interface PinCodeChangeViewController : UIViewController

@end


text:
PKG_NAME = OctoPrint
PKG_VERS = 1.2.8
PKG_EXT = tar.gz
PKG_DIST_SITE = https://github.com/foosel/OctoPrint/archive
PKG_DIST_NAME = $(PKG_VERS).$(PKG_EXT)
PKG_DIST_FILE = $(PKG_NAME)-$(PKG_VERS).$(PKG_EXT)
PKG_DIR = $(PKG_NAME)-$(PKG_VERS)

DEPENDS =

HOMEPAGE = http://octoprint.org/
COMMENT  = OctoPrint is a so called host software for 3D printers that controls your 3D printer and sends it the actual commands to do its job.
LICENSE  = AGPLv3

CONFIGURE_TARGET = nop
COMPILE_TARGET = nop
INSTALL_TARGET = myInstall

include ../../mk/spksrc.cross-cc.mk

myInstall:
	mkdir -p $(STAGING_INSTALL_PREFIX)/share/OctoPrint
	tar -cf - -C $(WORK_DIR)/$(PKG_DIR) . | tar -xf - -C $(STAGING_INSTALL_PREFIX)/share/OctoPrint


text:
<?php

namespace Kdyby\RabbitMq;

/**
 * Marker interface for consumers. It's constants can be used for responding on messages.
 *
 * @author Alvaro Videla <videlalvaro@gmail.com>
 * @author Filip Procházka <filip@prochazka.su>
 */
interface IConsumer
{

	/**
	 * Flag for message ack
	 */
	const MSG_ACK = 1;

	/**
	 * Flag single for message nack and requeue
	 */
	const MSG_SINGLE_NACK_REQUEUE = 2;

	/**
	 * Flag for reject and requeue
	 */
	const MSG_REJECT_REQUEUE = 0;

	/**
	 * Flag for reject and drop
	 */
	const MSG_REJECT = -1;

}


text:
class PathSum {
public:
    bool hasPathSum(TreeNode *root, int sum);
};

#endif // PATH_SUM_HPP_


text:
var hierarchy =
[
    [ "charliesoft::AlgoPerformance", "classcharliesoft_1_1_algo_performance.html", null ],
    [ "charliesoft::Block", "classcharliesoft_1_1_block.html", [
      [ "charliesoft::SubBlock", "classcharliesoft_1_1_sub_block.html", [
        [ "charliesoft::ForBlock", "classcharliesoft_1_1_for_block.html", null ]
      ] ]
    ] ],
    [ "charliesoft::BlockLink", "structcharliesoft_1_1_block_link.html", null ],
    [ "charliesoft::ConditionOfRendering", "classcharliesoft_1_1_condition_of_rendering.html", null ],
    [ "charliesoft::ErrorValidator", "classcharliesoft_1_1_error_validator.html", null ],
    [ "charliesoft::GlobalConfig", "classcharliesoft_1_1_global_config.html", null ],
    [ "charliesoft::GraphOfProcess", "classcharliesoft_1_1_graph_of_process.html", null ],
    [ "charliesoft::Internationalizator", "classcharliesoft_1_1_internationalizator.html", null ],
    [ "charliesoft::Not_A_Value", "structcharliesoft_1_1_not___a___value.html", null ],
    [ "charliesoft::ParamDefinition", "structcharliesoft_1_1_param_definition.html", null ],
    [ "charliesoft::ParamValidator", "classcharliesoft_1_1_param_validator.html", [
      [ "charliesoft::FileIsFolder", "classcharliesoft_1_1_file_is_folder.html", null ],
      [ "charliesoft::ValExclusif", "classcharliesoft_1_1_val_exclusif.html", null ],
      [ "charliesoft::ValFileExist", "classcharliesoft_1_1_val_file_exist.html", null ],
      [ "charliesoft::ValNeeded", "classcharliesoft_1_1_val_needed.html", null ],
      [ "charliesoft::ValNegativ", "classcharliesoft_1_1_val_negativ.html", null ],
      [ "charliesoft::ValPositiv", "classcharliesoft_1_1_val_positiv.html", null ],
      [ "charliesoft::ValRange", "classcharliesoft_1_1_val_range.html", null ]
    ] ],
    [ "charliesoft::ProcessManager", "classcharliesoft_1_1_process_manager.html", null ],
    [ "QDialog", null, [
      [ "charliesoft::ConditionConfigurator", "classcharliesoft_1_1_condition_configurator.html", null ],
      [ "charliesoft::CreateParamWindow", "classcharliesoft_1_1_create_param_window.html", null ],
      [ "charliesoft::ParamsConfigurator", "classcharliesoft_1_1_params_configurator.html", null ],
      [ "MatrixViewer", "class_matrix_viewer.html", null ]
    ] ],
    [ "QGraphicsLineItem", null, [
      [ "charliesoft::LinkPath", "classcharliesoft_1_1_link_path.html", null ]
    ] ],
    [ "QGraphicsView", null, [
      [ "DefaultViewPort", "class_default_view_port.html", null ]
    ] ],
    [ "QLabel", null, [
      [ "charliesoft::LinkConnexionRepresentation", "classcharliesoft_1_1_link_connexion_representation.html", [
        [ "charliesoft::ConditionLinkRepresentation", "classcharliesoft_1_1_condition_link_representation.html", null ],
        [ "charliesoft::ParamRepresentation", "classcharliesoft_1_1_param_representation.html", null ],
        [ "charliesoft::SubGraphParamRepresentation", "classcharliesoft_1_1_sub_graph_param_representation.html", null ]
      ] ]
    ] ],
    [ "QLayout", null, [
      [ "charliesoft::GraphLayout", "classcharliesoft_1_1_graph_layout.html", null ]
    ] ],
    [ "QMainWindow", null, [
      [ "charliesoft::Window", "classcharliesoft_1_1_window.html", null ]
    ] ],
    [ "QObject", null, [
      [ "charliesoft::Converter", "classcharliesoft_1_1_converter.html", null ],
      [ "charliesoft::ParamValue", "classcharliesoft_1_1_param_value.html", null ],
      [ "GuiReceiver", "class_gui_receiver.html", null ]
    ] ],
    [ "QTreeWidget", null, [
      [ "charliesoft::DraggableContainer", "classcharliesoft_1_1_draggable_container.html", null ]
    ] ],
    [ "QWidget", null, [
      [ "charliesoft::AnyTypeWidget", "classcharliesoft_1_1_any_type_widget.html", null ],
      [ "charliesoft::GroupParamRepresentation", "classcharliesoft_1_1_group_param_representation.html", [
        [ "charliesoft::VertexRepresentation", "classcharliesoft_1_1_vertex_representation.html", null ]
      ] ],
      [ "charliesoft::ImageViewer", "classcharliesoft_1_1_image_viewer.html", null ],
      [ "charliesoft::MainVertexBlock", "classcharliesoft_1_1_main_vertex_block.html", null ],
      [ "charliesoft::MainWidget", "classcharliesoft_1_1_main_widget.html", [
        [ "charliesoft::MainWidget_SubGraph", "classcharliesoft_1_1_main_widget___sub_graph.html", [
          [ "charliesoft::MainWidget_ForGraph", "classcharliesoft_1_1_main_widget___for_graph.html", null ]
        ] ]
      ] ],
      [ "GraphViewer", "class_graph_viewer.html", null ],
      [ "ToolsWindow", "class_tools_window.html", null ]
    ] ],
    [ "QwtPlotZoomer", null, [
      [ "Zoomer", "class_zoomer.html", null ]
    ] ],
    [ "ViewPort", "class_view_port.html", [
      [ "DefaultViewPort", "class_default_view_port.html", null ]
    ] ]
];


text:
package gnu.java.net.protocol.ftp;

import java.io.IOException;
import java.io.OutputStream;

/**
 * A DTP output stream that implements the FTP stream transfer mode.
 *
 * @author Chris Burdess (dog@gnu.org)
 */
class StreamOutputStream
  extends DTPOutputStream
{

  StreamOutputStream(DTP dtp, OutputStream out)
  {
    super(dtp, out);
  }

  public void write(int c)
    throws IOException
  {
    if (transferComplete)
      {
        return;
      }
    out.write(c);
  }

  public void write(byte[] b)
    throws IOException
  {
    write(b, 0, b.length);
  }

  public void write(byte[] b, int off, int len)
    throws IOException
  {
    if (transferComplete)
      {
        return;
      }
    out.write(b, off, len);
  }

}


text:
namespace Rollbar
{
    using System;

    using Rollbar.Common;

    /// <summary>
    /// Interface IRollbarInfrastructureConfig
    /// Implements the <see cref="Rollbar.Common.IReconfigurable{T,TBase}" />
    /// Implements the <see cref="System.IEquatable{T}" />
    /// Implements the <see cref="Rollbar.ITraceable" />
    /// </summary>
    /// <seealso cref="Rollbar.Common.IReconfigurable{T,TBase}" />
    /// <seealso cref="System.IEquatable{T}" />
    /// <seealso cref="Rollbar.ITraceable" />
    public interface IRollbarInfrastructureConfig
        : IReconfigurable<IRollbarInfrastructureConfig, IRollbarInfrastructureConfig>
        , IEquatable<IRollbarInfrastructureConfig>
        , ITraceable
    {
        /// <summary>
        /// Gets the rollbar infrastructure options.
        /// </summary>
        /// <value>The rollbar infrastructure options.</value>
        IRollbarInfrastructureOptions RollbarInfrastructureOptions
        {
            get;
        }

        /// <summary>
        /// Gets the rollbar telemetry options.
        /// </summary>
        /// <value>The rollbar telemetry options.</value>
        IRollbarTelemetryOptions RollbarTelemetryOptions
        {
            get;
        }

        /// <summary>
        /// Gets the rollbar offline store options.
        /// </summary>
        /// <value>The rollbar offline store options.</value>
        IRollbarOfflineStoreOptions RollbarOfflineStoreOptions
        {
            get;
        }

        /// <summary>
        /// Gets the rollbar logger configuration.
        /// </summary>
        /// <value>The rollbar logger configuration.</value>
        IRollbarLoggerConfig RollbarLoggerConfig
        {
            get;
        }

    }
}


text:
#define DMA_BYTE_TRANSFER	1
#define DMA_WORD_TRANSFER	5

#define DEV_BYTE		0
#define DEV_WORD		1

#define DEV_INPUT		0
#define DEV_OUTPUT		1

#define DEV_AUTO_OFF		0
#define DEV_AUTO_ON		1

#define DEV_CLOCK_EXTERNAL	0
#define DEV_CLOCK_TIMER		1

#define DEV_INTER_DISABLE	-1
#define DEV_INTER_EXT_POS	0
#define DEV_INTER_EXT_NEG	1
#define DEV_INTER_TERMINAL	2
#define DEV_INTER_TIMER		3

#define DEV_CONFIG_NO_CHANGE	0
#define DEV_CONFIG_CHANGE	1

struct dev_rec {
	L_TOKEN	select;			/* hardware device selected */
	double	xtalSpeed;		/* crystal clock speed of timer */
	int	baseAddress;		/* 0x100 - 0x3F0 */
	int	dmaLevel;		/* 0-1, 3, 5-7 */
	int	interruptLevel;		/* 9-12, 15 */
	int	portMode;		/* 0=byte I/O, 1=word I/O */
	Word	numTransfers;		/* number of transfers in bytes or words */
	int	direction;		/* 0=input, 1=output */
	int	autoRecycle;		/* 0=off, 1=on */
	int	clockSource;		/* 0=external, 1=timer */
	Word	buffSeg;		/* transfer segment of D.M.A. buffer */
	Word	buffOff;		/* transfer offset  of D.M.A. buffer */
	Word	counter0;		/* 2 - 65535 */
	Word	counter1;		/* 2 - 65535 */
	double	frequency;		/* actual base rate in Hz */
	double	unitTime;		/* smallest time frame in uS */
	int	interruptSource;	/* -1=disable, 0=extern pos, 1=extern neg, 2=D.M.A. terminal, 3=timer */
	Word	aux[3];			/* auxiliary data bits */
	};

extern struct dev_rec	dev;

void	SemanticAction(Symbol *sym, char *mask, Q_TYPE qualify, long val);
void	SemanticDeviceBase(int adr);
void	SemanticDeviceClock(int source, long desired);
void	SemanticDeviceInterrupt(int source);
void	SemanticDeviceMode(int mode);
void	SemanticDeviceSelect(L_TOKEN select);
Symbol	*SemanticID(T_TYPE type);
void	SemanticState(Symbol *sym, char *mask);
void	SemanticText(Symbol *sym);


text:
layout: doc-page
title: "Type System"
---

The types are defined in [dotty/tools/dotc/core/Types.scala][1]

## Class diagram ##
- [PDF][2], generated with [a fork of scaladiagrams][3]

## Proxy types and ground types ##
A type which inherits `TypeProxy` is a proxy for another type accessible using
the `underlying` method, other types are called _ground_ types and inherit
`CachedGroundType` or `UncachedGroundType`.

Here's a diagram, copied from [dotty/tools/dotc/core/Types.scala][1]:

```
Type -+- ProxyType --+- NamedType ----+--- TypeRef
      |              |                 \
      |              +- SingletonType-+-+- TermRef
      |              |                |
      |              |                +--- ThisType
      |              |                +--- SuperType
      |              |                +--- ConstantType
      |              |                +--- TermParamRef
      |              |                +----RecThis
      |              |                +--- SkolemType
      |              +- TypeParamRef
      |              +- RefinedOrRecType -+-- RefinedType
      |              |                   -+-- RecType
      |              +- AppliedType
      |              +- TypeBounds
      |              +- ExprType
      |              +- AnnotatedType
      |              +- TypeVar
      |              +- HKTypeLambda
      |              +- MatchType
      |
      +- GroundType -+- AndType
                     +- OrType
                     +- MethodOrPoly ---+-- PolyType
                     |                  +-- MethodType
                     +- ClassInfo
                     |
                     +- NoType
                     +- NoPrefix
                     +- ErrorType
                     +- WildcardType

```

## Representations of types ##
 Type                      | Representation
 ------------------------- | -----------------------------
 `p.x.type`                | `TermRef(p, x)`
 `p#T`                     | `TypeRef(p, T)`
 `p.x.T` == `p.x.type#T`   | `TypeRef(TermRef(p, x), T)`
 `this.type`               | `ThisType`
 `A & B`                   | `AndType(A, B)`
 A \| B       | `OrType(A, B)`
 `=> T`                    | `ExprType(T)`
 `p { refinedName }`       | `RefinedType(p, refinedName)`
 type of the value `super` | `SuperType`
 `type T >: A <: B`        | `TypeRef` with underlying type `RealTypeBounds(A, B)`
 `type T = A`              | `TypeRef` with underlying type `TypeAlias(A)`
 `class p.C ...`           | `ClassInfo(p, C, ...)`

### Representation of methods ###
```scala
def f[A, B <: Ord[A]](x: A, y: B): Unit
```
is represented as:

```scala
val p = PolyType(List("A", "B"))(
  List(TypeBounds(Nothing, Any),
       TypeBounds(Nothing,
         RefinedType(Ordering,
           scala$math$Ordering$$T, TypeAlias(PolyParam(p, 0))))),
  m)

val m = MethodType(List("x", "y"),
  List(PolyParam(p, 0), PolyParam(p, 1)))(Unit)
```
(This is a slightly simplified version, e.g. we write `Unit` instead of
`TypeRef(TermRef(ThisType(TypeRef(NoPrefix,<root>)),scala),Unit)`).

Note that a PolyParam refers to a type parameter using its index (here A is 0
and B is 1).

## Subtyping checks ##
`topLevelSubType(tp1, tp2)` in [dotty/tools/dotc/core/TypeComparer.scala][4]
checks if `tp1` is a subtype of `tp2`.

### Type rebasing ###
**FIXME**: This section is no longer accurate because
https://github.com/lampepfl/dotty/pull/331 changed the handling of refined
types.

Consider [tests/pos/refinedSubtyping.scala][5]
```scala
class Test {

  class C { type T; type Coll }

  type T1 = C { type T = Int }

  type T11 = T1 { type Coll = Set[Int] }

  type T2 = C { type Coll = Set[T] }

  type T22 = T2 { type T = Int }

  var x: T11 = _
  var y: T22 = _

  x = y
  y = x

}
```
We want to do the subtyping checks recursively, since it would be nice if we
could check if `T22 <: T11` by first checking if `T2 <: T1`. To achieve this
recursive subtyping check, we remember that `T2#T` is really `T22#T`. This
procedure is called rebasing and is done by storing refined names in
`pendingRefinedBases` and looking them up using `rebase`.

## Type caching ##
TODO

## Type inference via constraint solving ##
TODO

[1]: https://github.com/lampepfl/dotty/blob/main/compiler/src/dotty/tools/dotc/core/Types.scala
[2]: https://github.com/samuelgruetter/dotty/blob/classdiagrampdf/dotty-types.pdf
[3]: https://github.com/samuelgruetter/scaladiagrams/tree/print-descendants
[4]: https://github.com/lampepfl/dotty/blob/main/compiler/src/dotty/tools/dotc/core/TypeComparer.scala
[5]: https://github.com/lampepfl/dotty/blob/main/tests/pos/refinedSubtyping.scala


text:
#import "ABI43_0_0RCTRootContentView.h"

#import "ABI43_0_0RCTBridge.h"
#import "ABI43_0_0RCTPerformanceLogger.h"
#import "ABI43_0_0RCTRootView.h"
#import "ABI43_0_0RCTRootViewInternal.h"
#import "ABI43_0_0RCTTouchHandler.h"
#import "ABI43_0_0RCTUIManager.h"
#import "ABI43_0_0UIView+React.h"

@implementation ABI43_0_0RCTRootContentView

- (instancetype)initWithFrame:(CGRect)frame
                       bridge:(ABI43_0_0RCTBridge *)bridge
                     ABI43_0_0ReactTag:(NSNumber *)ABI43_0_0ReactTag
               sizeFlexiblity:(ABI43_0_0RCTRootViewSizeFlexibility)sizeFlexibility
{
  if ((self = [super initWithFrame:frame])) {
    _bridge = bridge;
    self.ABI43_0_0ReactTag = ABI43_0_0ReactTag;
    _sizeFlexibility = sizeFlexibility;
    _touchHandler = [[ABI43_0_0RCTTouchHandler alloc] initWithBridge:_bridge];
    [_touchHandler attachToView:self];
    [_bridge.uiManager registerRootView:self];
  }
  return self;
}

ABI43_0_0RCT_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame)
ABI43_0_0RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (nonnull NSCoder *)aDecoder)

- (void)layoutSubviews
{
  [super layoutSubviews];
  [self updateAvailableSize];
}

- (void)insertABI43_0_0ReactSubview:(UIView *)subview atIndex:(NSInteger)atIndex
{
  [super insertABI43_0_0ReactSubview:subview atIndex:atIndex];
  [_bridge.performanceLogger markStopForTag:ABI43_0_0RCTPLTTI];
  dispatch_async(dispatch_get_main_queue(), ^{
    if (!self->_contentHasAppeared) {
      self->_contentHasAppeared = YES;
      [[NSNotificationCenter defaultCenter] postNotificationName:ABI43_0_0RCTContentDidAppearNotification object:self.superview];
    }
  });
}

- (void)setSizeFlexibility:(ABI43_0_0RCTRootViewSizeFlexibility)sizeFlexibility
{
  if (_sizeFlexibility == sizeFlexibility) {
    return;
  }

  _sizeFlexibility = sizeFlexibility;
  [self setNeedsLayout];
}

- (CGSize)availableSize
{
  CGSize size = self.bounds.size;
  return CGSizeMake(
      _sizeFlexibility & ABI43_0_0RCTRootViewSizeFlexibilityWidth ? INFINITY : size.width,
      _sizeFlexibility & ABI43_0_0RCTRootViewSizeFlexibilityHeight ? INFINITY : size.height);
}

- (void)updateAvailableSize
{
  if (!self.ABI43_0_0ReactTag || !_bridge.isValid) {
    return;
  }

  [_bridge.uiManager setAvailableSize:self.availableSize forRootView:self];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
  // The root content view itself should never receive touches
  UIView *hitView = [super hitTest:point withEvent:event];
  if (_passThroughTouches && hitView == self) {
    return nil;
  }
  return hitView;
}

- (void)invalidate
{
  if (self.userInteractionEnabled) {
    self.userInteractionEnabled = NO;
    [(ABI43_0_0RCTRootView *)self.superview contentViewInvalidated];

    [_bridge enqueueJSCall:@"AppRegistry"
                    method:@"unmountApplicationComponentAtRootTag"
                      args:@[ self.ABI43_0_0ReactTag ]
                completion:NULL];
  }
}

@end


text:
	#pragma warning ( disable : 4996 )	// '...' was declared deprecated
#endif

using namespace std;

// =================================================================================================
/// \file SonyHDV_Handler.cpp
/// \brief Folder format handler for Sony HDV.
///
/// This handler is for the Sony HDV video format. This is a pseudo-package, visible files but with
/// a very well-defined layout and naming rules.
///
/// A typical Sony HDV layout looks like:
///
/// .../MyMovie/
/// 	VIDEO/
/// 		HDV/
/// 			00_0001_2007-08-06_165555.IDX
/// 			00_0001_2007-08-06_165555.M2T
/// 			00_0001_2007-08-06_171740.M2T
/// 			00_0001_2007-08-06_171740.M2T.ese
/// 			tracks.dat
///
/// The logical clip name can be "00_0001" or "00_0001_" plus anything. We'll find the .IDX file,
/// which defines the existence of the clip. Full file names as input will pull out the camera/clip
/// parts and match in the same way. The .XMP file will use the date/time suffix from the .IDX file.
// =================================================================================================

// =================================================================================================
// SonyHDV_CheckFormat
// ===================
//
// This version does fairly simple checks. The top level folder (.../MyMovie) must contain the
// VIDEO/HVR subtree. The HVR folder must contain a .IDX file for the desired clip. The name checks
// are case insensitive.
//
// The state of the string parameters depends on the form of the path passed by the client. If the
// client passed a logical clip path, like ".../MyMovie/00_0001", the parameters are:
//   rootPath   - ".../MyMovie"
//   gpName     - empty
//   parentName - empty
//   leafName   - "00_0001"
//
// If the client passed a full file path, like ".../MyMovie/VIDEO/HVR/00_0001_2007-08-06_165555.M2T",
// they are:
//   rootPath   - ".../MyMovie"
//   gpName     - "VIDEO"
//   parentName - "HVR"
//   leafName   - "00_0001_2007-08-06_165555.M2T"
//
// The logical clip name can be short like "00_0001", or long like "00_0001_2007-08-06_165555". We
// only key off of the portion before a second underscore.

// ! The common code has shifted the gpName, parentName, and leafName strings to upper case. It has
// ! also made sure that for a logical clip path the rootPath is an existing folder, and that the
// ! file exists for a full file path.

bool SonyHDV_CheckFormat ( XMP_FileFormat format,
						   const std::string & rootPath,
						   const std::string & gpName,
						   const std::string & parentName,
						   const std::string & leafName,
						   XMPFiles * parent )
{
	// Do some basic checks on the root path and component names.

	if ( gpName.empty() != parentName.empty() ) return false;	// Must be both empty or both non-empty.

	std::string tempPath = rootPath;
	tempPath += kDirChar;
	tempPath += "VIDEO";

	if ( gpName.empty() ) {
		// This is the logical clip path case. Look for VIDEO/HVR subtree.
		if ( GetChildMode ( tempPath, "HVR" ) != kFMode_IsFolder ) return false;
	} else {
		// This is the existing file case. Check the parent and grandparent names.
		if ( (gpName != "VIDEO") || (parentName != "HVR") ) return false;
	}

	// Look for the clip's .IDX file. If found use that as the full clip name.

	tempPath += kDirChar;
	tempPath += "HVR";

	std::string clipName = leafName;
	int usCount = 0;
	size_t i, limit = leafName.size();
	for ( i = 0; i < limit; ++i ) {
		if ( clipName[i] == '_' ) {
			++usCount;
			if ( usCount == 2 ) break;
		}
	}
	if ( i < limit ) clipName.erase ( i );
	clipName += '_';	// Make sure a final '_' is there for the search comparisons.

	XMP_FolderInfo folderInfo;
	std::string childName;
	bool found = false;

	folderInfo.Open ( tempPath.c_str() );
	while ( (! found) && folderInfo.GetNextChild ( &childName ) ) {
		size_t childLen = childName.size();
		if ( childLen < 4 ) continue;
		MakeUpperCase ( &childName );
		if ( childName.compare ( childLen-4, 4, ".IDX" ) != 0 ) continue;
		if ( childName.compare ( 0, clipName.size(), clipName ) == 0 ) {
			found = true;
			clipName = childName;
			clipName.erase ( childLen-4 );
		}
	}
	if ( ! found ) return false;

	// Disabled until Sony HDV clip spanning is supported.
	// Since segments of spanned clips are currently considered separate entities,
	// information such as frame count needs to be considered on a per segment basis. JPM
	clipName = leafName;

	// Set tempPath to <root>/<clip-name>, e.g. ".../MyMovie/00_0001_2007-08-06_165555". This is
	// passed to the handler via the tempPtr hackery.

	tempPath = rootPath;
	tempPath += kDirChar;
	tempPath += clipName;

	size_t pathLen = tempPath.size() + 1;	// Include a terminating nul.
	parent->tempPtr = malloc ( pathLen );
	if ( parent->tempPtr == 0 ) XMP_Throw ( "No memory for SonyHDV clip info", kXMPErr_NoMemory );
	memcpy ( parent->tempPtr, tempPath.c_str(), pathLen );	// AUDIT: Safe, allocated above.

	return true;

}	// SonyHDV_CheckFormat

// =================================================================================================
// ReadIDXFile
// ===========

#define ExtractTimeCodeByte(ch,mask)	( (((ch & mask) >> 4) * 10) + (ch & 0xF) )

static bool ReadIDXFile ( const std::string& idxPath,
						  const std::string& clipName,
						  SXMPMeta* xmpObj,
						  bool& containsXMP,
						  MD5_CTX* md5Context,
						  bool digestFound )
{
	bool result = true;
	containsXMP = false;

	if ( clipName.size() != 25 ) return false;

	try {

		AutoFile idxFile;
		idxFile.fileRef = LFA_Open ( idxPath.c_str(), 'r' );
		if ( idxFile.fileRef == 0 ) return false;	// The open failed.

		struct SHDV_HeaderBlock
		{
			char			mHeader[8];
			unsigned char	mValidFlag;
			unsigned char	mReserved;
			unsigned char	mECCTB;
			unsigned char   mSignalMode;
			unsigned char	mFileThousands;
			unsigned char	mFileHundreds;
			unsigned char	mFileTens;
			unsigned char	mFileUnits;
		};

		SHDV_HeaderBlock hdvHeaderBlock;
		memset ( &hdvHeaderBlock, 0, sizeof(SHDV_HeaderBlock) );

		LFA_Read ( idxFile.fileRef, hdvHeaderBlock.mHeader, 8 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mValidFlag, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mReserved, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mECCTB, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mSignalMode, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mFileThousands, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mFileHundreds, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mFileTens, 1 );
		LFA_Read ( idxFile.fileRef, &hdvHeaderBlock.mFileUnits, 1 );

		const int fileCount = (hdvHeaderBlock.mFileThousands - '0') * 1000 +
							  (hdvHeaderBlock.mFileHundreds  - '0') *  100 +
							  (hdvHeaderBlock.mFileTens      - '0') *   10 +
							  (hdvHeaderBlock.mFileUnits     - '0');

		// Read file info block.
		struct	SHDV_FileBlock
		{
			char			mDT[2];
			unsigned char	mFileNameYear;
			unsigned char	mFileNameMonth;
			unsigned char	mFileNameDay;
			unsigned char	mFileNameHour;
			unsigned char	mFileNameMinute;
			unsigned char	mFileNameSecond;
			unsigned char	mStartTimeCode[4];
			unsigned char	mTotalFrame[4];
		};

		SHDV_FileBlock hdvFileBlock;
		memset ( &hdvFileBlock, 0, sizeof(SHDV_FileBlock) );

		char filenameBuffer[256];
		std::string fileDateAndTime = clipName.substr(8);

		bool foundFileBlock = false;

		for ( int i=0; ((i < fileCount) && (! foundFileBlock)); ++i ) {

			LFA_Read ( idxFile.fileRef, hdvFileBlock.mDT, 2 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameYear, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameMonth, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameDay, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameHour, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameMinute, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mFileNameSecond, 1 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mStartTimeCode, 4 );
			LFA_Read ( idxFile.fileRef, &hdvFileBlock.mTotalFrame, 4 );

			// Compose file name we expect from file contents and break out on match.
			sprintf ( filenameBuffer, "%02d-%02d-%02d_%02d%02d%02d",
					  hdvFileBlock.mFileNameYear + 2000,
					  hdvFileBlock.mFileNameMonth,
					  hdvFileBlock.mFileNameDay,
					  hdvFileBlock.mFileNameHour,
					  hdvFileBlock.mFileNameMinute,
					  hdvFileBlock.mFileNameSecond );

			foundFileBlock = (fileDateAndTime==filenameBuffer);

		}

		LFA_Close ( idxFile.fileRef );
		idxFile.fileRef = 0;

		if ( ! foundFileBlock ) return false;

		// If digest calculation requested, calculate it and return.
		if ( md5Context != 0 ) {
			MD5Update ( md5Context, (XMP_Uns8*)(&hdvHeaderBlock), sizeof(SHDV_HeaderBlock) );
			MD5Update ( md5Context, (XMP_Uns8*)(&hdvFileBlock), sizeof(SHDV_FileBlock) );
		}

		// The xmpObj parameter must be provided in order to extract XMP
		if ( xmpObj == 0 ) return (md5Context != 0);

		// Standard def?
		const bool isSD = ((hdvHeaderBlock.mSignalMode == 0x80) || (hdvHeaderBlock.mSignalMode == 0));

		// Progressive vs interlaced extracted from high bit of ECCTB byte
		const bool clipIsProgressive = ((hdvHeaderBlock.mECCTB & 0x80) != 0);

		// Lowest three bits contain frame rate information
		const int sfr = (hdvHeaderBlock.mECCTB & 7) + (clipIsProgressive ? 0 : 8);

		// Sample scale and sample size.
		int clipSampleScale = 0;
		int clipSampleSize  = 0;
		std::string frameRate;

		// Frame rate
		switch ( sfr ) {
			case 0	: break; // Not valid in spec, but it's happening in test files.
			case 1	: clipSampleScale = 24000;	clipSampleSize = 1001; frameRate = "23.98p"; break;
			case 3	: clipSampleScale = 25;		clipSampleSize = 1;	   frameRate =    "25p"; break;
			case 4	: clipSampleScale = 30000;	clipSampleSize = 1001; frameRate = "29.97p"; break;
			case 11	: clipSampleScale = 25;		clipSampleSize = 1;	   frameRate =    "50i"; break;
			case 12	: clipSampleScale = 30000;	clipSampleSize = 1001; frameRate = "59.94i"; break;
		}

		containsXMP = true;

		// Frame size and PAR for HD (not clear on SD yet).
		std::string xmpString;
		XMP_StringPtr xmpValue = 0;

		if ( ! isSD ) {

			if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "videoFrameSize" )) ) {

				xmpValue = "1440";
				xmpObj->GetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_DM, "w", &xmpString, 0 );
				if ( xmpString != xmpValue ) {
					xmpObj->SetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_XMP_Dimensions, "w", xmpValue, 0 );
				}

				xmpValue = "1080";
				xmpObj->GetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_DM, "h", &xmpString, 0 );
				if ( xmpString != xmpValue ) {
					xmpObj->SetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_XMP_Dimensions, "h", xmpValue, 0 );
				}

				xmpValue = "pixels";
				xmpObj->GetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_DM, "unit", &xmpString, 0 );
				if ( xmpString != xmpValue ) {
					xmpObj->SetStructField ( kXMP_NS_DM, "videoFrameSize", kXMP_NS_XMP_Dimensions, "unit", xmpValue, 0 );
				}
			}

			xmpValue = "4/3";
			if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "videoPixelAspectRatio" )) ) {
				xmpObj->SetProperty ( kXMP_NS_DM, "videoPixelAspectRatio", xmpValue, kXMP_DeleteExisting );
			}

		}

		// Sample size and scale.
		if ( clipSampleScale != 0 ) {

			char buffer[255];

			if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "startTimeScale" )) ) {
				sprintf(buffer, "%d", clipSampleScale);
				xmpValue = buffer;
				xmpObj->SetProperty ( kXMP_NS_DM, "startTimeScale", xmpValue, kXMP_DeleteExisting );
			}

			if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "startTimeSampleSize" )) ) {
				sprintf(buffer, "%d", clipSampleSize);
				xmpValue = buffer;
				xmpObj->SetProperty ( kXMP_NS_DM, "startTimeSampleSize", xmpValue, kXMP_DeleteExisting );
			}

			if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "duration" )) ) {

				const int frameCount = (hdvFileBlock.mTotalFrame[0] << 24) + (hdvFileBlock.mTotalFrame[1] << 16) +
									   (hdvFileBlock.mTotalFrame[2] << 8) + hdvFileBlock.mTotalFrame[3];

				sprintf ( buffer, "%d", frameCount );
				xmpValue = buffer;
				xmpObj->SetStructField ( kXMP_NS_DM, "duration", kXMP_NS_DM, "value", xmpValue, 0 );

				sprintf ( buffer, "%d/%d", clipSampleSize, clipSampleScale );
				xmpValue = buffer;
				xmpObj->SetStructField ( kXMP_NS_DM, "duration", kXMP_NS_DM, "scale", xmpValue, 0 );

			}

		}

		// Time Code.
		if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "startTimecode" )) ) {

			if ( (clipSampleScale != 0) && (clipSampleSize != 0) ) {

				const bool dropFrame = ( (0x40 & hdvFileBlock.mStartTimeCode[0]) != 0 ) && ( sfr == 4 || sfr == 12 );
				const char chDF = dropFrame ? ';' : ':';
				const int tcFrames  = ExtractTimeCodeByte ( hdvFileBlock.mStartTimeCode[0], 0x30 );
				const int tcSeconds = ExtractTimeCodeByte ( hdvFileBlock.mStartTimeCode[1], 0x70 );
				const int tcMinutes = ExtractTimeCodeByte ( hdvFileBlock.mStartTimeCode[2], 0x70 );
				const int tcHours   = ExtractTimeCodeByte ( hdvFileBlock.mStartTimeCode[3], 0x30 );

				// HH:MM:SS:FF or HH;MM;SS;FF
				char timecode[256];
				sprintf ( timecode, "%02d%c%02d%c%02d%c%02d", tcHours, chDF, tcMinutes, chDF, tcSeconds, chDF, tcFrames );
				std::string sonyTimeString = timecode;

				xmpObj->GetStructField ( kXMP_NS_DM, "startTimecode", kXMP_NS_DM, "timeValue", &xmpString, 0 );
				if ( xmpString != sonyTimeString ) {

					xmpObj->SetStructField ( kXMP_NS_DM, "startTimecode", kXMP_NS_DM, "timeValue", sonyTimeString, 0 );

					std::string timeFormat;
					if ( clipSampleSize == 1 ) {

						// 24, 25, 40, 50, 60
						switch ( clipSampleScale ) {
							case 24 : timeFormat = "24"; break;
							case 25 : timeFormat = "25"; break;
							case 50 : timeFormat = "50"; break;
							default : XMP_Assert ( false );
						}

						timeFormat += "Timecode";

					} else {

						// 23.976, 29.97, 59.94
						XMP_Assert ( clipSampleSize == 1001 );
						switch ( clipSampleScale ) {
							case 24000 : timeFormat = "23976"; break;
							case 30000 : timeFormat =  "2997"; break;
							case 60000 : timeFormat =  "5994"; break;
							default	   : XMP_Assert( false );  break;
						}

						timeFormat += dropFrame ? "DropTimecode" : "NonDropTimecode";

					}

					xmpObj->SetStructField ( kXMP_NS_DM, "startTimecode", kXMP_NS_DM, "timeFormat", timeFormat, 0 );

				}

			}

		}

		if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "CreateDate" )) ) {

			// Clip has date and time in the case of DT (otherwise date and time haven't been set).
			bool clipHasDate = ((hdvFileBlock.mDT[0] == 'D') && (hdvFileBlock.mDT[1] == 'T'));

			// Creation date
			if ( clipHasDate ) {

				// YYYY-MM-DDThh:mm:ssZ
				char date[256];
				sprintf ( date, "%4d-%02d-%02dT%02d:%02d:%02dZ",
						  hdvFileBlock.mFileNameYear + 2000,
						  hdvFileBlock.mFileNameMonth,
						  hdvFileBlock.mFileNameDay,
						  hdvFileBlock.mFileNameHour,
						  hdvFileBlock.mFileNameMinute,
						  hdvFileBlock.mFileNameSecond );

				XMP_StringPtr xmpDate = date;
				xmpObj->SetProperty ( kXMP_NS_XMP, "CreateDate", xmpDate, kXMP_DeleteExisting );

			}

		}

		// Frame rate.
		if ( digestFound || (! xmpObj->DoesPropertyExist ( kXMP_NS_DM, "videoFrameRate" )) ) {

			if ( frameRate.size() != 0 ) {
				xmpString = frameRate;
				xmpObj->SetProperty ( kXMP_NS_DM, "videoFrameRate", xmpString, kXMP_DeleteExisting );
			}

		}

	} catch ( ... ) {

		result = false;

	}

	return result;

}	// ReadIDXFile

// =================================================================================================
// SonyHDV_MetaHandlerCTor
// =======================

XMPFileHandler * SonyHDV_MetaHandlerCTor ( XMPFiles * parent )
{
	return new SonyHDV_MetaHandler ( parent );

}	// SonyHDV_MetaHandlerCTor

// =================================================================================================
// SonyHDV_MetaHandler::SonyHDV_MetaHandler
// ========================================

SonyHDV_MetaHandler::SonyHDV_MetaHandler ( XMPFiles * _parent )
{

	this->parent = _parent;	// Inherited, can't set in the prefix.
	this->handlerFlags = kSonyHDV_HandlerFlags;
	this->stdCharForm  = kXMP_Char8Bit;

	// Extract the root path and clip name.

	XMP_Assert ( this->parent->tempPtr != 0 );

	this->rootPath.assign ( (char*) this->parent->tempPtr );
	free ( this->parent->tempPtr );
	this->parent->tempPtr = 0;

	SplitLeafName ( &this->rootPath, &this->clipName );

}	// SonyHDV_MetaHandler::SonyHDV_MetaHandler

// =================================================================================================
// SonyHDV_MetaHandler::~SonyHDV_MetaHandler
// =========================================

SonyHDV_MetaHandler::~SonyHDV_MetaHandler()
{

	if ( this->parent->tempPtr != 0 ) {
		free ( this->parent->tempPtr );
		this->parent->tempPtr = 0;
	}

}	// SonyHDV_MetaHandler::~SonyHDV_MetaHandler

// =================================================================================================
// SonyHDV_MetaHandler::MakeClipFilePath
// =====================================

void SonyHDV_MetaHandler::MakeClipFilePath ( std::string * path, XMP_StringPtr suffix )
{

	*path = this->rootPath;
	*path += kDirChar;
	*path += "VIDEO";
	*path += kDirChar;
	*path += "HVR";
	*path += kDirChar;
	*path += this->clipName;
	*path += suffix;

}	// SonyHDV_MetaHandler::MakeClipFilePath

// =================================================================================================
// SonyHDV_MetaHandler::MakeIndexFilePath
// ======================================

bool SonyHDV_MetaHandler::MakeIndexFilePath ( std::string& idxPath, const std::string& rootPath, const std::string& leafName )
{
	std::string tempPath;
	tempPath = rootPath;
	tempPath += kDirChar;
	tempPath += "VIDEO";
	tempPath += kDirChar;
	tempPath += "HVR";

	idxPath = tempPath;
	idxPath += kDirChar;
	idxPath += leafName;
	idxPath += ".IDX";

	// Default case
	if ( GetFileMode ( idxPath.c_str() ) == kFMode_IsFile ) return true;

	// Spanned clip case

	// Scanning code taken from SonyHDV_CheckFormat
	// Can be isolated to a separate function.

	std::string clipName = leafName;
	int usCount = 0;
	size_t i, limit = leafName.size();

	for ( i = 0; i < limit; ++i ) {
		if ( clipName[i] == '_' ) {
			++usCount;
			if ( usCount == 2 ) break;
		}
	}

	if ( i < limit ) clipName.erase ( i );
	clipName += '_';	// Make sure a final '_' is there for the search comparisons.

	XMP_FolderInfo folderInfo;
	std::string childName;
	bool found = false;

	folderInfo.Open ( tempPath.c_str() );
	while ( (! found) && folderInfo.GetNextChild ( &childName ) ) {
		size_t childLen = childName.size();
		if ( childLen < 4 ) continue;
		MakeUpperCase ( &childName );
		if ( childName.compare ( childLen-4, 4, ".IDX" ) != 0 ) continue;
		if ( childName.compare ( 0, clipName.size(), clipName ) == 0 ) {
			found = true;
			clipName = childName;
			clipName.erase ( childLen-4 );
		}
	}
	if ( ! found ) return false;

	idxPath = tempPath;
	idxPath += kDirChar;
	idxPath += clipName;
	idxPath += ".IDX";

	return true;
}

// =================================================================================================
// SonyHDV_MetaHandler::MakeLegacyDigest
// =====================================

#define kHexDigits "0123456789ABCDEF"

void SonyHDV_MetaHandler::MakeLegacyDigest ( std::string * digestStr )
{
	std::string idxPath;
	if ( ! this->MakeIndexFilePath ( idxPath, this->rootPath, this->clipName ) ) return;

	MD5_CTX context;
	unsigned char digestBin [16];
	bool dummy = false;
	MD5Init ( &context );
	ReadIDXFile ( idxPath, this->clipName, 0,  dummy, &context, false );
	MD5Final ( digestBin, &context );

	char buffer [40];
	for ( int in = 0, out = 0; in < 16; in += 1, out += 2 ) {
		XMP_Uns8 byte = digestBin[in];
		buffer[out]   = kHexDigits [ byte >> 4 ];
		buffer[out+1] = kHexDigits [ byte & 0xF ];
	}
	buffer[32] = 0;
	digestStr->erase();
	digestStr->append ( buffer, 32 );

}	// MakeLegacyDigest

// =================================================================================================
// SonyHDV_MetaHandler::CacheFileData
// ==================================

void SonyHDV_MetaHandler::CacheFileData()
{
	XMP_Assert ( ! this->containsXMP );

	// See if the clip's .XMP file exists.

	std::string xmpPath;
	this->MakeClipFilePath ( &xmpPath, ".XMP" );
	if ( GetFileMode ( xmpPath.c_str() ) != kFMode_IsFile ) return;	// No XMP.

	// Read the entire .XMP file.

	char openMode = 'r';
	if ( this->parent->openFlags & kXMPFiles_OpenForUpdate ) openMode = 'w';

	LFA_FileRef xmpFile = LFA_Open ( xmpPath.c_str(), openMode );
	if ( xmpFile == 0 ) return;	// The open failed.

	XMP_Int64 xmpLen = LFA_Measure ( xmpFile );
	if ( xmpLen > 100*1024*1024 ) {
		XMP_Throw ( "SonyHDV XMP is outrageously large", kXMPErr_InternalFailure );	// Sanity check.
	}

	this->xmpPacket.erase();
	this->xmpPacket.reserve ( (size_t)xmpLen );
	this->xmpPacket.append ( (size_t)xmpLen, ' ' );

	XMP_Int32 ioCount = LFA_Read ( xmpFile, (void*)this->xmpPacket.data(), (XMP_Int32)xmpLen, kLFA_RequireAll );
	XMP_Assert ( ioCount == xmpLen );

	this->packetInfo.offset = 0;
	this->packetInfo.length = (XMP_Int32)xmpLen;
	FillPacketInfo ( this->xmpPacket, &this->packetInfo );

	XMP_Assert ( this->parent->fileRef == 0 );
	if ( openMode == 'r' ) {
		LFA_Close ( xmpFile );
	} else {
		this->parent->fileRef = xmpFile;
	}

	this->containsXMP = true;

}	// SonyHDV_MetaHandler::CacheFileData

// =================================================================================================
// SonyHDV_MetaHandler::ProcessXMP
// ===============================

void SonyHDV_MetaHandler::ProcessXMP()
{
	if ( this->processedXMP ) return;
	this->processedXMP = true;	// Make sure only called once.

	if ( this->containsXMP ) {
		this->xmpObj.ParseFromBuffer ( this->xmpPacket.c_str(), (XMP_StringLen)this->xmpPacket.size() );
	}

	// Check the legacy digest.
	std::string oldDigest, newDigest;
	bool digestFound;
	digestFound = this->xmpObj.GetStructField ( kXMP_NS_XMP, "NativeDigests", kXMP_NS_XMP, "SonyHDV", &oldDigest, 0 );
	if ( digestFound ) {
		this->MakeLegacyDigest ( &newDigest );
		if ( oldDigest == newDigest ) return;
	}

	// Read the IDX legacy.
	std::string idxPath;
	if ( ! this->MakeIndexFilePath ( idxPath, this->rootPath, this->clipName ) ) return;
	ReadIDXFile ( idxPath, this->clipName, &this->xmpObj,  this->containsXMP, 0, digestFound );

}	// SonyHDV_MetaHandler::ProcessXMP

// =================================================================================================
// SonyHDV_MetaHandler::UpdateFile
// ===============================
//
// Note that UpdateFile is only called from XMPFiles::CloseFile, so it is OK to close the file here.

void SonyHDV_MetaHandler::UpdateFile ( bool doSafeUpdate )
{
	if ( ! this->needsUpdate ) return;
	this->needsUpdate = false;	// Make sure only called once.

	std::string newDigest;
	this->MakeLegacyDigest ( &newDigest );
	this->xmpObj.SetStructField ( kXMP_NS_XMP, "NativeDigests", kXMP_NS_XMP, "SonyHDV", newDigest.c_str(), kXMP_DeleteExisting );

	LFA_FileRef oldFile = this->parent->fileRef;

	this->xmpObj.SerializeToBuffer ( &this->xmpPacket, this->GetSerializeOptions() );

	if ( oldFile == 0 ) {

		// The XMP does not exist yet.

		std::string xmpPath;
		this->MakeClipFilePath ( &xmpPath, ".XMP" );

		LFA_FileRef xmpFile = LFA_Create ( xmpPath.c_str() );
		if ( xmpFile == 0 ) XMP_Throw ( "Failure creating SonyHDV XMP file", kXMPErr_ExternalFailure );
		LFA_Write ( xmpFile, this->xmpPacket.data(), (XMP_StringLen)this->xmpPacket.size() );
		LFA_Close ( xmpFile );

	} else if ( ! doSafeUpdate ) {

		// Over write the existing XMP file.

		LFA_Seek ( oldFile, 0, SEEK_SET );
		LFA_Truncate ( oldFile, 0 );
		LFA_Write ( oldFile, this->xmpPacket.data(), (XMP_StringLen)this->xmpPacket.size() );
		LFA_Close ( oldFile );

	} else {

		// Do a safe update.

		// *** We really need an LFA_SwapFiles utility.

		std::string xmpPath, tempPath;

		this->MakeClipFilePath ( &xmpPath, ".XMP" );

		CreateTempFile ( xmpPath, &tempPath );
		LFA_FileRef tempFile = LFA_Open ( tempPath.c_str(), 'w' );
		LFA_Write ( tempFile, this->xmpPacket.data(), (XMP_StringLen)this->xmpPacket.size() );
		LFA_Close ( tempFile );

		LFA_Close ( oldFile );
		LFA_Delete ( xmpPath.c_str() );
		LFA_Rename ( tempPath.c_str(), xmpPath.c_str() );

	}

	this->parent->fileRef = 0;

}	// SonyHDV_MetaHandler::UpdateFile

// =================================================================================================
// SonyHDV_MetaHandler::WriteFile
// ==============================

void SonyHDV_MetaHandler::WriteFile ( LFA_FileRef sourceRef, const std::string & sourcePath )
{

	// ! WriteFile is not supposed to be called for handlers that own the file.
	XMP_Throw ( "SonyHDV_MetaHandler::WriteFile should not be called", kXMPErr_InternalFailure );

}	// SonyHDV_MetaHandler::WriteFile

// =================================================================================================


text:
layout:     post
title:      "数据持久化"
subtitle:   "常用总结"
date:       2016-01-18 00:00:00
author:     "BigabilityLiu"
header-img: "img/post-bg-04.jpg"
---

第一种方式,直接取得XCode目录中的.plist文件,这个文件应该是自己手动创建或添加的

{% highlight Objective-C %}
let pathBundle = NSBundle.mainBundle().pathForResource("UserList", ofType: "plist")
print(pathBundle!)
{% endhighlight %}
输出结果为
{% highlight Objective-C %}
/Users/LiusMac/Library/Developer/CoreSimulator/Devices/51C2CCD9-FE37-4D64-A272-389F3CF17AFA/data/Containers/Bundle/Application/37C9C0D6-E0E5-4FDE-BBC8-14AF375DCE4F/TayoOffice.app/UserList.plist
{% endhighlight %}
第二种方式,获得的就是所谓的沙盒目录
{% highlight Objective-C %}
let documentsDirectorys = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as NSArray
let documentsDirectory = documentsDirectorys.objectAtIndex(0) as! NSString
let pathDocuments = documentsDirectory.stringByAppendingPathComponent("UserList.plist") as String
print(pathDocuments)
{% endhighlight %}
输出结果
{% highlight Objective-C %}
/Users/LiusMac/Library/Developer/CoreSimulator/Devices/51C2CCD9-FE37-4D64-A272-389F3CF17AFA/data/Containers/Data/Application/A80045CB-75FF-4A06-B2D9-CB9FEB9B7478/Documents/UserList.plist
{% endhighlight %}
如何在电脑中查看沙盒内文件?在Finder中按CMD+SHIFT+G,然后再前往的框中输入~/Library,也就是直接前往,而不是通过点击前往。然后按上面路径依次进入即可

保存图片到本地

{% highlight Objective-C %}
func saveImage(image: UIImage, filename: String) {
let path = NSHomeDirectory().stringByAppendingString("/Documents/\(filename)")
let data = UIImagePNGRepresentation(image)
data.writeToFile(path, atomically: true)
}
{% endhighlight %}

从本地取出图片

{% highlight Objective-C %}
func getImage(filename: String) -> UIImage? {
var error: NSError?
let path = NSHomeDirectory().stringByAppendingString("/Documents/\(filename)")
let data = NSData(contentsOfFile: path, options: .UncachedRead, error: &error)
if let unwrappedError = error {
return nil
} else {
return UIImage(data: data!)
}
}
{% endhighlight %}

NSUserDefaults

参考地址
[NSUserDefaults](http://my.oschina.net/u/1245365/blog/294449)

PersistencyManager将登录成功与否数据通过广播发送出去ViewController接受处理,如果登录成功将用户常用数据存入NSUserDefaults

{% highlight Objective-C %}
//将用户信息存入NSUserDefaults
let onlineUser = OnlineUser(code: loginResults[1][0][0] as! String, name: loginResults[1][0][1]! as! String, teamCode: loginResults[1][0][2]! as! String, job: loginResults[1][0][3]!  as! String, depaCode: loginResults[1][0][4]! as! String, depaName: (loginResults[1][0][5] as? String)!)
//转换为NSDate
let onlineUserDate: NSData = NSKeyedArchiver.archivedDataWithRootObject(onlineUser)
let user: NSUserDefaults = NSUserDefaults.standardUserDefaults()
user.setObject(onlineUserDate, forKey: "onlineUser")

{% endhighlight %}
取出NSUserDefaults的数据
{% highlight Objective-C %}
func test(){
let user = NSUserDefaults.standardUserDefaults()
if(user.objectForKey("onlineUser") != nil){
let onlineUserData:NSData = user.objectForKey("onlineUser") as! NSData
let onlineUser: OnlineUser = NSKeyedUnarchiver.unarchiveObjectWithData(onlineUserData) as! OnlineUser
print(onlineUser.description)
}else{
}
}
{% endhighlight %}


text:
<?php
//creating personal object, going to be able to call object
//ectablishing connection, easier to read code
 class Database{
//creating variables and functions
//setting visibily, cant acess outside of file
		private $connection;
		private $host;
		private $username;
		private $password;
		private $database;
		public $error;
//want information to this variable
//global variables, able to be acessed throughout program
//cut down lines of code
//public so it can be acessed anywhere
//anytime we call on it it will create object
//info ends up in construct
//this gives acess to all global variables
//local variables disappear once function is done running
//construct allows to build objects of type database
//it uses info in these clases then able to use these objects
 public function __construct($host, $username, $password, $database){
		$this->host = $host;
		$this->username = $username;
		$this->password = $password;
		$this->database = $database;

	$this->connection = new mysqli($host, $username, $password);
//checks if there is an error with the connection
	if ($this->connection->connect_error) {
		die("
Error:" . $this->connection->connect_error). "
";
	}
//variable that checks if other variable exists
	$exists = $this->connection->select_db($database);

//if variable exists then do the command underneath
// creating database
	if(!$exists){
		$query = $this->connection->query("CREATE DATABASE $database");
//checking if database is created if databse was created print out this message
// create the database ONCE
	//if($query) {
		echo "
sucessfully created database:" . $database. "
";
	//}
}
//executed if we already have a database
	//else {
		///echo "
Database already exists.
";
	//}

	}
//no longer call code over and over again, it is present here
//call on the functionn and it will preform code
//opening connection & closing connection
//every time pass a query call a string
 public function openConnection(){
	$this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
//established connection
//referencing correct varaiable
//checks if there is an error with the connection
	if ($this->connection->connect_error) {
		die("
Error:" . $this->connection->connect_error). "
";
		}
	}
//close connection that was opened
 public function closeConnection(){
//checck wether or not we've opened connection, if so it can be closed
//checks if variable has been set
	if(isset($this->connection)){
		$this->connection->close();
	   }
	}

 public function query($string){
	$this->openConnection();
//telling it to query
	$query = $this->connection->query($string);
//execute query on our database
//huge lines of code stored in string variable
	if(!$query){
		$this->error = $this->connection->error;
	}

	$this->closeConnection();
    	return $query;
	}
//open connection to database
//get result if query was true or false
//return result true because it was successful or false because it wasn't
}


text:
import React from 'react';
import { storiesOf } from '@kadira/storybook';

import { AppNavigationContainer } from '.';

const stories = storiesOf('AppNavigationContainer', module);

stories.add('default', () => (
  <AppNavigationContainer />
));


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

namespace LegendaryClient.Logic.UpdateRegion
{
    public sealed class PBE : BaseUpdateRegion
    {
        public override string AirListing
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe/projects/lol_air_client/releases/releaselisting_PBE"; }
        }

        public override string AirManifest
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe/projects/lol_air_client/"; }
        }

        public override string GameListing
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe/projects/lol_game_client/releases/releaselisting_PBE"; }
        }

        public override string SolutionListing
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe/solutions/lol_game_client_sln/releases/releaselisting_PBE"; }
        }

        public override string SolutionManifest
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe/solutions/lol_game_client_sln/"; }
        }

        public override string BaseLink
        {
            get { return "http://l3cdn.riotgames.com/releases/pbe"; }
        }
    }
}


text:
define([
    'angular',
    'angular-animate'
], function (ng) {
    'use strict';

    return ng.module('timelineModule', ['ngAnimate']);
});


text:
using System.Xml.Serialization;

namespace WolframAlpha
{
    public class AssumptionValue
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("desc")]
        public string Description { get; set; }

        [XmlAttribute("input")]
        public string Input { get; set; }
    }
}


text:
<?php
namespace Shopvel\Console\Command;

use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;

class VersionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shopvel:version';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get current version number';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Current version: ' . SHOPVEL_VERSION);
    }
}


text:
package bio.terra.workspace.db.exception;

import bio.terra.common.exception.InternalServerErrorException;

public class InvalidMetadataException extends InternalServerErrorException {

  public InvalidMetadataException(String message) {
    super(message);
  }
}


text:
\documentclass[varwidth]{standalone}
\usepackage{amsmath}
\begin{document}
	$f\ \star\ g\ =$
	$\sum\limits_{k=0}^\infty \hbar^k C_k(f,g)$
\end{document}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.harvard.iq.dataverse.ingest;

import edu.harvard.iq.dataverse.DataFile;
//import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.util.ShapefileHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
//import javax.ejb.EJB;

/**
 *  Used by the IngestServiceBean to redistribute a zipped Shapefile*
 *
 *  - Accomplish the actions described in the ShapefileHandler function "rezipShapefileSets"
 *  - Return a list of DataFile objects
 *
 * @author raprasad
 */
public class IngestServiceShapefileHelper {

    //@EJB
    //DataFileServiceBean fileService;

    /*
        code to add to IngestServiceBean
            File rezipFolder = this.getShapefileUnzipTempDirectory();
            IngestServiceShapefileHelper shapefileIngestHelper = new IngestServiceShapefileHelper(tempFile.toFile(), rezipFolder);
            List<DataFile> dataFiles = shapefileIngestHelper.getDataFiles();
            rezipFolder.delete();
     */

    private static final Logger logger = Logger.getLogger(IngestServiceShapefileHelper.class.getCanonicalName());

    private ShapefileHandler shpHandler;
    private DatasetVersion datasetVersion;
    List<DataFile> dataFileList = null;
    private File zippedShapefile;
    private File rezipFolder;

    public List<DataFile> getDataFileList(){
        if (this.dataFileList==null){
            return null;
        }
        if (this.dataFileList.size()==0){
            return null;
        }
        return this.dataFileList;
    }

    private boolean isValidFile(File fileObject){

         if (fileObject==null){
            logger.warning("fileObject was null");
            return false;
        }
        if (!fileObject.isFile()){
            logger.warning("fileObject was not a file.  Failed \"isFile()\": " + fileObject.getAbsolutePath());
            return false;
        }
        return true;
    }

   private boolean isValidFolder(File fileObject){

         if (fileObject==null){
            logger.warning("fileObject was null");
            return false;
        }
        if (!fileObject.isDirectory()){
            logger.warning("fileObject was not a directory.  Failed \"isFile()\": " + fileObject.getAbsolutePath());
            return false;
        }
        return true;
    }
    /*
        Constructor that accepts a file object
    */
   public IngestServiceShapefileHelper(File zippedShapefile, File rezipFolder){

        if ((!isValidFile(zippedShapefile))||(!isValidFolder(rezipFolder))){
            return;
        }
        this.zippedShapefile = zippedShapefile;
        this.rezipFolder = rezipFolder;
        //this.datasetVersion = version;

        //this.processFile(zippedShapefile, rezipFolder);

    }

   private FileInputStream getFileInputStream(File fileObject){
       if (fileObject==null){
           return null;
       }
       try {
            return new FileInputStream(fileObject);
        } catch (FileNotFoundException ex) {
            logger.severe("Failed to create FileInputStream from File: " + fileObject.getAbsolutePath());
            return null;
        }
   }

   private void closeFileInputStream(FileInputStream fis){
       if (fis==null){
           return;
       }
        try {
            fis.close();
        } catch (IOException ex) {
            logger.info("Failed to close FileInputStream");
        }
   }

    public boolean processFile() {

       if ((!isValidFile(this.zippedShapefile))||(!isValidFolder(this.rezipFolder))){
            return false;
        }

       // (1) Use the ShapefileHandler to the .zip for a shapefile
       //
        FileInputStream shpfileInputStream = this.getFileInputStream(zippedShapefile);
        if (shpfileInputStream==null){
            return false;
        }

        this.shpHandler = new ShapefileHandler(shpfileInputStream);
        if (!shpHandler.containsShapefile()){
            logger.severe("Shapefile was incorrectly detected upon Ingest (FileUtil) and passed here");
            return false;
        }

        this.closeFileInputStream(shpfileInputStream);

        //  (2) Rezip the shapefile pieces
        logger.info("rezipFolder: " + rezipFolder.getAbsolutePath());
        shpfileInputStream = this.getFileInputStream(zippedShapefile);
        if (shpfileInputStream==null){
            return false;
        }

        boolean rezipSuccess;
        try {
            rezipSuccess = shpHandler.rezipShapefileSets(shpfileInputStream, rezipFolder);
        } catch (IOException ex) {
            logger.severe("Shapefile was not correctly unpacked/repacked");
            logger.severe("shpHandler message: " + shpHandler.errorMessage);
            return false;
        }

        this.closeFileInputStream(shpfileInputStream);

        return rezipSuccess;

        //   return createDataFiles(rezipFolder);

    }

    public List<File> getFinalRezippedFiles(){
        if (this.shpHandler==null){
            return null;
        }
        return this.shpHandler.getFinalRezippedFiles();
    }
    /*
        Note: This creates DataFile objects, the files themselves already exist!
    */
    /*
    private boolean createDataFiles(File rezipFolder){
        if (!isValidFolder(rezipFolder)){
            return false;
        }

        // Initialize dataFileList
        this.dataFileList = new ArrayList<DataFile>();

        for (File singleFile : rezipFolder.listFiles()){
            if (!singleFile.isFile()){
                continue; // not a file
            }
            DataFile datafile = createSingleDataFile(singleFile);
            if (!(datafile==null)){
                   this.dataFileList.add(datafile);
            }
        }

        return false;
    }
    */

}


text:
/*>
# String Lists

Often we need a list of strings. This section provides an abstract data type.

## Interface

First we define an abstract data type and functions to create and destroy instances of this data type. You can pass the constructor the minimal initial capacity to allocate.
<*/
#if !defined(str_lst_h)
#define str_lst_h

	#include <stdbool.h>

	typedef struct str_lst str_lst;

	str_lst *str_lst_create(int min_capacity);
	str_lst *str_lst_free(str_lst *sl);
/*>
### Accessors

The accessor functions let you know how many strings are stored in the list, and get a pointer to the first string and behind the last string. The string pointers are stored in one block of
memory.
<*/
	int str_lst_count(str_lst *sl);
	char **str_lst_begin(str_lst *sl);
	char **str_lst_end(str_lst *sl);
/*>
### Adding Strings

There are two methods to add a string. The `str_lst_add` function stores a copy of the string in the list.

The function `str_lst_add_and_consume` stores the string passed in the list and frees its memory, when the list is freed.
<*/
	bool str_lst_add(str_lst *sl, const char *str);
	bool str_lst_add_and_consume(str_lst *sl, char *str);

#endif


text:
require 'jira-ruby'
require_relative '../tracker_base'
require_relative './project'

module StoryBranch
  module Jira
    # JIRA API wrapper for story branch tracker
    class Tracker < StoryBranch::TrackerBase
      def initialize(tracker_domain:, project_id:, api_key:, username:, extra_query:)
        super

        @tracker_url = "https://#{tracker_domain}.atlassian.net"
        @project_id = project_id
        @issue_regex = Regexp.new("#{@project_id}-(\\d+)")
        @api_key = api_key
        @username = username
        @extra_query = extra_query
      end

      def valid?
        [@api_key, @project_id, @username, @tracker_url].none?(&:nil?)
      end

      # TODO: This should probably be renamed to something more meaningful
      # in the sense that it should be workable stories/issues
      # which depend on the tracker's workflow. PivotalTracker they need to
      # be started and estimated, while for Github they just need to be open
      def stories
        project.stories
      end

      def get_story_by_id(story_id)
        project.stories(id: story_id).first
      end

      private

      def options
        {
          username: @username,
          password: @api_key,
          site: @tracker_url,
          auth_type: :basic,
          read_timeout: 120,
          context_path: ''
        }
      end

      def configure_api
        JIRA::Client.new(options)
      end

      def project
        return @project if @project
        raise 'project key must be set' unless @project_id

        jira_project = api.Project.find(@project_id)
        @project = Project.new(jira_project, @extra_query)
      rescue JIRA::HTTPError => e
        raise "failed to authenticate: #{e.inspect}"
      end
    end
  end
end


text:
package org.elasticsearch.xpack.core.ml.utils;

import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesAction;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexAction;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.ClusterAdminClient;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.IndexTemplateMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.ml.inference.persistence.InferenceIndexConstants;
import org.elasticsearch.xpack.core.template.IndexTemplateConfig;
import org.junit.After;
import org.junit.Before;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.stubbing.Answer;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

public class MlIndexAndAliasTests extends ESTestCase {

    private static final String TEST_INDEX_PREFIX = "test";
    private static final String TEST_INDEX_ALIAS = "test-alias";
    private static final String LEGACY_INDEX_WITHOUT_SUFFIX = TEST_INDEX_PREFIX;
    private static final String FIRST_CONCRETE_INDEX = "test-000001";

    private ThreadPool threadPool;
    private IndicesAdminClient indicesAdminClient;
    private ClusterAdminClient clusterAdminClient;
    private AdminClient adminClient;
    private Client client;
    private ActionListener<Boolean> listener;

    private ArgumentCaptor<CreateIndexRequest> createRequestCaptor;
    private ArgumentCaptor<IndicesAliasesRequest> aliasesRequestCaptor;

    @Before
    public void setUpMocks() {
        threadPool = mock(ThreadPool.class);
        when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));

        indicesAdminClient = mock(IndicesAdminClient.class);
        when(indicesAdminClient.prepareCreate(FIRST_CONCRETE_INDEX))
            .thenReturn(new CreateIndexRequestBuilder(client, CreateIndexAction.INSTANCE, FIRST_CONCRETE_INDEX));
        doAnswer(withResponse(new CreateIndexResponse(true, true, FIRST_CONCRETE_INDEX))).when(indicesAdminClient).create(any(), any());
        when(indicesAdminClient.prepareAliases()).thenReturn(new IndicesAliasesRequestBuilder(client, IndicesAliasesAction.INSTANCE));
        doAnswer(withResponse(AcknowledgedResponse.TRUE)).when(indicesAdminClient).aliases(any(), any());
        doAnswer(withResponse(AcknowledgedResponse.TRUE)).when(indicesAdminClient).putTemplate(any(), any());

        clusterAdminClient = mock(ClusterAdminClient.class);
        doAnswer(invocationOnMock -> {
            @SuppressWarnings("unchecked")
            ActionListener<ClusterHealthResponse> listener = (ActionListener<ClusterHealthResponse>) invocationOnMock.getArguments()[1];
            listener.onResponse(new ClusterHealthResponse());
            return null;
        }).when(clusterAdminClient).health(any(ClusterHealthRequest.class), any(ActionListener.class));

        adminClient = mock(AdminClient.class);
        when(adminClient.indices()).thenReturn(indicesAdminClient);
        when(adminClient.cluster()).thenReturn(clusterAdminClient);

        client = mock(Client.class);
        when(client.threadPool()).thenReturn(threadPool);
        when(client.admin()).thenReturn(adminClient);

        listener = mock(ActionListener.class);

        createRequestCaptor = ArgumentCaptor.forClass(CreateIndexRequest.class);
        aliasesRequestCaptor = ArgumentCaptor.forClass(IndicesAliasesRequest.class);
    }

    @After
    public void verifyNoMoreInteractionsWithMocks() {
        verifyNoMoreInteractions(indicesAdminClient, listener);
    }

    public void testInstallIndexTemplateIfRequired_GivenTemplateExists() {
        ClusterState clusterState = createClusterState(Collections.emptyMap(),
            Collections.singletonMap(InferenceIndexConstants.LATEST_INDEX_NAME,
                createIndexTemplateMetaData(InferenceIndexConstants.LATEST_INDEX_NAME,
                    Collections.singletonList(InferenceIndexConstants.LATEST_INDEX_NAME))));

        IndexTemplateConfig inferenceTemplate = new IndexTemplateConfig(InferenceIndexConstants.LATEST_INDEX_NAME,
            "not_a_real_file.json", Version.CURRENT.id, "xpack.ml.version",
            Collections.singletonMap("xpack.ml.version.id", String.valueOf(Version.CURRENT.id)));

        MlIndexAndAlias.installIndexTemplateIfRequired(clusterState, client, inferenceTemplate, listener);
        verify(listener).onResponse(true);
        verifyNoMoreInteractions(client);
    }

    public void testInstallIndexTemplateIfRequired() {
        ClusterState clusterState = createClusterState(Collections.emptyMap());

        IndexTemplateConfig inferenceTemplate = new IndexTemplateConfig(InferenceIndexConstants.LATEST_INDEX_NAME,
            "/org/elasticsearch/xpack/core/ml/inference_index_template.json", Version.CURRENT.id, "xpack.ml.version",
            Collections.singletonMap("xpack.ml.version.id", String.valueOf(Version.CURRENT.id)));

        MlIndexAndAlias.installIndexTemplateIfRequired(clusterState, client, inferenceTemplate, listener);
        InOrder inOrder = inOrder(indicesAdminClient, listener);
        inOrder.verify(indicesAdminClient).putTemplate(any(), any());
        inOrder.verify(listener).onResponse(true);
    }

    public void testCreateStateIndexAndAliasIfNecessary_CleanState() {
        ClusterState clusterState = createClusterState(Collections.emptyMap());
        createIndexAndAliasIfNecessary(clusterState);

        InOrder inOrder = inOrder(indicesAdminClient, listener);
        inOrder.verify(indicesAdminClient).prepareCreate(FIRST_CONCRETE_INDEX);
        inOrder.verify(indicesAdminClient).create(createRequestCaptor.capture(), any());
        inOrder.verify(listener).onResponse(true);

        CreateIndexRequest createRequest = createRequestCaptor.getValue();
        assertThat(createRequest.index(), equalTo(FIRST_CONCRETE_INDEX));
        assertThat(createRequest.aliases(), equalTo(Collections.singleton(new Alias(TEST_INDEX_ALIAS).isHidden(true))));
    }

    private void assertNoClientInteractionsWhenWriteAliasAlreadyExists(String indexName) {
        ClusterState clusterState = createClusterState(Collections.singletonMap(indexName, createIndexMetadataWithAlias(indexName)));
        createIndexAndAliasIfNecessary(clusterState);

        verify(listener).onResponse(false);
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasAlreadyExistsAndPointsAtInitialStateIndex() {
        assertNoClientInteractionsWhenWriteAliasAlreadyExists(FIRST_CONCRETE_INDEX);
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasAlreadyExistsAndPointsAtSubsequentStateIndex() {
        assertNoClientInteractionsWhenWriteAliasAlreadyExists("test-000007");
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasAlreadyExistsAndPointsAtDummyIndex() {
        assertNoClientInteractionsWhenWriteAliasAlreadyExists("dummy-index");
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasAlreadyExistsAndPointsAtLegacyStateIndex() {
        ClusterState clusterState =
            createClusterState(
                Collections.singletonMap(LEGACY_INDEX_WITHOUT_SUFFIX, createIndexMetadataWithAlias(LEGACY_INDEX_WITHOUT_SUFFIX)));
        createIndexAndAliasIfNecessary(clusterState);

        InOrder inOrder = inOrder(indicesAdminClient, listener);
        inOrder.verify(indicesAdminClient).prepareCreate(FIRST_CONCRETE_INDEX);
        inOrder.verify(indicesAdminClient).create(createRequestCaptor.capture(), any());
        inOrder.verify(indicesAdminClient).prepareAliases();
        inOrder.verify(indicesAdminClient).aliases(aliasesRequestCaptor.capture(), any());
        inOrder.verify(listener).onResponse(true);

        CreateIndexRequest createRequest = createRequestCaptor.getValue();
        assertThat(createRequest.index(), equalTo(FIRST_CONCRETE_INDEX));
        assertThat(createRequest.aliases(), empty());

        IndicesAliasesRequest indicesAliasesRequest = aliasesRequestCaptor.getValue();
        assertThat(
            indicesAliasesRequest.getAliasActions(),
            contains(
                AliasActions.add().alias(TEST_INDEX_ALIAS).index(FIRST_CONCRETE_INDEX).isHidden(true),
                AliasActions.remove().alias(TEST_INDEX_ALIAS).index(LEGACY_INDEX_WITHOUT_SUFFIX)));
    }

    private void assertMlStateWriteAliasAddedToMostRecentMlStateIndex(List<String> existingIndexNames, String expectedWriteIndexName) {
        ClusterState clusterState =
            createClusterState(
                existingIndexNames.stream().collect(toMap(Function.identity(), MlIndexAndAliasTests::createIndexMetadata)));
        createIndexAndAliasIfNecessary(clusterState);

        InOrder inOrder = inOrder(indicesAdminClient, listener);
        inOrder.verify(indicesAdminClient).prepareAliases();
        inOrder.verify(indicesAdminClient).aliases(aliasesRequestCaptor.capture(), any());
        inOrder.verify(listener).onResponse(true);

        IndicesAliasesRequest indicesAliasesRequest = aliasesRequestCaptor.getValue();
        assertThat(
            indicesAliasesRequest.getAliasActions(),
            contains(AliasActions.add().alias(TEST_INDEX_ALIAS).index(expectedWriteIndexName).isHidden(true)));
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasDoesNotExistButInitialStateIndexExists() {
        assertMlStateWriteAliasAddedToMostRecentMlStateIndex(
            Arrays.asList(FIRST_CONCRETE_INDEX), FIRST_CONCRETE_INDEX);
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasDoesNotExistButSubsequentStateIndicesExist() {
        assertMlStateWriteAliasAddedToMostRecentMlStateIndex(
            Arrays.asList("test-000003", "test-000040", "test-000500"), "test-000500");
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasDoesNotExistButBothLegacyAndNewIndicesExist() {
        assertMlStateWriteAliasAddedToMostRecentMlStateIndex(
            Arrays.asList(LEGACY_INDEX_WITHOUT_SUFFIX, "test-000003", "test-000040", "test-000500"), "test-000500");
    }

    public void testCreateStateIndexAndAliasIfNecessary_WriteAliasDoesNotExistButLegacyStateIndexExists() {
        ClusterState clusterState =
            createClusterState(Collections.singletonMap(LEGACY_INDEX_WITHOUT_SUFFIX, createIndexMetadata(LEGACY_INDEX_WITHOUT_SUFFIX)));
        createIndexAndAliasIfNecessary(clusterState);

        InOrder inOrder = inOrder(indicesAdminClient, listener);
        inOrder.verify(indicesAdminClient).prepareCreate(FIRST_CONCRETE_INDEX);
        inOrder.verify(indicesAdminClient).create(createRequestCaptor.capture(), any());
        inOrder.verify(listener).onResponse(true);

        CreateIndexRequest createRequest = createRequestCaptor.getValue();
        assertThat(createRequest.index(), equalTo(FIRST_CONCRETE_INDEX));
        assertThat(createRequest.aliases(), equalTo(Collections.singleton(new Alias(TEST_INDEX_ALIAS).isHidden(true))));
    }

    public void testIndexNameComparator() {
        Comparator<String> comparator = MlIndexAndAlias.INDEX_NAME_COMPARATOR;
        assertThat(
            Stream.of("test-000001").max(comparator).get(),
            equalTo("test-000001"));
        assertThat(
            Stream.of("test-000002", "test-000001").max(comparator).get(),
            equalTo("test-000002"));
        assertThat(
            Stream.of("test-000003", "test-000040", "test-000500").max(comparator).get(),
            equalTo("test-000500"));
        assertThat(
            Stream.of("test-000042", "test-000049", "test-000038").max(comparator).get(),
            equalTo("test-000049"));
        assertThat(
            Stream.of("test", "test-000003", "test-000040", "test-000500").max(comparator).get(),
            equalTo("test-000500"));
        assertThat(
            Stream.of(".reindexed-6-test", "test-000042").max(comparator).get(),
            equalTo("test-000042"));
        assertThat(
            Stream.of(".a-000002", ".b-000001").max(comparator).get(),
            equalTo(".a-000002"));
    }

    private void createIndexAndAliasIfNecessary(ClusterState clusterState) {
        MlIndexAndAlias.createIndexAndAliasIfNecessary(
            client, clusterState, new IndexNameExpressionResolver(new ThreadContext(Settings.EMPTY)),
            TEST_INDEX_PREFIX, TEST_INDEX_ALIAS, listener);
    }

    @SuppressWarnings("unchecked")
    private static <Response> Answer<Response> withResponse(Response response) {
        return invocationOnMock -> {
            ActionListener<Response> listener = (ActionListener<Response>) invocationOnMock.getArguments()[1];
            listener.onResponse(response);
            return null;
        };
    }

    private static ClusterState createClusterState(Map<String, IndexMetadata> indices) {
        return createClusterState(indices, Collections.emptyMap());
    }

    private static ClusterState createClusterState(Map<String, IndexMetadata> indices, Map<String, IndexTemplateMetadata> templates) {
        return ClusterState.builder(ClusterName.DEFAULT)
            .metadata(Metadata.builder()
                .indices(ImmutableOpenMap.<String, IndexMetadata>builder().putAll(indices).build())
                .templates(ImmutableOpenMap.<String, IndexTemplateMetadata>builder().putAll(templates).build())
                .build())
            .build();
    }

    private static IndexMetadata createIndexMetadata(String indexName) {
        return createIndexMetadata(indexName, false);
    }

    private static IndexMetadata createIndexMetadataWithAlias(String indexName) {
        return createIndexMetadata(indexName, true);
    }

    private static IndexTemplateMetadata createIndexTemplateMetaData(String templateName, List<String> patterns) {
        return IndexTemplateMetadata.builder(templateName).patterns(patterns).build();
    }

    private static IndexMetadata createIndexMetadata(String indexName, boolean withAlias) {
        Settings settings =
            Settings.builder()
                .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
                .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .build();
        IndexMetadata.Builder builder = IndexMetadata.builder(indexName)
            .settings(settings);
        if (withAlias) {
            builder.putAlias(AliasMetadata.builder(TEST_INDEX_ALIAS).build());
        }
        return builder.build();
    }
}


text:
package de.uxnr.tsoexpert.game.communication.vo;

import java.util.List;

import de.uxnr.amf.v3.AMF3_Object;

public class ResourcesVO extends AMF3_Object {
  private int free;
  private int military;
  private List<ResourceVO> resources_vector;
  private int workers;

  public int getFree() {
    return this.free;
  }

  public int getMilitary() {
    return this.military;
  }

  public List<ResourceVO> getResources_vector() {
    return this.resources_vector;
  }

  public int getWorkers() {
    return this.workers;
  }
}


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

namespace TestFoundations.UnitTests
{
    public class ConcreteClassWithParametersAttributes
    {
        [CustomContractWithParameters(42, "value", typeof(void))]
        public void Method()
        {
            throw new NotImplementedException();
        }
    }
}


text:
jest.unmock('./responses.json')
const responses = require('./responses.json')

function fetch(url) {
  return new Promise((resolve, reject) => {
    const endPoint = /[^/]*/.exec(url.substr(20))[0]
    const response = {
      json() {
        let template = {
          "meta": responses.meta,
          "results": [responses[endPoint]]
        }
        return JSON.stringify(template)
      }
    }
    process.nextTick(() => {
      if (responses[endPoint]) {
        resolve(response)
      }
      reject({
        "statusCode": 404,
        "error": "Not Found"
      })
    })
  })
}

module.exports = fetch


text:
package limelight.styles.compiling;

import limelight.styles.abstrstyling.StyleCompiler;
import limelight.styles.abstrstyling.StyleValue;
import limelight.styles.values.SimpleFontStyleValue;

public class FontStyleAttributeCompiler extends StyleCompiler
{
  public StyleValue compile(Object value)
  {
    String lowerCase = stringify(value).toLowerCase().trim();

    if("plain".equals(lowerCase))
      return new SimpleFontStyleValue("plain");
    else
    {
      String[] tokens = lowerCase.split(" ");
      for(String token : tokens)
      {
        if(!"bold".equals(token) && !"italic".equals(token))
          throw makeError(value);
      }
      return new SimpleFontStyleValue(lowerCase);
    }

  }
}


text:
import {SequenceParams} from '../../data';
import {hash} from '../../util';
import {SequenceTransform as VgSequenceTransform} from 'vega';
import {DataFlowNode} from './dataflow';

export class SequenceNode extends DataFlowNode {
  public clone() {
    return new SequenceNode(null, this.params);
  }

  constructor(parent: DataFlowNode, private params: SequenceParams) {
    super(parent);
  }

  public dependentFields() {
    return new Set<string>();
  }

  public producedFields() {
    return new Set([this.params.as ?? 'data']);
  }

  public hash() {
    return `Hash ${hash(this.params)}`;
  }

  public assemble(): VgSequenceTransform {
    return {
      type: 'sequence',
      ...this.params
    };
  }
}


text:
<template name="messagePopupChannel">
	{{name}}
</template>


text:
using con = Anycmd.Xacml.Context;

namespace Anycmd.Xacml.ControlCenter.ContextTreeNodes
{
	/// <summary>
	///
	/// </summary>
	public class Resource : TreeNodes.NoBoldNode
	{
		/// <summary>
		///
		/// </summary>
		private con.ResourceElementReadWrite _resource;

		/// <summary>
		///
		/// </summary>
		/// <param name="resource"></param>
		public Resource( con.ResourceElementReadWrite resource )
		{
			_resource = resource;

			this.Text = "Resource";
			this.SelectedImageIndex = 2;
			this.ImageIndex = 2;

			foreach( con.AttributeElementReadWrite attr in _resource.Attributes )
			{
				this.Nodes.Add( new Attribute( attr ) );
			}
		}

		/// <summary>
		///
		/// </summary>
		public con.ResourceElementReadWrite ResourceDefinition
		{
			get{ return _resource; }
		}
	}
}


text:
<!DOCTYPE html>

        <title>com.quest.doradus.mbeans</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

                This package implements the interfaces of MBeans/MXBeans which compose the
                management interface of the Doradus-server.