text:
import {createHash} from 'crypto';
import {totalmem} from 'os';
import * as path from 'path';
import chalk = require('chalk');
import merge = require('deepmerge');
import {sync as glob} from 'glob';
import {statSync} from 'graceful-fs';
import micromatch = require('micromatch');
import type {Config} from '@jest/types';
import {replacePathSepForRegex} from 'jest-regex-util';
import Resolver, {
  resolveRunner,
  resolveSequencer,
  resolveTestEnvironment,
  resolveWatchPlugin,
} from 'jest-resolve';
import {
  clearLine,
  replacePathSepForGlob,
  requireOrImportModule,
  tryRealpath,
} from 'jest-util';
import {ValidationError, validate} from 'jest-validate';
import DEFAULT_CONFIG from './Defaults';
import DEPRECATED_CONFIG from './Deprecated';
import {validateReporters} from './ReporterValidationErrors';
import {
  initialOptions as VALID_CONFIG,
  initialProjectOptions as VALID_PROJECT_CONFIG,
} from './ValidConfig';
import {getDisplayNameColor} from './color';
import {DEFAULT_JS_PATTERN} from './constants';
import getMaxWorkers from './getMaxWorkers';
import {parseShardPair} from './parseShardPair';
import setFromArgv from './setFromArgv';
import stringToBytes from './stringToBytes';
import {
  BULLET,
  DOCUMENTATION_NOTE,
  _replaceRootDirTags,
  escapeGlobCharacters,
  replaceRootDirInPath,
  resolve,
} from './utils';
import validatePattern from './validatePattern';

const ERROR = `${BULLET}Validation Error`;
const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs'];
const PRESET_NAME = 'jest-preset';

export type AllOptions = Config.ProjectConfig & Config.GlobalConfig;

const createConfigError = (message: string) =>
  new ValidationError(ERROR, message, DOCUMENTATION_NOTE);

function verifyDirectoryExists(path: string, key: string) {
  try {
    const rootStat = statSync(path);

    if (!rootStat.isDirectory()) {
      throw createConfigError(
        `  ${chalk.bold(path)} in the ${chalk.bold(
          key,
        )} option is not a directory.`,
      );
    }
  } catch (err: any) {
    if (err instanceof ValidationError) {
      throw err;
    }

    if (err.code === 'ENOENT') {
      throw createConfigError(
        `  Directory ${chalk.bold(path)} in the ${chalk.bold(
          key,
        )} option was not found.`,
      );
    }

    // Not sure in which cases `statSync` can throw, so let's just show the underlying error to the user
    throw createConfigError(
      `  Got an error trying to find ${chalk.bold(path)} in the ${chalk.bold(
        key,
      )} option.\n\n  Error was: ${err.message}`,
    );
  }
}

const mergeOptionWithPreset = <T extends 'moduleNameMapper' | 'transform'>(
  options: Config.InitialOptions,
  preset: Config.InitialOptions,
  optionName: T,
) => {
  if (options[optionName] && preset[optionName]) {
    options[optionName] = {
      ...options[optionName],
      ...preset[optionName],
      ...options[optionName],
    };
  }
};

const mergeGlobalsWithPreset = (
  options: Config.InitialOptions,
  preset: Config.InitialOptions,
) => {
  if (options.globals && preset.globals) {
    options.globals = merge(preset.globals, options.globals);
  }
};

const setupPreset = async (
  options: Config.InitialOptionsWithRootDir,
  optionsPreset: string,
): Promise<Config.InitialOptionsWithRootDir> => {
  let preset: Config.InitialOptions;
  const presetPath = replaceRootDirInPath(options.rootDir, optionsPreset);
  const presetModule = Resolver.findNodeModule(
    presetPath.startsWith('.')
      ? presetPath
      : path.join(presetPath, PRESET_NAME),
    {
      basedir: options.rootDir,
      extensions: PRESET_EXTENSIONS,
    },
  );

  try {
    if (!presetModule) {
      throw new Error(`Cannot find module '${presetPath}'`);
    }

    // Force re-evaluation to support multiple projects
    try {
      delete require.cache[require.resolve(presetModule)];
    } catch {}

    preset = await requireOrImportModule(presetModule);
  } catch (error: any) {
    if (error instanceof SyntaxError || error instanceof TypeError) {
      throw createConfigError(
        `  Preset ${chalk.bold(presetPath)} is invalid:\n\n  ${
          error.message
        }\n  ${error.stack}`,
      );
    }

    if (error.message.includes('Cannot find module')) {
      if (error.message.includes(presetPath)) {
        const preset = Resolver.findNodeModule(presetPath, {
          basedir: options.rootDir,
        });

        if (preset) {
          throw createConfigError(
            `  Module ${chalk.bold(
              presetPath,
            )} should have "jest-preset.js" or "jest-preset.json" file at the root.`,
          );
        }
        throw createConfigError(
          `  Preset ${chalk.bold(presetPath)} not found.`,
        );
      }
      throw createConfigError(
        `  Missing dependency in ${chalk.bold(presetPath)}:\n\n  ${
          error.message
        }\n  ${error.stack}`,
      );
    }

    throw createConfigError(
      `  An unknown error occurred in ${chalk.bold(presetPath)}:\n\n  ${
        error.message
      }\n  ${error.stack}`,
    );
  }

  if (options.setupFiles) {
    options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles);
  }
  if (options.setupFilesAfterEnv) {
    options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat(
      options.setupFilesAfterEnv,
    );
  }
  if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) {
    options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat(
      options.modulePathIgnorePatterns,
    );
  }
  mergeOptionWithPreset(options, preset, 'moduleNameMapper');
  mergeOptionWithPreset(options, preset, 'transform');
  mergeGlobalsWithPreset(options, preset);

  return {...preset, ...options};
};

const setupBabelJest = (options: Config.InitialOptionsWithRootDir) => {
  const transform = options.transform;
  let babelJest;
  if (transform) {
    const customJSPattern = Object.keys(transform).find(pattern => {
      const regex = new RegExp(pattern);
      return regex.test('a.js') || regex.test('a.jsx');
    });
    const customTSPattern = Object.keys(transform).find(pattern => {
      const regex = new RegExp(pattern);
      return regex.test('a.ts') || regex.test('a.tsx');
    });

    [customJSPattern, customTSPattern].forEach(pattern => {
      if (pattern) {
        const customTransformer = transform[pattern];
        if (Array.isArray(customTransformer)) {
          if (customTransformer[0] === 'babel-jest') {
            babelJest = require.resolve('babel-jest');
            customTransformer[0] = babelJest;
          } else if (customTransformer[0].includes('babel-jest')) {
            babelJest = customTransformer[0];
          }
        } else {
          if (customTransformer === 'babel-jest') {
            babelJest = require.resolve('babel-jest');
            transform[pattern] = babelJest;
          } else if (customTransformer.includes('babel-jest')) {
            babelJest = customTransformer;
          }
        }
      }
    });
  } else {
    babelJest = require.resolve('babel-jest');
    options.transform = {
      [DEFAULT_JS_PATTERN]: babelJest,
    };
  }
};

const normalizeCollectCoverageFrom = (
  options: Config.InitialOptions &
    Required<Pick<Config.InitialOptions, 'collectCoverageFrom'>>,
  key: keyof Pick<Config.InitialOptions, 'collectCoverageFrom'>,
) => {
  const initialCollectCoverageFrom = options[key];
  let value: Array<string> | undefined;
  if (!initialCollectCoverageFrom) {
    value = [];
  }

  if (!Array.isArray(initialCollectCoverageFrom)) {
    try {
      value = JSON.parse(initialCollectCoverageFrom);
    } catch {}

    if (options[key] && !Array.isArray(value)) {
      value = [initialCollectCoverageFrom];
    }
  } else {
    value = initialCollectCoverageFrom;
  }

  if (value) {
    value = value.map(filePath =>
      filePath.replace(/^(!?)(<rootDir>\/)(.*)/, '$1$3'),
    );
  }

  return value;
};

const normalizeUnmockedModulePathPatterns = (
  options: Config.InitialOptionsWithRootDir,
  key: keyof Pick<
    Config.InitialOptions,
    | 'coveragePathIgnorePatterns'
    | 'modulePathIgnorePatterns'
    | 'testPathIgnorePatterns'
    | 'transformIgnorePatterns'
    | 'watchPathIgnorePatterns'
    | 'unmockedModulePathPatterns'
  >,
) =>
  // _replaceRootDirTags is specifically well-suited for substituting
  // <rootDir> in paths (it deals with properly interpreting relative path
  // separators, etc).
  //
  // For patterns, direct global substitution is far more ideal, so we
  // special case substitutions for patterns here.
  options[key]!.map(pattern =>
    replacePathSepForRegex(pattern.replace(/<rootDir>/g, options.rootDir)),
  );

const normalizeMissingOptions = (
  options: Config.InitialOptionsWithRootDir,
  configPath: string | null | undefined,
  projectIndex: number,
): Config.InitialOptionsWithRootDir => {
  if (!options.id) {
    options.id = createHash('sha1')
      .update(options.rootDir)
      // In case we load config from some path that has the same root dir
      .update(configPath || '')
      .update(String(projectIndex))
      .digest('hex')
      .substring(0, 32);
  }

  if (!options.setupFiles) {
    options.setupFiles = [];
  }

  return options;
};

const normalizeRootDir = (
  options: Config.InitialOptions,
): Config.InitialOptionsWithRootDir => {
  // Assert that there *is* a rootDir
  if (!options.rootDir) {
    throw createConfigError(
      `  Configuration option ${chalk.bold('rootDir')} must be specified.`,
    );
  }
  options.rootDir = path.normalize(options.rootDir);

  try {
    // try to resolve windows short paths, ignoring errors (permission errors, mostly)
    options.rootDir = tryRealpath(options.rootDir);
  } catch {
    // ignored
  }

  verifyDirectoryExists(options.rootDir, 'rootDir');

  return {
    ...options,
    rootDir: options.rootDir,
  };
};

const normalizeReporters = ({
  reporters,
  rootDir,
}: Config.InitialOptionsWithRootDir):
  | Array<Config.ReporterConfig>
  | undefined => {
  if (!reporters || !Array.isArray(reporters)) {
    return undefined;
  }

  validateReporters(reporters);

  return reporters.map(reporterConfig => {
    const normalizedReporterConfig: Config.ReporterConfig =
      typeof reporterConfig === 'string'
        ? // if reporter config is a string, we wrap it in an array
          // and pass an empty object for options argument, to normalize
          // the shape.
          [reporterConfig, {}]
        : reporterConfig;

    const reporterPath = replaceRootDirInPath(
      rootDir,
      normalizedReporterConfig[0],
    );

    if (!['default', 'github-actions', 'summary'].includes(reporterPath)) {
      const reporter = Resolver.findNodeModule(reporterPath, {
        basedir: rootDir,
      });
      if (!reporter) {
        throw new Resolver.ModuleNotFoundError(
          'Could not resolve a module for a custom reporter.\n' +
            `  Module name: ${reporterPath}`,
        );
      }
      normalizedReporterConfig[0] = reporter;
    }
    return normalizedReporterConfig;
  });
};

const buildTestPathPattern = (argv: Config.Argv): string => {
  const patterns = [];

  if (argv._) {
    patterns.push(...argv._);
  }
  if (argv.testPathPattern) {
    patterns.push(...argv.testPathPattern);
  }

  const replacePosixSep = (pattern: string | number) => {
    // yargs coerces positional args into numbers
    const patternAsString = pattern.toString();
    if (path.sep === '/') {
      return patternAsString;
    }
    return patternAsString.replace(/\//g, '\\\\');
  };

  const testPathPattern = patterns.map(replacePosixSep).join('|');
  if (validatePattern(testPathPattern)) {
    return testPathPattern;
  } else {
    showTestPathPatternError(testPathPattern);
    return '';
  }
};

const showTestPathPatternError = (testPathPattern: string) => {
  clearLine(process.stdout);

  // eslint-disable-next-line no-console
  console.log(
    chalk.red(
      `  Invalid testPattern ${testPathPattern} supplied. ` +
        'Running all tests instead.',
    ),
  );
};

function validateExtensionsToTreatAsEsm(
  extensionsToTreatAsEsm: Config.InitialOptions['extensionsToTreatAsEsm'],
) {
  if (!extensionsToTreatAsEsm || extensionsToTreatAsEsm.length === 0) {
    return;
  }

  function printConfig(opts: Array<string>) {
    const string = opts.map(ext => `'${ext}'`).join(', ');

    return chalk.bold(`extensionsToTreatAsEsm: [${string}]`);
  }

  const extensionWithoutDot = extensionsToTreatAsEsm.some(
    ext => !ext.startsWith('.'),
  );

  if (extensionWithoutDot) {
    throw createConfigError(
      `  Option: ${printConfig(
        extensionsToTreatAsEsm,
      )} includes a string that does not start with a period (${chalk.bold(
        '.',
      )}).
  Please change your configuration to ${printConfig(
    extensionsToTreatAsEsm.map(ext => (ext.startsWith('.') ? ext : `.${ext}`)),
  )}.`,
    );
  }

  if (extensionsToTreatAsEsm.includes('.js')) {
    throw createConfigError(
      `  Option: ${printConfig(extensionsToTreatAsEsm)} includes ${chalk.bold(
        "'.js'",
      )} which is always inferred based on ${chalk.bold(
        'type',
      )} in its nearest ${chalk.bold('package.json')}.`,
    );
  }

  if (extensionsToTreatAsEsm.includes('.cjs')) {
    throw createConfigError(
      `  Option: ${printConfig(extensionsToTreatAsEsm)} includes ${chalk.bold(
        "'.cjs'",
      )} which is always treated as CommonJS.`,
    );
  }

  if (extensionsToTreatAsEsm.includes('.mjs')) {
    throw createConfigError(
      `  Option: ${printConfig(extensionsToTreatAsEsm)} includes ${chalk.bold(
        "'.mjs'",
      )} which is always treated as an ECMAScript Module.`,
    );
  }
}

export default async function normalize(
  initialOptions: Config.InitialOptions,
  argv: Config.Argv,
  configPath?: string | null,
  projectIndex = Infinity,
  isProjectOptions?: boolean,
): Promise<{
  hasDeprecationWarnings: boolean;
  options: AllOptions;
}> {
  const {hasDeprecationWarnings} = validate(initialOptions, {
    comment: DOCUMENTATION_NOTE,
    deprecatedConfig: DEPRECATED_CONFIG,
    exampleConfig: isProjectOptions ? VALID_PROJECT_CONFIG : VALID_CONFIG,
    recursiveDenylist: [
      // 'coverageThreshold' allows to use 'global' and glob strings on the same
      // level, there's currently no way we can deal with such config
      'coverageThreshold',
      'globals',
      'moduleNameMapper',
      'testEnvironmentOptions',
      'transform',
    ],
  });

  let options = normalizeMissingOptions(
    normalizeRootDir(setFromArgv(initialOptions, argv)),
    configPath,
    projectIndex,
  );

  if (options.preset) {
    options = await setupPreset(options, options.preset);
  }

  if (!options.setupFilesAfterEnv) {
    options.setupFilesAfterEnv = [];
  }

  options.testEnvironment = resolveTestEnvironment({
    requireResolveFunction: require.resolve,
    rootDir: options.rootDir,
    testEnvironment:
      options.testEnvironment ||
      require.resolve(DEFAULT_CONFIG.testEnvironment),
  });

  if (!options.roots) {
    options.roots = [options.rootDir];
  }

  if (
    !options.testRunner ||
    options.testRunner === 'circus' ||
    options.testRunner === 'jest-circus' ||
    options.testRunner === 'jest-circus/runner'
  ) {
    options.testRunner = require.resolve('jest-circus/runner');
  } else if (options.testRunner === 'jasmine2') {
    try {
      options.testRunner = require.resolve('jest-jasmine2');
    } catch (error: any) {
      if (error.code === 'MODULE_NOT_FOUND') {
        throw createConfigError(
          'jest-jasmine is no longer shipped by default with Jest, you need to install it explicitly or provide an absolute path to Jest',
        );
      }

      throw error;
    }
  }

  if (!options.coverageDirectory) {
    options.coverageDirectory = path.resolve(options.rootDir, 'coverage');
  }

  setupBabelJest(options);
  // TODO: Type this properly
  const newOptions = {
    ...DEFAULT_CONFIG,
  } as unknown as AllOptions;

  if (options.resolver) {
    newOptions.resolver = resolve(null, {
      filePath: options.resolver,
      key: 'resolver',
      rootDir: options.rootDir,
    });
  }

  validateExtensionsToTreatAsEsm(options.extensionsToTreatAsEsm);

  if (options.watchman == null) {
    options.watchman = DEFAULT_CONFIG.watchman;
  }

  const optionKeys = Object.keys(options) as Array<keyof Config.InitialOptions>;

  optionKeys.reduce((newOptions, key: keyof Config.InitialOptions) => {
    // The resolver has been resolved separately; skip it
    if (key === 'resolver') {
      return newOptions;
    }

    // This is cheating, because it claims that all keys of InitialOptions are Required.
    // We only really know it's Required for oldOptions[key], not for oldOptions.someOtherKey,
    // so oldOptions[key] is the only way it should be used.
    const oldOptions = options as Config.InitialOptions &
      Required<Pick<Config.InitialOptions, typeof key>>;
    let value;
    switch (key) {
      case 'setupFiles':
      case 'setupFilesAfterEnv':
      case 'snapshotSerializers':
        {
          const option = oldOptions[key];
          value =
            option &&
            option.map(filePath =>
              resolve(newOptions.resolver, {
                filePath,
                key,
                rootDir: options.rootDir,
              }),
            );
        }
        break;
      case 'modulePaths':
      case 'roots':
        {
          const option = oldOptions[key];
          value =
            option &&
            option.map(filePath =>
              path.resolve(
                options.rootDir,
                replaceRootDirInPath(options.rootDir, filePath),
              ),
            );
        }
        break;
      case 'collectCoverageFrom':
        value = normalizeCollectCoverageFrom(oldOptions, key);
        break;
      case 'cacheDirectory':
      case 'coverageDirectory':
        {
          const option = oldOptions[key];
          value =
            option &&
            path.resolve(
              options.rootDir,
              replaceRootDirInPath(options.rootDir, option),
            );
        }
        break;
      case 'dependencyExtractor':
      case 'globalSetup':
      case 'globalTeardown':
      case 'runtime':
      case 'snapshotResolver':
      case 'testResultsProcessor':
      case 'testRunner':
      case 'filter':
        {
          const option = oldOptions[key];
          value =
            option &&
            resolve(newOptions.resolver, {
              filePath: option,
              key,
              rootDir: options.rootDir,
            });
        }
        break;
      case 'runner':
        {
          const option = oldOptions[key];
          value =
            option &&
            resolveRunner(newOptions.resolver, {
              filePath: option,
              requireResolveFunction: require.resolve,
              rootDir: options.rootDir,
            });
        }
        break;
      case 'prettierPath':
        {
          // We only want this to throw if "prettierPath" is explicitly passed
          // from config or CLI, and the requested path isn't found. Otherwise we
          // set it to null and throw an error lazily when it is used.

          const option = oldOptions[key];

          value =
            option &&
            resolve(newOptions.resolver, {
              filePath: option,
              key,
              optional: option === DEFAULT_CONFIG[key],
              rootDir: options.rootDir,
            });
        }
        break;
      case 'moduleNameMapper':
        const moduleNameMapper = oldOptions[key];
        value =
          moduleNameMapper &&
          Object.keys(moduleNameMapper).map(regex => {
            const item = moduleNameMapper && moduleNameMapper[regex];
            return item && [regex, _replaceRootDirTags(options.rootDir, item)];
          });
        break;
      case 'transform':
        const transform = oldOptions[key];
        value =
          transform &&
          Object.keys(transform).map(regex => {
            const transformElement = transform[regex];
            return [
              regex,
              resolve(newOptions.resolver, {
                filePath: Array.isArray(transformElement)
                  ? transformElement[0]
                  : transformElement,
                key,
                rootDir: options.rootDir,
              }),
              Array.isArray(transformElement) ? transformElement[1] : {},
            ];
          });
        break;
      case 'reporters':
        value = normalizeReporters(oldOptions);
        break;
      case 'coveragePathIgnorePatterns':
      case 'modulePathIgnorePatterns':
      case 'testPathIgnorePatterns':
      case 'transformIgnorePatterns':
      case 'watchPathIgnorePatterns':
      case 'unmockedModulePathPatterns':
        value = normalizeUnmockedModulePathPatterns(oldOptions, key);
        break;
      case 'haste':
        value = {...oldOptions[key]};
        if (value.hasteImplModulePath != null) {
          const resolvedHasteImpl = resolve(newOptions.resolver, {
            filePath: replaceRootDirInPath(
              options.rootDir,
              value.hasteImplModulePath,
            ),
            key: 'haste.hasteImplModulePath',
            rootDir: options.rootDir,
          });

          value.hasteImplModulePath = resolvedHasteImpl || undefined;
        }
        break;
      case 'projects':
        value = (oldOptions[key] || [])
          .map(project =>
            typeof project === 'string'
              ? _replaceRootDirTags(options.rootDir, project)
              : project,
          )
          .reduce<Array<string | Config.InitialProjectOptions>>(
            (projects, project) => {
              // Project can be specified as globs. If a glob matches any files,
              // We expand it to these paths. If not, we keep the original path
              // for the future resolution.
              const globMatches =
                typeof project === 'string' ? glob(project) : [];
              return projects.concat(
                globMatches.length ? globMatches : project,
              );
            },
            [],
          );
        break;
      case 'moduleDirectories':
      case 'testMatch':
        {
          const replacedRootDirTags = _replaceRootDirTags(
            escapeGlobCharacters(options.rootDir),
            oldOptions[key],
          );

          if (replacedRootDirTags) {
            value = Array.isArray(replacedRootDirTags)
              ? replacedRootDirTags.map(replacePathSepForGlob)
              : replacePathSepForGlob(replacedRootDirTags);
          } else {
            value = replacedRootDirTags;
          }
        }
        break;
      case 'testRegex':
        {
          const option = oldOptions[key];
          value = option
            ? (Array.isArray(option) ? option : [option]).map(
                replacePathSepForRegex,
              )
            : [];
        }
        break;
      case 'moduleFileExtensions': {
        value = oldOptions[key];

        if (
          Array.isArray(value) && // If it's the wrong type, it can throw at a later time
          (options.runner === undefined ||
            options.runner === DEFAULT_CONFIG.runner) && // Only require 'js' for the default jest-runner
          !value.includes('js')
        ) {
          const errorMessage =
            "  moduleFileExtensions must include 'js':\n" +
            '  but instead received:\n' +
            `    ${chalk.bold.red(JSON.stringify(value))}`;

          // If `js` is not included, any dependency Jest itself injects into
          // the environment, like jasmine or sourcemap-support, will need to
          // `require` its modules with a file extension. This is not plausible
          // in the long run, so it's way easier to just fail hard early.
          // We might consider throwing if `json` is missing as well, as it's a
          // fair assumption from modules that they can do
          // `require('some-package/package') without the trailing `.json` as it
          // works in Node normally.
          throw createConfigError(
            `${errorMessage}\n  Please change your configuration to include 'js'.`,
          );
        }

        break;
      }
      case 'bail': {
        const bail = oldOptions[key];
        if (typeof bail === 'boolean') {
          value = bail ? 1 : 0;
        } else if (typeof bail === 'string') {
          value = 1;
          // If Jest is invoked as `jest --bail someTestPattern` then need to
          // move the pattern from the `bail` configuration and into `argv._`
          // to be processed as an extra parameter
          argv._.push(bail);
        } else {
          value = oldOptions[key];
        }
        break;
      }
      case 'displayName': {
        const displayName = oldOptions[key] as Config.DisplayName;
        /**
         * Ensuring that displayName shape is correct here so that the
         * reporters can trust the shape of the data
         */
        if (typeof displayName === 'object') {
          const {name, color} = displayName;
          if (
            !name ||
            !color ||
            typeof name !== 'string' ||
            typeof color !== 'string'
          ) {
            const errorMessage =
              `  Option "${chalk.bold('displayName')}" must be of type:\n\n` +
              '  {\n' +
              '    name: string;\n' +
              '    color: string;\n' +
              '  }\n';
            throw createConfigError(errorMessage);
          }
          value = oldOptions[key];
        } else {
          value = {
            color: getDisplayNameColor(options.runner),
            name: displayName,
          };
        }
        break;
      }
      case 'testTimeout': {
        if (oldOptions[key] < 0) {
          throw createConfigError(
            `  Option "${chalk.bold('testTimeout')}" must be a natural number.`,
          );
        }

        value = oldOptions[key];
        break;
      }
      case 'snapshotFormat': {
        value = {...DEFAULT_CONFIG.snapshotFormat, ...oldOptions[key]};

        break;
      }
      case 'automock':
      case 'cache':
      case 'changedSince':
      case 'changedFilesWithAncestor':
      case 'clearMocks':
      case 'collectCoverage':
      case 'coverageProvider':
      case 'coverageReporters':
      case 'coverageThreshold':
      case 'detectLeaks':
      case 'detectOpenHandles':
      case 'errorOnDeprecated':
      case 'expand':
      case 'extensionsToTreatAsEsm':
      case 'globals':
      case 'fakeTimers':
      case 'findRelatedTests':
      case 'forceCoverageMatch':
      case 'forceExit':
      case 'injectGlobals':
      case 'lastCommit':
      case 'listTests':
      case 'logHeapUsage':
      case 'maxConcurrency':
      case 'id':
      case 'noStackTrace':
      case 'notify':
      case 'notifyMode':
      case 'onlyChanged':
      case 'onlyFailures':
      case 'outputFile':
      case 'passWithNoTests':
      case 'replname':
      case 'resetMocks':
      case 'resetModules':
      case 'restoreMocks':
      case 'rootDir':
      case 'runTestsByPath':
      case 'sandboxInjectedGlobals':
      case 'silent':
      case 'showSeed':
      case 'skipFilter':
      case 'skipNodeResolution':
      case 'slowTestThreshold':
      case 'testEnvironment':
      case 'testEnvironmentOptions':
      case 'testFailureExitCode':
      case 'testLocationInResults':
      case 'testNamePattern':
      case 'useStderr':
      case 'verbose':
      case 'watch':
      case 'watchAll':
      case 'watchman':
        value = oldOptions[key];
        break;
      case 'workerIdleMemoryLimit':
        value = stringToBytes(oldOptions[key], totalmem());
        break;
      case 'watchPlugins':
        value = (oldOptions[key] || []).map(watchPlugin => {
          if (typeof watchPlugin === 'string') {
            return {
              config: {},
              path: resolveWatchPlugin(newOptions.resolver, {
                filePath: watchPlugin,
                requireResolveFunction: require.resolve,
                rootDir: options.rootDir,
              }),
            };
          } else {
            return {
              config: watchPlugin[1] || {},
              path: resolveWatchPlugin(newOptions.resolver, {
                filePath: watchPlugin[0],
                requireResolveFunction: require.resolve,
                rootDir: options.rootDir,
              }),
            };
          }
        });
        break;
    }
    // @ts-expect-error: automock is missing in GlobalConfig, so what
    newOptions[key] = value;
    return newOptions;
  }, newOptions);

  if (options.watchman && options.haste?.enableSymlinks) {
    throw new ValidationError(
      'Validation Error',
      'haste.enableSymlinks is incompatible with watchman',
      'Either set haste.enableSymlinks to false or do not use watchman',
    );
  }

  newOptions.roots.forEach((root, i) => {
    verifyDirectoryExists(root, `roots[${i}]`);
  });

  try {
    // try to resolve windows short paths, ignoring errors (permission errors, mostly)
    newOptions.cwd = tryRealpath(process.cwd());
  } catch {
    // ignored
  }

  newOptions.testSequencer = resolveSequencer(newOptions.resolver, {
    filePath:
      options.testSequencer || require.resolve(DEFAULT_CONFIG.testSequencer),
    requireResolveFunction: require.resolve,
    rootDir: options.rootDir,
  });

  if (newOptions.runner === DEFAULT_CONFIG.runner) {
    newOptions.runner = require.resolve(newOptions.runner);
  }

  newOptions.nonFlagArgs = argv._?.map(arg => `${arg}`);
  newOptions.testPathPattern = buildTestPathPattern(argv);
  newOptions.json = !!argv.json;

  newOptions.testFailureExitCode = parseInt(
    newOptions.testFailureExitCode as unknown as string,
    10,
  );

  if (
    newOptions.lastCommit ||
    newOptions.changedFilesWithAncestor ||
    newOptions.changedSince
  ) {
    newOptions.onlyChanged = true;
  }

  if (argv.all) {
    newOptions.onlyChanged = false;
    newOptions.onlyFailures = false;
  } else if (newOptions.testPathPattern) {
    // When passing a test path pattern we don't want to only monitor changed
    // files unless `--watch` is also passed.
    newOptions.onlyChanged = newOptions.watch;
  }

  newOptions.showSeed = newOptions.showSeed || argv.showSeed;

  const upperBoundSeedValue = 2 ** 31;

  // xoroshiro128plus is used in v8 and is used here (at time of writing)
  newOptions.seed =
    argv.seed ??
    Math.floor((2 ** 32 - 1) * Math.random() - upperBoundSeedValue);
  if (
    newOptions.seed < -upperBoundSeedValue ||
    newOptions.seed > upperBoundSeedValue - 1
  ) {
    throw new ValidationError(
      'Validation Error',
      `seed value must be between \`-0x80000000\` and \`0x7fffffff\` inclusive - is ${newOptions.seed}`,
    );
  }

  if (!newOptions.onlyChanged) {
    newOptions.onlyChanged = false;
  }

  if (!newOptions.lastCommit) {
    newOptions.lastCommit = false;
  }

  if (!newOptions.onlyFailures) {
    newOptions.onlyFailures = false;
  }

  if (!newOptions.watchAll) {
    newOptions.watchAll = false;
  }

  // as unknown since it can happen. We really need to fix the types here
  if (
    newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as unknown)
  ) {
    newOptions.moduleNameMapper = [];
  }

  if (argv.ci != null) {
    newOptions.ci = argv.ci;
  }

  newOptions.updateSnapshot =
    newOptions.ci && !argv.updateSnapshot
      ? 'none'
      : argv.updateSnapshot
      ? 'all'
      : 'new';

  newOptions.maxConcurrency = parseInt(
    newOptions.maxConcurrency as unknown as string,
    10,
  );
  newOptions.maxWorkers = getMaxWorkers(argv, options);

  if (newOptions.testRegex.length > 0 && options.testMatch) {
    throw createConfigError(
      `  Configuration options ${chalk.bold('testMatch')} and` +
        ` ${chalk.bold('testRegex')} cannot be used together.`,
    );
  }

  if (newOptions.testRegex.length > 0 && !options.testMatch) {
    // Prevent the default testMatch conflicting with any explicitly
    // configured `testRegex` value
    newOptions.testMatch = [];
  }

  // If argv.json is set, coverageReporters shouldn't print a text report.
  if (argv.json) {
    newOptions.coverageReporters = (newOptions.coverageReporters || []).filter(
      reporter => reporter !== 'text',
    );
  }

  // If collectCoverage is enabled while using --findRelatedTests we need to
  // avoid having false negatives in the generated coverage report.
  // The following: `--findRelatedTests '/rootDir/file1.js' --coverage`
  // Is transformed to: `--findRelatedTests '/rootDir/file1.js' --coverage --collectCoverageFrom 'file1.js'`
  // where arguments to `--collectCoverageFrom` should be globs (or relative
  // paths to the rootDir)
  if (newOptions.collectCoverage && argv.findRelatedTests) {
    let collectCoverageFrom = newOptions.nonFlagArgs.map(filename => {
      filename = replaceRootDirInPath(options.rootDir, filename);
      return path.isAbsolute(filename)
        ? path.relative(options.rootDir, filename)
        : filename;
    });

    // Don't override existing collectCoverageFrom options
    if (newOptions.collectCoverageFrom) {
      collectCoverageFrom = collectCoverageFrom.reduce((patterns, filename) => {
        if (
          micromatch(
            [replacePathSepForGlob(path.relative(options.rootDir, filename))],
            newOptions.collectCoverageFrom,
          ).length === 0
        ) {
          return patterns;
        }
        return [...patterns, filename];
      }, newOptions.collectCoverageFrom);
    }

    newOptions.collectCoverageFrom = collectCoverageFrom;
  } else if (!newOptions.collectCoverageFrom) {
    newOptions.collectCoverageFrom = [];
  }

  if (!newOptions.findRelatedTests) {
    newOptions.findRelatedTests = false;
  }

  if (!newOptions.projects) {
    newOptions.projects = [];
  }

  if (!newOptions.sandboxInjectedGlobals) {
    newOptions.sandboxInjectedGlobals = [];
  }

  if (!newOptions.forceExit) {
    newOptions.forceExit = false;
  }

  if (!newOptions.logHeapUsage) {
    newOptions.logHeapUsage = false;
  }

  if (argv.shard) {
    newOptions.shard = parseShardPair(argv.shard);
  }

  return {
    hasDeprecationWarnings,
    options: newOptions,
  };
}


text:
module Nanoc::Toolbox::Helpers

  # NANOC Helper for HTML Tags
  #
  # This module contains functions for generating simple tags with attribute
  #
  # @author Anouar ADLANI <anouar@adlani.com>
  module HtmlTag
    # Simple tag
    #
    # @param [String] name the tag name
    # @param [Hash] options options to set to the html element
    # @param [Boolean] open flag to set if the tag is self closing or not
    # @return [String] the requested tag string
    #
    # @example
    #   tag("br") # =>

    #   tag("hr", class => "thin", true) # =>

    #   tag("input", :type => 'text') # => <input type="text" />
    #
    def tag(name, options={}, open=false)
      "<#{name}#{tag_options(options) if options}#{open ? ">" : " />"}"
    end

    # Content tag
    #
    # @param [String] name the tag name
    # @param [Hash] options options to set to the html element
    # @param [Boolean] open flag to set if the tag is self closing or not
    # @return [String] the requested tag string
    #
    # @example
    #   content_tag(:p, "Hello world!")
    #    # =>
Hello world!

    #   content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
    #    # =>

Hello world!

    def content_tag(name, content, options={})
      "<#{name}#{tag_options(options) if options}>#{content}</#{name}>"
    end

    protected
      def tag_options(options)
        unless options.empty?
          attributes = []
          options.each do |key, value|
            attributes << %(#{key}="#{value}")
          end
          ' ' + attributes.join(' ')
        end
      end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

class Application
{

	protected $controller = "home";

	protected $method = "index";

	protected $params = array();

	public function __construct()
	{
		$url = $this->parseUrl();

		if(file_exists(INC_ROOT . "/app/controllers/" . $url[0] . ".php")) {
			$this->controller = $url[0];
			unset($url[0]);
		}

		require_once INC_ROOT . "/app/controllers/". $this->controller . ".php";

		$this->controller = new $this->controller;

		if(isset($url[1])) {
			if(method_exists($this->controller, $url[1])) {
				$this->method = $url[1];
				unset($url[1]);
			}
		}

		$this->params = $url ? array_values($url) : array();

		if(!empty($this->params))
		{
			call_user_func_array(array($this->controller, $this->method), $this->params);
		} else {
			call_user_func(array($this->controller, $this->method));
		}

	}

	protected function parseUrl()
	{
		$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
		$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
		if (strstr($uri, '?')){
			$uri = substr($uri, 0, strpos($uri, '?'));
		}
		$uri = explode('/', trim($uri, '/'));
		return $uri;
	}
}


text:
class ChangeWorkflowStatusToCmmWorkflowStatus < ActiveRecord::Migration
  def change
    rename_column :pa_requests, :workflow_status, :cmm_workflow_status
  end
end


text:
Test repo for Sabio.la

Testing out some conflicts

Testing a line


text:
package net.mcft.copy.backpacks;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.RenderPlayer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EnumPlayerModelParts;
import net.minecraft.item.ItemStack;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;

import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import net.mcft.copy.backpacks.BackpacksContent;
import net.mcft.copy.backpacks.WearableBackpacks;
import net.mcft.copy.backpacks.api.BackpackHelper;
import net.mcft.copy.backpacks.api.BackpackRegistry;
import net.mcft.copy.backpacks.api.IBackpack;
import net.mcft.copy.backpacks.api.BackpackRegistry.BackpackEntityEntry;
import net.mcft.copy.backpacks.ProxyCommon;
import net.mcft.copy.backpacks.block.entity.TileEntityBackpack;
import net.mcft.copy.backpacks.client.BakedModelDefaultTexture;
import net.mcft.copy.backpacks.client.KeyBindingHandler;
import net.mcft.copy.backpacks.client.RendererBackpack;
import net.mcft.copy.backpacks.item.ItemBackpack;
import net.mcft.copy.backpacks.misc.util.MiscUtils;
import net.mcft.copy.backpacks.misc.util.NbtUtils;
import net.mcft.copy.backpacks.misc.util.ReflectUtils;

@SideOnly(Side.CLIENT)
public class ProxyClient extends ProxyCommon {

	public static IBakedModel MODEL_BACKPACK;
	public static IBakedModel MODEL_BACKPACK_TOP;
	public static IBakedModel MODEL_BACKPACK_STRAPS;

	public static IBakedModel MODEL_BACKPACK_ENCH;
	public static IBakedModel MODEL_BACKPACK_ENCH_TOP;

	public static AxisAlignedBB MODEL_BACKPACK_BOX;

	@Override
	public void preInit() {
		super.preInit();
		MinecraftForge.EVENT_BUS.register(new KeyBindingHandler());
	}

	@Override
	public void init() {
		super.init();
		Minecraft mc = Minecraft.getMinecraft();

		if (BackpacksContent.BACKPACK != null) {
			mc.getBlockColors().registerBlockColorHandler(BLOCK_COLOR, MiscUtils.getBlockFromItem(BackpacksContent.BACKPACK));
			mc.getItemColors().registerItemColorHandler(ITEM_COLOR, BackpacksContent.BACKPACK);
			ClientRegistry.bindTileEntitySpecialRenderer(TileEntityBackpack.class, new RendererBackpack.TileEntity());
		}

		RenderManager manager = mc.getRenderManager();
		Map<String, RenderPlayer> skinMap = manager.getSkinMap();
		for (RenderPlayer renderer : skinMap.values()) {
			renderer.addLayer(new RendererBackpack.Layer(renderer));
		}
	}

	@Override
	public void initBackpackLayers() {
		// A for loop would be one less line.. but streams are pretty! >.<
		BackpackRegistry.getEntityEntries().stream()
			.map(BackpackEntityEntry::getEntityClass)
			.filter(Objects::nonNull)
			.forEach(ProxyClient::ensureHasBackpackLayer);
	}

	private static final Set<Class<? extends EntityLivingBase>> _hasLayerChecked = new HashSet<>();
	/** Ensures that the specified entity class' renderer has a backpack layer - if possible. */
	public static void ensureHasBackpackLayer(Class<? extends EntityLivingBase> entityClass) {
		if (!_hasLayerChecked.add(entityClass)) return;
		RenderManager manager = Minecraft.getMinecraft().getRenderManager();
		Render<?> render = manager.getEntityClassRenderObject(entityClass);
		if (!(render instanceof RenderLivingBase)) return;
		((RenderLivingBase<?>)render).addLayer(new RendererBackpack.Layer((RenderLivingBase<?>)render));
	}

	// Model related

	@SubscribeEvent
	public void onModelBake(ModelBakeEvent event) {
		MODEL_BACKPACK        = bakeBlockModel("wearablebackpacks:block/backpack");
		MODEL_BACKPACK_TOP    = bakeBlockModel("wearablebackpacks:block/backpack_top");
		MODEL_BACKPACK_STRAPS = bakeBlockModel("wearablebackpacks:block/backpack_straps");

		MODEL_BACKPACK_ENCH     = new BakedModelDefaultTexture(MODEL_BACKPACK);
		MODEL_BACKPACK_ENCH_TOP = new BakedModelDefaultTexture(MODEL_BACKPACK_TOP);

		MODEL_BACKPACK_BOX = ModelAABBCalculator.calcFrom(MODEL_BACKPACK, MODEL_BACKPACK_TOP);
	}
	private static IBakedModel bakeBlockModel(String location) {
		IModel model = getModel(new ResourceLocation(location));
		return model.bake(model.getDefaultState(), DefaultVertexFormats.BLOCK, loc ->
			Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(loc.toString()));
	}
	private static IModel getModel(ResourceLocation location) {
		try {
			IModel model = ModelLoaderRegistry.getModel(location);
			if (model == null) WearableBackpacks.LOG.error(
				"Model " + location + " is missing! THIS WILL CAUSE A CRASH!");
			return model;
		} catch (Exception e) { e.printStackTrace(); return null; }
	}

	@SubscribeEvent
	public void onRegisterModels(ModelRegistryEvent event) {
		if (BackpacksContent.BACKPACK != null) {
			ModelLoader.setCustomModelResourceLocation(BackpacksContent.BACKPACK, 0,
				new ModelResourceLocation("wearablebackpacks:backpack", "inventory"));
		}
	}

	private static class ModelAABBCalculator implements IVertexConsumer {

		public static AxisAlignedBB calcFrom(IBakedModel... models) {
			ModelAABBCalculator calc = new ModelAABBCalculator();
			for (IBakedModel model : models) calc.put(model);
			return calc.getAABB();
		}

		private double minX = 1.0F, minY = 1.0F, minZ = 1.0F;
		private double maxX = 0.0F, maxY = 0.0F, maxZ = 0.0F;

		public void put(IBakedModel model)
			{ for (BakedQuad quad : model.getQuads(null, null, 0)) quad.pipe(this); }

		public AxisAlignedBB getAABB()
			{ return new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); }

		// IVertexConsumer implementation

		public VertexFormat getVertexFormat() { return DefaultVertexFormats.POSITION; }

		public void setQuadTint(int tint) {  }
		public void setQuadOrientation(EnumFacing orientation) {  }
		public void setApplyDiffuseLighting(boolean diffuse) {  }
		public void setTexture(TextureAtlasSprite texture) {  }

		public void put(int element, float... data) {
			if (data[0] < minX) minX = data[0];
			if (data[0] > maxX) maxX = data[0];
			if (data[1] < minY) minY = data[1];
			if (data[1] > maxY) maxY = data[1];
			if (data[2] < minZ) minZ = data[2];
			if (data[2] > maxZ) maxZ = data[2];
		}

	}

	// IItemColor and IBlockColor implementations

	// TODO: Make this work for different default colors / non-dyeable backpacks.
	public static final IItemColor ITEM_COLOR = (stack, tintIndex) ->
		NbtUtils.get(stack, ItemBackpack.DEFAULT_COLOR, "display", "color");

	public static final IBlockColor BLOCK_COLOR = (state, world, pos, tintIndex) -> {
		ItemStack stack = ItemStack.EMPTY;
		if ((world != null) && (pos != null)) {
			IBackpack backpack = BackpackHelper.getBackpack(world.getTileEntity(pos));
			if (backpack != null) stack = backpack.getStack();
		}
		return ITEM_COLOR.colorMultiplier(stack, tintIndex);
	};

	// Lots of code just to disable capes when backpacks are equipped!

	private static DataParameter<Byte> PLAYER_MODEL_FLAG =
		ReflectUtils.get(EntityPlayer.class, "PLAYER_MODEL_FLAG", "field_184827_bp");

	/** Sets whether the player is currently wearing the specified model part.
	 *  This is the opposite of the {@link EntityPlayer#isWearing} method. */
	private static void setWearing(EntityPlayer player, EnumPlayerModelParts part, boolean value) {
		byte current = player.getDataManager().get(PLAYER_MODEL_FLAG).byteValue();
		if (value) current |= part.getPartMask();
		else current &= ~part.getPartMask();
		player.getDataManager().set(PLAYER_MODEL_FLAG, current);
	}

	private boolean _disabledCape = false;
	@SubscribeEvent(priority=EventPriority.LOWEST)
	public void onRenderPlayerPre(RenderPlayerEvent.Pre event) {
		EntityPlayer player = event.getEntityPlayer();
		if ((BackpackHelper.getBackpack(player) == null) ||
		    !player.isWearing(EnumPlayerModelParts.CAPE)) return;
		// Disable player rendering for players with equipped backpacks
		// by temporarily setting whether they are wearing it to false.
		setWearing(player, EnumPlayerModelParts.CAPE, false);
		_disabledCape = true;
	}
	@SubscribeEvent(priority=EventPriority.HIGHEST)
	public void onRenderPlayerPost(RenderPlayerEvent.Post event) {
		if (!_disabledCape) return;
		// Reenable cape rendering if it was disabled.
		EntityPlayer player = event.getEntityPlayer();
		setWearing(player, EnumPlayerModelParts.CAPE, true);
		_disabledCape = false;
	}

}


text:
#include "ProxyDestinationMap.h"

#include <folly/io/async/EventBase.h>
#include <folly/Memory.h>

#include "mcrouter/_router.h"
#include "mcrouter/lib/fbi/asox_timer.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/proxy.h"
#include "mcrouter/ProxyClientCommon.h"
#include "mcrouter/ProxyDestination.h"
#include "mcrouter/stats.h"

namespace facebook { namespace memcache { namespace mcrouter {

namespace {

void onResetTimer(const asox_timer_t timer, void* arg) {
  auto map = reinterpret_cast<ProxyDestinationMap*>(arg);
  map->resetAllInactive();
}

} // namespace

struct ProxyDestinationMap::StateList {
  using List = folly::IntrusiveList<ProxyDestination,
                                    &ProxyDestination::stateListHook_>;
  List list;
};

ProxyDestinationMap::ProxyDestinationMap(proxy_t* proxy)
  : proxy_(proxy),
    active_(folly::make_unique<StateList>()),
    inactive_(folly::make_unique<StateList>()),
    resetTimer_(nullptr) {
}

void ProxyDestinationMap::removeAllUnused() {
  /* We don't want to destroy any ProxyDestinations while holding
     the destinationsLock_, since the destruction obtains other locks */
  std::vector<std::shared_ptr<ProxyDestination>> toRemove;

  {
    std::lock_guard<std::mutex> lck(destinationsLock_);

    auto cur = destinations_.begin();
    while (cur != destinations_.end()) {
      auto& dest = cur->second;
      if (dest.unique()) {
        if (dest->stateList_ == active_.get()) {
          active_->list.erase(StateList::List::s_iterator_to(*dest));
        } else if (dest->stateList_ == inactive_.get()) {
          inactive_->list.erase(StateList::List::s_iterator_to(*dest));
        }
        dest->stateList_ = nullptr;
        toRemove.emplace_back(std::move(dest));
        cur = destinations_.erase(cur);
      } else {
        ++cur;
      }
    }
  }
}

std::shared_ptr<ProxyDestination>
ProxyDestinationMap::fetch(const ProxyClientCommon& client) {
  auto key = client.genProxyDestinationKey();
  std::shared_ptr<ProxyDestination> destination;
  {
    std::lock_guard<std::mutex> lck(destinationsLock_);

    auto it = destinations_.find(key);
    if (it != destinations_.end()) {
      destination = it->second;
    } else {
      destination = ProxyDestination::create(proxy_, client, key);
      destinations_.emplace(std::move(key), destination);
    }
  }

  // Update shared area of ProxyDestinations with same key from different
  // threads. This shared area is represented with ProxyClientShared class.
  if (proxy_->router != nullptr) {
    proxy_->router->pclient_owner.updateProxyClientShared(
        *destination,
        proxy_->router->opts.failures_until_tko,
        proxy_->router->opts.maximum_soft_tkos,
        proxy_->router->current_soft_tkos);
  }

  return destination;
}

std::pair<uint64_t, uint64_t>
ProxyDestinationMap::getOutstandingRequestStats() {
  std::lock_guard<std::mutex> lck(destinationsLock_);
  uint64_t pending = 0;
  uint64_t inflight = 0;
  for (const auto& it : destinations_) {
    pending += it.second->getPendingRequestCount();
    inflight += it.second->getInflightRequestCount();
  }
  return std::make_pair(pending, inflight);
}

void ProxyDestinationMap::markAsActive(ProxyDestination& destination) {
  if (destination.stateList_ == active_.get()) {
    return;
  }
  if (destination.stateList_ == inactive_.get()) {
    inactive_->list.erase(StateList::List::s_iterator_to(destination));
  }
  active_->list.push_back(destination);
  destination.stateList_ = active_.get();
}

void ProxyDestinationMap::resetAllInactive() {
  for (auto& it : inactive_->list) {
    it.resetInactive();
    it.stateList_ = nullptr;
  }
  inactive_->list.clear();
  active_.swap(inactive_);
}

void ProxyDestinationMap::setResetTimer(std::chrono::milliseconds interval) {
  assert(interval.count() > 0);
  auto delay = to<timeval_t>((unsigned int)interval.count());
  resetTimer_ = asox_add_timer(proxy_->eventBase->getLibeventBase(), delay,
                               onResetTimer, this);
}

ProxyDestinationMap::~ProxyDestinationMap() {
  if (resetTimer_ != nullptr) {
    asox_remove_timer(resetTimer_);
  }
}

}}} // facebook::memcache::mcrouter


text:
/* eslint-disable no-undef */
/**
 * For more information about the protocol you can read to protocol information
 * document at our wiki.
 *
 * @see {@link https://github.com/johnnymast/mysql_websocket_chat/wiki/Protocol|GitHub}
 */

const RECONNECT_IN_SEC = 10
const ws = {
  /**
   * Start the connection
   * @type {WebSocket}
   */
  conn: null
}

/**
 * Handle automatically reconnecting to a websocket server
 * if the connection was interrupted.
 *
 * @param {function} callback - The callback called upon reconnection
 */
WebSocket.prototype.reconnect = (callback) => {
  if (this.readyState === WebSocket.OPEN || this.readyState !== WebSocket.CONNECTING) {
    this.close()
  }

  let seconds = RECONNECT_IN_SEC
  const container = dom('.connection_alert .error_reconnect_countdown')
  const countHandle = setInterval(() => {
    if (--seconds <= 0) {
      clearInterval(countHandle)
      callback()
      return
    }
    container.text(seconds.toString())
  }, 1000)
}

/**
 * Connect to the websocket server.
 */
const connect = () => {
  if (ws.conn) {
    if (ws.conn.readyState === WebSocket.OPEN || ws.conn.readyState === WebSocket.CONNECTING) {
      ws.conn.close()
    }
    delete ws.conn
  }

  ws.conn = new WebSocket('ws://' + socketHost + ':' + socketPort)

  /**
   * Connection has been established
   *
   * @param {Event} event - The onopen event.
   */
  ws.conn.onopen = (event) => {
    dom('.client_chat').removeAttr('disabled')
    dom('.connection_alert').hide()

    /**
     * Register te client to the
     * server. This allows the server
     * to return a list of chat clients
     * to list on the side.
     */
    registerClient()

    /**
     * Request the user list from
     * the server. If the server replies the user list
     * will be populated.
     */
    requestUserlist()
  }

  /**
   * A new message (read package) has been received.
   *
   * @param {Event} event - The onmessage event.
   */
  ws.conn.onmessage = (event) => {
    const pkg = JSON.parse(event.data)

    if (pkg.type === 'message') {
      dialogOutput(pkg)
    } else if (pkg.type === 'userlist') {
      usersOutput(pkg.users)
    } else if (pkg.type === 'typing') {
      typingOutput(pkg)
    }
  }

  /**
   * Notify the user that the connection is closed
   * and disable the chat bar.
   *
   * @param {Event} event - The onclose event.
   */
  ws.conn.onclose = (event) => {
    console.log('Connection closed!')

    dom('.client_chat').prop('disabled', true)
    dom('.connection_alert').show()
    clearUserlist()

    if (event.target.readyState === WebSocket.CLOSING || event.target.readyState === WebSocket.CLOSED) {
      event.target.reconnect(connect)
    }
  }

  /**
   * Display a message in the terminal if
   * we run into an error.
   *
   * @param {Event} event - The error event.
   */
  ws.conn.onerror = (event) => {
    console.log('We have received an error!', event)
  }
}

/**
 * Remove all users from the users on the
 * side of the screen.
 */
clearUserlist = () => {
  /**
   * First of all clear the current userlist
   */
  while (userList.firstChild) {
    userList.removeChild(userList.firstChild)
  }
}

/**
 * Put a package (message) on the screen
 * for you or others to read.
 *
 * @param {object} pkg - The package object to display.
 */
dialogOutput = (pkg) => {
  if (pkg.to_user) {
    if (pkg.to_user.id === chat_user.id) {
      dom('.chat_dialog').append('(Private from << ' + pkg.user.username + ')  ' + pkg.message + '
')
    } else {
      dom('.chat_dialog').append('(Private to >> ' + pkg.to_user.username + '): ' + pkg.message + '
')
    }
  } else {
    dom('.chat_dialog').append('' + pkg.user.username + ': ' + pkg.message + '
')
  }
}

/**
 * Update the user list in the UI
 *
 * @param {array} users - Array of uses to display in the chatroom.
 */
usersOutput = (users) => {
  /**
   * First get the current select value
   * on the list. This is so we can restore
   * the selected list item after requesting
   * fow new users.
   */
  const selectedUser = userList.value

  /**
   * Before we start adding users
   * to the userlist make sure we erase
   * all the old users of the screen.
   */
  clearUserlist()

  for (const index in users) {
    if (typeof users[index] !== 'undefined') {
      const user = users[index]
      const elm = document.createElement('OPTION')

      elm.value = user.id
      elm.appendChild(document.createTextNode(user.username))

      if (elm.value === chat_user.id) {
        elm.classList = ['client_user_you']
        elm.disabled = 'disabled'
      }

      if (selectedUser.length > 0 && elm.value === selectedUser) {
        elm.selected = 'selected'
      }

      userList.appendChild(elm)
    }
  }
}

/**
 * Display a message on the screen indicating some is typing a message.
 *
 * @param {object} pkg - The received package from the server
 */
typingOutput = (pkg) => {
  if (typeof pkg === 'object') {
    const user = pkg.user
    const isTyping = pkg.value

    const indicator = dom('.typing_indicator').get()
    const typingMessage = dom(`.typing_indicator li[data-userid="${user.id}"]`).get()

    if (typingMessage) {
      typingMessage.parentNode.removeChild(typingMessage)
    }

    if (isTyping) {
      const msg = `${user.username} is typing a message`
      const li = document.createElement('LI')
      li.dataset.userid = user.id
      li.innerText = msg

      indicator.appendChild(li)
    }
  }
}

/**
 * We need to register this browser window (client)
 * to the server. We do this so we can sent private
 * messages to other users.
 */
registerClient = () => {
  /**
   * Create a registration package to send to the
   * server.
   */
  let pkg = {
    user: chat_user, /* Defined in index.php */
    type: 'registration'
  }

  pkg = JSON.stringify(pkg)

  /**
   * Send the package to the server
   */
  if (ws.conn && ws.conn.readyState === WebSocket.OPEN) {
    ws.conn.send(pkg)
  }
}

/**
 * Request a list of current active
 * chat users. We do this every x seconds
 * so we can update the ui.
 */
requestUserlist = () => {
  setInterval(() => {
    if (ws.conn.readyState !== WebSocket.CLOSING && ws.conn.readyState !== WebSocket.CLOSED) {
      /**
       * Create a package to request the list of users
       */
      let pkg = {
        user: chat_user, /* Defined in index.php */
        type: 'userlist'
      }

      /**
       * We need a object copy of package
       * to send to dialog_output() but we
       * also want to turn the original package
       * into a string so we can send it over the
       * socket to the server.
       *
       * @type {Object}
       */
      pkg = JSON.stringify(pkg)
      if (ws.conn && ws.conn.readyState === WebSocket.OPEN) {
        ws.conn.send(pkg)
      }
    }
  }, 2000)
}

/**
 * Register user is typing yes or no.
 *
 * @param {boolean} currently - Is this user currently typing?
 */
registerTyping = (currently) => {
  /**
   * Create a package to send to the
   * server.
   */
  let pkg = {
    user: chat_user, /* Defined in index.php */
    type: 'typing',
    value: currently || false
  }

  pkg = JSON.stringify(pkg)

  /**
   * Send the package to the server
   */
  if (ws.conn && ws.conn.readyState === WebSocket.OPEN) {
    ws.conn.send(pkg)
  }
}

/**
 * Send a chat message to the server
 */
sendMessage = () => {
  /**
   * Catch the chat text
   *
   * @type {string}
   */
  const chatMessage = dom('.client_chat').val()

  if (typeof chatMessage === 'undefined' || chatMessage.length === 0) {
    dom('.client_chat ').addClass('error')
    setTimeout(() => {
      dom('.client_chat ').removeClass('error')
    }, 500)
  }

  registerTyping(false)

  /**
   * When to_user is empty the
   * message will be sent to all users
   * in the chat room.
   *
   * @type {Object}
   */
  let toUser = null

  /**
   *  If a user is selected in the
   *  userlist this will mean send messages
   *  to that user.
   */
  if (userList.value) {
    toUser = {
      id: userList.value,
      username: userList.options[userList.selectedIndex].text
    }
  }

  /**
   * Create a package to send to the
   * server.
   */
  let pkg = {
    user: chat_user, /* Defined in index.php */
    message: chatMessage,
    to_user: toUser,
    type: 'message'
  }

  /**
   * We need a object copy of package
   * to send to dialog_output() but we
   * also want to turn the original package
   * into a string so we can send it over the
   * socket to the server.
   *
   * @type {Object}
   */
  const pkgObject = pkg
  pkg = JSON.stringify(pkg)

  /**
   * Send the package to the server
   */
  if (ws.conn && ws.conn.readyState === WebSocket.OPEN) {
    ws.conn.send(pkg)
  }

  /**
   * Display the message we just wrote
   * to the screen.
   */
  dialogOutput(pkgObject)

  /**
   * Empty the chat input bar
   * we don't need it anymore.
   */
  dom('.client_chat').val('')
}

const userList = dom('.user_list').get()

document.addEventListener('DOMContentLoaded', connect)
/* eslint-enable no-undef */


text:
free -m

#Free space in MB with totals
free -t -m

#Detailed memory info
cat /proc/meminfo

#Memory Statistics
vmstat

#Memory by process
top
OR
htop


text:
package hudson.tasks.junit;

import java.io.File;
import java.util.List;
import java.net.URISyntaxException;

import junit.framework.TestCase;

import hudson.XmlFile;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * Test cases for parsing JUnit report XML files.
 * As there are no XML schema for JUnit xml files, Hudson needs to handle
 * varied xml files.
 *
 * @author Erik Ramfelt
 */
public class SuiteResultTest extends TestCase {

    private File getDataFile(String name) throws URISyntaxException {
        return new File(SuiteResultTest.class.getResource(name).toURI());
    }

    private SuiteResult parseOne(File file) throws Exception {
        List<SuiteResult> results = SuiteResult.parse(file, false);
        assertEquals(1,results.size());
        return results.get(0);
    }

    /**
     * Verifying fix for issue #1233.
     * https://hudson.dev.java.net/issues/show_bug.cgi?id=1233
     */
    public void testIssue1233() throws Exception {
        SuiteResult result = parseOne(getDataFile("junit-report-1233.xml"));

        List<CaseResult> cases = result.getCases();
        assertEquals("Class name is incorrect", "test.foo.bar.DefaultIntegrationTest", cases.get(0).getClassName());
        assertEquals("Class name is incorrect", "test.foo.bar.BundleResolverIntegrationTest", cases.get(1).getClassName());
        assertEquals("Class name is incorrect", "test.foo.bar.BundleResolverIntegrationTest", cases.get(2).getClassName());
        assertEquals("Class name is incorrect", "test.foo.bar.ProjectSettingsTest", cases.get(3).getClassName());
        assertEquals("Class name is incorrect", "test.foo.bar.ProjectSettingsTest", cases.get(4).getClassName());
    }
    /**
     * Verifying fix for issue #1463.
     * JUnit report file is generated by SoapUI Pro 1.7.6
     * https://hudson.dev.java.net/issues/show_bug.cgi?id=1463
     */
    public void testIssue1463() throws Exception {
        SuiteResult result = parseOne(getDataFile("junit-report-1463.xml"));

        List<CaseResult> cases = result.getCases();
        for (CaseResult caseResult : cases) {
            assertEquals("Test class name is incorrect in " + caseResult.getDisplayName(), "WLI-FI-Tests-Fake", caseResult.getClassName());
        }
        assertEquals("Test name is incorrect", "IF_importTradeConfirmationToDwh", cases.get(0).getName());
        assertEquals("Test name is incorrect", "IF_getAmartaDisbursements", cases.get(1).getName());
        assertEquals("Test name is incorrect", "IF_importGLReconDataToDwh", cases.get(2).getName());
        assertEquals("Test name is incorrect", "IF_importTradeInstructionsToDwh", cases.get(3).getName());
        assertEquals("Test name is incorrect", "IF_getDeviationTradeInstructions", cases.get(4).getName());
        assertEquals("Test name is incorrect", "IF_getDwhGLData", cases.get(5).getName());
    }

    /**
     * Verifying fix for issue #1472.
     * JUnit report produced by TAP (Test Anything Protocol)
     * https://hudson.dev.java.net/issues/show_bug.cgi?id=1472
     */
    public void testIssue1472() throws Exception {
        List<SuiteResult> results = SuiteResult.parse(getDataFile("junit-report-1472.xml"), false);
        assertTrue(results.size()>20); // lots of data here

        SuiteResult sr0 = results.get(0);
        SuiteResult sr1 = results.get(1);
        assertEquals("make_test.t_basic_lint_t",sr0.getName());
        assertEquals("make_test.t_basic_meta_t",sr1.getName());
        assertTrue(!sr0.getStdout().equals(sr1.getStdout()));
    }

    /**
     * Verifying fix for issue #2874.
     * https://hudson.dev.java.net/issues/show_bug.cgi?id=2874
     */
    public void testIssue2874() throws Exception {
        SuiteResult result = parseOne(getDataFile("junit-report-2874.xml"));

        assertEquals("test suite name", "DummyTest", result.getName());
    }

    public void testErrorDetails() throws Exception {
        SuiteResult result = parseOne(getDataFile("junit-report-errror-details.xml"));

        List<CaseResult> cases = result.getCases();
        for (CaseResult caseResult : cases) {
            assertEquals("Test class name is incorrect in " + caseResult.getDisplayName(), "some.package.somewhere.WhooHoo", caseResult.getClassName());
        }
        assertEquals("this normally has the string like, expected mullet, but got bream", cases.get(0).getErrorDetails());
    }

    public void testSuiteResultPersistence() throws Exception {
        SuiteResult source = parseOne(getDataFile("junit-report-1233.xml"));

        File dest = File.createTempFile("testSuiteResultPersistence", ".xml");
        try {
            XmlFile xmlFile = new XmlFile(dest);
            xmlFile.write(source);

            SuiteResult result = (SuiteResult)xmlFile.read();
            assertNotNull(result);

            assertEquals(source.getName(), result.getName());
            assertEquals(source.getTimestamp(), result.getTimestamp());
            assertEquals(source.getDuration(), result.getDuration());
            assertEquals(source.getStderr(), result.getStderr());
            assertEquals(source.getStdout(), result.getStdout());
            assertEquals(source.getCases().size(), result.getCases().size());
            assertNotNull(result.getCase("testGetBundle"));
        } finally {
            dest.delete();
}
    }

    //@Bug(6516)
    public void testSuiteStdioTrimming() throws Exception {
        File data = File.createTempFile("testSuiteStdioTrimming", ".xml");
        try {
            Writer w = new FileWriter(data);
            try {
                PrintWriter pw = new PrintWriter(w);
                pw.println("<testsuites name='x'>");
                pw.println("<testsuite failures='0' errors='0' tests='1' name='x'>");
                pw.println("<testcase name='x' classname='x'/>");
                pw.println("<system-out/>");
                pw.print("<system-err><![CDATA[");
                pw.println("First line is intact.");
                for (int i = 0; i < 100; i++) {
                    pw.println("Line #" + i + " might be elided.");
                }
                pw.println("Last line is intact.");
                pw.println("]]></system-err>");
                pw.println("</testsuite>");
                pw.println("</testsuites>");
                pw.flush();
            } finally {
                w.close();
            }
            SuiteResult sr = parseOne(data);
            assertEquals(sr.getStderr(), 1028, sr.getStderr().length());
        } finally {
            data.delete();
        }
    }

}


text:
<?php namespace Rupertjeff\DynamicRouting\Laravel;

use Route;
use Rupertjeff\DynamicRouting\Contracts\Router as RouterInterface;

/**
 * Class Router
 * @package Rupertjeff\DynamicRouting\Laravel
 *
 * Connection to \Illuminate\Routing\Router
 * Implements \Rupertjeff\DynamicRouting\Support\Contracts\Router
 */
class Router implements RouterInterface {

	public function get($uri, $action)
	{
		Route::get($uri, $action);
	}

	public function post($uri, $action)
	{
		Route::post($uri, $action);
	}

	public function put($uri, $action)
	{
		Route::put($uri, $action);
	}

	public function patch($uri, $action)
	{
		Route::patch($uri, $action);
	}

	public function delete($uri, $action)
	{
		Route::delete($uri, $action);
	}

	public function options($uri, $action)
	{
		Route::options($uri, $action);
	}

	public function match($methods, $uri, $action)
	{
		Route::match($methods, $uri, $action);
	}

}


text:
<?php

namespace FrontCommsTemplates\Models;

use FrontCore\Adapters\AbstractCoreAdapter;
use FrontCommsTemplates\Entities\CommTemplateEntity; 	//	This provides a common setup for Entity objects.

/**
 * FrontCommstemplates{} creates business logic for the application.
 */
class FrontCommsTemplatesModel extends AbstractCoreAdapter
{
	/**
	 * Initializes/Instantiates/Gets/Retrieves/Loads Comms Templates form from Core System Forms
	 * using Service Manager\Locator (SM\L) from FrontCore Model.
	 * @return \FrontCore\Forms\FrontCoreSystemFormBase
	 */
	public function getCommsTemplatesForm()
	{
		$objForm = $this->getServiceLocator()->get("FrontCore\Models\SystemFormsModel")
						->getSystemForm("Core\Forms\SystemForms\Templates\CommTemplatesForm");

		return $objForm;
	} // end getCommsTemplatesForm()

	/**
	 * Gets the list of Comms Templates rows of data.
	 * @param string $arr_where
	 */
	public function getCommsTemplates($arr_where = array())
	{
		// Creates the API Model HTTP request object
		$objApiRequest = $this->getApiRequestModel();

		// Setup the object and specify the action for the form
		$objApiRequest->setApiAction("html/templates/comms");

		// Gets HTTP request METHOD=GET and return the form body
		// getBody() method - converts JSON object format to array data format.
		// Tranferring data from DB to ZF environment.
		$objCommsTemplates = $objApiRequest->performGETRequest($arr_where)->getBody();

		return $objCommsTemplates->data;

	} // end getComms($arr_where = NULL)

	/**
	 * Gets specific Comm Template row of data.
	 * @param mixed $id
	 * @return \FrontCommsTemplates\Entities\FrontCommTemplateEntity
	 */
	public function getCommTemplate($id)
	{
		// Creates the API Model HTTP request object
		$objApiRequest = $this->getApiRequestModel();

		// Setup the object and specify the action for the form
		// Connecting the FRONT-END to API
		$objApiRequest->setApiAction("html/templates/comms/$id");

		// Sets HTTP request METHOD=GET and return the form body
		// getBody() method - converts JSON object format to array data format.
		$objCommTemplate = $objApiRequest->performGETRequest(array("id" => $id))->getBody();

		// Creates Comm Template entity. Tranferring data from DB to ZF environment.
		$entity_commtemplate = $this->createCommTemplateEntity($objCommTemplate->data);

		return $entity_commtemplate;
	}// end getCommTemplate($id)

	/**
	 * Create Comm Template
	 * @triggers createCommTemplate.pre, createCommTemplate.post
	 * @param array $arr_data
	 * @return \FrontCommsTemplates\Entities\CommTemplateEntity
	 */
	public function createCommTemplate($arr_data)
	{
		// Creates Comm Template entity
		$objCommTemplate = $this->createCommTemplateEntity($arr_data);

		// 	trigger pre event. "PRE" - Initializes the event.
		//	$em = new EventManager();
		//	$em->listener(trigger/attach)->($event->getName(), $target->getTarget(), $params->getParams(), $priority);
		$this->getEventManager()->trigger(__FUNCTION__ . ".pre", $this, array("objCommTemplate" => $objCommTemplate));

		//create the HTTP request object
		$objApiRequest = $this->getApiRequestModel();

		//setup the object and specify the action
		$objApiRequest->setApiAction("html/templates/comms");

		// $_POST data in array format from JSON format
		$objCommTemplate = $objApiRequest->performPOSTRequest($objCommTemplate->getArrayCopy())->getBody();

		//recreate commtemplate entity
		$objCommTemplate = $this->createCommTemplateEntity($objCommTemplate);

		//trigger post event. "POST" - Confirm to execution of the event.
		$this->getEventManager()->trigger(__FUNCTION__ . ".post", $this, array("objCommTemplate" => $objCommTemplate));

		return $objCommTemplate;
	} //end createCommTemplates($arr_data)

	/**
	 * Update Comm Template
	 * @trigger updateCommTemplate.pre, updatecommTemplate.post
	 * @param CommTemplateEntity $objCommTmplate
	 * @return \FrontCommsTemplates\Entities\CommTemplateEntity
	 */
	public function updateCommTemplate(CommTemplateEntity $objCommTemplate)
	{
		//trigger pre event
		$result = $this->getEventManager()->trigger(__FUNCTION__ . ".pre", $this, array("objCommTemplate" => $objCommTemplate));

		//create the HTTP request object
		$objApiRequest = $this->getApiRequestModel();

		// Setup the object and specify the action
		// getHyperMedia() -
		$objApiRequest->setApiAction($objCommTemplate->getHyperMedia("edit-comm-html-template")->url);
		$objApiRequest->setApiModule(NULL);

		//data in array format from JSON format
		$objCommTemplate = $objApiRequest->performPUTRequest($objCommTemplate->getArrayCopy())->getBody();

		// recreate comm template entity
		$objCommTemplate = $this->createCommTemplateEntity($objCommTemplate->data);

		// trigger post event
		$result = $this->getEventManager()->trigger(__FUNCTION__ . ".post", $this, array("objCommTemplate" => $objCommTemplate));

		return $objCommTemplate;
	} // end function

	/**
	 * Delete Comm Template specific row of data.
	 * @param mixed $id
	 * @return \FrontCommsTemplate\Entities\CommTemplateEntity
	 */
	public function deleteCommTemplate($id)
	{
		// Instatiates Comm Template Entity
		$objCommTemplate = $this->getCommTemplate($id);

		// trigger pre event
		$result = $this->getEventManager()
				->trigger(__FUNCTION__ . ".pre", $this, array("objCommTemplate" => $objCommTemplate));

		// create the request object
		$objApiRequest = $this->getApiRequestModel();

		// setup the object and specify the action
		$objApiRequest->setApiAction($objCommTemplate->getHyperMedia("delete-comm-html-template")->url);
		$objApiRequest->setApiModule(NULL);

		// execute
		$objCommTemplate = $objApiRequest->performDELETERequest(array())->getBody();

		//trigger post event
		$result = $this->getEventManager()
				->trigger(__FUNCTION__ . ".post", $this, array("objCommTemplate" => $objCommTemplate));

		return $objCommTemplate;
	}// end deleteCommTemplate($id)

	/**
	 * Creates CommTemplate entity object
	 * @param $objData
	 * @return \FrontCommsTemplates\Entities\CommEntity
	 */
	public function createCommTemplateEntity($objData)
	{
		//	Stores data in the comms entity object
		$entity_commtemplate = $this->getServiceLocator()->get("FrontCommsTemplates\Entities\CommTemplateEntity");
		//	populates data.
		$entity_commtemplate->set($objData);
		return $entity_commtemplate;
	} // end createCommTemplateEntity($objData)

} // end FrontCommsTemplates{}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/ffmpeg4android_lib/ffmpeg4android_lib.iml" filepath="$PROJECT_DIR$/ffmpeg4android_lib/ffmpeg4android_lib.iml" />
      <module fileurl="file://$PROJECT_DIR$/ffmpegsuperimpose.iml" filepath="$PROJECT_DIR$/ffmpegsuperimpose.iml" />
    </modules>
  </component>
</project>


text:
package org.hisp.dhis.system.notification;

import java.util.List;

import org.hisp.dhis.scheduling.TaskId;

/**
 * @author Lars Helge Overland
 */
public interface Notifier
{
    Notifier notify( TaskId id, String message );

    Notifier notify( TaskId id, NotificationLevel level, String message );

    Notifier notify( TaskId id, NotificationLevel level, String message, boolean completed );

    Notifier update( TaskId id, String message );

    Notifier update( TaskId id, NotificationLevel level, String message );

    Notifier update( TaskId id, NotificationLevel level, String message, boolean completed );

    List<Notification> getNotifications( TaskId id, String lastUid );

    Notifier clear( TaskId id );

    Notifier addTaskSummary( TaskId id, Object taskSummary );

    Notifier addTaskSummary( TaskId id, NotificationLevel level, Object taskSummary );

    Object getTaskSummary( TaskId id );
}


text:
<!DOCTYPE html>

    <title>OpenLayers ArcGIS Cache Example (Autoconfigure with JSONP)</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" href="../theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="style.css" type="text/css">

OpenLayers ArcGIS Cache Example (Autoconfigure with JSONP)

        arcgis, arcgiscache, cache, tms, jsonp

        Demonstrates the basic initialization of the ArcGIS Cache layer by using the server capabilities object.

This example demonstrates using the ArcGISCache layer for
        accessing ESRI's ArcGIS Server (AGS) Map Cache tiles normally through
        a live AGS MapServer.  Toggle the visibility of the overlay to
        demonstrate how the two layers are lined up correctly.

Notes on this Layer

        This method automatically configures the layer using the capabilities object
        generated by the server itself.  This page shows how to construct the url for the server capabilities object,
        retrieve it using JSONP, and pass it in during construction.  Note that in this case,
        the layer is constructed before the map.  This approach greatly simplifies the
        configuration of your map, and works best when all your tiles / overlays are similarly laid out.
        If you are using a live AGS map server for your layer, it can be helpful to check your
        server configuration using this technique before trying one of the other examples for this layer.

 Other Examples

This is one of three examples for this layer.  You can also configure this
        layer to use prebuilt tiles in a file store (not a live server).
        As well a retrieve tiles from a live server.


text:
package com.mcgoodtime.productionline.entity;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

import javax.annotation.Nonnull;

/**
 * Created by BestOwl on 2015.12.10.0010.
 *
 * @author BestOwl
 */
public class EntityRay extends EntityArrow {

    public EntityRay(World world) {
        super(world);
    }

    public EntityRay(World world, double x, double y, double z) {
        super(world, x, y, z);
    }

    public EntityRay(World world, EntityLivingBase entityLivingBase) {
        super(world, entityLivingBase);
        this.pickupStatus = PickupStatus.DISALLOWED;
    }

    public EntityRay(World world, EntityLivingBase entity, double damage) {
        this(world, entity);
        setDamage(damage);
    }

    @Override
    @Nonnull
    protected ItemStack getArrowStack() {
        throw new AssertionError("This should not be called");
    }

    /**
     * Called to update the entity's position/logic.
     */
    @Override
    public void onUpdate() {
        super.onUpdate();
        if (this.inGround) {
            this.setDead();
        }
    }
}


text:
namespace boost {
namespace asio {
namespace fiber {

/// Default service implementation for a fiber acceptor.
template <typename Protocol>
class fiber_acceptor_service
#if defined(GENERATING_DOCUMENTATION)
    : public boost::asio::io_service::service
#else
    : public boost::asio::detail::service_base<
          fiber_acceptor_service<Protocol> >
#endif
      {
 public:
  /// The protocol type.
  typedef Protocol protocol_type;

  /// The endpoint type.
  typedef typename Protocol::endpoint endpoint_type;

  /// Type of the demultiplexer.
  typedef typename Protocol::demux_type demux_type;

  typedef boost::asio::fiber::detail::basic_fiber_impl<
      typename Protocol::socket_type> implementation_deref_type;

  /// Implementation type
  typedef std::shared_ptr<implementation_deref_type> implementation_type;

/// (Deprecated: Use native_handle_type.) The native fiber type.
#if defined(GENERATING_DOCUMENTATION)
  typedef implementation_defined native_type;
#else
  typedef implementation_type native_type;
#endif

/// The native fiber type
#if defined(GENERATING_DOCUMENTATION)
  typedef implementation_defined native_handle_type;
#else
  typedef implementation_type native_handle_type;
#endif

  /// Construct a new fiber acceptor service for the specified io_service.
  explicit fiber_acceptor_service(boost::asio::io_service& io_service)
      : boost::asio::detail::service_base<fiber_acceptor_service<Protocol> >(
            io_service) {}

  /// Construct a new fiber acceptor implementation.
  void construct(implementation_type& impl) {
    impl = implementation_deref_type::create();
  }

  void move_construct(implementation_type& impl, implementation_type& other) {
    impl = std::move(other);
    construct(other);
  }

  void move_assign(implementation_type& impl,
                   fiber_acceptor_service& other_service,
                   implementation_type& other_impl) {
    //
  }

  /// Destroy a fiber acceptor implementation.
  void destroy(implementation_type& impl) {}

  /// Open a new fiber acceptor implementation.
  boost::system::error_code open(implementation_type& impl,
                                 const protocol_type& protocol,
                                 boost::system::error_code& ec) {
    return ec;
  }

  /// Determine whether the acceptor is open.
  bool is_open(const implementation_type& impl) const {
    boost::recursive_mutex::scoped_lock lock_state(impl->state_mutex);
    return !impl->closed;
  }

  /// Cancel all asynchronous operations associated with the acceptor.
  boost::system::error_code cancel(implementation_type& impl,
                                   boost::system::error_code& ec) {
    impl->cancel_operations();
    return ec;
  }

  /// Bind the fiber acceptor to the specified local endpoint.
  boost::system::error_code bind(implementation_type& impl,
                                 const endpoint_type& endpoint,
                                 boost::system::error_code& ec) {
    impl->p_fib_demux = &(endpoint.demux());
    impl->p_fib_demux->bind(endpoint.port(), impl, ec);

    return ec;
  }

  /// Place the fiber acceptor into the state where it will listen for new
  /// connections.
  boost::system::error_code listen(implementation_type& impl, int backlog,
                                   boost::system::error_code& ec) {
    impl->p_fib_demux->listen(impl->id.local_port(), ec);
    return ec;
  }

  /// Close a fiber acceptor implementation.
  boost::system::error_code close(implementation_type& impl,
                                  boost::system::error_code& ec) {
    if (!impl->p_fib_demux) {
      return ec;
    }

    impl->p_fib_demux->close_fiber(impl);
    return ec;
  }

  /// (Deprecated: Use native_handle().) Get the native acceptor implementation.
  native_type native(implementation_type& impl) { return impl; }

  /// Get the native acceptor implementation.
  native_handle_type native_handle(implementation_type& impl) { return impl; }

  /// Get the local endpoint.
  endpoint_type local_endpoint(const implementation_type& impl,
                               boost::system::error_code& ec) const {
    return endpoint_type(*(impl->p_fib_demux), impl->id.local_port());
  }

  /// Start an asynchronous accept.
  template <typename Protocol1, typename SocketService, typename AcceptHandler>
  BOOST_ASIO_INITFN_RESULT_TYPE(AcceptHandler, void(boost::system::error_code))
      async_accept(implementation_type& impl,
                   basic_socket<Protocol1, SocketService>& peer,
                   endpoint_type* peer_endpoint,
                   BOOST_ASIO_MOVE_ARG(AcceptHandler) handler,
                   typename enable_if<
                       is_convertible<Protocol, Protocol1>::value>::type* = 0) {
    boost::asio::detail::async_result_init<AcceptHandler,
                                           void(boost::system::error_code)>
                                           init(BOOST_ASIO_MOVE_CAST(AcceptHandler)(handler));

    {
      boost::recursive_mutex::scoped_lock lock_state(impl->state_mutex);
      if (impl->closed) {
        auto handler_to_post = [init]() mutable {
          init.handler(
            boost::system::error_code(ssf::error::not_connected,
            ssf::error::get_ssf_category()));
        };
        this->get_io_service().post(handler_to_post);

        return init.result.get();
      }
    }

    boost::system::error_code ec;

    auto fiber_impl = peer.native_handle();
    fiber_impl->p_fib_demux = impl->p_fib_demux;
    fiber_impl->id.set_local_port(impl->id.local_port());

    BOOST_LOG_TRIVIAL(debug) << "fiber acceptor: local port set " << impl->id.local_port();

    typedef detail::pending_accept_operation<
        AcceptHandler, typename Protocol::socket_type> op;
    typename op::ptr p = {
        boost::asio::detail::addressof(init.handler),
        boost_asio_handler_alloc_helpers::allocate(sizeof(op), init.handler),
        0};

    p.p = new (p.v)
        op(peer.native_handle(), &(peer.native_handle()->id), init.handler);
    {
      boost::recursive_mutex::scoped_lock lock(impl->accept_op_queue_mutex);
      impl->accept_op_queue.push(p.p);
    }
    p.v = p.p = 0;
    impl->a_queues_handler();

    return init.result.get();
  }

 private:
  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service() {}
};

}  // namespace fiber
}  // namespace asio
}  // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif  // SSF_COMMON_BOOST_ASIO_FIBER_FIBER_ACCEPTOR_SERVICE_HPP


text:
module UploadHelper

  # Use this as part of the XHR data params for the upload form
  # Options include:
  #
  #   expires_at: defaults to 1 hour from now
  #   max_file_size: defaults to 5GB (not currently used)
  #   acl: defaults to authenticated-read
  #   starts_with: defaults to "uploads/#{h(current_user.to_param)}/#{SecureRandom.hex}"
  #
  def aws_upload_params(options={})
    expires_at = options[:expires_at] || 1.hours.from_now
    max_file_size = options[:max_file_size] || 5.gigabyte
    acl = options[:acl] || 'authenticated-read'
    hash = "#{SecureRandom.hex}"
    starts_with = options[:starts_with] || "uploads/#{hash}"
    bucket = ENV['aws_bucket']
    # This used to include , but it threw Server IO errors
    policy = Base64.encode64(
      "{'expiration': '#{expires_at.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')}',
        'conditions': [
          ['starts-with', '$key', '#{starts_with}'],
          ['starts-with', '$hash', '#{hash}'],
          ['starts-with', '$utf8', ''],
          ['starts-with', '$x-requested-with', ''],
          ['eq', '$success_action_status', '201'],
          ['content-length-range', 0, #{max_file_size}],
          {'bucket': '#{bucket}'},
          {'acl': '#{acl}'},
          {'success_action_status': '201'}
        ]
      }").gsub(/\n|\r/, '')

    signature = Base64.encode64(
                  OpenSSL::HMAC.digest(
                    OpenSSL::Digest::Digest.new('sha1'),
                    ENV['aws_secret_access_key'], policy)).gsub("\n","")

    return {
      "key" => "#{starts_with}/${filename}",
      "hash" => "#{hash}",
      "utf8" => "",
      "x-requested-with" => "",
      "AWSAccessKeyId" => "#{ENV['aws_access_key_id']}",
      "acl" => "#{acl}",
      "policy" => "#{policy}",
      "signature" => "#{signature}",
      "success_action_status" => "201"
    }
  end

  # Use aws_upload_tags when embedding the upload params in a form.
  # For example:
  #
  #   <form action="<%= aws_upload_url %>" method="post" enctype="multipart/form-data" id="avatar_form">
  #     <input type="file" name="file" id="avatar_attachment">
  #     <%= aws_upload_tags %>
  #   </form>
  #
  def aws_upload_tags
    aws_upload_params.each do |name, value|
      concat text_field_tag(name, value)
    end
    nil
  end

  # The destination host for the upload always uses https even though it can be slower.
  # Safe and sure wins the race
  def aws_bucket_url
    UploadHelper.aws_bucket_url
  end

  def self.aws_bucket_url
    "https://#{ENV['aws_bucket']}.#{ENV['aws_region'] || 's3'}.amazonaws.com"
  end

  # Authenticated url for S3 objects with expiration. By default the URL will expire in
  # 1 day. The path should not include the bucket name.
  def aws_url_for(path, expires=nil)
    UploadHelper.aws_url_for(path, expires)
  end

  def self.aws_url_for(path, expires=nil)
    path = "/#{path}" unless path =~ /\A\//
    path = URI.encode(path)
    expires ||= 1.day.from_now
    string_to_sign = "GET\n\n\n#{expires.to_i}\n/#{ENV['aws_bucket']}#{path}"
    signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), ENV['aws_secret_access_key'], string_to_sign)).gsub("\n","")
    query_string = URI.encode_www_form("AWSAccessKeyId" => ENV['aws_access_key_id'], "Signature" => signature, "Expires" => expires.to_i)
    "#{aws_bucket_url}#{path}?#{query_string}"
  end
end


text:
namespace base {
namespace debug {

namespace {

class TestActivityTracker : public ThreadActivityTracker {
 public:
  TestActivityTracker(std::unique_ptr<char[]> memory, size_t mem_size)
      : ThreadActivityTracker(memset(memory.get(), 0, mem_size), mem_size),
        mem_segment_(std::move(memory)) {}

  ~TestActivityTracker() override {}

 private:
  std::unique_ptr<char[]> mem_segment_;
};

}  // namespace

class ActivityTrackerTest : public testing::Test {
 public:
  const int kMemorySize = 1 << 20;  // 1MiB
  const int kStackSize  = 1 << 10;  // 1KiB

  using ActivityId = ThreadActivityTracker::ActivityId;

  ActivityTrackerTest() {}

  ~ActivityTrackerTest() override {
    GlobalActivityTracker* global_tracker = GlobalActivityTracker::Get();
    if (global_tracker) {
      global_tracker->ReleaseTrackerForCurrentThreadForTesting();
      delete global_tracker;
    }
  }

  std::unique_ptr<ThreadActivityTracker> CreateActivityTracker() {
    std::unique_ptr<char[]> memory(new char[kStackSize]);
    return MakeUnique<TestActivityTracker>(std::move(memory), kStackSize);
  }

  size_t GetGlobalActiveTrackerCount() {
    GlobalActivityTracker* global_tracker = GlobalActivityTracker::Get();
    if (!global_tracker)
      return 0;
    return global_tracker->thread_tracker_count_.load(
        std::memory_order_relaxed);
  }

  size_t GetGlobalInactiveTrackerCount() {
    GlobalActivityTracker* global_tracker = GlobalActivityTracker::Get();
    if (!global_tracker)
      return 0;
    base::AutoLock autolock(global_tracker->thread_tracker_allocator_lock_);
    return global_tracker->thread_tracker_allocator_.cache_used();
  }

  size_t GetGlobalUserDataMemoryCacheUsed() {
    return GlobalActivityTracker::Get()->user_data_allocator_.cache_used();
  }

  static void DoNothing() {}
};

TEST_F(ActivityTrackerTest, UserDataTest) {
  char buffer[256];
  memset(buffer, 0, sizeof(buffer));
  ActivityUserData data(buffer, sizeof(buffer));
  ASSERT_EQ(sizeof(buffer) - 8, data.available_);

  data.SetInt("foo", 1);
  ASSERT_EQ(sizeof(buffer) - 8 - 24, data.available_);

  data.SetUint("b", 1U);  // Small names fit beside header in a word.
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16, data.available_);

  data.Set("c", buffer, 10);
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24, data.available_);

  data.SetString("dear john", "it's been fun");
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32, data.available_);

  data.Set("c", buffer, 20);
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32, data.available_);

  data.SetString("dear john", "but we're done together");
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32, data.available_);

  data.SetString("dear john", "bye");
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32, data.available_);

  data.SetChar("d", 'x');
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32 - 8, data.available_);

  data.SetBool("ee", true);
  ASSERT_EQ(sizeof(buffer) - 8 - 24 - 16 - 24 - 32 - 8 - 16, data.available_);
}

TEST_F(ActivityTrackerTest, PushPopTest) {
  std::unique_ptr<ThreadActivityTracker> tracker = CreateActivityTracker();
  ThreadActivityTracker::Snapshot snapshot;

  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(0U, snapshot.activity_stack_depth);
  ASSERT_EQ(0U, snapshot.activity_stack.size());

  char origin1;
  ActivityId id1 = tracker->PushActivity(&origin1, Activity::ACT_TASK,
                                         ActivityData::ForTask(11));
  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(1U, snapshot.activity_stack_depth);
  ASSERT_EQ(1U, snapshot.activity_stack.size());
  EXPECT_NE(0, snapshot.activity_stack[0].time_internal);
  EXPECT_EQ(Activity::ACT_TASK, snapshot.activity_stack[0].activity_type);
  EXPECT_EQ(reinterpret_cast<uintptr_t>(&origin1),
            snapshot.activity_stack[0].origin_address);
  EXPECT_EQ(11U, snapshot.activity_stack[0].data.task.sequence_id);

  char origin2;
  char lock2;
  ActivityId id2 = tracker->PushActivity(&origin2, Activity::ACT_LOCK,
                                         ActivityData::ForLock(&lock2));
  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(2U, snapshot.activity_stack_depth);
  ASSERT_EQ(2U, snapshot.activity_stack.size());
  EXPECT_LE(snapshot.activity_stack[0].time_internal,
            snapshot.activity_stack[1].time_internal);
  EXPECT_EQ(Activity::ACT_LOCK, snapshot.activity_stack[1].activity_type);
  EXPECT_EQ(reinterpret_cast<uintptr_t>(&origin2),
            snapshot.activity_stack[1].origin_address);
  EXPECT_EQ(reinterpret_cast<uintptr_t>(&lock2),
            snapshot.activity_stack[1].data.lock.lock_address);

  tracker->PopActivity(id2);
  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(1U, snapshot.activity_stack_depth);
  ASSERT_EQ(1U, snapshot.activity_stack.size());
  EXPECT_EQ(Activity::ACT_TASK, snapshot.activity_stack[0].activity_type);
  EXPECT_EQ(reinterpret_cast<uintptr_t>(&origin1),
            snapshot.activity_stack[0].origin_address);
  EXPECT_EQ(11U, snapshot.activity_stack[0].data.task.sequence_id);

  tracker->PopActivity(id1);
  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(0U, snapshot.activity_stack_depth);
  ASSERT_EQ(0U, snapshot.activity_stack.size());
}

TEST_F(ActivityTrackerTest, ScopedTaskTest) {
  GlobalActivityTracker::CreateWithLocalMemory(kMemorySize, 0, "", 3);

  ThreadActivityTracker* tracker =
      GlobalActivityTracker::Get()->GetOrCreateTrackerForCurrentThread();
  ThreadActivityTracker::Snapshot snapshot;
  ASSERT_EQ(0U, GetGlobalUserDataMemoryCacheUsed());

  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(0U, snapshot.activity_stack_depth);
  ASSERT_EQ(0U, snapshot.activity_stack.size());

  {
    PendingTask task1(FROM_HERE, base::Bind(&DoNothing));
    ScopedTaskRunActivity activity1(task1);
    ActivityUserData& user_data1 = activity1.user_data();
    (void)user_data1;  // Tell compiler it's been used.

    ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
    ASSERT_EQ(1U, snapshot.activity_stack_depth);
    ASSERT_EQ(1U, snapshot.activity_stack.size());
    EXPECT_EQ(Activity::ACT_TASK, snapshot.activity_stack[0].activity_type);

    {
      PendingTask task2(FROM_HERE, base::Bind(&DoNothing));
      ScopedTaskRunActivity activity2(task2);
      ActivityUserData& user_data2 = activity2.user_data();
      (void)user_data2;  // Tell compiler it's been used.

      ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
      ASSERT_EQ(2U, snapshot.activity_stack_depth);
      ASSERT_EQ(2U, snapshot.activity_stack.size());
      EXPECT_EQ(Activity::ACT_TASK, snapshot.activity_stack[1].activity_type);
    }

    ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
    ASSERT_EQ(1U, snapshot.activity_stack_depth);
    ASSERT_EQ(1U, snapshot.activity_stack.size());
    EXPECT_EQ(Activity::ACT_TASK, snapshot.activity_stack[0].activity_type);
  }

  ASSERT_TRUE(tracker->CreateSnapshot(&snapshot));
  ASSERT_EQ(0U, snapshot.activity_stack_depth);
  ASSERT_EQ(0U, snapshot.activity_stack.size());
  ASSERT_EQ(2U, GetGlobalUserDataMemoryCacheUsed());
}

TEST_F(ActivityTrackerTest, CreateWithFileTest) {
  const char temp_name[] = "CreateWithFileTest";
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath temp_file = temp_dir.GetPath().AppendASCII(temp_name);
  const size_t temp_size = 64 << 10;  // 64 KiB

  // Create a global tracker on a new file.
  ASSERT_FALSE(PathExists(temp_file));
  GlobalActivityTracker::CreateWithFile(temp_file, temp_size, 0, "foo", 3);
  GlobalActivityTracker* global = GlobalActivityTracker::Get();
  EXPECT_EQ(std::string("foo"), global->allocator()->Name());
  global->ReleaseTrackerForCurrentThreadForTesting();
  delete global;

  // Create a global tracker over an existing file, replacing it. If the
  // replacement doesn't work, the name will remain as it was first created.
  ASSERT_TRUE(PathExists(temp_file));
  GlobalActivityTracker::CreateWithFile(temp_file, temp_size, 0, "bar", 3);
  global = GlobalActivityTracker::Get();
  EXPECT_EQ(std::string("bar"), global->allocator()->Name());
  global->ReleaseTrackerForCurrentThreadForTesting();
  delete global;
}

// GlobalActivityTracker tests below.

class SimpleActivityThread : public SimpleThread {
 public:
  SimpleActivityThread(const std::string& name,
                       const void* origin,
                       Activity::Type activity,
                       const ActivityData& data)
      : SimpleThread(name, Options()),
        origin_(origin),
        activity_(activity),
        data_(data),
        exit_condition_(&lock_) {}

  ~SimpleActivityThread() override {}

  void Run() override {
    ThreadActivityTracker::ActivityId id =
        GlobalActivityTracker::Get()
            ->GetOrCreateTrackerForCurrentThread()
            ->PushActivity(origin_, activity_, data_);

    {
      AutoLock auto_lock(lock_);
      ready_ = true;
      while (!exit_)
        exit_condition_.Wait();
    }

    GlobalActivityTracker::Get()->GetTrackerForCurrentThread()->PopActivity(id);
  }

  void Exit() {
    AutoLock auto_lock(lock_);
    exit_ = true;
    exit_condition_.Signal();
  }

  void WaitReady() {
    SPIN_FOR_1_SECOND_OR_UNTIL_TRUE(ready_);
  }

 private:
  const void* origin_;
  Activity::Type activity_;
  ActivityData data_;

  bool ready_ = false;
  bool exit_ = false;
  Lock lock_;
  ConditionVariable exit_condition_;

  DISALLOW_COPY_AND_ASSIGN(SimpleActivityThread);
};

TEST_F(ActivityTrackerTest, ThreadDeathTest) {
  GlobalActivityTracker::CreateWithLocalMemory(kMemorySize, 0, "", 3);
  GlobalActivityTracker::Get()->GetOrCreateTrackerForCurrentThread();
  const size_t starting_active = GetGlobalActiveTrackerCount();
  const size_t starting_inactive = GetGlobalInactiveTrackerCount();

  SimpleActivityThread t1("t1", nullptr, Activity::ACT_TASK,
                          ActivityData::ForTask(11));
  t1.Start();
  t1.WaitReady();
  EXPECT_EQ(starting_active + 1, GetGlobalActiveTrackerCount());
  EXPECT_EQ(starting_inactive, GetGlobalInactiveTrackerCount());

  t1.Exit();
  t1.Join();
  EXPECT_EQ(starting_active, GetGlobalActiveTrackerCount());
  EXPECT_EQ(starting_inactive + 1, GetGlobalInactiveTrackerCount());

  // Start another thread and ensure it re-uses the existing memory.

  SimpleActivityThread t2("t2", nullptr, Activity::ACT_TASK,
                          ActivityData::ForTask(22));
  t2.Start();
  t2.WaitReady();
  EXPECT_EQ(starting_active + 1, GetGlobalActiveTrackerCount());
  EXPECT_EQ(starting_inactive, GetGlobalInactiveTrackerCount());

  t2.Exit();
  t2.Join();
  EXPECT_EQ(starting_active, GetGlobalActiveTrackerCount());
  EXPECT_EQ(starting_inactive + 1, GetGlobalInactiveTrackerCount());
}

}  // namespace debug
}  // namespace base